rayzee 8.6.1 → 8.8.0

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.
@@ -112,7 +112,7 @@
112
112
  return seed;
113
113
 
114
114
  }
115
- `,[ne,z]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},V=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.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)}},be=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.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={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.appliedValues={},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._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),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=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},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=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):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,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,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}},H,xe=y((()=>{H={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`}}));xe();var Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:H.LOADING_RESET}),U=e=>{Se?.({type:H.LOADING_UPDATE,...e})},Te=e=>{Se?.({type:H.STATS_UPDATE,...e})};function Ee(e){return e.frameCount||0}function De(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Oe(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Oe(e),e.dispose()}}function Oe(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 ke({material:e,geometry:t,children:n}){if(e&&De(e),t&&t.dispose(),n.length>0)for(let e of n)ke(e)}function Ae(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function je(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){De(e);return}for(;e.children.length>0;)for(let t of e.children)je(t);ke(e),e.removeFromParent(),e.clear()}}function Me(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function Ne(e,t){return t}function Pe(e,t=!1){return t?1:1/(e+1)}function Fe(){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}}}var Ie=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Le(e=`viewer`){let t=Ie[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Ie).join(`, `)}`);return t}var W={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Ie.viewer.toneMapping,exposure:1,saturation:Ie.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Ie.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Re=6e4,ze=3,Be=.1,Ve=.01,He=4096,G=2048;function Ue(e){return G=Math.max(256,Math.min(He,Math.floor(e)||256)),G}var We={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Ge={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Ke=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],qe={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},Je={fov:{min:10,max:90,default:W.fov},focusDistance:{min:.3,max:100,default:W.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:W.aperture},focalLength:{min:0,max:200,default:W.focalLength}},Ye={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}},Xe={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}},Ze={MANUAL:`manual`,AUTO:`auto`},Qe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},$e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19},et=16777215;function tt(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function K(e,t){return(e&et|(t?.side??0)<<24|tt(t)<<26)>>>0}function nt(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var q={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32}},rt=e=>Number.isFinite(e)&&e>0?e:0,J=it({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function it(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var at=1073741824,ot=1073741824,st=1073741823,ct={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function lt(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function ut(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${at.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var dt={PIXELS_PER_MATERIAL:30,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,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},ft=64;function pt(e,t){let n=Math.ceil(Math.max(1,e)/ft)*ft;return Math.min(t,Math.max(dt.MIN_TEXTURE_WIDTH,n))}function mt(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function ht(e,t){return pt(e.width,t)*e.height*e.count*4}function gt(e,t){return e.reduce((e,n)=>e+ht(n,t),0)}function _t(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=mt(r[t].units.concat(r[i].units)),o=ht(a,n)-ht(r[t],n)-ht(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function vt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(dt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(mt)}function yt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(mt(t))}else e===a?o.push(mt(n[e].units.concat([r]))):o.push(n[e]);if(gt(o,t)<gt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function bt(e,t,n=dt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>mt([e]));if(a.length>n){let e=vt(i,n,t),r=_t(a,n,t);a=gt(e,t)<gt(r,t)?e:r,a=yt(a,t)}return a.map(e=>({width:pt(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function xt(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function St(e,t){return e*dt.BUCKET_LAYER_STRIDE+t}var Ct=[0,0,1,1,0,0,0,1],wt={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},Tt={maxSamples:W.maxSamples,bounces:W.bounces,renderMode:W.renderMode,enableAlphaShadows:W.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:W.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function Et(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??W.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??W.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??W.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??W.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??W.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??W.interactionModeEnabled}}var Dt={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};function Ot(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function kt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function At(){if(Ut!==null)return Ut;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Lt?(Ut=Lt[e],Ut):(Ut=Lt[Ot(zt)]??Lt[Rt],Ut)}function jt(){if(Wt!==null)return Wt;let e=globalThis.__RAYZEE_LOG_NS__??Ot(Bt);return Wt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Wt}function Mt(e,t){if(t<Lt.debug)return!0;let n=jt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Nt(e,t,n){if(e>At()||!Mt(t,e))return;let r=e===Lt.error?console.error:e===Lt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Vt,Ht,...n.slice(1)):r(`%c${i}`,Vt,...n)}function Pt(e){return{namespace:e,error:(...t)=>Nt(Lt.error,e,t),warn:(...t)=>Nt(Lt.warn,e,t),info:(...t)=>Nt(Lt.info,e,t),debug:(...t)=>Nt(Lt.debug,e,t),isEnabled:e=>Gt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Nt(Lt.info,e,[t]),r.forEach(t=>Nt(Lt.debug,e,[t]));return}Lt.info>At()||((At()>=Lt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Vt,Ht),r.forEach(e=>console.log(e)),console.groupEnd())}}}function Ft(e,t,...n){Kt.has(t)||(Kt.add(t),e.warn(...n))}function It(){return Gt.getLevel()}var Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Y,Gt,Kt,qt=y((()=>{Lt={silent:0,error:1,warn:2,info:3,debug:4},Rt=`info`,zt=`rayzeeLogLevel`,Bt=`rayzeeLogNamespaces`,Vt=`color:#7c8494`,Ht=`color:inherit`,Ut=null,Wt=null,Y={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${Y.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Gt={levels:Lt,setLevel(e){return e in Lt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Ut=Lt[e],kt(zt,e===Rt?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Lt).join(`, `)}`),this.getLevel())},getLevel(){let e=At();return Object.keys(Lt).find(t=>Lt[t]===e)},isEnabled(e){return(Lt[e]??Lt.debug)<=At()},only(...e){let t=e.flat().filter(Boolean);return Wt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),kt(Bt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Ut=null,Wt=null,this.getLevel()}},Kt=new Set}));qt();var Jt=Pt(`gpu`);function Yt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Xt=()=>Yt(),Zt=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,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Xt(),this.writeNormalDepth=Xt(),this.writeAlbedo=Xt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Jt.debug(`storage texture pool ${Y.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}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,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}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.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}},Qt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},$t=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=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}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,W.bounces,`int`),i(`maxSamples`,W.maxSamples,`int`),i(`transmissiveBounces`,W.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,W.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,W.maxTransparentBounces,`int`),i(`visMode`,W.debugMode,`int`),i(`debugVisScale`,W.debugVisScale,`float`),a(`useAdaptiveSampling`,W.useAdaptiveSampling),i(`noiseThreshold`,W.noiseThreshold,`float`),i(`adaptiveMinSamples`,W.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,W.adaptiveStopFraction,`float`),a(`usePixelFreeze`,W.usePixelFreeze),i(`pixelFreezeThreshold`,W.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,W.pixelFreezeStability,`int`),a(`convergenceOverlay`,W.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,W.environmentIntensity,`float`),i(`backgroundIntensity`,W.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,W.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,W.backgroundBlurSamples,`int`),a(`showBackground`,W.showBackground),a(`transparentBackground`,W.transparentBackground),a(`enableEnvironment`,W.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,W.groundProjectionEnabled),i(`groundProjectionRadius`,W.groundProjectionRadius,`float`),i(`groundProjectionHeight`,W.groundProjectionHeight,`float`),i(`groundProjectionLevel`,W.groundProjectionLevel,`float`),a(`enableGroundCatcher`,W.enableGroundCatcher),i(`groundCatcherHeight`,W.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,W.globalIlluminationIntensity,`float`),i(`exposure`,W.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(192),`float`),area:(0,n.uniformArray)(new Float32Array(256),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(320),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,+(W.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(W.panoramaLonRange),`vec2`),i(`panoLatRange`,o(W.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,W.panoramaLevelHorizon),a(`enableDOF`,W.enableDOF),i(`focusDistance`,W.focusDistance,`float`),i(`focalLength`,W.focalLength,`float`),i(`aperture`,W.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,W.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,N),N.value=W.samplingTechnique,i(`fireflyThreshold`,W.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,W.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,W.enableEmissiveTriangleSampling),i(`emissiveBoost`,W.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,W.renderMode,`int`),a(`enableAlphaShadows`,W.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Qt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},en=[1,0,0,0,1,0,0,0],tn=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.SHEEN_COLOR+3,q.DISPLACEMENT_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+2,q.SPECULAR_COLOR_MAP_INDEX+3]);var nn=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`])),rn=e=>Math.min(Math.max(e,0),1);function an(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function on(e){return Number.isInteger(e)?e:-1}function sn(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=an(i,r[0]),e[t+1]=an(a,r[1]),e[t+2]=an(o,r[2])}function cn(e,t,n){let r=(n,r,i)=>{e[t+n]=an(r,i)},i=(n,r,i)=>{e[t+n]=rn(an(r,i))};r(q.IOR,n.ior,J.ior),i(q.TRANSMISSION,n.transmission,J.transmission),r(q.THICKNESS,n.thickness,J.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,J.emissiveIntensity),sn(e,t+q.ATTENUATION_COLOR,n.attenuationColor,J.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=rt(n.attenuationDistance??J.attenuationDistance),i(q.OPACITY,n.opacity,J.opacity),r(q.SIDE,n.side,J.side),r(q.TRANSPARENT,n.transparent,J.transparent),r(q.ALPHA_TEST,n.alphaTest,J.alphaTest),r(q.ALPHA_MODE,n.alphaMode,J.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,J.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],J.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],J.normalScale[1]),sn(e,t+q.COLOR,n.color,J.color),i(q.METALNESS,n.metalness,J.metalness),sn(e,t+q.EMISSIVE,n.emissive,J.emissive),i(q.ROUGHNESS,n.roughness,J.roughness),e[t+q.ALBEDO_MAP_INDEX]=on(n.map),e[t+q.NORMAL_MAP_INDEX]=on(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=on(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=on(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=on(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=on(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,J.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,J.clearcoatRoughness),r(q.DISPERSION,n.dispersion,J.dispersion),i(q.SHEEN,n.sheen,J.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,J.sheenRoughness),sn(e,t+q.SHEEN_COLOR,n.sheenColor,J.sheenColor),i(q.SPECULAR_INTENSITY,n.specularIntensity,J.specularIntensity),sn(e,t+q.SPECULAR_COLOR,n.specularColor,J.specularColor),i(q.IRIDESCENCE,n.iridescence,J.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,J.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],J.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],J.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,J.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,J.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=on(n.displacementMap);for(let[r,i]of tn){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=an(a?.[n],en[n])}sn(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,J.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,J.subsurface),sn(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,J.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,J.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,J.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,J.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,J.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=on(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=on(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=on(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=on(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=on(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=on(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=on(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=on(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=on(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=on(n.specularColorMap),e[t+q.VISIBLE]=1,e[t+q.SHEEN_COLOR+3]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+2]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+3]=0}var ln=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`}),un=Object.freeze({ERROR:`error`,WARNING:`warning`}),dn=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},fn=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=un.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===un.ERROR)throw new dn(i);return i}warn(e,t,n){return this.record(e,t,n,un.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===un.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},pn=64*1024*1024,mn=typeof SharedArrayBuffer<`u`,hn=null;function gn(e){hn=e}function _n(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return hn&&r.byteLength>0&&hn(r.byteLength,n),r}var vn=class e{constructor(e,t,n,r=pn,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(_n(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(_n(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=pn,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=_n(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};qt();var yn=Pt(`geometry`),bn=dt.MAX_TEXTURES_LIMIT,xn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`]),Sn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),Cn=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function wn(e){for(let t=0;t<16;t++)if(e[t]!==Cn[t])return!1;return!0}function Tn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function En(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function Dn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function On(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function kn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var An=1<<21;function jn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function Mn(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Nn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:Dn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=this._compressed,n=(e,t)=>{if(!e.userData?.__rayzeeExternal){t(e);for(let r of e.children)n(r,t)}};n(e,e=>{let n=e.geometry;if(!(!e.isMesh||!n||t.has(n.uuid))){t.add(n.uuid);for(let e of[`normal`,`tangent`,`color`]){let t=n.getAttribute(e);if(!t||t.normalized||!(t.array instanceof Float32Array)||n.morphAttributes?.[e]?.length)continue;let i=t.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);n.setAttribute(e,new r.BufferAttribute(o,t.itemSize,!0))}}})}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e){this.triangles=new vn(e,$e.FLOATS_PER_TRIANGLE,Uint32Array,void 0,mn),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=jn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=wn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=An?!0:(this._issues?.record(ln.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:An}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,Ft(yn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(J))e[t]=xn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:J.normalScale[0],y:J.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=Tn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=Sn.MATERIAL,e[n]):(a[n]=Sn.DEFAULT,t[n]):(a[n]=Sn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=Sn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:En(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<bn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${bn} distinct textures for one map type; the rest render untextured`,{limit:bn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,Mn(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&Mn(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(On(u,y),On(d,y),On(f,y),kn(p,b),kn(m,b),kn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=$e,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=nt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=nt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=nt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=K(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}getTriangleData(){return this.triangles?this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*$e.FLOATS_PER_TRIANGLE*4;yn.debug(Y.list([`${Y.count(this.currentTriangleIndex,`tri`)} (${Y.mb(e)})`,Y.count(this.materials.length,`material`),Y.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}},Pn=null,Fn=null;function In(e,t=null){Pn=e,Fn=e?t:null}function Ln(){return Pn}function Rn(){return Fn}function zn(e){if(!Pn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Pn[0]*t+Pn[1]*n+Pn[2]*r,e[1]=Pn[3]*t+Pn[4]*n+Pn[5]*r,e[2]=Pn[6]*t+Pn[7]*n+Pn[8]*r,!0}function Bn(e,t,n){if(!Pn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Pn[0]*a+Pn[1]*o+Pn[2]*s,e[n+1]=Pn[3]*a+Pn[4]*o+Pn[5]*s,e[n+2]=Pn[6]*a+Pn[7]*o+Pn[8]*s,r++}return r}qt();var Vn=new WeakSet,Hn=Pt(`material`),Un=q.SLOTS_PER_MATERIAL,Wn=$e.MATERIAL_FLAGS_OFFSET,Gn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Kn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1]],qn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION},Jn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Vn.has(t))return;Vn.add(t);let n=Bn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Hn.debug(`converted ${n} material colour(s) into ${Rn()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];zn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Un),this._sources=[...r],this._hostSet=[],Hn.debug(`${Y.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=qn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?Sn.HOST:this._sources[e]?.[t]}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(nn.has(t)&&typeof n==`number`&&(n=rn(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=rt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Hn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Set).add(t),Gn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;cn(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=Tn(t);for(let[t,r]of Kn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Hn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=tt({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=$e.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+Wn]&16777215)===e&&(n[r+Wn]=(n[r+Wn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},Yn=`function e(e,t,n,r){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 t(t,n,r){let i=n*r,a=new Float32Array(i),o=0;for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let s=e*n+r,c=t[4*s],l=t[4*s+1],u=t[4*s+2],d=(.2126*c+.7152*l+.0722*u)*i;a[s]=d,o+=d}}let s=o/i,c=0;for(let e=0;e<i;e++)a[e]=Math.max(0,a[e]-s),c+=a[e];let l=c>0,u=l?c:o,d=l?s:0;if(!l)for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let o=e*n+r,s=t[4*o],c=t[4*o+1],l=t[4*o+2];a[o]=(.2126*s+.7152*c+.0722*l)*i}}let f=new Float32Array(i),p=new Float32Array(r),m=0;for(let e=0;e<r;e++){let t=0;for(let r=0;r<n;r++){let i=e*n+r;t+=a[i],f[i]=t}if(t!==0)for(let r=e*n,i=e*n+n;r<i;r++)f[r]/=t;m+=t,p[e]=m}if(m!==0)for(let e=0,t=p.length;e<t;e++)p[e]/=m;let h=new Float32Array(r);for(let t=0;t<r;t++)h[t]=(e(p,(t+1)/r,0,r)+.5)/r;let g=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let i=t*n+r;g[i]=(e(f,(r+1)/n,t*n,n)+.5)/n}return{marginalData:h,conditionalData:g,totalSum:u,compensationDelta:d}}self.onmessage=function(e){let{floatData:n,width:r,height:i}=e.data;try{let e=t(n,r,i);self.postMessage({marginalData:e.marginalData,conditionalData:e.conditionalData,totalSum:e.totalSum,compensationDelta:e.compensationDelta,width:r,height:i},[e.marginalData.buffer,e.conditionalData.buffer])}catch(e){self.postMessage({error:e.message})}};`,Xn=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Yn],{type:`text/javascript;charset=utf-8`});function Zn(e){let t;try{if(t=Xn&&(self.URL||self.webkitURL).createObjectURL(Xn),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Yn),{type:`module`,name:e?.name})}}function Qn(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 $n(e,t,n){return .2126*e+.7152*t+.0722*n}function er(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=er(o[e]),o[e+1]=er(o[e+1]),o[e+2]=er(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nr=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=tr(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tr(e);this._worker=new Zn;try{let e=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$n(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$n(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qn(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qn(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rr=Math.PI,ir=Math.PI*2,ar=Math.E,or=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],sr=[183999185144339.78,277980239196605.28,407904795438610.94],cr=1.6110731556870734,lr=1.5,ur=1e3,dr=8400,fr=1250,pr=.9999566769464484,mr=.05968310365946075,hr=.07957747154594767;function gr(e){return ur*Math.max(0,1-ar**+(-(cr-Math.acos(Math.max(-1,Math.min(1,e))))/lr))}function _r(e){let t=.2*e*1e-17;return[.434*t*sr[0],.434*t*sr[1],.434*t*sr[2]]}function vr(e){return mr*(1+e**2)}function yr(e,t){let n=t*t;return hr*((1-n)/(1-2*t*e+n)**1.5)}function br(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xr(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 Sr(e,t,n,r,i,a,o,s){let c=(1-t)*rr,l=(e-.5)*ir,u=Math.sin(c),d=xr([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xr(n),p=gr(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[or[0]*m,or[1]*m,or[2]*m],g=_r(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/rr*v)**-1.253,b=dr/y,x=fr/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=br(d,f),w=vr(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yr(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 P=[.1*S[0],.1*S[1],.1*S[2]],F=Cr(pr,pr+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*F;let I=65504;return[Math.min((A[0]+P[0])*.04,I),Math.min((A[1]+P[1])*.04+3e-4,I),Math.min((A[2]+P[2])*.04+75e-5,I),1]}function Cr(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=Sr((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,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,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,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}};function Er(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Dr(e){e&&Object.assign(kr,e)}function Or(){return{...kr}}var kr,Ar=y((()=>{kr={stbnScalarAtlas:`https://assets.rayzee.atulmourya.com/noise/stbn_scalar_atlas.png`,stbnVec2Atlas:`https://assets.rayzee.atulmourya.com/noise/stbn_vec2_atlas.png`,ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,neuralRuntimeUrl:`/neural/neural-runtime.js`,neuralAssetBaseUrl:null,cacheNamespace:`rayzee`}}));Ar(),qt();var jr=Pt(`ocio`);function Mr(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?jr.error(t):/\[OpenColorIO Warning\]/.test(t)?jr.warn(t):jr.debug(t)}var Nr=null,Pr=null,Fr=null,Ir=null,Lr=null;async function Rr(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Or();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function zr(){return Pr||(Nr||=(async()=>{let e=await Rr();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Or();return Pr=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:Mr,printErr:Mr}}),Pr})().catch(e=>{throw Nr=null,e}),await Nr)}async function Br(){return(await zr()).ocio.listBuiltinConfigs()}async function Vr({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await zr();if(e)Fr=a.loadBuiltinConfig(e),Ir=e,Lr=qr(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);Fr=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),Ir=i??Fr.id;let o=e.find(e=>e.relativePath===r);Lr=o?new TextDecoder().decode(o.data):null}return Kr()}function Hr(){Fr=null,Ir=null,Lr=null}function Ur(){return Fr!==null}function Wr(){return Fr?Pr:null}function Gr(){return Fr}function Kr(){if(!Fr)return null;let e=Object.fromEntries(Fr.roles.map(e=>[e.name,e.colorSpace]));return{id:Ir,name:Lr?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:Fr.ocioVersion,version:Fr.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:Fr.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:Fr.displays.slice(),defaultDisplay:Fr.defaultDisplay,views:Object.fromEntries(Object.entries(Fr.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...Fr.defaultViewsByDisplay},looks:Fr.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:Fr.namedTransforms.map(e=>e.name),fileRules:Fr.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:Jr()}}function qr(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function Jr(){if(!Lr)return[];let e=new Map,t=Lr.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of Lr.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Yr(){Hr(),Pr?.dispose?.(),Pr=null,Nr=null}var Xr=1<<20,Zr=new Map,Qr=new Map,$r=4096,ei=new Map;function ti(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function ni(){for(let e of Zr.values())e.dispose?.();Zr.clear(),Qr.clear(),ei.clear()}function ri(e,t,{context:n=null}={}){if(!Wr()||e===t)return null;let r=ti(e,t,n),i=Zr.get(r);if(i!==void 0)return i;try{i=si().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return Zr.set(r,i),i}var ii=null,ai=null,oi=!1;function si(){let e=Wr();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=Gr();if(ii&&ai===t.id)return ii;if(oi&&ii?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ii=e.ocio.createBuiltinConfig(t.id),oi=!0,ai=t.id,ii}function ci(){oi&&ii?.dispose?.(),ii=null,ai=null,oi=!1,ni()}function li(e,t,n,{context:r=null}={}){let i=Wr();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${ti(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=Qr.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return Qr.size>=$r&&Qr.clear(),Qr.set(a,s),s.slice()}function ui(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=ri(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=Xr)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=Xr){let n=Math.min(Xr,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var di=.055;function fi(e){return e<=.04045?e/12.92:((e+di)/(1+di))**2.4}function pi(e){return e<=0?0:e<=.0031308?12.92*e:(1+di)*e**(1/2.4)-di}var mi=new Float32Array(256);for(let e=0;e<256;e++)mi[e]=fi(e/255);var hi=new Float32Array(256);for(let e=0;e<256;e++)hi[e]=e/255;function gi(e){return e===`srgb`?mi:hi}function _i(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=ri(t,n,{context:r});if(!o)return e;let s=e.length/4,c=gi(i),l=a===`srgb`?bi:xi,u=new Float32Array(Math.min(Xr,s)*4);for(let t=0;t<s;t+=Xr){let n=Math.min(Xr,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var vi=65536,yi=new Uint8Array(vi+1);for(let e=0;e<=vi;e++){let t=e/vi;yi[e]=Math.round(pi(t*t)*255)}function bi(e){return e>0?e>=1?255:yi[Math.sqrt(e)*vi+.5|0]:0}function xi(e){return e>0?e>=1?255:e*255+.5|0:0}function Si(e,t,n=`srgb`){if(!t)return e;let r=gi(n),i=n===`srgb`?bi:xi,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Ci(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!Wr())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=ti(e,t,n);if(ei.has(i))return ei.get(i);let a=ri(e,t,{context:n});if(!a)return ei.set(i,[1,0,0,0,1,0,0,0,1]),ei.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return ei.set(i,f),f}function wi(e){let t=Gr();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Ti(e){let t=Gr();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Ei(e,t,n,r,i){i[0]=Ni(e),i[1]=Ni(t),i[2]=Ni(n)}function Di(e,t,n,r,i){i[0]=Ni(e*r),i[1]=Ni(t*r),i[2]=Ni(n*r)}function Oi(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=Ni(e/(e+1)),i[1]=Ni(t/(t+1)),i[2]=Ni(n/(n+1))}function ki(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Ai(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=Ni(1.60475*a-.53108*o-.07367*s),i[1]=Ni(-.10208*a+1.10813*o-.00605*s),i[2]=Ni(-.00327*a-.07276*o+1.07602*s)}function ji(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=Ni((Math.log2(Math.max(c,1e-10))-d)/f),l=Ni((Math.log2(Math.max(l,1e-10))-d)/f),u=Ni((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=Ni(1.6605*m-.5876*h-.0728*g),i[1]=Ni(-.1246*m+1.1329*h-.0083*g),i[2]=Ni(-.0182*m-.1006*h+1.1187*g)}function Mi(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var Ni,Pi,Fi,Ii,Li,Ri,zi,Bi=y((()=>{Ni=e=>Math.min(Math.max(e,0),1),Pi=`
115
+ `,[ne,z]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},V=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.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)}},be=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.appliedValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={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.appliedValues={},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._resolveQualityValue(e,this.interactionQualitySettings[e]),this.appliedValues[e]=this.material.uniforms[e].value)}),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=>{if(e===`dpr`)this.renderer.setPixelRatio(this.originalValues.dpr);else if(this.material.uniforms[e]){let t=this.appliedValues[e];(t===void 0||this.material.uniforms[e].value===t)&&(this.material.uniforms[e].value=this.originalValues[e])}}),this.interactionMode=!1,this.originalValues={},this.appliedValues={},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=this._resolveQualityValue(t,e[t]),this.appliedValues[t]=this.material.uniforms[t].value)})}_resolveQualityValue(e,t){return typeof t==`function`?t(this.originalValues[e]??this.material.uniforms[e].value):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,pixelRatio:.125,enableAccumulation:!1},low:{maxBounceCount:1,pixelRatio:.25,enableAccumulation:!1},medium:{maxBounceCount:2,pixelRatio:.5,enableAccumulation:!1},high:{maxBounceCount:3,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}},H,xe=y((()=>{H={RENDER_COMPLETE:`engine:renderComplete`,RENDER_RESET:`engine:renderReset`,FRAME:`engine:frame`,DENOISING_START:`engine:denoisingStart`,DENOISING_END:`engine:denoisingEnd`,UPSCALING_START:`engine:upscalingStart`,UPSCALING_PROGRESS:`engine:upscalingProgress`,UPSCALING_END:`engine:upscalingEnd`,LOADING_UPDATE:`engine:loadingUpdate`,LOADING_RESET:`engine:loadingReset`,STATS_UPDATE:`engine:statsUpdate`,OBJECT_SELECTED:`engine:objectSelected`,OBJECT_DESELECTED:`engine:objectDeselected`,OBJECT_DOUBLE_CLICKED:`engine:objectDoubleClicked`,SELECT_MODE_CHANGED:`engine:selectModeChanged`,OBJECT_TRANSFORM_START:`engine:objectTransformStart`,OBJECT_TRANSFORM_END:`engine:objectTransformEnd`,TRANSFORM_MODE_CHANGED:`engine:transformModeChanged`,AUTO_FOCUS_UPDATED:`engine:autoFocusUpdated`,AUTO_EXPOSURE_UPDATED:`engine:autoExposureUpdated`,AF_POINT_PLACED:`engine:afPointPlaced`,SETTING_CHANGED:`engine:settingChanged`,ANIMATION_STARTED:`engine:animationStarted`,ANIMATION_PAUSED:`engine:animationPaused`,ANIMATION_STOPPED:`engine:animationStopped`,ANIMATION_FINISHED:`engine:animationFinished`,VIDEO_RENDER_PROGRESS:`engine:videoRenderProgress`,VIDEO_RENDER_COMPLETE:`engine:videoRenderComplete`,DISPOSE:`engine:dispose`,DEVICE_LOST:`engine:deviceLost`,ISSUE:`engine:issue`,SCENE_METADATA_APPLIED:`engine:sceneMetadataApplied`}}));xe();var Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:H.LOADING_RESET}),U=e=>{Se?.({type:H.LOADING_UPDATE,...e})},Te=e=>{Se?.({type:H.STATS_UPDATE,...e})};function Ee(e){return e.frameCount||0}function De(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Oe(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Oe(e),e.dispose()}}function Oe(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 ke({material:e,geometry:t,children:n}){if(e&&De(e),t&&t.dispose(),n.length>0)for(let e of n)ke(e)}function Ae(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize);let t=e.dispose();return e._canvasTarget=null,t}function je(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){De(e);return}for(;e.children.length>0;)for(let t of e.children)je(t);ke(e),e.removeFromParent(),e.clear()}}function Me(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function Ne(e,t){return t}function Pe(e,t=!1){return t?1:1/(e+1)}function Fe(){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}}}var Ie=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Le(e=`viewer`){let t=Ie[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Ie).join(`, `)}`);return t}var W={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Ie.viewer.toneMapping,exposure:1,saturation:Ie.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Ie.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Re=6e4,ze=3,Be=.1,Ve=.01,He=4096,G=2048;function Ue(e){return G=Math.max(256,Math.min(He,Math.floor(e)||256)),G}var We={low:{temporalAlpha:.1,gradientStrength:.8,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:3,phiColor:1,phiNormal:64,phiDepth:.1,phiLuminance:6,maxAccumFrames:16,varianceBoost:.5},medium:{temporalAlpha:.03,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:4,phiColor:.5,phiNormal:128,phiDepth:.05,phiLuminance:4,maxAccumFrames:64,varianceBoost:1},high:{temporalAlpha:0,gradientStrength:1,gradientSigmaScale:2.5,gradientNoiseFloor:.05,atrousIterations:6,phiColor:.3,phiNormal:256,phiDepth:.02,phiLuminance:2,maxAccumFrames:128,varianceBoost:1.5}},Ge={maxAccumulatedFrameNum:30,maxFastAccumulatedFrameNum:6,maxStabilizedFrameNum:63,historyFixFrameNum:3,historyFixBasePixelStride:14,prepassBlurRadius:30,minBlurRadius:1,maxBlurRadius:30,lobeAngleFraction:.15,roughnessFraction:.15,planeDistanceSensitivity:.02,minHitDistanceWeight:.1,fastHistoryClampingSigmaScale:2,fireflySuppressorMinRelativeScale:2,enableAntiFirefly:!0,antilagLuminanceSigmaScale:2,antilagLuminanceSensitivity:3,disocclusionThreshold:.01,convergenceS:1,convergenceB:.2,convergenceP:.8,lobeVolumePercent:.1,handoverFrames:0},Ke=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],qe={low:{maxAccumulatedFrameNum:16,maxFastAccumulatedFrameNum:4,maxStabilizedFrameNum:16,historyFixFrameNum:2,prepassBlurRadius:0,maxBlurRadius:20,enableAntiFirefly:!1},medium:{},high:{maxAccumulatedFrameNum:45,maxFastAccumulatedFrameNum:8,historyFixFrameNum:4,prepassBlurRadius:40,maxBlurRadius:40}},Je={fov:{min:10,max:90,default:W.fov},focusDistance:{min:.3,max:100,default:W.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:W.aperture},focalLength:{min:0,max:200,default:W.focalLength}},Ye={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}},Xe={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}},Ze={MANUAL:`manual`,AUTO:`auto`},Qe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},$e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11,UV_AB_OFFSET:12,UV_C_OFFSET:16,MATERIAL_FLAGS_OFFSET:18,MESH_INDEX_OFFSET:19},et=16777215;function tt(e){return!e||!((e.transmission||0)===0&&(!(e.transparent|0)||(e.opacity??1)>=1))?0:e.alphaMode|0?2:1}function K(e,t){return(e&et|(t?.side??0)<<24|tt(t)<<26)>>>0}function nt(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var q={SLOTS_PER_MATERIAL:33,FLOATS_PER_MATERIAL:132,IOR:0,TRANSMISSION:1,THICKNESS:2,EMISSIVE_INTENSITY:3,ATTENUATION_COLOR:4,ATTENUATION_DISTANCE:7,OPACITY:8,SIDE:9,TRANSPARENT:10,ALPHA_TEST:11,ALPHA_MODE:12,DEPTH_WRITE:13,NORMAL_SCALE:14,COLOR:16,METALNESS:19,EMISSIVE:20,ROUGHNESS:23,ALBEDO_MAP_INDEX:24,NORMAL_MAP_INDEX:25,ROUGHNESS_MAP_INDEX:26,METALNESS_MAP_INDEX:27,EMISSIVE_MAP_INDEX:28,BUMP_MAP_INDEX:29,CLEARCOAT:30,CLEARCOAT_ROUGHNESS:31,DISPERSION:32,VISIBLE:33,SHEEN:34,SHEEN_ROUGHNESS:35,SHEEN_COLOR:36,SPECULAR_INTENSITY:40,SPECULAR_COLOR:41,IRIDESCENCE:44,IRIDESCENCE_IOR:45,IRIDESCENCE_THICKNESS_RANGE:46,BUMP_SCALE:48,DISPLACEMENT_SCALE:49,DISPLACEMENT_MAP_INDEX:50,ALBEDO_TRANSFORM:52,NORMAL_TRANSFORM:60,ROUGHNESS_TRANSFORM:68,METALNESS_TRANSFORM:76,EMISSIVE_TRANSFORM:84,BUMP_TRANSFORM:92,DISPLACEMENT_TRANSFORM:100,SUBSURFACE_COLOR:108,SUBSURFACE:111,SUBSURFACE_RADIUS:112,SUBSURFACE_RADIUS_SCALE:115,SUBSURFACE_ANISOTROPY:116,ANISOTROPY:117,ANISOTROPY_ROTATION:118,ANISOTROPY_MAP_INDEX:119,TRANSMISSION_MAP_INDEX:120,CLEARCOAT_MAP_INDEX:121,CLEARCOAT_ROUGHNESS_MAP_INDEX:122,SHEEN_COLOR_MAP_INDEX:123,SHEEN_ROUGHNESS_MAP_INDEX:124,IRIDESCENCE_MAP_INDEX:125,IRIDESCENCE_THICKNESS_MAP_INDEX:126,SPECULAR_INTENSITY_MAP_INDEX:127,SPECULAR_COLOR_MAP_INDEX:128,SLOT:{IOR_TRANSMISSION:0,ATTENUATION:1,OPACITY_ALPHA:2,ALPHA_MODE:3,COLOR_METALNESS:4,EMISSIVE_ROUGHNESS:5,MAP_INDICES_A:6,MAP_INDICES_B:7,DISPERSION_SHEEN:8,SHEEN_COLOR:9,SPECULAR:10,IRIDESCENCE:11,BUMP_DISPLACEMENT:12,ALBEDO_TRANSFORM_A:13,ALBEDO_TRANSFORM_B:14,NORMAL_TRANSFORM_A:15,NORMAL_TRANSFORM_B:16,ROUGHNESS_TRANSFORM_A:17,ROUGHNESS_TRANSFORM_B:18,METALNESS_TRANSFORM_A:19,METALNESS_TRANSFORM_B:20,EMISSIVE_TRANSFORM_A:21,EMISSIVE_TRANSFORM_B:22,BUMP_TRANSFORM_A:23,BUMP_TRANSFORM_B:24,DISPLACEMENT_TRANSFORM_A:25,DISPLACEMENT_TRANSFORM_B:26,SUBSURFACE_A:27,SUBSURFACE_B:28,SUBSURFACE_C:29,EXT_MAP_INDICES_A:30,EXT_MAP_INDICES_B:31,EXT_MAP_INDICES_C:32}},rt=e=>Number.isFinite(e)&&e>0?e:0,J=it({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function it(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}var at=1073741824,ot=1073741824,st=1073741823,ct={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function lt(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function ut(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${at.toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}var dt={PIXELS_PER_MATERIAL:30,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,DEFAULT_MAX_TEXTURE_SIZE:4096,MAX_TEXTURES_LIMIT:4*256,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256},ft=64;function pt(e,t){let n=Math.ceil(Math.max(1,e)/ft)*ft;return Math.min(t,Math.max(dt.MIN_TEXTURE_WIDTH,n))}function mt(e){let t=0,n=0,r=0;for(let i of e)t=Math.max(t,i.width),n=Math.max(n,i.height),r+=i.count;return{units:e,width:t,height:n,count:r}}function ht(e,t){return pt(e.width,t)*e.height*e.count*4}function gt(e,t){return e.reduce((e,n)=>e+ht(n,t),0)}function _t(e,t,n){let r=e.slice();for(;r.length>t;){let e=null;for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=mt(r[t].units.concat(r[i].units)),o=ht(a,n)-ht(r[t],n)-ht(r[i],n);(!e||o<e.delta)&&(e={i:t,j:i,delta:o,fused:a})}r=r.filter((t,n)=>n!==e.i&&n!==e.j).concat([e.fused])}return r}function vt(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(dt.MIN_TEXTURE_WIDTH,Math.round(n/2**e)));let i=r.map(()=>[]);for(let t of e){let e=2**Math.ceil(Math.log2(Math.max(t.width,t.height))),n=r.findIndex(t=>e<=t);n<0&&(n=r.length-1),i[n].push(t)}return i.filter(e=>e.length).map(mt)}function yt(e,t){let n=e;for(let e=0;e<8;e++){let e=!1;for(let r of n.flatMap(e=>e.units)){let i=n.findIndex(e=>e.units.includes(r));if(!(i<0))for(let a=0;a<n.length;a++){if(a===i)continue;let o=[];for(let e=0;e<n.length;e++)if(e===i){let t=n[e].units.filter(e=>e!==r);t.length&&o.push(mt(t))}else e===a?o.push(mt(n[e].units.concat([r]))):o.push(n[e]);if(gt(o,t)<gt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function bt(e,t,n=dt.MATERIAL_BUCKET_COUNT){let r=new Map;for(let{width:n,height:i}of e){let e=Math.min(t,Math.max(1,n||1)),a=Math.min(t,Math.max(1,i||1)),o=`${e}x${a}`,s=r.get(o);s?s.count++:r.set(o,{width:e,height:a,count:1})}let i=[...r.values()],a=i.map(e=>mt([e]));if(a.length>n){let e=vt(i,n,t),r=_t(a,n,t);a=gt(e,t)<gt(r,t)?e:r,a=yt(a,t)}return a.map(e=>({width:pt(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function xt(e,t,n){let r=Math.max(1,e||1),i=Math.max(1,t||1);for(let e=0;e<n.length;e++)if(n[e].width>=r&&n[e].height>=i)return e;return Math.max(0,n.length-1)}function St(e,t){return e*dt.BUCKET_LAYER_STRIDE+t}var Ct=[0,0,1,1,0,0,0,1],wt={maxSamples:30,bounces:20,transmissiveBounces:24,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},Tt={maxSamples:W.maxSamples,bounces:W.bounces,renderMode:W.renderMode,enableAlphaShadows:W.enableAlphaShadows,transmissiveBounces:12,maxSubsurfaceSteps:W.maxSubsurfaceSteps,enableOIDN:!0,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0};function Et(e){return{maxSamples:e.maxSamples,maxBounces:e.bounces,transmissiveBounces:e.transmissiveBounces,maxSubsurfaceSteps:e.maxSubsurfaceSteps,enableAlphaShadows:e.enableAlphaShadows??!1,useAdaptiveSampling:e.useAdaptiveSampling??!1,noiseThreshold:e.noiseThreshold??W.noiseThreshold,adaptiveStopFraction:e.adaptiveStopFraction??W.adaptiveStopFraction,adaptiveMinSamples:e.adaptiveMinSamples??W.adaptiveMinSamples,usePixelFreeze:e.usePixelFreeze??!1,pixelFreezeThreshold:e.pixelFreezeThreshold??W.pixelFreezeThreshold,pixelFreezeStability:e.pixelFreezeStability??W.pixelFreezeStability,interactionModeEnabled:e.interactionModeEnabled??W.interactionModeEnabled}}var Dt={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};function Ot(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function kt(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function At(){if(Ut!==null)return Ut;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Lt?(Ut=Lt[e],Ut):(Ut=Lt[Ot(zt)]??Lt[Rt],Ut)}function jt(){if(Wt!==null)return Wt;let e=globalThis.__RAYZEE_LOG_NS__??Ot(Bt);return Wt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],Wt}function Mt(e,t){if(t<Lt.debug)return!0;let n=jt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Nt(e,t,n){if(e>At()||!Mt(t,e))return;let r=e===Lt.error?console.error:e===Lt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,Vt,Ht,...n.slice(1)):r(`%c${i}`,Vt,...n)}function Pt(e){return{namespace:e,error:(...t)=>Nt(Lt.error,e,t),warn:(...t)=>Nt(Lt.warn,e,t),info:(...t)=>Nt(Lt.info,e,t),debug:(...t)=>Nt(Lt.debug,e,t),isEnabled:e=>Gt.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Nt(Lt.info,e,[t]),r.forEach(t=>Nt(Lt.debug,e,[t]));return}Lt.info>At()||((At()>=Lt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,Vt,Ht),r.forEach(e=>console.log(e)),console.groupEnd())}}}function Ft(e,t,...n){Kt.has(t)||(Kt.add(t),e.warn(...n))}function It(){return Gt.getLevel()}var Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Y,Gt,Kt,qt=y((()=>{Lt={silent:0,error:1,warn:2,info:3,debug:4},Rt=`info`,zt=`rayzeeLogLevel`,Bt=`rayzeeLogNamespaces`,Vt=`color:#7c8494`,Ht=`color:inherit`,Ut=null,Wt=null,Y={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${Y.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Gt={levels:Lt,setLevel(e){return e in Lt?(globalThis.__RAYZEE_LOG_LEVEL__=e,Ut=Lt[e],kt(zt,e===Rt?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Lt).join(`, `)}`),this.getLevel())},getLevel(){let e=At();return Object.keys(Lt).find(t=>Lt[t]===e)},isEnabled(e){return(Lt[e]??Lt.debug)<=At()},only(...e){let t=e.flat().filter(Boolean);return Wt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),kt(Bt,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return Ut=null,Wt=null,this.getLevel()}},Kt=new Set}));qt();var Jt=Pt(`gpu`);function Yt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Xt=()=>Yt(),Zt=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,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),e>0&&t>0&&this.create(e,t)}create(e,n){this.dispose(),this.renderWidth=e,this.renderHeight=n,this.writeColor=Xt(),this.writeNormalDepth=Xt(),this.writeAlbedo=Xt(),this.readTarget=new t.RenderTarget(e,n,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1,count:3}),this.readTarget.textures[0].name=`gColor`,this.readTarget.textures[1].name=`gNormalDepth`,this.readTarget.textures[2].name=`gAlbedo`,Jt.debug(`storage texture pool ${Y.px(e,n)} — 3 write StorageTextures + 1 MRT RenderTarget`)}ensureSize(e,t){return this.writeColor?this.renderWidth!==e||this.renderHeight!==t?(this.setSize(e,t),!0):!1:(this.create(e,t),!0)}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,t=!0){this._srcRegion.max.set(this.renderWidth,this.renderHeight),e.copyTextureToTexture(this.writeColor,this.readTarget.textures[0],this._srcRegion),t&&(e.copyTextureToTexture(this.writeNormalDepth,this.readTarget.textures[1],this._srcRegion),e.copyTextureToTexture(this.writeAlbedo,this.readTarget.textures[2],this._srcRegion))}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.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}},Qt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},$t=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._arrayWarned=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}Array.isArray(t)&&t.length===1&&(this._booleans.has(e)||typeof n.value==`number`)&&(this._arrayWarned.has(e)||(this._arrayWarned.add(e),console.warn(`UniformManager: "${e}" was set to [${t[0]}] but expects a scalar — unwrapping. Fix the caller; a slider handler is probably forwarding its array value unchanged.`)),t=t[0]),this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,W.bounces,`int`),i(`maxSamples`,W.maxSamples,`int`),i(`transmissiveBounces`,W.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,W.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,W.maxTransparentBounces,`int`),i(`visMode`,W.debugMode,`int`),i(`debugVisScale`,W.debugVisScale,`float`),a(`useAdaptiveSampling`,W.useAdaptiveSampling),i(`noiseThreshold`,W.noiseThreshold,`float`),i(`adaptiveMinSamples`,W.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,W.adaptiveStopFraction,`float`),a(`usePixelFreeze`,W.usePixelFreeze),i(`pixelFreezeThreshold`,W.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,W.pixelFreezeStability,`int`),a(`convergenceOverlay`,W.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,W.environmentIntensity,`float`),i(`backgroundIntensity`,W.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,W.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,W.backgroundBlurSamples,`int`),a(`showBackground`,W.showBackground),a(`transparentBackground`,W.transparentBackground),a(`enableEnvironment`,W.enableEnvironment),i(`environmentMatrix`,new r.Matrix4,`mat4`),i(`envTotalSum`,0,`float`),i(`envCompensationDelta`,0,`float`),i(`envResolution`,new r.Vector2(1,1),`vec2`),a(`groundProjectionEnabled`,W.groundProjectionEnabled),i(`groundProjectionRadius`,W.groundProjectionRadius,`float`),i(`groundProjectionHeight`,W.groundProjectionHeight,`float`),i(`groundProjectionLevel`,W.groundProjectionLevel,`float`),a(`enableGroundCatcher`,W.enableGroundCatcher),i(`groundCatcherHeight`,W.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,W.globalIlluminationIntensity,`float`),i(`exposure`,W.exposure,`float`),i(`numDirectionalLights`,0,`int`),i(`numAreaLights`,0,`int`),i(`numPointLights`,0,`int`),i(`numSpotLights`,0,`int`),this._lightBuffers={directional:(0,n.uniformArray)(new Float32Array(192),`float`),area:(0,n.uniformArray)(new Float32Array(256),`float`),point:(0,n.uniformArray)(new Float32Array(144),`float`),spot:(0,n.uniformArray)(new Float32Array(320),`float`)},i(`cameraWorldMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrixInverse`,new r.Matrix4,`mat4`),i(`cameraViewMatrix`,new r.Matrix4,`mat4`),i(`cameraProjectionMatrix`,new r.Matrix4,`mat4`);let o=([e,t])=>new r.Vector2(e,t).multiplyScalar(r.MathUtils.DEG2RAD);i(`cameraProjection`,+(W.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(W.panoramaLonRange),`vec2`),i(`panoLatRange`,o(W.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,W.panoramaLevelHorizon),a(`enableDOF`,W.enableDOF),i(`focusDistance`,W.focusDistance,`float`),i(`focalLength`,W.focalLength,`float`),i(`aperture`,W.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,W.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,N),N.value=W.samplingTechnique,i(`fireflyThreshold`,W.fireflyThreshold,`float`),i(`shadowTerminatorOffset`,W.shadowTerminatorOffset,`float`),a(`enableEmissiveTriangleSampling`,W.enableEmissiveTriangleSampling),i(`emissiveBoost`,W.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,W.renderMode,`int`),a(`enableAlphaShadows`,W.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Qt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},en=[1,0,0,0,1,0,0,0],tn=[[`mapMatrix`,q.ALBEDO_TRANSFORM],[`normalMapMatrices`,q.NORMAL_TRANSFORM],[`roughnessMapMatrices`,q.ROUGHNESS_TRANSFORM],[`metalnessMapMatrices`,q.METALNESS_TRANSFORM],[`emissiveMapMatrices`,q.EMISSIVE_TRANSFORM],[`bumpMapMatrices`,q.BUMP_TRANSFORM],[`displacementMapMatrices`,q.DISPLACEMENT_TRANSFORM]];Object.freeze([q.VISIBLE,q.SHEEN_COLOR+3,q.DISPLACEMENT_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+1,q.SPECULAR_COLOR_MAP_INDEX+2,q.SPECULAR_COLOR_MAP_INDEX+3]);var nn=Object.freeze(new Set([`metalness`,`roughness`,`transmission`,`opacity`,`clearcoat`,`clearcoatRoughness`,`sheen`,`sheenRoughness`,`specularIntensity`,`iridescence`,`subsurface`,`anisotropy`])),rn=e=>Math.min(Math.max(e,0),1);function an(e,t){let n=typeof e==`boolean`?+e:e;return Number.isFinite(n)?n:t}function on(e){return Number.isInteger(e)?e:-1}function sn(e,t,n,r){let i=n?.r??n?.[0]??n?.x,a=n?.g??n?.[1]??n?.y,o=n?.b??n?.[2]??n?.z;e[t]=an(i,r[0]),e[t+1]=an(a,r[1]),e[t+2]=an(o,r[2])}function cn(e,t,n){let r=(n,r,i)=>{e[t+n]=an(r,i)},i=(n,r,i)=>{e[t+n]=rn(an(r,i))};r(q.IOR,n.ior,J.ior),i(q.TRANSMISSION,n.transmission,J.transmission),r(q.THICKNESS,n.thickness,J.thickness),r(q.EMISSIVE_INTENSITY,n.emissiveIntensity,J.emissiveIntensity),sn(e,t+q.ATTENUATION_COLOR,n.attenuationColor,J.attenuationColor),e[t+q.ATTENUATION_DISTANCE]=rt(n.attenuationDistance??J.attenuationDistance),i(q.OPACITY,n.opacity,J.opacity),r(q.SIDE,n.side,J.side),r(q.TRANSPARENT,n.transparent,J.transparent),r(q.ALPHA_TEST,n.alphaTest,J.alphaTest),r(q.ALPHA_MODE,n.alphaMode,J.alphaMode),r(q.DEPTH_WRITE,n.depthWrite,J.depthWrite);let a=n.normalScale,o=typeof a==`number`?a:void 0;r(q.NORMAL_SCALE,o??a?.x??a?.[0],J.normalScale[0]),r(q.NORMAL_SCALE+1,o??a?.y??a?.[1],J.normalScale[1]),sn(e,t+q.COLOR,n.color,J.color),i(q.METALNESS,n.metalness,J.metalness),sn(e,t+q.EMISSIVE,n.emissive,J.emissive),i(q.ROUGHNESS,n.roughness,J.roughness),e[t+q.ALBEDO_MAP_INDEX]=on(n.map),e[t+q.NORMAL_MAP_INDEX]=on(n.normalMap),e[t+q.ROUGHNESS_MAP_INDEX]=on(n.roughnessMap),e[t+q.METALNESS_MAP_INDEX]=on(n.metalnessMap),e[t+q.EMISSIVE_MAP_INDEX]=on(n.emissiveMap),e[t+q.BUMP_MAP_INDEX]=on(n.bumpMap),i(q.CLEARCOAT,n.clearcoat,J.clearcoat),i(q.CLEARCOAT_ROUGHNESS,n.clearcoatRoughness,J.clearcoatRoughness),r(q.DISPERSION,n.dispersion,J.dispersion),i(q.SHEEN,n.sheen,J.sheen),i(q.SHEEN_ROUGHNESS,n.sheenRoughness,J.sheenRoughness),sn(e,t+q.SHEEN_COLOR,n.sheenColor,J.sheenColor),i(q.SPECULAR_INTENSITY,n.specularIntensity,J.specularIntensity),sn(e,t+q.SPECULAR_COLOR,n.specularColor,J.specularColor),i(q.IRIDESCENCE,n.iridescence,J.iridescence),r(q.IRIDESCENCE_IOR,n.iridescenceIOR,J.iridescenceIOR),r(q.IRIDESCENCE_THICKNESS_RANGE,n.iridescenceThicknessRange?.[0],J.iridescenceThicknessRange[0]),r(q.IRIDESCENCE_THICKNESS_RANGE+1,n.iridescenceThicknessRange?.[1],J.iridescenceThicknessRange[1]),r(q.BUMP_SCALE,n.bumpScale,J.bumpScale),r(q.DISPLACEMENT_SCALE,n.displacementScale,J.displacementScale),e[t+q.DISPLACEMENT_MAP_INDEX]=on(n.displacementMap);for(let[r,i]of tn){let a=n[r];for(let n=0;n<8;n++)e[t+i+n]=an(a?.[n],en[n])}sn(e,t+q.SUBSURFACE_COLOR,n.subsurfaceColor,J.subsurfaceColor),i(q.SUBSURFACE,n.subsurface,J.subsurface),sn(e,t+q.SUBSURFACE_RADIUS,n.subsurfaceRadius,J.subsurfaceRadius),r(q.SUBSURFACE_RADIUS_SCALE,n.subsurfaceRadiusScale,J.subsurfaceRadiusScale),r(q.SUBSURFACE_ANISOTROPY,n.subsurfaceAnisotropy,J.subsurfaceAnisotropy),i(q.ANISOTROPY,n.anisotropy,J.anisotropy),r(q.ANISOTROPY_ROTATION,n.anisotropyRotation,J.anisotropyRotation),e[t+q.ANISOTROPY_MAP_INDEX]=on(n.anisotropyMap),e[t+q.TRANSMISSION_MAP_INDEX]=on(n.transmissionMap),e[t+q.CLEARCOAT_MAP_INDEX]=on(n.clearcoatMap),e[t+q.CLEARCOAT_ROUGHNESS_MAP_INDEX]=on(n.clearcoatRoughnessMap),e[t+q.SHEEN_COLOR_MAP_INDEX]=on(n.sheenColorMap),e[t+q.SHEEN_ROUGHNESS_MAP_INDEX]=on(n.sheenRoughnessMap),e[t+q.IRIDESCENCE_MAP_INDEX]=on(n.iridescenceMap),e[t+q.IRIDESCENCE_THICKNESS_MAP_INDEX]=on(n.iridescenceThicknessMap),e[t+q.SPECULAR_INTENSITY_MAP_INDEX]=on(n.specularIntensityMap),e[t+q.SPECULAR_COLOR_MAP_INDEX]=on(n.specularColorMap),e[t+q.VISIBLE]=1,e[t+q.SHEEN_COLOR+3]=1,e[t+q.DISPLACEMENT_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+1]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+2]=0,e[t+q.SPECULAR_COLOR_MAP_INDEX+3]=0}var ln=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,ASSET_ARCHIVE_TOO_LARGE:`asset.archive_too_large`,ASSET_ENTRY_TOO_LARGE:`asset.entry_too_large`,TEXTURE_BUILD_FAILED:`texture.build_failed`,TEXTURE_PROCESSING_FALLBACK:`texture.processing_fallback`,TEXTURE_LIMIT_EXCEEDED:`texture.limit_exceeded`,ENVIRONMENT_LOAD_FAILED:`environment.load_failed`,SETTING_UNKNOWN_KEY:`setting.unknown_key`,RENDER_SIZE_DECLINED:`render.size_declined`,STAGE_RENDER_FAILED:`stage.render_failed`,RENDER_RESERVE_CAPPED:`render.reserve_capped`,SCENE_MEMORY_BUDGET:`scene.memory_budget`,EMISSIVE_INSTANCES_COLLAPSED:`emissive.instances_collapsed`,REFIT_SHARED_GEOMETRY:`refit.shared_geometry`,VIEW_TRANSFORM_DISPLAY_MISMATCH:`viewTransform.display_mismatch`,VIEW_TRANSFORM_BAKE_FAILED:`viewTransform.bake_failed`,COLOR_CONFIG_LOAD_FAILED:`color.config_load_failed`}),un=Object.freeze({ERROR:`error`,WARNING:`warning`}),dn=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},fn=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=un.ERROR){let i=Object.freeze({code:e,message:t,detail:n,severity:r,at:Date.now()});if(this._entries.push(i),this._onIssue?.(i),this.strict&&r===un.ERROR)throw new dn(i);return i}warn(e,t,n){return this.record(e,t,n,un.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===un.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},pn=64*1024*1024,mn=typeof SharedArrayBuffer<`u`,hn=null;function gn(e){hn=e}function _n(e,t,n){let r=n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t);return hn&&r.byteLength>0&&hn(r.byteLength,n),r}var vn=class e{constructor(e,t,n,r=pn,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(_n(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(_n(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=pn,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=_n(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};qt();var yn=Pt(`geometry`),bn=dt.MAX_TEXTURES_LIMIT,xn=new Set([`color`,`emissive`,`attenuationColor`,`sheenColor`,`specularColor`,`subsurfaceColor`]),Sn=Object.freeze({MATERIAL:`material`,MAPPED:`mapped`,DEFAULT:`default`,HOST:`host`}),Cn=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];function wn(e){for(let t=0;t<16;t++)if(e[t]!==Cn[t])return!1;return!0}function Tn(e){return{map:e.map,normalMap:e.normalMap,bumpMap:e.bumpMap,roughnessMap:e.roughnessMap,metalnessMap:e.metalnessMap,emissiveMap:e.emissiveMap??(e.isMeshBasicMaterial?e.map:void 0),displacementMap:e.displacementMap,anisotropyMap:e.anisotropyMap,clearcoatMap:e.clearcoatMap,clearcoatRoughnessMap:e.clearcoatRoughnessMap,transmissionMap:e.transmissionMap,sheenColorMap:e.sheenColorMap,sheenRoughnessMap:e.sheenRoughnessMap,specularIntensityMap:e.specularIntensityMap,specularColorMap:e.specularColorMap,iridescenceMap:e.iridescenceMap,iridescenceThicknessMap:e.iridescenceThicknessMap}}function En(e){if(e.userData?.gltfExtensions?.KHR_materials_unlit?.alphaMode){let t=e.userData.gltfExtensions.KHR_materials_unlit.alphaMode;return t===`BLEND`?2:+(t===`MASK`)}return e.alphaTest>0?1:e.transparent&&e.opacity<1||e.map&&e.map.format===r.RGBAFormat&&e.transparent?2:0}function Dn(e){let t=0,n=new Set,r=e=>{let i=e.isMesh&&e.material?e.geometry:null;if(i&&!n.has(i.uuid)){n.add(i.uuid);for(let e in i.attributes)t+=i.attributes[e].array?.byteLength??0;t+=i.index?.array?.byteLength??0}if(e.children)for(let t of e.children)r(t)};return r(e),t}function On(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[4]*r+t[8]*i+t[12],e.y=t[1]*n+t[5]*r+t[9]*i+t[13],e.z=t[2]*n+t[6]*r+t[10]*i+t[14]}function kn(e,t){let n=e.x,r=e.y,i=e.z;e.x=t[0]*n+t[3]*r+t[6]*i,e.y=t[1]*n+t[4]*r+t[7]*i,e.z=t[2]*n+t[5]*r+t[8]*i}var An=1<<21;function jn(e){return!!(e.isSkinnedMesh||Object.keys(e.geometry?.morphAttributes??{}).length)}function Mn(e){return e[0]*(e[5]*e[10]-e[9]*e[6])-e[4]*(e[1]*e[10]-e[9]*e[2])+e[8]*(e[1]*e[6]-e[5]*e[2])}var Nn=class{constructor({issues:e=null}={}){this._issues=e,this._droppedTextures=0,this._vectorPool={vec3:Array(9).fill().map(()=>new r.Vector3),vec2:[,,,,,,].fill().map(()=>new r.Vector2)},this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this._matrixPool={mat3:new r.Matrix3,mat4:new r.Matrix4},this.resetArrays(),this.triangleCount=0,this.currentTriangleIndex=0}_getVec3(e=0){return this._vectorPool.vec3[e%this._vectorPool.vec3.length]}_getVec2(e=0){return this._vectorPool.vec2[e%this._vectorPool.vec2.length]}extract(e){this.resetArrays();let t=this._countTriangles(e);return this._triangleCapacity=Math.max(1024,t),this._allocateTriangles(this._triangleCapacity),this.currentTriangleIndex=0,this._allocatePlacements(this._countPlacements(e)),this._geometryUses=this._countGeometryUses(e),this.bakeInverse=new Map,this.traverseObject(e),this._shareInstanceMatrices(),this._compressAttributes(e),this.logStats(),this.getExtractedData()}surveyScene(e){let t=0,n=e=>{if(e.isMesh&&e.geometry&&e.material&&t++,e.children)for(let t of e.children)n(t)};return n(e),{triangles:this._countTriangles(e),placements:this._countPlacements(e),meshes:t,geometryBytes:Dn(e)}}_countGeometryUses(e){let t=new Map;return e.traverse(e=>{if(!e.isMesh||!e.geometry||!e.material)return;let n=`${e.geometry.uuid}|${e.material.uuid}`;t.set(n,(t.get(n)??0)+1)}),t}_countPlacements(e){let t=0;if(e.isMesh&&e.geometry&&e.material&&(t+=e.isInstancedMesh&&e.instanceMatrix?e.count??e.instanceMatrix.array.length/16:1),e.children)for(let n of e.children)t+=this._countPlacements(n);return t}_allocatePlacements(e){this.instanceCount=0,this.instanceCapacity=e,this.instanceSource=new Int32Array(e),this.instanceMatrices=new Float32Array(e*16),this._shareable=[],this._compressed=new Set}_compressAttributes(e){let t=this._compressed,n=(e,t)=>{if(!e.userData?.__rayzeeExternal){t(e);for(let r of e.children)n(r,t)}};n(e,e=>{let n=e.geometry;if(!(!e.isMesh||!n||t.has(n.uuid))){t.add(n.uuid);for(let e of[`normal`,`tangent`,`color`]){let t=n.getAttribute(e);if(!t||t.normalized||!(t.array instanceof Float32Array)||n.morphAttributes?.[e]?.length)continue;let i=t.array,a=!0;for(let e=0;e<i.length;e++){let t=i[e];if(!(t>=-1.0001&&t<=1.0001)){a=!1;break}}if(!a)continue;let o=new Int16Array(i.length);for(let e=0;e<i.length;e++)o[e]=Math.round(Math.max(-1,Math.min(1,i[e]))*32767);n.setAttribute(e,new r.BufferAttribute(o,t.itemSize,!0))}}})}_shareInstanceMatrices(){for(let{mesh:e,start:t,count:n}of this._shareable){let r=e.instanceMatrix;!r||r.array.length!==n*16||(r.array=this.instanceMatrices.subarray(t*16,(t+n)*16))}this._shareable=[]}_countTriangles(e){let t=0;if(e.isMesh&&e.geometry&&e.material){let n=e.geometry.index,r=e.geometry.attributes.position;n?t+=Math.ceil(n.count/3):r&&(t+=Math.ceil(r.count/3))}if(e.children)for(let n of e.children)t+=this._countTriangles(n);return t}_ensureCapacity(e){if(e<=this._triangleCapacity)return;let t=this.triangles,n=this.currentTriangleIndex;this._allocateTriangles(e);for(let e=0;e<n;e++)this.triangles.chunkFor(e).set(t.chunkFor(e).subarray(t.baseOf(e),t.baseOf(e)+t.lanesPerRecord),this.triangles.baseOf(e));this._triangleCapacity=e}_allocateTriangles(e){this.triangles=new vn(e,$e.FLOATS_PER_TRIANGLE,Uint32Array,void 0,mn),this.triangleFloatChunks=this.triangles.viewAs(Float32Array),this.triangleData=this.triangles.single,this.triangleFloats=this.triangleFloatChunks.single}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=`${e.geometry.uuid}|${t}`,i=jn(e),a=!this._emissiveMaterial(t)&&!i,o=a?this._geometryRanges.get(r):null;if(o){let t={start:o.start,count:o.count,expandedStart:this.expandedTriangleCount,sharedFrom:o.meshIndex};this.expandedTriangleCount+=o.count,this.meshTriangleRanges.push(t),this._recordPlacements(e,n);return}let s=this.currentTriangleIndex,c=e.isInstancedMesh&&!i&&this._emissiveMaterial(t)&&this._canExpand(e),l=c||!e.isInstancedMesh&&!i&&(this._geometryUses.get(`${e.geometry.uuid}|${e.material?.uuid}`)===1||this._emissiveMaterial(t));this.extractGeometry(e,t,n,l,c);let u={start:s,count:this.currentTriangleIndex-s,expandedStart:this.expandedTriangleCount};this.expandedTriangleCount+=u.count,this.meshTriangleRanges.push(u),u.count>0&&!l&&a&&this._geometryRanges.set(r,{...u,meshIndex:n}),this._recordPlacements(e,n,l,c)}_recordPlacements(e,t,n=!1,r=!1){let i=e.matrixWorld.elements,a=this.instanceMatrices,o=this.instanceSource;if(!e.isInstancedMesh||!e.instanceMatrix||r){let r=this._nextPlacement();if(o[r]=t,n){for(let e=0;e<16;e++)a[r*16+e]=+(e%5==0);this.bakeInverse.set(t,Float32Array.from(this._matrixPool.mat4.copy(e.matrixWorld).invert().elements))}else for(let e=0;e<16;e++)a[r*16+e]=i[e];return}let s=e.instanceMatrix.array,c=e.count??s.length/16,l=wn(i);l&&s.length===c*16&&this._shareable.push({mesh:e,start:this.instanceCount,count:c});for(let e=0;e<c;e++){let n=e*16,r=this._nextPlacement(),c=r*16;if(o[r]=t,l){for(let e=0;e<16;e++)a[c+e]=s[n+e];continue}for(let e=0;e<4;e++)for(let t=0;t<4;t++)a[c+e*4+t]=i[t]*s[n+e*4]+i[4+t]*s[n+e*4+1]+i[8+t]*s[n+e*4+2]+i[12+t]*s[n+e*4+3]}}_nextPlacement(){if(this.instanceCount>=this.instanceCapacity){let e=Math.max(16,this.instanceCapacity*2),t=new Int32Array(e),n=new Float32Array(e*16);t.set(this.instanceSource),n.set(this.instanceMatrices),this.instanceSource=t,this.instanceMatrices=n,this.instanceCapacity=e}return this.instanceCount++}_canExpand(e){let t=e.geometry,n=(t.index?t.index.count:t.attributes.position.count)/3,r=e.count??(e.instanceMatrix?.array.length??0)/16;return n*r<=An?!0:(this._issues?.record(ln.EMISSIVE_INSTANCES_COLLAPSED,`"${e.name||`instanced mesh`}" would need ${Math.round(n*r).toLocaleString()} triangles to light every instance; lighting the first one only`,{instances:r,trianglesPerInstance:n,limit:An}),!1)}_emissiveMaterial(e){let t=this.materials[e];if(!t||!(t.emissiveIntensity>0))return!1;let n=t.emissive;return!!n&&(n.r>0||n.g>0||n.b>0)}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,Ft(yn,`depthWrite`,`material had depthWrite disabled — enabled for rastered rendering`));let n=this.createMaterialObject(e);this.materials.push(n),t=this.materials.length-1,this._materialUuidMap.set(e.uuid,t)}return t}getMaterialType(e){return e.isMeshPhysicalMaterial?`physical`:e.isMeshStandardMaterial?`standard`:e.isMeshPhongMaterial?`phong`:e.isMeshLambertMaterial?`lambert`:e.isMeshBasicMaterial?`basic`:e.isMeshToonMaterial?`toon`:`unknown`}getPhysicalDefaults(){let e={};for(let[t,n]of Object.entries(J))e[t]=xn.has(t)?new r.Color().fromArray(n):Array.isArray(n)?[...n]:n;return e.normalScale={x:J.normalScale[0],y:J.normalScale[1]},e}mapLegacyMaterialToPhysical(e,t){let n={};switch(t){case`basic`:n.emissive=e.color.clone(),n.emissiveIntensity=1,n.color=new r.Color(0),n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`lambert`:n.roughness=1,n.metalness=0,n.specularIntensity=0;break;case`phong`:{let t=e.shininess||30;n.roughness=Math.sqrt(2/(t+2)),n.metalness=0}if(e.specular){let t=e.specular,i=t.r*.299+t.g*.587+t.b*.114,a=Math.max(t.r,t.g,t.b);n.specularIntensity=Math.min(i*2,1),n.specularColor=a>0?t.clone().multiplyScalar(1/a):new r.Color(1,1,1)}break;case`toon`:n.roughness=.9,n.metalness=0;break;case`standard`:case`physical`:break}return n}createMaterialObject(e){let t=this.getPhysicalDefaults(),n=this.getMaterialType(e),r=this.mapLegacyMaterialToPhysical(e,n),i=Tn(e),a={},o=n=>r[n]===void 0?e[n]!==void 0&&e[n]!==null?(a[n]=Sn.MATERIAL,e[n]):(a[n]=Sn.DEFAULT,t[n]):(a[n]=Sn.MAPPED,r[n]);for(let e of[`transparent`,`alphaMode`,`side`,`depthWrite`])a[e]=Sn.MATERIAL;return{uuid:e.uuid,color:o(`color`),emissive:o(`emissive`),emissiveIntensity:o(`emissiveIntensity`),roughness:Math.max(.02,o(`roughness`)),metalness:o(`metalness`),ior:o(`ior`),opacity:o(`opacity`),transmission:o(`transmission`),thickness:o(`thickness`),attenuationColor:o(`attenuationColor`),attenuationDistance:o(`attenuationDistance`),dispersion:o(`dispersion`),sheen:o(`sheen`),sheenRoughness:o(`sheenRoughness`),sheenColor:o(`sheenColor`),clearcoat:o(`clearcoat`),clearcoatRoughness:o(`clearcoatRoughness`),iridescence:o(`iridescence`),iridescenceIOR:o(`iridescenceIOR`),iridescenceThicknessRange:o(`iridescenceThicknessRange`),subsurface:o(`subsurface`),subsurfaceColor:o(`subsurfaceColor`),subsurfaceRadius:o(`subsurfaceRadius`),subsurfaceRadiusScale:o(`subsurfaceRadiusScale`),subsurfaceAnisotropy:o(`subsurfaceAnisotropy`),anisotropy:o(`anisotropy`),anisotropyRotation:o(`anisotropyRotation`),specularIntensity:o(`specularIntensity`),specularColor:o(`specularColor`),normalScale:o(`normalScale`),bumpScale:o(`bumpScale`),displacementScale:o(`displacementScale`),transparent:+!!e.transparent,alphaTest:o(`alphaTest`),alphaMode:En(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(i.map,this.maps),normalMap:this.processTexture(i.normalMap,this.normalMaps),bumpMap:this.processTexture(i.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(i.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(i.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(i.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(i.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(i.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(i.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(i.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(i.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(i.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(i.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(i.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(i.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(i.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(i.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(i.map),normalMapMatrices:this.getTextureMatrix(i.normalMap),bumpMapMatrices:this.getTextureMatrix(i.bumpMap),roughnessMapMatrices:this.getTextureMatrix(i.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(i.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(i.emissiveMap),displacementMapMatrices:this.getTextureMatrix(i.displacementMap),sources:a,originalType:n}}getTextureMatrix(e){return e?(e.matrixAutoUpdate&&e.updateMatrix(),e.matrix.elements):new r.Matrix3().elements}getMaterialSide(e){if(e.transmission>0)return 2;switch(e.side){case r.FrontSide:return 0;case r.BackSide:return 1;case r.DoubleSide:return 2;default:return 0}}processTexture(e,t){if(!e)return-1;let n=this._textureIndexCache.get(t);n||(n=new Map,this._textureIndexCache.set(t,n));let r=e.source.uuid,i=n.get(r);if(i!==void 0)return i;if(t.length<bn){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${bn} distinct textures for one map type; the rest render untextured`,{limit:bn,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n,i=!1,a=!1){e.updateMatrix(),e.updateMatrixWorld();let o=e.geometry;o.attributes.normal||o.computeVertexNormals();let s=o.attributes.position,c=o.attributes.normal,l=o.attributes.uv,u=o.index?o.index.array:null,d=u?u.length/3:s.count/3;if(a){let i=e.count??e.instanceMatrix.array.length/16,a=this._matrixPool.mat4,o=new r.Matrix4;for(let f=0;f<i;f++){a.fromArray(e.instanceMatrix.array,f*16),o.multiplyMatrices(e.matrixWorld,a);let i=new r.Matrix3().getNormalMatrix(o);this.extractTrianglesInBatch(s,c,l,u,d,t,n,o,i,Mn(o.elements)<0)}return}let f=i?this._matrixPool.mat4.copy(e.matrixWorld):null,p=i?this._matrixPool.mat3.getNormalMatrix(e.matrixWorld):null,m=i&&Mn(f.elements)<0;this.extractTrianglesInBatch(s,c,l,u,d,t,n,f,p,m)}extractTrianglesInBatch(e,t,n,r,i,a,o,s=null,c=null,l=!1){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let u=this._getVec3(0),d=this._getVec3(1),f=this._getVec3(2),p=this._getVec3(3),m=this._getVec3(4),h=this._getVec3(5),g=this._getVec2(0),_=this._getVec2(1),v=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);let y=s?.elements,b=c?.elements;for(let c=0;c<i;c++){let i=c*3,x=r?r[i+0]:i+0,S=l?2:1,C=l?1:2,w=r?r[i+S]:i+S,T=r?r[i+C]:i+C;this.getVertex(e,x,u),this.getVertex(e,w,d),this.getVertex(e,T,f),this.getVertex(t,x,p),this.getVertex(t,w,m),this.getVertex(t,T,h),n?(this.getVertex(n,x,g),this.getVertex(n,w,_),this.getVertex(n,T,v)):(g.set(0,0),_.set(0,0),v.set(0,0)),s&&(On(u,y),On(d,y),On(f,y),kn(p,b),kn(m,b),kn(h,b)),p.normalize(),m.normalize(),h.normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,u,d,f,p,m,h,g,_,v,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=$e,p=this.triangles.baseOf(e),m=this.triangleFloatChunks.chunkFor(e),h=this.triangles.chunkFor(e);m[p+f.POSITION_A_OFFSET+0]=t.x,m[p+f.POSITION_A_OFFSET+1]=t.y,m[p+f.POSITION_A_OFFSET+2]=t.z,h[p+f.NORMAL_A_PACKED_OFFSET]=nt(i.x,i.y,i.z),m[p+f.POSITION_B_OFFSET+0]=n.x,m[p+f.POSITION_B_OFFSET+1]=n.y,m[p+f.POSITION_B_OFFSET+2]=n.z,h[p+f.NORMAL_B_PACKED_OFFSET]=nt(a.x,a.y,a.z),m[p+f.POSITION_C_OFFSET+0]=r.x,m[p+f.POSITION_C_OFFSET+1]=r.y,m[p+f.POSITION_C_OFFSET+2]=r.z,h[p+f.NORMAL_C_PACKED_OFFSET]=nt(o.x,o.y,o.z),m[p+f.UV_AB_OFFSET+0]=s.x,m[p+f.UV_AB_OFFSET+1]=s.y,m[p+f.UV_AB_OFFSET+2]=c.x,m[p+f.UV_AB_OFFSET+3]=c.y,m[p+f.UV_C_OFFSET+0]=l.x,m[p+f.UV_C_OFFSET+1]=l.y,h[p+f.MATERIAL_FLAGS_OFFSET]=K(u,this.materials[u]),h[p+f.MESH_INDEX_OFFSET]=d}getTriangleData(){return this.triangles?this.triangles.trimTo(this.currentTriangleIndex):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*$e.FLOATS_PER_TRIANGLE*4;yn.debug(Y.list([`${Y.count(this.currentTriangleIndex,`tri`)} (${Y.mb(e)})`,Y.count(this.materials.length,`material`),Y.count(this.maps.length,`map`)]))}extractMaterialsOnly(e){return this.resetArrays(),this._traverseMaterialsOnly(e),this.getExtractedData()}_traverseMaterialsOnly(e){if(e.isMesh&&e.geometry&&e.material){let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n}else e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e);if(e.children)for(let t of e.children)this._traverseMaterialsOnly(t)}resetArrays(){this._droppedTextures=0,this.triangles=null,this.triangleData=null,this.triangleFloatChunks=null,this.triangleFloats=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],this._geometryRanges=new Map,this.expandedTriangleCount=0,this._allocatePlacements(0),this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.roughnessMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this._materialUuidMap=new Map,this._textureIndexCache=new WeakMap}getExtractedData(){return{triangleData:this.getTriangleData(),triangleCount:this.getTriangleCount(),materials:this.materials,materialTriangleCounts:this.materialTriangleCounts,meshes:this.meshes,meshTriangleRanges:this.meshTriangleRanges,expandedTriangleCount:this.expandedTriangleCount,instanceSource:this.instanceSource.subarray(0,this.instanceCount),instanceMatrices:this.instanceMatrices.subarray(0,this.instanceCount*16),instanceCount:this.instanceCount,bakeInverse:this.bakeInverse,maps:this.maps,normalMaps:this.normalMaps,bumpMaps:this.bumpMaps,metalnessMaps:this.metalnessMaps,emissiveMaps:this.emissiveMaps,roughnessMaps:this.roughnessMaps,displacementMaps:this.displacementMaps,anisotropyMaps:this.anisotropyMaps,transmissionMaps:this.transmissionMaps,clearcoatMaps:this.clearcoatMaps,clearcoatRoughnessMaps:this.clearcoatRoughnessMaps,sheenColorMaps:this.sheenColorMaps,sheenRoughnessMaps:this.sheenRoughnessMaps,iridescenceMaps:this.iridescenceMaps,iridescenceThicknessMaps:this.iridescenceThicknessMaps,specularIntensityMaps:this.specularIntensityMaps,specularColorMaps:this.specularColorMaps,directionalLights:this.directionalLights,cameras:this.cameras}}},Pn=null,Fn=null;function In(e,t=null){Pn=e,Fn=e?t:null}function Ln(){return Pn}function Rn(){return Fn}function zn(e){if(!Pn)return!1;let t=e[0],n=e[1],r=e[2];return e[0]=Pn[0]*t+Pn[1]*n+Pn[2]*r,e[1]=Pn[3]*t+Pn[4]*n+Pn[5]*r,e[2]=Pn[6]*t+Pn[7]*n+Pn[8]*r,!0}function Bn(e,t,n){if(!Pn||n.length===0)return 0;let r=0;for(let i=0;i+t<=e.length;i+=t)for(let t of n){let n=i+t,a=e[n],o=e[n+1],s=e[n+2];e[n]=Pn[0]*a+Pn[1]*o+Pn[2]*s,e[n+1]=Pn[3]*a+Pn[4]*o+Pn[5]*s,e[n+2]=Pn[6]*a+Pn[7]*o+Pn[8]*s,r++}return r}qt();var Vn=new WeakSet,Hn=Pt(`material`),Un=q.SLOTS_PER_MATERIAL,Wn=$e.MATERIAL_FLAGS_OFFSET,Gn=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Kn=[[`map`,!0],[`emissiveMap`,!0],[`sheenColorMap`,!0],[`specularColorMap`,!0],[`normalMap`,!1],[`bumpMap`,!1],[`roughnessMap`,!1],[`metalnessMap`,!1],[`displacementMap`,!1],[`anisotropyMap`,!1],[`transmissionMap`,!1],[`clearcoatMap`,!1],[`clearcoatRoughnessMap`,!1],[`sheenRoughnessMap`,!1],[`iridescenceMap`,!1],[`iridescenceThicknessMap`,!1],[`specularIntensityMap`,!1]],qn={ior:q.IOR,transmission:q.TRANSMISSION,thickness:q.THICKNESS,emissiveIntensity:q.EMISSIVE_INTENSITY,attenuationDistance:q.ATTENUATION_DISTANCE,opacity:q.OPACITY,alphaTest:q.ALPHA_TEST,metalness:q.METALNESS,roughness:q.ROUGHNESS,clearcoat:q.CLEARCOAT,clearcoatRoughness:q.CLEARCOAT_ROUGHNESS,dispersion:q.DISPERSION,sheen:q.SHEEN,sheenRoughness:q.SHEEN_ROUGHNESS,specularIntensity:q.SPECULAR_INTENSITY,iridescence:q.IRIDESCENCE,iridescenceIOR:q.IRIDESCENCE_IOR,subsurface:q.SUBSURFACE,subsurfaceRadiusScale:q.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:q.SUBSURFACE_ANISOTROPY,anisotropy:q.ANISOTROPY,anisotropyRotation:q.ANISOTROPY_ROTATION},Jn=class e{constructor(e){this.sdfs=e,this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.callbacks={},this._sources=[],this._hostSet=[]}static COLOR_OFFSETS=[q.COLOR,q.EMISSIVE,q.ATTENUATION_COLOR,q.SHEEN_COLOR,q.SPECULAR_COLOR,q.SUBSURFACE_COLOR].filter(e=>Number.isInteger(e));_convertColorsToWorkingSpace(t){if(Vn.has(t))return;Vn.add(t);let n=Bn(t,q.FLOATS_PER_MATERIAL,e.COLOR_OFFSETS);n&&Hn.debug(`converted ${n} material colour(s) into ${Rn()}`)}_writeColor(e,t,n,r,i){let a=[n,r,i];zn(a)&&([n,r,i]=a),e[t]=n,e[t+1]=r,e[t+2]=i}setMaterialData(e,r=[]){if(!e)return;this._convertColorsToWorkingSpace(e);let i=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=i):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,i).toReadOnly()),this.materialCount=Math.floor(i/Un),this._sources=[...r],this._hostSet=[],Hn.debug(`${Y.n(this.materialCount)} materials (storage buffer)`)}getStorageAttr(){return this.materialStorageAttr}getStorageNode(){return this.materialStorageNode}setMaterialTextures(e){e.srgbBuckets&&(this.srgbBuckets=e.srgbBuckets),e.linearBuckets&&(this.linearBuckets=e.linearBuckets)}setTexturePackMaps(e,t){this._srgbTexPacked=e||null,this._linearTexPacked=t||null}getPackedTextureIndex(e,t){if(!e)return-1;let n=e.source?.uuid??e.uuid,r=(t?this._srgbTexPacked:this._linearTexPacked)?.get(n);return r===void 0?-1:r}loadTexturesFromSdfs(){this.srgbBuckets=this.sdfs.srgbBucketTextures,this.linearBuckets=this.sdfs.linearBucketTextures,this.setTexturePackMaps(this.sdfs._srgbTexPacked,this.sdfs._linearTexPacked)}getTextureArrays(){return{srgbBuckets:this.srgbBuckets,linearBuckets:this.linearBuckets}}getMaterialProperty(e,t){let n=this.materialStorageAttr?.array;if(!n)return;let r=qn[t];if(r===void 0)return;let i=e*q.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}getMaterialPropertySource(e,t){return this._hostSet[e]?.has(t)?Sn.HOST:this._sources[e]?.[t]}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL;switch(nn.has(t)&&typeof n==`number`&&(n=rn(n)),t){case`color`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.COLOR,n.r,n.g,n.b);break;case`metalness`:r[i+q.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.EMISSIVE,n[0],n[1],n[2]):this._writeColor(r,i+q.EMISSIVE,n.r,n.g,n.b);break;case`roughness`:r[i+q.ROUGHNESS]=n;break;case`ior`:r[i+q.IOR]=n;break;case`transmission`:r[i+q.TRANSMISSION]=n;break;case`thickness`:r[i+q.THICKNESS]=n;break;case`emissiveIntensity`:r[i+q.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.ATTENUATION_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.ATTENUATION_COLOR,n.r,n.g,n.b);break;case`attenuationDistance`:r[i+q.ATTENUATION_DISTANCE]=rt(n);break;case`dispersion`:r[i+q.DISPERSION]=n;break;case`sheen`:r[i+q.SHEEN]=n;break;case`sheenRoughness`:r[i+q.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SHEEN_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SHEEN_COLOR,n.r,n.g,n.b);break;case`specularIntensity`:r[i+q.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SPECULAR_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SPECULAR_COLOR,n.r,n.g,n.b);break;case`iridescence`:r[i+q.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+q.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+q.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+q.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+q.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+q.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+q.OPACITY]=n;break;case`side`:r[i+q.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+q.TRANSPARENT]=n;break;case`alphaTest`:r[i+q.ALPHA_TEST]=n;break;case`alphaMode`:r[i+q.ALPHA_MODE]=n;break;case`depthWrite`:r[i+q.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+q.NORMAL_SCALE]=n,r[i+q.NORMAL_SCALE+1]=n):(r[i+q.NORMAL_SCALE]=n.x,r[i+q.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+q.BUMP_SCALE]=n;break;case`displacementScale`:r[i+q.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+q.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+q.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+q.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+q.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+q.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&this._writeColor(r,i+q.SUBSURFACE_COLOR,n[0],n[1],n[2]):this._writeColor(r,i+q.SUBSURFACE_COLOR,n.r,n.g,n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+q.SUBSURFACE_RADIUS]=n[0],r[i+q.SUBSURFACE_RADIUS+1]=n[1],r[i+q.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+q.SUBSURFACE_RADIUS]=n.x,r[i+q.SUBSURFACE_RADIUS+1]=n.y,r[i+q.SUBSURFACE_RADIUS+2]=n.z);break;default:Hn.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,(this._hostSet[e]??=new Set).add(t),Gn.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=t*q.FLOATS_PER_MATERIAL;cn(r,i,n);for(let t of e.COLOR_OFFSETS)this._writeColor(r,i+t,r[i+t],r[i+t+1],r[i+t+2]);this._sources[t]=n.sources,this._hostSet[t]=void 0,this._patchTriangleSideForMaterial(t,r[i+q.SIDE]),this._recomputeOpaqueBlockerForMaterial(t),this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);if(this._srgbTexPacked||this._linearTexPacked){let e=Tn(t);for(let[t,r]of Kn)n[t]=this.getPackedTextureIndex(e[t],r)}this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){Hn.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*q.FLOATS_PER_MATERIAL,a={map:q.ALBEDO_TRANSFORM,normalMap:q.NORMAL_TRANSFORM,roughnessMap:q.ROUGHNESS_TRANSFORM,metalnessMap:q.METALNESS_TRANSFORM,emissiveMap:q.EMISSIVE_TRANSFORM,bumpMap:q.BUMP_TRANSFORM,displacementMap:q.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){Hn.warn(`unknown texture name for transform update: ${t}`);return}for(let e=0;e<8;e++)i+a+e<r.length&&(r[i+a+e]=n[e]);this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*q.FLOATS_PER_MATERIAL,r=tt({alphaMode:t[n+q.ALPHA_MODE],transparent:t[n+q.TRANSPARENT],transmission:t[n+q.TRANSMISSION],opacity:t[n+q.OPACITY]});this._patchTriangleFlagForMaterial(e,26,2,r)}_patchTriangleFlagForMaterial(e,t,n,r){let i=this.callbacks.getTriangleData?.(),a=i?.records,o=a?null:i?.array,s=i?.count|0;if(!o&&!a||s===0)return;let c=$e.FLOATS_PER_TRIANGLE,l=(1<<n)-1<<t>>>0,u=(r<<t&l)>>>0,d=0;for(let t=0;t<s;t++){let n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*c;(n[r+Wn]&16777215)===e&&(n[r+Wn]=(n[r+Wn]&~l|u)>>>0,d++)}d>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,24,2,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this._sources=[],this._hostSet=[]}},Yn=`function e(e,t,n,r){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 t(t,n,r){let i=n*r,a=new Float32Array(i),o=0;for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let s=e*n+r,c=t[4*s],l=t[4*s+1],u=t[4*s+2],d=(.2126*c+.7152*l+.0722*u)*i;a[s]=d,o+=d}}let s=o/i,c=0;for(let e=0;e<i;e++)a[e]=Math.max(0,a[e]-s),c+=a[e];let l=c>0,u=l?c:o,d=l?s:0;if(!l)for(let e=0;e<r;e++){let i=Math.sin(Math.PI*(e+.5)/r);for(let r=0;r<n;r++){let o=e*n+r,s=t[4*o],c=t[4*o+1],l=t[4*o+2];a[o]=(.2126*s+.7152*c+.0722*l)*i}}let f=new Float32Array(i),p=new Float32Array(r),m=0;for(let e=0;e<r;e++){let t=0;for(let r=0;r<n;r++){let i=e*n+r;t+=a[i],f[i]=t}if(t!==0)for(let r=e*n,i=e*n+n;r<i;r++)f[r]/=t;m+=t,p[e]=m}if(m!==0)for(let e=0,t=p.length;e<t;e++)p[e]/=m;let h=new Float32Array(r);for(let t=0;t<r;t++)h[t]=(e(p,(t+1)/r,0,r)+.5)/r;let g=new Float32Array(n*r);for(let t=0;t<r;t++)for(let r=0;r<n;r++){let i=t*n+r;g[i]=(e(f,(r+1)/n,t*n,n)+.5)/n}return{marginalData:h,conditionalData:g,totalSum:u,compensationDelta:d}}self.onmessage=function(e){let{floatData:n,width:r,height:i}=e.data;try{let e=t(n,r,i);self.postMessage({marginalData:e.marginalData,conditionalData:e.conditionalData,totalSum:e.totalSum,compensationDelta:e.compensationDelta,width:r,height:i},[e.marginalData.buffer,e.conditionalData.buffer])}catch(e){self.postMessage({error:e.message})}};`,Xn=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Yn],{type:`text/javascript;charset=utf-8`});function Zn(e){let t;try{if(t=Xn&&(self.URL||self.webkitURL).createObjectURL(Xn),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Yn),{type:`module`,name:e?.name})}}function Qn(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 $n(e,t,n){return .2126*e+.7152*t+.0722*n}function er(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function tr(e){let{width:t,height:n}=e.image,i=e.image.data,a=!1;if(!i){let r=new OffscreenCanvas(t,n).getContext(`2d`);r.drawImage(e.image,0,0,t,n),i=r.getImageData(0,0,t,n).data,a=!0}let o;if(e.type===r.FloatType&&i instanceof Float32Array)o=new Float32Array(i);else if(e.type===r.HalfFloatType){o=new Float32Array(i.length);for(let e=0,t=i.length;e<t;e++)o[e]=r.DataUtils.fromHalfFloat(i[e])}else{let e;e=i instanceof Int8Array||i instanceof Int16Array||i instanceof Int32Array?2**(8*i.BYTES_PER_ELEMENT-1)-1:2**(8*i.BYTES_PER_ELEMENT)-1,o=new Float32Array(i.length);for(let t=0,n=i.length;t<n;t++)o[t]=i[t]/e}if(!a&&e.colorSpace===r.SRGBColorSpace&&(a=!0),a)for(let e=0,t=o.length;e<t;e+=4)o[e]=er(o[e]),o[e+1]=er(o[e+1]),o[e+2]=er(o[e+2]);if(e.flipY){let e=new Float32Array(o.length);for(let r=0;r<n;r++){let i=n-r-1,a=r*t*4,s=i*t*4;e.set(o.subarray(a,a+t*4),s)}o=e}return{floatData:o,width:t,height:n}}var nr=class e{constructor(){this.marginalData=new Float32Array([0,1]),this.conditionalData=new Float32Array([0,0,1,1]),this.totalSum=0,this.compensationDelta=0,this.width=0,this.height=0,this._worker=null}dispose(){this.marginalData=null,this.conditionalData=null,this._worker&&=(this._worker.terminate(),null)}updateFrom(t){let{floatData:n,width:r,height:i}=tr(t),a=e.computeCDF(n,r,i);this.marginalData=a.marginalData,this.conditionalData=a.conditionalData,this.totalSum=a.totalSum,this.compensationDelta=a.compensationDelta,this.width=r,this.height=i}async updateFromAsync(e){let{floatData:t,width:n,height:r}=tr(e);this._worker=new Zn;try{let e=await new Promise((e,i)=>{this._worker.onmessage=t=>{t.data.error?i(Error(t.data.error)):e(t.data)},this._worker.onerror=i,this._worker.postMessage({floatData:t,width:n,height:r},[t.buffer])});this.marginalData=e.marginalData,this.conditionalData=e.conditionalData,this.totalSum=e.totalSum,this.compensationDelta=e.compensationDelta,this.width=e.width,this.height=e.height}finally{this._worker&&=(this._worker.terminate(),null)}}static computeCDF(e,t,n){let r=t*n,i=new Float32Array(r),a=0;for(let r=0;r<n;r++){let o=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let s=r*t+n,c=$n(e[4*s],e[4*s+1],e[4*s+2])*o;i[s]=c,a+=c}}let o=a/r,s=0;for(let e=0;e<r;e++)i[e]=Math.max(0,i[e]-o),s+=i[e];let c=s>0,l=c?s:a,u=c?o:0;if(!c)for(let r=0;r<n;r++){let a=Math.sin(Math.PI*(r+.5)/n);for(let n=0;n<t;n++){let o=r*t+n;i[o]=$n(e[4*o],e[4*o+1],e[4*o+2])*a}}let d=new Float32Array(r),f=new Float32Array(n),p=0;for(let e=0;e<n;e++){let n=0;for(let r=0;r<t;r++){let a=e*t+r;n+=i[a],d[a]=n}if(n!==0)for(let r=e*t,i=e*t+t;r<i;r++)d[r]/=n;p+=n,f[e]=p}if(p!==0)for(let e=0,t=f.length;e<t;e++)f[e]/=p;let m=new Float32Array(n),h=new Float32Array(r);for(let e=0;e<n;e++)m[e]=(Qn(f,(e+1)/n)+.5)/n;for(let e=0;e<n;e++)for(let n=0;n<t;n++){let r=e*t+n;h[r]=(Qn(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},rr=Math.PI,ir=Math.PI*2,ar=Math.E,or=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],sr=[183999185144339.78,277980239196605.28,407904795438610.94],cr=1.6110731556870734,lr=1.5,ur=1e3,dr=8400,fr=1250,pr=.9999566769464484,mr=.05968310365946075,hr=.07957747154594767;function gr(e){return ur*Math.max(0,1-ar**+(-(cr-Math.acos(Math.max(-1,Math.min(1,e))))/lr))}function _r(e){let t=.2*e*1e-17;return[.434*t*sr[0],.434*t*sr[1],.434*t*sr[2]]}function vr(e){return mr*(1+e**2)}function yr(e,t){let n=t*t;return hr*((1-n)/(1-2*t*e+n)**1.5)}function br(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function xr(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 Sr(e,t,n,r,i,a,o,s){let c=(1-t)*rr,l=(e-.5)*ir,u=Math.sin(c),d=xr([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=xr(n),p=gr(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[or[0]*m,or[1]*m,or[2]*m],g=_r(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/rr*v)**-1.253,b=dr/y,x=fr/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=br(d,f),w=vr(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=yr(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 P=[.1*S[0],.1*S[1],.1*S[2]],F=Cr(pr,pr+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*F;let I=65504;return[Math.min((A[0]+P[0])*.04,I),Math.min((A[1]+P[1])*.04+3e-4,I),Math.min((A[2]+P[2])*.04+75e-5,I),1]}function Cr(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var wr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}render(e){let t=performance.now(),n=[e.sunDirection.x,e.sunDirection.y,e.sunDirection.z],r=e.sunIntensity||1,i=e.rayleighDensity||2,a=e.mieDensity||.005,o=e.mieAnisotropy||.8,s=e.turbidity||2,{width:c,height:l}=this,u=this._pixels;for(let e=0;e<l;e++){let t=(e+.5)/l;for(let l=0;l<c;l++){let d=Sr((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,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tr=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,delete this._texture.userData?.__rayzeeColorSpace,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,delete this._texture.userData?.__rayzeeColorSpace,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}};function Er(e){let t=String(e??``);return/(hdr|pq|hlg|2100|st2084)/i.test(t)?null:/^display\s*p3\b/i.test(t)?`display-p3`:/^(srgb|rec\.?\s*1886|bt\.?\s*1886|gamma\s*2\.2\s*rec\.?\s*709)\b(?!.*(p3|2020))/i.test(t)?`srgb`:null}function Dr(e){e&&Object.assign(kr,e)}function Or(){return{...kr}}var kr,Ar=y((()=>{kr={stbnScalarAtlas:`https://assets.rayzee.atulmourya.com/noise/stbn_scalar_atlas.png`,stbnVec2Atlas:`https://assets.rayzee.atulmourya.com/noise/stbn_vec2_atlas.png`,ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,dracoDecoderPath:`https://www.gstatic.com/draco/v1/decoders/`,ktx2TranscoderPath:`https://cdn.jsdelivr.net/npm/three@0.183.2/examples/jsm/libs/basis/`,oidnWeightsBaseUrl:`https://assets.rayzee.atulmourya.com/oidn/denoiser-0.0.11/`,ocioRuntimeFactory:null,ocioRuntimeUrl:null,ocioWasmUrl:null,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,neuralRuntimeUrl:`/neural/neural-runtime.js`,neuralAssetBaseUrl:null,cacheNamespace:`rayzee`}}));Ar(),qt();var jr=Pt(`ocio`);function Mr(e){let t=String(e);/\[OpenColorIO Error\]/.test(t)?jr.error(t):/\[OpenColorIO Warning\]/.test(t)?jr.warn(t):jr.debug(t)}var Nr=null,Pr=null,Fr=null,Ir=null,Lr=null;async function Rr(){let{ocioRuntimeFactory:e,ocioRuntimeUrl:t}=Or();if(typeof e==`function`)return await e();if(typeof t==`string`&&t)return await import(t);throw Error(`OpenColorIO runtime not configured. Call configureAssets({ ocioRuntimeFactory: () => import('@bb-studio/ocio') }) before loading a config.`)}async function zr(){return Pr||(Nr||=(async()=>{let e=await Rr();if(typeof e.createOcioRuntime!=`function`)throw Error(`OCIO module has no createOcioRuntime() — wrong package or version`);let{ocioWasmUrl:t}=Or();return Pr=await e.createOcioRuntime({...t?{wasmUrl:t}:{},moduleOptions:{print:Mr,printErr:Mr}}),Pr})().catch(e=>{throw Nr=null,e}),await Nr)}async function Br(){return(await zr()).ocio.listBuiltinConfigs()}async function Vr({builtin:e,text:t,files:n=[],configPath:r=`config.ocio`,id:i}={}){let a=await zr();if(e)Fr=a.loadBuiltinConfig(e),Ir=e,Lr=qr(a,e);else{let e=n.map(e=>({relativePath:e.relativePath??e.path??e.name,data:e.data instanceof Uint8Array?e.data:new Uint8Array(e.data)}));if(t!==void 0&&e.unshift({relativePath:r,data:new TextEncoder().encode(t)}),!e.some(e=>e.relativePath===r))throw Error(`config package has no "${r}" — pass configPath to name the .ocio file`);Fr=a.loadConfigPackage({configRelativePath:r,files:e},i?{id:i}:void 0),Ir=i??Fr.id;let o=e.find(e=>e.relativePath===r);Lr=o?new TextDecoder().decode(o.data):null}return Kr()}function Hr(){Fr=null,Ir=null,Lr=null}function Ur(){return Fr!==null}function Wr(){return Fr?Pr:null}function Gr(){return Fr}function Kr(){if(!Fr)return null;let e=Object.fromEntries(Fr.roles.map(e=>[e.name,e.colorSpace]));return{id:Ir,name:Lr?.match(/^name:\s*(\S.*?)\s*$/m)?.[1]??null,ocioVersion:Fr.ocioVersion,version:Fr.version,roles:e,sceneLinear:e.scene_linear??null,colorPicking:e.color_picking??e.texture_paint??null,texturePaint:e.texture_paint??e.color_picking??null,data:e.data??null,compositingLog:e.compositing_log??e.color_timing??null,colorSpaces:Fr.colorSpaces.map(e=>({name:e.name,family:e.family,categories:e.categories??[],encoding:e.encoding,isData:e.isData,aliases:e.aliases,description:e.description})),displays:Fr.displays.slice(),defaultDisplay:Fr.defaultDisplay,views:Object.fromEntries(Object.entries(Fr.viewsByDisplay).map(([e,t])=>[e,t.map(e=>({name:e.name,transform:e.transform,colorSpace:e.colorSpace,looks:e.looks,description:e.description}))])),defaultViews:{...Fr.defaultViewsByDisplay},looks:Fr.looks.map(e=>({name:e.name,processSpace:e.processSpace,description:e.description,forward:e.hasForwardTransform,inverse:e.hasInverseTransform})),namedTransforms:Fr.namedTransforms.map(e=>e.name),fileRules:Fr.fileRules.map(e=>({index:e.index,name:e.name,colorSpace:e.colorSpace,pattern:e.pattern,extension:e.extension,regex:e.regex})),contextVariables:Jr()}}function qr(e,t){try{return e.ocio.getBuiltinConfigYaml(t)}catch{return null}}function Jr(){if(!Lr)return[];let e=new Map,t=Lr.split(/\r?\n/),n=t.findIndex(e=>/^environment:\s*(\{\s*\})?\s*$/.test(e));if(n>=0&&!/\{\s*\}/.test(t[n]))for(let r=n+1;r<t.length;r++){let n=t[r];if(/^\S/.test(n))break;let i=n.match(/^\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/);i&&e.set(i[1],{name:i[1],default:i[2].replace(/^["']|["']$/g,``)||null,declared:!0})}for(let t of Lr.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g))e.has(t[1])||e.set(t[1],{name:t[1],default:null,declared:!1});return[...e.values()].sort((e,t)=>e.name.localeCompare(t.name))}function Yr(){Hr(),Pr?.dispose?.(),Pr=null,Nr=null}var Xr=1<<20,Zr=new Map,Qr=new Map,$r=4096,ei=new Map;function ti(e,t,n){return`${e}\u0000${t}\u0000${n?JSON.stringify(n):``}`}function ni(){for(let e of Zr.values())e.dispose?.();Zr.clear(),Qr.clear(),ei.clear()}function ri(e,t,{context:n=null}={}){if(!Wr()||e===t)return null;let r=ti(e,t,n),i=Zr.get(r);if(i!==void 0)return i;try{i=si().createColorSpaceProcessor(e,t,n?{context:n}:void 0),i.isNoOp&&(i.dispose(),i=null)}catch(n){throw Error(`no OCIO transform from "${e}" to "${t}": ${n.message}`)}return Zr.set(r,i),i}var ii=null,ai=null,oi=!1;function si(){let e=Wr();if(!e)throw Error(`no OCIO config loaded`);if(e.config)return e.config;let t=Gr();if(ii&&ai===t.id)return ii;if(oi&&ii?.dispose?.(),!t.id?.startsWith(`ocio://`))throw Error(`OCIO runtime exposes no Config handle for this config`);return ii=e.ocio.createBuiltinConfig(t.id),oi=!0,ai=t.id,ii}function ci(){oi&&ii?.dispose?.(),ii=null,ai=null,oi=!1,ni()}function li(e,t,n,{context:r=null}={}){let i=Wr();if(!i||t===n)return[e[0],e[1],e[2]];let a=`${ti(t,n,r)}\u0000${e[0]},${e[1]},${e[2]}`,o=Qr.get(a);if(o)return o.slice();let s=i.transformRgb(t,n,[e[0],e[1],e[2]],r?{context:r}:void 0);return Qr.size>=$r&&Qr.clear(),Qr.set(a,s),s.slice()}function ui(e,t,n,{context:r=null}={}){if(e.length%4!=0)throw Error(`convertPixelsF32 wants 4 floats per pixel`);let i=ri(t,n,{context:r});if(!i)return e;let a=e.length/4;if(a<=Xr)return i.applyRGBAF32(e),e;for(let t=0;t<a;t+=Xr){let n=Math.min(Xr,a-t);i.applyRGBAF32(e.subarray(t*4,(t+n)*4))}return e}var di=.055;function fi(e){return e<=.04045?e/12.92:((e+di)/(1+di))**2.4}function pi(e){return e<=0?0:e<=.0031308?12.92*e:(1+di)*e**(1/2.4)-di}var mi=new Float32Array(256);for(let e=0;e<256;e++)mi[e]=fi(e/255);var hi=new Float32Array(256);for(let e=0;e<256;e++)hi[e]=e/255;function gi(e){return e===`srgb`?mi:hi}function _i(e,t,n,{context:r=null,inputEncoding:i=`raw`,outputEncoding:a=`srgb`}={}){if(e.length%4!=0)throw Error(`convertEncodedRGBA8 wants 4 bytes per pixel`);let o=ri(t,n,{context:r});if(!o)return e;let s=e.length/4,c=gi(i),l=a===`srgb`?bi:xi,u=new Float32Array(Math.min(Xr,s)*4);for(let t=0;t<s;t+=Xr){let n=Math.min(Xr,s-t),r=n*4===u.length?u:u.subarray(0,n*4);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;r[a]=c[e[n]],r[a+1]=c[e[n+1]],r[a+2]=c[e[n+2]],r[a+3]=1}o.applyRGBAF32(r);for(let i=0;i<n;i++){let n=(t+i)*4,a=i*4;e[n]=l(r[a]),e[n+1]=l(r[a+1]),e[n+2]=l(r[a+2])}}return e}var vi=65536,yi=new Uint8Array(vi+1);for(let e=0;e<=vi;e++){let t=e/vi;yi[e]=Math.round(pi(t*t)*255)}function bi(e){return e>0?e>=1?255:yi[Math.sqrt(e)*vi+.5|0]:0}function xi(e){return e>0?e>=1?255:e*255+.5|0:0}function Si(e,t,n=`srgb`){if(!t)return e;let r=gi(n),i=n===`srgb`?bi:xi,[a,o,s,c,l,u,d,f,p]=t;for(let t=0;t<e.length;t+=4){let n=r[e[t]],m=r[e[t+1]],h=r[e[t+2]];e[t]=i(a*n+o*m+s*h),e[t+1]=i(c*n+l*m+u*h),e[t+2]=i(d*n+f*m+p*h)}return e}function Ci(e,t,{context:n=null,tolerance:r=1e-4}={}){if(!Wr())return null;if(e===t)return[1,0,0,0,1,0,0,0,1];let i=ti(e,t,n);if(ei.has(i))return ei.get(i);let a=ri(e,t,{context:n});if(!a)return ei.set(i,[1,0,0,0,1,0,0,0,1]),ei.get(i);let o=e=>{let t=new Float32Array([e[0],e[1],e[2],1]);return a.applyRGBAF32(t),[t[0],t[1],t[2]]},s=[o([1,0,0]),o([0,1,0]),o([0,0,1])],c=[s[0][0],s[1][0],s[2][0],s[0][1],s[1][1],s[2][1],s[0][2],s[1][2],s[2][2]],l=e=>[c[0]*e[0]+c[1]*e[1]+c[2]*e[2],c[3]*e[0]+c[4]*e[1]+c[5]*e[2],c[6]*e[0]+c[7]*e[1]+c[8]*e[2]],u=[[.18,.18,.18],[.5,.25,.75],[2,.1,.4],[.02,.9,.3],[8,4,1],[.001,.002,.004]],d=!0;for(let e of u){let t=o(e),n=l(e),i=Math.max(.001,Math.abs(n[0]),Math.abs(n[1]),Math.abs(n[2]));for(let e=0;e<3;e++)Math.abs(t[e]-n[e])>r*i&&(d=!1);if(!d)break}let f=d?c:null;return ei.set(i,f),f}function wi(e){let t=Gr();if(!t)return!1;let n=t.colorSpaces.find(t=>t.name===e||t.aliases?.includes(e));return n?n.isData:!1}function Ti(e){let t=Gr();return!t||!e?!1:t.colorSpaces.some(t=>t.name===e||t.aliases?.includes(e))}function Ei(e,t,n,r,i){i[0]=Ni(e),i[1]=Ni(t),i[2]=Ni(n)}function Di(e,t,n,r,i){i[0]=Ni(e*r),i[1]=Ni(t*r),i[2]=Ni(n*r)}function Oi(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=Ni(e/(e+1)),i[1]=Ni(t/(t+1)),i[2]=Ni(n/(n+1))}function ki(e,t,n,r,i){e=Math.max(e*r-.004,0),t=Math.max(t*r-.004,0),n=Math.max(n*r-.004,0);let a=e=>(e*(6.2*e+.5)/(e*(6.2*e+1.7)+.06))**2.2;i[0]=a(e),i[1]=a(t),i[2]=a(n)}function Ai(e,t,n,r,i){e=e*r/.6,t=t*r/.6,n=n*r/.6;let a=.59719*e+.35458*t+.04823*n,o=.076*e+.90834*t+.01566*n,s=.0284*e+.13383*t+.83777*n,c=e=>(e*(e+.0245786)-90537e-9)/(e*(.983729*e+.432951)+.238081);a=c(a),o=c(o),s=c(s),i[0]=Ni(1.60475*a-.53108*o-.07367*s),i[1]=Ni(-.10208*a+1.10813*o-.00605*s),i[2]=Ni(-.00327*a-.07276*o+1.07602*s)}function ji(e,t,n,r,i){e*=r,t*=r,n*=r;let a=.6274*e+.3293*t+.0433*n,o=.0691*e+.9195*t+.0113*n,s=.0164*e+.088*t+.8956*n,c=.856627153315983*a+.0951212405381588*o+.0482516061458583*s,l=.137318972929847*a+.761241990602591*o+.101439036467562*s,u=.11189821299995*a+.0767994186031903*o+.811302368396859*s,d=-12.47393,f=4.026069-d;c=Ni((Math.log2(Math.max(c,1e-10))-d)/f),l=Ni((Math.log2(Math.max(l,1e-10))-d)/f),u=Ni((Math.log2(Math.max(u,1e-10))-d)/f);let p=e=>{let t=e*e,n=t*t;return 15.5*n*t-40.14*n*e+31.96*n-6.868*t*e+.4298*t+.1191*e-.00232};c=p(c),l=p(l),u=p(u);let m=1.1271005818144368*c-.11060664309660323*l-.016493938717834573*u,h=-.1413297634984383*c+1.157823702216272*l-.016493938717834257*u,g=-.14132976349843826*c-.11060664309660294*l+1.2519364065950405*u;m=Math.max(0,m)**2.2,h=Math.max(0,h)**2.2,g=Math.max(0,g)**2.2,i[0]=Ni(1.6605*m-.5876*h-.0728*g),i[1]=Ni(-.1246*m+1.1329*h-.0083*g),i[2]=Ni(-.0182*m-.1006*h+1.1187*g)}function Mi(e,t,n,r,i){let a=.76;e*=r,t*=r,n*=r;let o=Math.min(e,Math.min(t,n)),s=o<.08?o-6.25*o*o:.04;e-=s,t-=s,n-=s;let c=Math.max(e,Math.max(t,n));if(c<a){i[0]=e,i[1]=t,i[2]=n;return}let l=1-a,u=1-l*l/(c+l-a),d=u/c;e*=d,t*=d,n*=d;let f=1-1/(.15*(c-u)+1);i[0]=e+(u-e)*f,i[1]=t+(u-t)*f,i[2]=n+(u-n)*f}var Ni,Pi,Fi,Ii,Li,Ri,zi,Bi=y((()=>{Ni=e=>Math.min(Math.max(e,0),1),Pi=`
116
116
  fn tm_reinhard( c: vec3<f32> ) -> vec3<f32> {
117
117
  return clamp( c / ( c + vec3<f32>( 1.0 ) ), vec3<f32>( 0.0 ), vec3<f32>( 1.0 ) );
118
118
  }
@@ -712,7 +712,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
712
712
  let p = o + xu * x + yv * y + z0 * z;
713
713
  return vec4f( p, 1.0f / S );
714
714
  }
715
- `);qt();var Pl=Pt(`shader`),Fl=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),Pl.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode;ps(e.uniforms.get(`enableAlphaShadows`));let c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d=e.goboMaps?(0,n.texture)(e.goboMaps):u();wl(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();Ol(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},Il=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new Ll;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new Ll;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},Ll=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Rl=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};qt();var zl=Pt(`bvh`),Bl=1073741824,Vl=1073741826,Hl=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Ul=1073741824;function Wl(e,t){if(e>=Ul)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Ul}`);return e}var Gl=null;function Kl(e){Gl=e}var ql={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Jl=ql.FLOATS_PER_TRIANGLE,Yl=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Xl=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Zl=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Yl(this.triangles),n=ql.POSITION_A_OFFSET,r=ql.POSITION_B_OFFSET,i=ql.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Jl,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Jl*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Gl&&typeof Worker<`u`?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;zl.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Jl*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Gl())}catch(i){zl.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Jl*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new Il(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){zl.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new Rl(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){zl.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Jl);for(let e=0;e<a;e++){let t=this.indices[e]*Jl,n=e*Jl;f.set(d.subarray(t,t+Jl),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return zl.debug(`${Y.n(a)} tris → ${Y.n(this.totalNodes)} nodes in ${Y.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Xl;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Xl;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Wl(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Hl(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=Bl}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Wl(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Hl(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=Vl,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Bl}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;Wl(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Hl(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<Bl&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Ql={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},$l=Ql.FLOATS_PER_TRIANGLE,eu=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),tu=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),nu=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):tu(e)}},ru=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,iu=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,au=(e,t)=>e.chunked?e.chunked.baseOf(t):t*cu,ou=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):eu(e),u:t?e:tu(e)}};function su(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var cu=16,lu=1073741824,uu=1073741825,du=1e-12;function fu(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=du*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,ee=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}var pu=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length,i=ou(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*$l,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+Ql.POSITION_A_OFFSET]=l,a[s+Ql.POSITION_A_OFFSET+1]=u,a[s+Ql.POSITION_A_OFFSET+2]=d,a[s+Ql.POSITION_B_OFFSET]=f,a[s+Ql.POSITION_B_OFFSET+1]=p,a[s+Ql.POSITION_B_OFFSET+2]=m,a[s+Ql.POSITION_C_OFFSET]=h,a[s+Ql.POSITION_C_OFFSET+1]=g,a[s+Ql.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=su(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Ql.NORMAL_A_PACKED_OFFSET]=w,o[s+Ql.NORMAL_B_PACKED_OFFSET]=w,o[s+Ql.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=ou(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=this._bounds,o=n+r,s=nu(e);for(let e=o-1;e>=n;e--){let t=ru(s,e),r=iu(s,e),o=au(s,e),c=(e-n)*6;if(r[o+3]===lu){let e=r[o],t=r[o+1],n=1/0,s=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let r=0;r<t;r++){let t=e+r,a=i.chunked?i.f.chunkFor(t):i.f,o=i.chunked?i.chunked.baseOf(t):t*$l,c=a[o+Ql.POSITION_A_OFFSET],p=a[o+Ql.POSITION_A_OFFSET+1],m=a[o+Ql.POSITION_A_OFFSET+2],h=a[o+Ql.POSITION_B_OFFSET],g=a[o+Ql.POSITION_B_OFFSET+1],_=a[o+Ql.POSITION_B_OFFSET+2],v=a[o+Ql.POSITION_C_OFFSET],y=a[o+Ql.POSITION_C_OFFSET+1],b=a[o+Ql.POSITION_C_OFFSET+2];n=Math.min(n,c,h,v),s=Math.min(s,p,g,y),l=Math.min(l,m,_,b),u=Math.max(u,c,h,v),d=Math.max(d,p,g,y),f=Math.max(f,m,_,b)}a[c]=n,a[c+1]=s,a[c+2]=l,a[c+3]=u,a[c+4]=d,a[c+5]=f}else{let e=r[o+3],i=r[o+7],s=(e-n)*6,l=(i-n)*6,u=a[s],d=a[s+1],f=a[s+2],p=a[s+3],m=a[s+4],h=a[s+5],g=a[l],_=a[l+1],v=a[l+2],y=a[l+3],b=a[l+4],x=a[l+5];t[o]=u,t[o+1]=d,t[o+2]=f,t[o+4]=p,t[o+5]=m,t[o+6]=h,t[o+8]=g,t[o+9]=_,t[o+10]=v,t[o+12]=y,t[o+13]=b,t[o+14]=x,a[c]=Math.min(u,g),a[c+1]=Math.min(d,_),a[c+2]=Math.min(f,v),a[c+3]=Math.max(p,y),a[c+4]=Math.max(m,b),a[c+5]=Math.max(h,x)}}}refit(e,t,n){let r=ou(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=this._bounds,a=nu(e);for(let e=n-1;e>=0;e--){let t=ru(a,e),n=iu(a,e),o=au(a,e),s=e*6,c=n[o+3];if(c===lu){let e=n[o],t=n[o+1],a=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let n=0;n<t;n++){let t=e+n,i=r.chunked?r.f.chunkFor(t):r.f,o=r.chunked?r.chunked.baseOf(t):t*$l,s=i[o+Ql.POSITION_A_OFFSET],p=i[o+Ql.POSITION_A_OFFSET+1],m=i[o+Ql.POSITION_A_OFFSET+2],h=i[o+Ql.POSITION_B_OFFSET],g=i[o+Ql.POSITION_B_OFFSET+1],_=i[o+Ql.POSITION_B_OFFSET+2],v=i[o+Ql.POSITION_C_OFFSET],y=i[o+Ql.POSITION_C_OFFSET+1],b=i[o+Ql.POSITION_C_OFFSET+2];a=Math.min(a,s,h,v),c=Math.min(c,p,g,y),l=Math.min(l,m,_,b),u=Math.max(u,s,h,v),d=Math.max(d,p,g,y),f=Math.max(f,m,_,b)}i[s]=a,i[s+1]=c,i[s+2]=l,i[s+3]=u,i[s+4]=d,i[s+5]=f}else if(c===uu)fu(t,o,i,n[o]*6,i,s);else{let e=n[o+3],r=n[o+7],a=e*6,c=r*6,l=i[a],u=i[a+1],d=i[a+2],f=i[a+3],p=i[a+4],m=i[a+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];t[o]=l,t[o+1]=u,t[o+2]=d,t[o+4]=f,t[o+5]=p,t[o+6]=m,t[o+8]=h,t[o+9]=g,t[o+10]=_,t[o+12]=v,t[o+13]=y,t[o+14]=b,i[s]=Math.min(l,h),i[s+1]=Math.min(u,g),i[s+2]=Math.min(d,_),i[s+3]=Math.max(f,v),i[s+4]=Math.max(p,y),i[s+5]=Math.max(m,b)}}}},mu="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=y(`bvh`),S=1073741824,C=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),w=1073741824;function T(e,t){if(e>=w)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${w}`);return e}const E={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},D=E.FLOATS_PER_TRIANGLE,O=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var k=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},A=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=O(this.triangles),n=E.POSITION_A_OFFSET,r=E.POSITION_B_OFFSET,i=E.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*D,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(D*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(D*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){x.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){x.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*D);for(let e=0;e<s;e++){let t=this.indices[e]*D,n=e*D;m.set(p.subarray(t,t+D),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return x.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new k;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new k;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}T(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=C(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=S}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}T(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=C(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=S}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;T(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=C(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<S&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const j=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?M(t):n===`assemble`?N(t):P(t)};function M(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new A;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;j.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){j.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function N(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c}=e;try{let e=performance.now(),l=new A().assembleParallelBVH(t,n,r,i),u=new Uint32Array(o),d=new Uint32Array(a),f=new Uint32Array(s);for(let e=0;e<c;e++){let t=u[e]*20,n=e*20;f.set(d.subarray(t,t+20),n)}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[u[e]]=e;let m=performance.now()-e;j.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(l.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:l,originalToBvh:p,triangleCount:c},[l.buffer,p.buffer])}catch(e){j.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function P(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f}=e,p=new A;l!==void 0&&(p.maxLeafSize=l),u!==void 0&&(p.numBins=u),d!==void 0&&(p.maxBins=d),f!==void 0&&(p.minBins=f);try{o&&p.setTreeletConfig(o),s&&p.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=p.buildSync(l,i,e,u),f=performance.now(),m=p.flattenBVH(d),h=performance.now()-f;j.debug(`flatten ${_.ms(h)} (${_.mb(m.byteLength)})`);let g=p.originalToBvhMap||null;if(c){let e=[m.buffer];g&&e.push(g.buffer),self.postMessage({bvhData:m,originalToBvh:g,triangleCount:l.length/20,treeletStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/80,n=[m.buffer,e.buffer];g&&n.push(g.buffer),self.postMessage({bvhData:m,triangles:e,originalToBvh:g,triangleCount:t,treeletStats:p.splitStats},n)}}catch(e){j.error(`build failed:`,e),self.postMessage({error:e.message})}}",hu=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,mu],{type:`text/javascript;charset=utf-8`});function gu(e){let t;try{if(t=hu&&(self.URL||self.webkitURL).createObjectURL(hu),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(mu),{type:`module`,name:e?.name})}}var _u="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=y(`bvh`),x=1073741824,S=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),C=1073741824;function w(e,t){if(e>=C)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${C}`);return e}const T={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},E=T.FLOATS_PER_TRIANGLE,D=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var O=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},k=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=D(this.triangles),n=T.POSITION_A_OFFSET,r=T.POSITION_B_OFFSET,i=T.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*E,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(E*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(E*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){b.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){b.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*E);for(let e=0;e<s;e++){let t=this.indices[e]*E,n=e*E;m.set(p.subarray(t,t+E),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return b.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new O;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new O;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}w(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=S(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=x}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}w(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=S(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=x}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;w(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=S(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<x&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new k;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",vu=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,_u],{type:`text/javascript;charset=utf-8`});function yu(e){let t;try{if(t=vu&&(self.URL||self.webkitURL).createObjectURL(vu),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(_u),{type:`module`,name:e?.name})}}qt(),Kl(()=>new gu);var bu=Pt(`bvh`),xu=20,Su=5e4,Cu=8;function wu(e,t,n,r){let i=e.byteLength/(xu*4),a=Math.min(navigator.hardwareConcurrency||4,Cu),o=Math.ceil(Math.log2(a*2.5+1));return bu.debug(`parallel build ${Y.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let c=new SharedArrayBuffer(e.byteLength);new Uint32Array(c).set(e),e=null;let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*xu*4),h=new gu,g=null,_=[h],v={id:null},y=!1,b=()=>{v.id&&=(clearTimeout(v.id),null);for(let e of _)try{e.terminate()}catch{}},x=e=>{if(y)return;y=!0,bu.warn(`parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Uint32Array(i).set(new Uint32Array(c)),s(Eu(new Uint32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,Tu(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r).catch(e=>x(e.message));return}if(t.type===`assembleResult`){y=!0,b();let e=new Uint32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{bu.warn(`parallel build setup failed:`,e),c(e)})})}async function Tu(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){bu.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},[_.buffer]);return}bu.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=new yu;d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Eu(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=new gu,s=e.byteLength/(xu*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*xu*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])})().catch(e=>{bu.warn(`single worker fallback failed:`,e),a(e)})})}function Du(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Su}var Ou=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ku(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function Au(e,t,n){let r=ku(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(Ou),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function ju(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function Mu(e){for(let t=0;t<16;t++)if(e[t]!==Ou[t])return!1;return!0}function Nu(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function Pu(e,t){for(let n=0;n<16;n++)if(e[t+n]!==Ou[n])return!1;return!0}var Fu=class{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(Ou,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(ku(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return Au(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}Nu(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}Nu(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e){for(let t=0;t<this.templateCount;t++){if(this.tplOwner[t]<0)continue;let n=this.blasData.get(t);n&&this._readRootAABB(n,t,e,this.tplObjectAABB,t*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(e,t,n,r,i){if(!e||lt(e)[3]===ct.TRIANGLE_LEAF){this._computeAABBFromTriangles(t,n,r,i);return}r[i]=Math.min(e[0],e[8]),r[i+1]=Math.min(e[1],e[9]),r[i+2]=Math.min(e[2],e[10]),r[i+3]=Math.max(e[4],e[12]),r[i+4]=Math.max(e[5],e[13]),r[i+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){let i=$e.FLOATS_PER_TRIANGLE,a=t&&t.chunks?t.viewAs(Float32Array):null,o=a?null:t instanceof Float32Array?t:new Float32Array(t.buffer,t.byteOffset,t.length),s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0,p=this.tplTriOffset[e],m=this.tplTriCount[e];for(let e=0;e<m;e++){let t=p+e,n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*i;for(let e=0;e<=8;e+=4){let t=n[r+e],i=n[r+e+1],a=n[r+e+2];t<s&&(s=t),i<c&&(c=i),a<l&&(l=a),t>u&&(u=t),i>d&&(d=i),a>f&&(f=a)}}n[r]=s,n[r+1]=c,n[r+2]=l,n[r+3]=u,n[r+4]=d,n[r+5]=f}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,ut(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}},Iu=16,Lu=32,Ru=e=>e<Lu?e:Lu,zu=8,Bu=64,Vu=new Float64Array(16),Hu=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Lu*3),this._binBounds=new Float64Array(Lu*6*3),this._binSuffix=new Float64Array(Lu),this._binSuffixCount=new Int32Array(Lu),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};ut(r,`TLAS node count`);let i=r*Iu;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=lt(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(Bu);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*Iu;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=ct.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*Iu;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=lt(t);for(let r=0;r<n;r++){let n=r*Iu;if(l[n+3]!==ct.BLAS_POINTER_LEAF)continue;let u=l[n+1]&st;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=Vu;Au(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(Pu(r,i*16)?ot:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=zu)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=Ru(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Uu=$e.FLOATS_PER_TRIANGLE*4,Wu=64,Gu=.9,Ku=64,qu=4,Ju=7040*1024*1024,Yu=9216*1024*1024,Xu=1.15,Zu=12*1024*1024*1024;function Qu({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Uu,bvh:Math.ceil(e*Gu)*Wu,geometry:n,placements:t*Ku,orderMaps:e*qu};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function $u(e,{chunkBytes:t=pn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Zu),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var ed=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}},td="let e,t;const n={MAX_BYTES_PER_TEXTURE:256*1024*1024,MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};self.onmessage=async function(t){let{textures:n,maxTextureSize:a,method:o=`direct-transfer`}=t.data;try{e||r(a);let t=await i(n,a,o);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function r(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function i(e,t,r){let i=h(e,t),o=i.maxWidth*i.maxHeight*e.length*4;if(o>n.MAX_BYTES_PER_TEXTURE)return console.log(`Large texture array detected (${(o/1024/1024).toFixed(2)}MB), using chunked processing`),await a(e,t,r);switch(r){case`direct-transfer`:return await d(e,t);case`offscreen-optimized`:return await p(e,t);case`imageBitmap-batch`:return await m(e,t);default:return await d(e,t)}}async function a(e,t,n){let{maxWidth:r,maxHeight:i}=h(e,t),a=e.length,c=o(r,i,a),l=Math.ceil(a/c);console.log(`Processing ${a} textures in ${l} chunks of up to ${c} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*c*4/1024/1024).toFixed(2)}MB`);let u;try{u=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await f(e,g(e,t),n)}let d=r*i*c*4,p;try{p=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await f(e,g(e,t),n)}for(let t=0;t<l;t++){let n=t*c,o=Math.min(n+c,a),l=o-n,d=await s(e.slice(n,o),r,i,p.subarray(0,r*i*l*4)),f=n*r*i*4,m=l*r*i*4;u.set(new Uint8Array(d.data.slice(0,m)),f),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:u.buffer,width:r,height:i,depth:a}}function o(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function s(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await c(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function c(e,n,r,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function l(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await l(e,i,a)}return await s(e,t,n,r)}async function u(e,t,n,r,i){await c(e,n,r*i*4*t,r,i)}async function d(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await u(t,e,c,i,o)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function f(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await l(e,r,i,n)}async function p(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}t.clearRect(0,0,i,o),t.drawImage(n,0,0);let a=t.getImageData(0,0,i,o),s=i*o*4*e;c.set(a.data,s),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function m(n,r){let{maxWidth:i,maxHeight:s}=h(n,r),c=n.length,l;try{l=new Uint8Array(i*s*c*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`imageBitmap-batch`)}let u=Math.min(o(i,s,n.length),n.length);for(let r=0;r<n.length;r+=u){let a=Math.min(r+u,n.length),o=[];for(let e=r;e<a;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}o.push(r.then(t=>({bitmap:t,index:e})))}let c=await Promise.all(o);e.width=i,e.height=s,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of c){t.clearRect(0,0,i,s),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,s),a=i*s*4*n;l.set(r.data,a),e.close()}}return{data:l.buffer,width:i,height:s,depth:c}}function h(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function g(e,t){let n=h(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",nd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,td],{type:`text/javascript;charset=utf-8`});function rd(e){let t;try{if(t=nd&&(self.URL||self.webkitURL).createObjectURL(nd),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(td),{type:`module`,name:e?.name})}}ca();var id=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),ad=new Map;function od(){ad.clear();for(let e of oa.values())ad.set(e.id,id(e.cpu))}od(),Ui(od);function sd(e){return Wi(e)?.outputEncoded===!0}var cd=1/2.2;function ld(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ud(e,t){let n=Wi(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var dd=.2126,fd=.7152,pd=.0722;function md(e,t){if(t===1)return;let n=e[0]*dd+e[1]*fd+e[2]*pd;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function hd(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=ad.get(n)??ad.get(r.NoToneMapping),s=ud(t,n),c=sd(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,md(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=ld(u[0])*255+.5,l[t+1]=ld(u[1])*255+.5,l[t+2]=ld(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}qt();var gd=Pt(`textures`),_d={toSRGB:null,toLinear:null};function vd(e){if(!_d[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?ld(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}_d[e]=t}return _d[e]}var yd=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=dt.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},bd=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Dt.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Dt.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<dt.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},xd=class{constructor(e=dt.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Sd=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=dt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??dt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new yd,this.bufferPool=new bd({maxMemory:e.maxBufferMemory||Dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new xd,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){this._issues?.record(ln.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||dt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(dt.MIN_TEXTURE_WIDTH,Math.min(t,dt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new xd,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:navigator.hardwareConcurrency||4}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=so();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){gd.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,gd.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=vd(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?gd.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):gd.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=so()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Dt.MAX_TEXTURE_MEMORY?{method:`main-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;try{let t=new rd,n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return t.terminate(),this.createDataArrayTextureFromResult(r)}finally{this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[];for(let n of e){if(!n?.image)continue;let e=n.flipY!==!1;try{let r=n.image;if(typeof createImageBitmap<`u`&&(r instanceof HTMLImageElement||typeof ImageBitmap<`u`&&r instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&r instanceof OffscreenCanvas)){let r=await createImageBitmap(n.image,{imageOrientation:e?`flipY`:`none`});t.push({bitmap:r,width:n.image.width,height:n.image.height,isDirect:!0})}else{let r=n.image.width,i=n.image.height,a=await createImageBitmap(n.image,{imageOrientation:e?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(r,i);o.context.drawImage(a,0,0),a.close();let s=o.context.getImageData(0,0,r,i);t.push({data:s.data.buffer,width:r,height:i,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){console.warn(`Failed to prepare texture for worker:`,e)}}return t}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Dt.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)cn(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=dt.VEC4_PER_BVH_NODE*dt.FLOATS_PER_VEC4;ut(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=lt(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=ct.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new xd;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:pt(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e)if(n?.image){if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Cd(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(n.image instanceof HTMLImageElement)&&!(n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:Cd(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else console.warn(`[TextureCreator] Failed to create ImageBitmap:`,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function Cd(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var wd=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Ed(E,Td(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Ed(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Td(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Ed(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}qt();var Dd=Object.freeze({r:0,g:0,b:0});function Od(e){if(!e)return Dd;if(!Ln())return e;let t=[e.r,e.g,e.b];return zn(t),{r:t[0],g:t[1],b:t[2]}}var kd=Pt(`emissive`),Ad=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this.totalEmissivePower=0,this._totalTriangleCount=n;let i=$e.FLOATS_PER_TRIANGLE,a=$e.MATERIAL_FLAGS_OFFSET,o=$e.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&et,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Od(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let z=g.side===2,ne=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:ne,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:z}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&kd.debug(`${Y.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,kd.debug(`emissive texture ${Y.px(t,n)} · ${Y.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return kd.debug(`emissive raw data ${Y.n(this.emissiveCount)} entries (${Y.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Od(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new wd().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,kd.debug(`rebuilt sorted emissive data · ${Y.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};qt();var jd=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=Pt(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=Y.list([this.label,...e,Y.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(Y.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Md="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},t=e.FLOATS_PER_TRIANGLE,n=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),r=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),i=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):r(e)}},a=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,o=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,s=(e,t)=>e.chunked?e.chunked.baseOf(t):t*u,c=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):n(e),u:t?e:r(e)}};function l(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const u=16,d=1073741824;function f(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}var p=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(n,r,i){let a=i.length,o=c(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,u=o.chunked?o.chunked.baseOf(n):n*t,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];s[u+e.POSITION_A_OFFSET]=f,s[u+e.POSITION_A_OFFSET+1]=p,s[u+e.POSITION_A_OFFSET+2]=m,s[u+e.POSITION_B_OFFSET]=h,s[u+e.POSITION_B_OFFSET+1]=g,s[u+e.POSITION_B_OFFSET+2]=_,s[u+e.POSITION_C_OFFSET]=v,s[u+e.POSITION_C_OFFSET+1]=y,s[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=l(S*E-C*T,C*w-x*E,x*T-S*w);c[u+e.NORMAL_A_PACKED_OFFSET]=D,c[u+e.NORMAL_B_PACKED_OFFSET]=D,c[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(n,r,l,u){let f=c(r);u>this._boundsNodeCount&&(this._bounds=new Float32Array(u*6),this._boundsNodeCount=u);let p=this._bounds,m=l+u,h=i(n);for(let n=m-1;n>=l;n--){let r=a(h,n),i=o(h,n),c=s(h,n),u=(n-l)*6;if(i[c+3]===d){let n=i[c],r=i[c+1],a=1/0,o=1/0,s=1/0,l=-1/0,d=-1/0,m=-1/0;for(let i=0;i<r;i++){let r=n+i,c=f.chunked?f.f.chunkFor(r):f.f,u=f.chunked?f.chunked.baseOf(r):r*t,p=c[u+e.POSITION_A_OFFSET],h=c[u+e.POSITION_A_OFFSET+1],g=c[u+e.POSITION_A_OFFSET+2],_=c[u+e.POSITION_B_OFFSET],v=c[u+e.POSITION_B_OFFSET+1],y=c[u+e.POSITION_B_OFFSET+2],b=c[u+e.POSITION_C_OFFSET],x=c[u+e.POSITION_C_OFFSET+1],S=c[u+e.POSITION_C_OFFSET+2];a=Math.min(a,p,_,b),o=Math.min(o,h,v,x),s=Math.min(s,g,y,S),l=Math.max(l,p,_,b),d=Math.max(d,h,v,x),m=Math.max(m,g,y,S)}p[u]=a,p[u+1]=o,p[u+2]=s,p[u+3]=l,p[u+4]=d,p[u+5]=m}else{let e=i[c+3],t=i[c+7],n=(e-l)*6,a=(t-l)*6,o=p[n],s=p[n+1],d=p[n+2],f=p[n+3],m=p[n+4],h=p[n+5],g=p[a],_=p[a+1],v=p[a+2],y=p[a+3],b=p[a+4],x=p[a+5];r[c]=o,r[c+1]=s,r[c+2]=d,r[c+4]=f,r[c+5]=m,r[c+6]=h,r[c+8]=g,r[c+9]=_,r[c+10]=v,r[c+12]=y,r[c+13]=b,r[c+14]=x,p[u]=Math.min(o,g),p[u+1]=Math.min(s,_),p[u+2]=Math.min(d,v),p[u+3]=Math.max(f,y),p[u+4]=Math.max(m,b),p[u+5]=Math.max(h,x)}}}refit(n,r,l){let u=c(r);l!==this._boundsNodeCount&&(this._bounds=new Float32Array(l*6),this._boundsNodeCount=l);let p=this._bounds,m=i(n);for(let n=l-1;n>=0;n--){let r=a(m,n),i=o(m,n),c=s(m,n),l=n*6,h=i[c+3];if(h===d){let n=i[c],r=i[c+1],a=1/0,o=1/0,s=1/0,d=-1/0,f=-1/0,m=-1/0;for(let i=0;i<r;i++){let r=n+i,c=u.chunked?u.f.chunkFor(r):u.f,l=u.chunked?u.chunked.baseOf(r):r*t,p=c[l+e.POSITION_A_OFFSET],h=c[l+e.POSITION_A_OFFSET+1],g=c[l+e.POSITION_A_OFFSET+2],_=c[l+e.POSITION_B_OFFSET],v=c[l+e.POSITION_B_OFFSET+1],y=c[l+e.POSITION_B_OFFSET+2],b=c[l+e.POSITION_C_OFFSET],x=c[l+e.POSITION_C_OFFSET+1],S=c[l+e.POSITION_C_OFFSET+2];a=Math.min(a,p,_,b),o=Math.min(o,h,v,x),s=Math.min(s,g,y,S),d=Math.max(d,p,_,b),f=Math.max(f,h,v,x),m=Math.max(m,g,y,S)}p[l]=a,p[l+1]=o,p[l+2]=s,p[l+3]=d,p[l+4]=f,p[l+5]=m}else if(h===1073741825)f(r,c,p,i[c]*6,p,l);else{let e=i[c+3],t=i[c+7],n=e*6,a=t*6,o=p[n],s=p[n+1],u=p[n+2],d=p[n+3],f=p[n+4],m=p[n+5],h=p[a],g=p[a+1],_=p[a+2],v=p[a+3],y=p[a+4],b=p[a+5];r[c]=o,r[c+1]=s,r[c+2]=u,r[c+4]=d,r[c+5]=f,r[c+6]=m,r[c+8]=h,r[c+9]=g,r[c+10]=_,r[c+12]=v,r[c+13]=y,r[c+14]=b,p[l]=Math.min(o,h),p[l+1]=Math.min(s,g),p[l+2]=Math.min(u,_),p[l+3]=Math.max(d,v),p[l+4]=Math.max(f,y),p[l+5]=Math.max(m,b)}}}};const m=64*1024*1024;function h(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var g=class e{constructor(e,t,n,r=m,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(h(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(h(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=m,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=h(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};const _=new p;let v=null,y=null,b=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){v=g.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),y=g.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),b=v.recordCount;return}if(t===`refit`)try{let e=performance.now();_.refit(v,y,b),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-e})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Nd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Md],{type:`text/javascript;charset=utf-8`});function Pd(e){let t;try{if(t=Nd&&(self.URL||self.webkitURL).createObjectURL(Nd),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Md),{type:`module`,name:e?.name})}}var Fd="const e=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})}),t={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:e.viewer.toneMapping,exposure:1,saturation:e.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:e.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};t.fov,t.focusDistance,t.aperture,t.focalLength,n({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function n(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const r={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function i(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function a(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),t.maxSamples,t.bounces,t.renderMode,t.enableAlphaShadows,t.maxSubsurfaceSteps;const o=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function s(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function c(e,t,n){let r=s(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(o),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function l(e,t){for(let n=0;n<16;n++)if(e[t+n]!==o[n])return!1;return!0}const u=e=>e<32?e:32,d=new Float64Array(16);var f=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let o=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};a(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=i(c);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let u=this._order;for(let e=0;e<n;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let e=f*16;l[e]=0,l[e+1]=u[p],c[e+2]=0,l[e+3]=r.BLAS_POINTER_LEAF}else{let e=this._partition(t,u,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=r,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=i,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=n<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?i:r,o?e:p,o?m:e,h,S),f=o?r:i,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let e=d*3,n=d*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,a){let o=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=i(t);for(let i=0;i<n;i++){let n=i*16;if(d[n+3]!==r.BLAS_POINTER_LEAF)continue;let a=d[n+1]&1073741823;d[n]=c[s[a]],t[n+2]=+!!l[a],e.writeLeafMatrix(t,d,n,o,a),u[a]=i}}static writeLeafMatrix(e,t,n,r,i){let a=d;c(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(l(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=u(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const p={silent:0,error:1,warn:2,info:3,debug:4},m=`info`,h=`rayzeeLogLevel`,g=`rayzeeLogNamespaces`,_=`color:#7c8494`,v=`color:inherit`;let y=null,b=null;function x(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function S(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function C(){if(y!==null)return y;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in p?(y=p[e],y):(y=p[x(h)]??p[m],y)}function w(){if(b!==null)return b;let e=globalThis.__RAYZEE_LOG_NS__??x(g);return b=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],b}function T(e,t){if(t<p.debug)return!0;let n=w();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function E(e,t,n){if(e>C()||!T(t,e))return;let r=e===p.error?console.error:e===p.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,_,v,...n.slice(1)):r(`%c${i}`,_,...n)}const D={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${D.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},O={levels:p,setLevel(e){return e in p?(globalThis.__RAYZEE_LOG_LEVEL__=e,y=p[e],S(h,e===m?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(p).join(`, `)}`),this.getLevel())},getLevel(){let e=C();return Object.keys(p).find(t=>p[t]===e)},isEnabled(e){return(p[e]??p.debug)<=C()},only(...e){let t=e.flat().filter(Boolean);return b=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),S(g,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return y=null,b=null,this.getLevel()}};function k(e){return{namespace:e,error:(...t)=>E(p.error,e,t),warn:(...t)=>E(p.warn,e,t),info:(...t)=>E(p.info,e,t),debug:(...t)=>E(p.debug,e,t),isEnabled:e=>O.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){E(p.info,e,[t]),r.forEach(t=>E(p.debug,e,[t]));return}p.info>C()||((C()>=p.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,_,v),r.forEach(e=>console.log(e)),console.groupEnd())}}}function A(e){e&&e in p&&(globalThis.__RAYZEE_LOG_LEVEL__=e,y=p[e])}const j=k(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;A(r);try{let e=performance.now(),{data:r,nodeCount:i}=new f().buildStructure(new Float64Array(t),n);j.debug(`TLAS ${D.n(i)} nodes in ${D.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){j.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Id=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Fd],{type:`text/javascript;charset=utf-8`});function Ld(e){let t;try{if(t=Id&&(self.URL||self.webkitURL).createObjectURL(Id),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Fd),{type:`module`,name:e?.name})}}qt();var Rd=5e4,zd=Pt(`scene`),Bd=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:dt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),maxSceneBytes:Yu,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new ed,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Nn({issues:this.config.issues}),this.bvhBuilder=new Zl,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new Sd({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ad,this.tlasBuilder=new Hu,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?zd.debug(e):zd.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Qu(n),i={...n,estimate:r,safeBytes:Ju,maxBytes:t,fits:r.total<=Ju};if(this.memoryPreflight=i,r.total<1610612736)return i;if(zd.debug(Y.list([`memory preflight: ${Y.mb(r.total)} estimated`,`triangles ${Y.mb(r.triangles)} · bvh ${Y.mb(r.bvh)} · geometry ${Y.mb(r.geometry)}`,`${Y.n(n.triangles)} tris · ${Y.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${Y.mb(r.total)} of CPU memory, past the ${Y.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${Y.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(ln.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(ln.SCENE_MEMORY_BUDGET,`Scene needs about ${Y.mb(r.total)} of CPU memory, above the ${Y.mb(Ju)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Ju}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=$u(Math.ceil(t*Xu),{shared:mn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(ln.SCENE_MEMORY_BUDGET,`BVH assembly needs ${Y.mb(t)} but only ${Y.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?.byteLength??0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${Y.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;zd.debug(Y.list([`memory: peak live ${Y.mb(t)}`,`allocated ${Y.mb(e)}`,i?`predicted ${Y.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,gn(e=>this.memory.alloc(e));let t=new jd(e.name??``,{namespace:`scene`});try{this._reset(),this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this._geometryBytes=Dn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,U({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||U({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,U({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,zd.error(`processing failed:`,e),U({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{gn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){U({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this._setTriangleData(n.triangleData),this.triangleCount=ut(n.triangleCount,`triangle count`),this.expandedTriangleCount=n.expandedTriangleCount??n.triangleCount,this.instanceSource=n.instanceSource||null,this.instanceMatrices=n.instanceMatrices||null,this.instanceCount=n.instanceCount||0,this.bakeInverse=n.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.materialTriangleCounts=n.materialTriangleCounts,this.meshes=n.meshes,this.meshTriangleRanges=n.meshTriangleRanges,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.anisotropyMaps=n.anisotropyMaps,this.transmissionMaps=n.transmissionMaps,this.clearcoatMaps=n.clearcoatMaps,this.clearcoatRoughnessMaps=n.clearcoatRoughnessMaps,this.sheenColorMaps=n.sheenColorMaps,this.sheenRoughnessMaps=n.sheenRoughnessMaps,this.iridescenceMaps=n.iridescenceMaps,this.iridescenceThicknessMaps=n.iridescenceThicknessMaps,this.specularIntensityMaps=n.specularIntensityMaps,this.specularColorMaps=n.specularColorMaps,this.directionalLights=n.directionalLights,this.cameras=n.cameras;let r=performance.now()-t;this._log(`Geometry extraction complete (${r.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),U({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw zd.error(`geometry extraction failed:`,e),U({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _buildBVH(){if(U({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new Fu,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this.config.enableTreeletOptimization,c=[],l=[],u=new Map,d=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=d.get(n.start);if(r!==void 0){u.set(e,r);continue}d.set(n.start,e),n.count>=2e5&&Du(n.count)?l.push({m:e,range:n}):c.push({m:e,range:n})}let f={depth:this.config.bvhDepth,treeletOptimization:{enabled:s!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:It()},p=c.length+l.length,m=0,h=()=>{m++,U({status:`Building BLAS ${m}/${p}...`,progress:25+Math.floor(m/p*45)})},g=this._buildBLASesWithPool(c,f,h),_=[],v=(async()=>{for(let{m:e,range:t}of l){let n=await wu(this.triangles.copyOf(t.start,t.count),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...f});n.reorderedTriangles&&(this.triangles.setRecords(t.start,n.reorderedTriangles),delete n.reorderedTriangles),_.push({m:e,range:t,result:n}),h()}})(),[y]=await Promise.all([g,v]),b={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:t,result:r}of[...y,..._]){let i=r.splitStats;i&&(b.sah+=i.sahSplits??0,b.objMed+=i.objectMedianSplits??0,b.spatMed+=i.spatialMedianSplits??0,b.failed+=i.failedSplits??0,b.treeletsImproved+=i.treeletsImproved??0,b.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of u)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);U({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,U({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let x=performance.now(),S=this.instanceTable;this.instanceTable.computeAABBs(this.triangles),this.instanceTable.assignOffsets(Hu.nodeCountFor(S.count));let C=this.instanceTable.totalNodeCount,w=await this._buildTLAS(S);this.performanceMetrics.tlasBuildTime=performance.now()-x,this.memory.mark(`assemble`);let T=performance.now();this._checkAssemblyHeadroom(C),this._setBVHData(vn.lazy(C,16,Float32Array,void 0,mn)),this.bvh.setRecords(0,w),w=null,this.tlasBuilder.releaseFlattenBuffer();let E=Math.max(1,Math.ceil(S.templateCount/32));for(let e=0;e<S.templateCount;e++){let t=S.blasData.get(e);if(!t)continue;let n=S.tplBlasOffset[e];this.bvh.setRecords(n,t),this._offsetBLASInPlace(n,t.length/16,n,S.tplTriOffset[e]),S.blasData.delete(e),e%E===0&&this._sampleMemory(`assembling ${e}/${S.templateCount}`)}this._setBVHData(this.bvh.materializeAll()),this._buildBvhToOriginalMaps(),this.performanceMetrics.bvhAssembleTime=performance.now()-T,S.originalToBvhMap.clear(),S.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let D=performance.now()-e;zd.debug(Y.list([`${Y.n(S.setCount)} BLASes + TLAS`,`${Y.n(this.bvh.recordCount)} nodes`,`SAH ${Y.n(b.sah)} · objMed ${b.objMed} · spatMed ${b.spatMed} · failed ${b.failed}`,b.treeletsProcessed?`treelets ${b.treeletsImproved}/${b.treeletsProcessed} improved`:null,Y.ms(D)])),U({status:`BVH construction complete`,progress:75})}catch(e){throw zd.error(`BVH build failed:`,e),U({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=0;a<t;a++){let t=e+a,o=i.chunkFor(t),s=i.baseOf(t);o[s+3]===ct.TRIANGLE_LEAF?o[s]+=r:(o[s+3]+=n,o[s+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),i=[],a=0,o=0;return new Promise((s,c)=>{let l=[],u=n=>{if(a>=e.length){n.terminate(),l.splice(l.indexOf(n),1),l.length===0&&s(i);return}let{m:r,range:o}=e[a++],c=this.triangles.copyOf(o.start,o.count),u=o.count,d=u<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:r,range:o},n.postMessage({triangleData:c.buffer,triangleByteOffset:c.byteOffset,triangleByteLength:c.byteLength,triangleCount:u,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:d,reinsertionOptimization:t.reinsertionOptimization,maxLeafSize:t.maxLeafSize,numBins:t.numBins,maxBins:t.maxBins,minBins:t.minBins,logLevel:t.logLevel},[c.buffer])},d=(e,t)=>{let r=t.data;if(r.error){l.forEach(e=>e.terminate()),c(Error(r.error));return}if(r.progress!==void 0)return;let{m:a,range:s}=e._currentTask;r.triangles&&this.triangles.setRecords(s.start,r.triangles),i.push({m:a,range:s,result:{bvhData:r.bvhData,originalToBvh:r.originalToBvh||null,splitStats:r.treeletStats||null}}),o++,n?.(o),u(e)};(async()=>{for(let e=0;e<r;e++){let e;try{e=new gu}catch(e){c(e);return}e.onmessage=t=>d(e,t),e.onerror=e=>{l.forEach(e=>e.terminate()),c(e)},l.push(e),u(e)}})().catch(c)})}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw zd.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=dt.MATERIAL_BUCKET_COUNT,n=dt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps],o=bt(r(i),e,t),s=bt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(ln.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=xt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return St(o,c);if(t[o].length>=n)return zd.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=St(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){zd.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw zd.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=vn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=new Pd,!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;let t=n(e);if(t&&(this._updateMeshTrianglePositions(e,t),r)){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}}return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new pu;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(ln.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16),i=0;for(let t of e){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?this._ownInstanceMatrices(e):null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;n.isSet[t]&&(s?(ju(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(ju(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t),i++)}}return this._refitTLAS(),{refitTimeMs:performance.now()-t,placements:i}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Hu.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=$e.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):zd.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n),!0):(zd.error(`failed to get BVH data`),!1)):(zd.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}_collectEmissivePayload(){return this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:this.emissiveBitTrailMap,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}async _buildTLAS(e){let t=e.count;if(t>=Rd&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Hu.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,zd.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=new Ld;let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:It()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof vn?e:vn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=$e.FLOATS_PER_TRIANGLE,n=e?e instanceof vn?e:vn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=$e.POSITION_A_OFFSET,r=$e.POSITION_B_OFFSET,i=$e.POSITION_C_OFFSET,a=$e.NORMAL_A_PACKED_OFFSET,o=$e.NORMAL_B_PACKED_OFFSET,s=$e.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=Mu(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=nt(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=$e.NORMAL_A_PACKED_OFFSET,o=$e.NORMAL_B_PACKED_OFFSET,s=$e.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Mu(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=nt(f,p,m)}}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6));let t=this.instanceTable;for(let n=e-1;n>=0;n--){let e=this.bvhIndexChunks.chunkFor(n),r=this.bvh.chunkFor(n),i=this.bvh.baseOf(n),a=e[i+3];if(a===ct.BLAS_POINTER_LEAF){let r=e[i+1]&st;r<t.count&&t.writeWorldAABB(r,this._tlasBounds,n*6)}else if(a<ct.TRIANGLE_LEAF){let t=a,o=e[i+7],s=t*6,c=o*6,l=this._tlasBounds;r[i]=l[s],r[i+1]=l[s+1],r[i+2]=l[s+2],r[i+4]=l[s+3],r[i+5]=l[s+4],r[i+6]=l[s+5],r[i+8]=l[c],r[i+9]=l[c+1],r[i+10]=l[c+2],r[i+12]=l[c+3],r[i+13]=l[c+4],r[i+14]=l[c+5];let u=n*6;l[u]=Math.min(l[s],l[c]),l[u+1]=Math.min(l[s+1],l[c+1]),l[u+2]=Math.min(l[s+2],l[c+2]),l[u+3]=Math.max(l[s+3],l[c+3]),l[u+4]=Math.max(l[s+4],l[c+4]),l[u+5]=Math.max(l[s+5],l[c+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){zd.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{zd.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,new gu)}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){zd.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},Vd=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],Hd=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],Ud=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function Wd(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=Vd[i],o=Hd[i],s=Ud[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}var Gd=1/(4*Math.PI);function Kd(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=Wd(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return zn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var qd=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=Kd(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=Kd(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=Kd(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Gd,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=Kd(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*Gd,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}};Ar(),qt();var Jd=Pt(`pathtracer`),Yd=100,Xd=4,Zd=class extends V{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:ye.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new Bd,this.lightSerializer=new qd,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Zt(0,0),this.uniforms=new $t(a,o),this._defineUniformGetters(),this.materialData=new Jn(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this.triangleStorageAttr?.array,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleStorageAttr&&(this._triangleRecords?w(this.renderer,this.triangleStorageAttr,this._triangleRecords.chunks):this.triangleStorageAttr.needsUpdate=!0)},this.environment=new _o(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new Fl,this._initRenderingState(),this.setupBlueNoise(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this._triangleRecords=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.stbnScalarTexture=null,this.stbnVec2Texture=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new be(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:W.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupBlueNoise(){let e=new r.TextureLoader;e.setCrossOrigin(`anonymous`);let t=e=>(e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e.wrapS=r.RepeatWrapping,e.wrapT=r.RepeatWrapping,e.generateMipmaps=!1,e),{stbnScalarAtlas:n,stbnVec2Atlas:i}=Or(),a=e.loadAsync(n).then(e=>{this.stbnScalarTexture=t(e),L.value=e,Jd.debug(`STBN scalar atlas ${Y.px(e.image.width,e.image.height)}`)}),o=e.loadAsync(i).then(e=>{this.stbnVec2Texture=t(e),R.value=e,Jd.debug(`STBN vec2 atlas ${Y.px(e.image.width,e.image.height)}`)});this.blueNoiseReady=Promise.allSettled([a,o]).then(e=>{for(let t of e)t.status===`rejected`&&Jd.warn(`STBN atlas failed to load`,t.reason)})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};if(this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this.hasSun.value){let t=this.environment.envParams.skySunIntensity*950,n={intensity:t,color:{r:1,g:1,b:1},userData:{angle:this.sunAngularSize.value},updateMatrixWorld:()=>{},getWorldPosition:e=>{let t=this.sunDirection.value;return e.set(t.x,t.y,t.z).multiplyScalar(1e10)}};this.lightSerializer.addDirectionalLight(n),this.lightSerializer.preprocessLights(),this.lightSerializer.updateShaderUniforms(e),this.directionalLightsData=e.uniforms.directionalLights.value,Jd.debug(`sun added as directional light · intensity ${t.toFixed(2)}`)}this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/12)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/16)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/20)):this.numSpotLights.value=0}reset(){this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,this._pinSeedToFrame&&(this._seedTick=0)}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Yd}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,r){if(!e)return;let i=e.chunks&&e.chunks.length>1?e:null,a=i?null:e.chunks?e.chunks[0]:e,o=(i?i.recordCount*i.lanesPerRecord:a.length)/4,s=()=>i?S(o,4,Uint32Array):new t.StorageInstancedBufferAttribute(a,4);this.triangleStorageNode?(this.triangleStorageAttr=s(),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=o):(this.triangleStorageAttr=s(),this.triangleStorageNode=(0,n.storage)(this.triangleStorageAttr,`uvec4`,o).toReadOnly()),this._triangleRecords=i,i&&w(this.renderer,this.triangleStorageAttr,i.chunks),this.triangleCount=r,Jd.debug(`${Y.n(this.triangleCount)} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=(r?r.recordCount*r.lanesPerRecord:i.length)/4,o=()=>r?S(a,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=o(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=a):(this.bvhStorageAttr=o(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,a).toReadOnly()),this._bvhRecords=r,r&&w(this.renderer,this.bvhStorageAttr,r.chunks),this.bvhNodeCount=Math.floor(a/Xd),Jd.debug(`${Y.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){this.bvhStorageAttr.needsUpdate=!0,this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){if(this._triangleRecords){w(this.renderer,this.triangleStorageAttr,this._triangleRecords.chunks);return}this._updateStorageBuffer(this.triangleStorageAttr,e?.chunks?e.chunks[0]:e)}updateBVHData(e){if(this._bvhRecords){w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}this._updateStorageBuffer(this.bvhStorageAttr,e?.chunks?e.chunks[0]:e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0)if(this._triangleRecords)for(let t of e)T(this.renderer,this.triangleStorageAttr,this._triangleRecords,t.offset,t.count);else{this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){Jd.error(`triangle data required`);return}if(!this.bvhStorageNode){Jd.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e,t){let n=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=n,this.accumulationEnabled?n?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=Pe(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=Ne(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(e){this.stbnScalarTexture=e,e&&(L.value=e)}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this._bitTrailMapCache,i=e?e.length:0,a=n?n.length:0,o=r?Math.ceil(r.length/4)*4:0,s=Math.max(i+a+o,4);if(this.lightStorageAttr&&s<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,i),r&&t.set(r,i+a),this.lightStorageAttr.needsUpdate=!0}else{let o=new Float32Array(s);e&&o.set(e,0),n&&o.set(n,i),r&&o.set(r,i+a),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(o,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=o.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(i+a)/4}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),Jd.debug(`${Y.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),Jd.debug(`light BVH ${Y.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{Jd.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),Jd.debug(`material rebuild complete`)}catch(e){Jd.error(`material rebuild failed:`,e);try{Jd.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Jd.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.stbnScalarTexture?.dispose(),this.stbnVec2Texture?.dispose(),this.placeholderTexture?.dispose(),this.triangleStorageAttr=null,this._triangleRecords=null,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};qt();var Qd=Pt(`gpu`),$d={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},ef={DIST_TRI_BARY:0,NORMAL_MAT:1},tf=0,nf=(e,t)=>t===0?e:e.add(t*tf);function rf(e,t){t&&e?._attributes?.delete?.(t)}var af=class{constructor(e=0,t=null){this.capacity=0,this._renderer=t,this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,tf=e;let t=e*7,r=S(t,4);this._attrs.ray=r,this.rayBuffer={rw:(0,n.storage)(r,`vec4`),ro:(0,n.storage)(r,`vec4`).toReadOnly()};let i=S(e,1,Uint32Array);this._attrs.rng=i,this.rngBuffer={rw:(0,n.storage)(i,`uint`),ro:(0,n.storage)(i,`uint`).toReadOnly()};let a=e*2,o=S(a,4,Uint32Array);this._attrs.hit=o,this.hitBuffer={rw:(0,n.storage)(o,`uvec4`),ro:(0,n.storage)(o,`uvec4`).toReadOnly()},this.rayBytes=t*16+e*4,this.hitBytes=a*16,this.totalBytes=this.rayBytes+this.hitBytes,Qd.debug(`ray pool capacity ${Y.n(e)} · ${Y.mb(this.totalBytes)} (rays ${Y.mb(this.rayBytes)} · hits ${Y.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){rf(this._renderer,this._attrs.ray),rf(this._renderer,this._attrs.rng),rf(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,this.capacity=0}},of=(e,t)=>e.element(nf(t,$d.ORIGIN_META)).xyz,sf=(e,t)=>e.element(nf(t,$d.DIR_FLAGS)).xyz,cf=(e,t)=>(0,n.floatBitsToUint)(e.element(nf(t,$d.DIR_FLAGS)).w),lf=(e,t)=>e.element(nf(t,$d.THROUGHPUT_PDF)).xyz,uf=(e,t)=>e.element(nf(t,$d.THROUGHPUT_PDF)).w,df=(e,t)=>e.element(nf(t,$d.RADIANCE_ALPHA)),ff=e=>(0,n.uint)(e).mul(1),pf=(e,t,r,i,a,o=null)=>{let s=ff(t),c=o===null?(0,n.unpackUnorm2x16)(e.element(s).w).y:(0,n.float)(o);return e.element(s).assign((0,n.uvec4)((0,n.packSnorm2x16)((0,n.vec2)(r.x,r.y)),(0,n.packSnorm2x16)((0,n.vec2)(r.z,i)),(0,n.packUnorm2x16)((0,n.vec2)(a.x,a.y)),(0,n.packUnorm2x16)((0,n.vec2)(a.z,c))))},mf=(e,t,r)=>{let i=ff(t),a=e.element(i).toVar();return e.element(i).assign((0,n.uvec4)(a.x,a.y,a.z,(0,n.packUnorm2x16)((0,n.vec2)((0,n.unpackUnorm2x16)(a.w).x,r))))},hf=(e,t)=>e.element(ff(t)),gf=e=>(0,n.unpackUnorm2x16)(e.w).y,_f=e=>{let t=(0,n.unpackSnorm2x16)(e.x),r=(0,n.unpackSnorm2x16)(e.y);return(0,n.vec4)((0,n.vec3)(t.x,t.y,r.x).mul(.5).add(.5),r.y)},vf=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),yf=e=>{let t=(0,n.clamp)((0,n.floor)((0,n.log2)((0,n.max)(e,1e-6))),-8,7),r=(0,n.clamp)((0,n.float)(e).mul((0,n.exp2)(t.negate())).sub(1).mul(64),0,63);return(0,n.select)((0,n.float)(e).lessThan(.004),(0,n.uint)(0),(0,n.uint)(t.add(8)).shiftLeft(6).bitOr((0,n.uint)(r)))},bf=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(22),i=(0,n.float)(r.shiftRight(6).bitAnd((0,n.uint)(15))).sub(8),a=(0,n.float)(r.bitAnd((0,n.uint)(63))).div(64).add(1);return(0,n.select)(r.equal((0,n.uint)(0)),(0,n.float)(0),a.mul((0,n.exp2)(i)))},xf=(e,t,r,i,a,o=(0,n.uint)(0),s=null)=>{let c=(0,n.uint)(i).bitAnd((0,n.uint)(255)).bitOr((0,n.uint)(a).bitAnd((0,n.uint)(255)).shiftLeft(8)).bitOr((0,n.uint)(o).bitAnd((0,n.uint)(63)).shiftLeft(16));return s!==null&&(c=c.bitOr(yf(s).shiftLeft(22))),e.element(nf(t,$d.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Sf=(e,t,r,i)=>e.element(nf(t,$d.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Cf=(e,t,r,i)=>e.element(nf(t,$d.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),wf=(e,t,n)=>e.element(nf(t,$d.RADIANCE_ALPHA)).assign(n),Tf=(e,t)=>(0,n.uintBitsToFloat)(e.element(nf(t,ef.DIST_TRI_BARY)).x),Ef=(e,t)=>e.element(nf(t,ef.DIST_TRI_BARY)).y,Df=(e,t)=>(0,n.uintBitsToFloat)(e.element(nf(t,ef.DIST_TRI_BARY)).zw),Of=(e,t)=>ss(e.element(nf(t,ef.NORMAL_MAT)).x),kf=(e,t)=>(0,n.uint)(e.element(nf(t,ef.NORMAL_MAT)).y),Af=(e,t)=>(0,n.int)(e.element(nf(t,ef.NORMAL_MAT)).z).sub((0,n.int)(1)),jf=(e,t)=>e.element(nf(t,ef.NORMAL_MAT)).w,Mf=(e,t,r,i,a,o,s,c,l,u=(0,n.uint)(0))=>{e.element(nf(t,ef.DIST_TRI_BARY)).assign((0,n.uvec4)((0,n.floatBitsToUint)(r),i,(0,n.floatBitsToUint)(a),(0,n.floatBitsToUint)(o))),e.element(nf(t,ef.NORMAL_MAT)).assign((0,n.uvec4)(os(s),c,l,u))},Nf=(e,t)=>{let r=e.element(nf(t,$d.MEDIUM_STACK)),i=(0,n.floatBitsToUint)(r.x);return{stackDepth:i.bitAnd(255),transTraversals:i.shiftRight(8).bitAnd(255),wavelength:i.shiftRight(16).bitAnd(65535),ior1:r.y,ior2:r.z,ior3:r.w}},Pf=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(nf(t,$d.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),Ff=(e,t)=>e.element(nf(t,$d.MEDIUM_SIGMA_A)).xyz,If=(e,t,r)=>{let i=e.element(nf(t,$d.MEDIUM_SIGMA_A)).w.toVar();e.element(nf(t,$d.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},Lf=e=>{let t=(0,n.clamp)(e,(0,n.vec3)(0),(0,n.vec3)(1)).mul(1023).add(.5);return(0,n.uint)(t.x).bitOr((0,n.uint)(t.y).shiftLeft(10)).bitOr((0,n.uint)(t.z).shiftLeft(20))},Rf=e=>(0,n.vec3)((0,n.float)(e.bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(10).bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(20).bitAnd((0,n.uint)(1023)))).div(1023),zf=(e,t)=>Rf((0,n.floatBitsToUint)(e.element(nf(t,$d.MEDIUM_SIGMA_A)).w)),Bf=(e,t,r)=>{let i=e.element(nf(t,$d.MEDIUM_SIGMA_A)).xyz.toVar();e.element(nf(t,$d.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(Lf(r))))},Vf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).bitAnd(255)),Hf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),Uf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),Wf=(e,t)=>{let n=e.element(nf(t,$d.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},Gf=(e,t,r,i)=>e.element(nf(t,$d.SSS_SIGMA_S)).assign((0,n.vec4)(r,i));qt();var Kf=Pt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},qf=65535,Jf={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18},Yf=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Kf.debug(`queues capacity ${Y.n(e)} · ${Y.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){rf(this._renderer,this._countersAttr),rf(this._renderer,this._bounceCountsAttr),rf(this._renderer,this._attrA),rf(this._renderer,this._attrB),rf(this._renderer,this._sortAttr),rf(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Xf={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Zf={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function Qf(e){return(Xf[e.format]??4)*(Zf[e.type]??4)}function $f(e){return e?.gpuByteLength??e?.array?.byteLength??0}function ep(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*Qf(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*Qf(e)}var tp=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*Qf(e));return a}return this._isResident(e)?ep(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};qt();var np=Pt(`wavefront`),rp=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);np.info(Y.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${Y.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${Y.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>np.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${Y.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);n&&(n.dispatchSize=[Math.ceil(t/n.workgroupSize[0]),1,1])}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},ip=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal((0,n.int)(1)),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),ap=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h])=>{let g=(0,n.vec3)(r[3]).toVar(),_=ip(e,r,i,a,o,s,c).toVar(),v=g.toVar(),y=_.toVar();return(0,n.If)(l.and(u.greaterThan(0)).and(d.lessThan(64)).and(f.greaterThan(.001)),()=>{let e=u.div(d).mul(.001).mul(p).mul(m),i=ie(t),o=i.x.mul(h.max(.01)),s=i.y,c=(0,n.vec3)(0).toVar();(0,n.If)(a.equal((0,n.int)(1)),()=>{c.assign($o({N:_}).mul((0,n.vec3)(o,s,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));c.assign(e.mul(o).add(t.mul(s)))}),v.assign(g.add(c.mul(e))),y.assign((0,n.normalize)(g.add(_.mul(f)).sub(v)))}),vo({origin:v,direction:y})});function op(e){let{rayBufferRW:t,rngBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,sceneScale:_,apertureScale:v,anamorphicRatio:y,renderWidth:b,chunkRowBase:x,chunkRows:S,transmissiveBounces:C,transparentBackground:w,auxGBufferEnabled:T,listDriven:E=!1,activeIndicesRO:D=null,counters:O=null}=e,k=T.greaterThan((0,n.uint)(0)),A=(e,b,x)=>{let S=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(b).add(.5)),w=z({state:ve({pixelCoord:S,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),T=_e(S,(0,n.int)(1),(0,n.int)(1),w,a,o).toVar().sub(.5),E=(0,n.vec2)(S.x.add(T.x),S.y.sub(T.y)).div(a),D=vo.wrap(ap(E,w,s,c,l,u,d,f,p,m,h,g,_,v,y));xf(t,x,D.origin,(0,n.int)(0),(0,n.int)(0)),Sf(t,x,D.direction,(0,n.uint)(Jf.ACTIVE)),Cf(t,x,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),wf(t,x,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(k,()=>{pf(i,x,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),Bf(t,x,(0,n.vec3)(1))}),Pf(t,x,(0,n.uint)(0),(0,n.uint)(C),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),r.element(x).assign(w)};return(0,n.Fn)(()=>{if(E){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(O.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(D.element(e)),r=t.add(x.mul(b));A(r.mod(b),r.div(b),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(b).and(t.lessThan(S)),()=>{A(e,t.add(x),(0,n.uint)(t.mul(b).add(e)))})}})}var sp=32,cp=4096,lp=4,up=1e8,dp=()=>(0,n.array)(`int`,sp).toVar(),fp=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(up).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},pp=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),mp=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),hp=(0,n.wgslFn)(`
715
+ `);qt();var Pl=Pt(`shader`),Fl=class{constructor(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}updateSceneTextures(e){let t=this._sceneTextureNodes,n=e.environment;n.environmentTexture&&t.envTex&&(t.envTex.value=n.environmentTexture),e.goboMaps&&t.goboMapsTex&&(t.goboMapsTex.value=e.goboMaps),e.iesProfiles&&t.iesProfilesTex&&(t.iesProfilesTex.value=e.iesProfiles),Pl.debug(`scene textures updated in-place`)}updateGoboMaps(e){let t=this._sceneTextureNodes;!t||!t.goboMapsTex||e&&(t.goboMapsTex.value=e)}updateIESProfiles(e){let t=this._sceneTextureNodes;!t||!t.iesProfilesTex||e&&(t.iesProfilesTex.value=e)}getSceneTextureNodes(){return this._sceneTextureNodes}createSceneTextureNodes(e,t){let i=e.triangleStorageNode,a=e.bvhStorageNode,o=e.materialData.materialStorageNode,s=e.lightStorageNode;ps(e.uniforms.get(`enableAlphaShadows`));let c=(0,n.texture)(e.environment.environmentTexture),l=t.getReadTextures();this.prevColorTexNode=(0,n.texture)(l.color),this.prevAlbedoTexNode=(0,n.texture)(l.albedo),this.prevNormalDepthTexNode=(0,n.texture)(l.normalDepth);let u=()=>{let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.generateMipmaps=!1,e.needsUpdate=!0,(0,n.texture)(e)},d=e.goboMaps?(0,n.texture)(e.goboMaps):u();wl(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();Ol(f);let p={triStorage:i,bvhStorage:a,matStorage:o,lightBufferStorage:s,envTex:c,goboMapsTex:d,iesProfilesTex:f};return this._sceneTextureNodes=p,p}dispose(){this.prevColorTexNode=null,this.prevAlbedoTexNode=null,this.prevNormalDepthTexNode=null,this._sceneTextureNodes=null}},Il=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,t,n){if(typeof e==`number`){let r=t[n[e]],i=new Ll;return i.minX=r.minX,i.minY=r.minY,i.minZ=r.minZ,i.maxX=r.maxX,i.maxY=r.maxY,i.maxZ=r.maxZ,i.triangleOffset=r.triangleOffset,i.triangleCount=r.triangleCount,i}let r=this.buildSubtree(e[0],t,n),i=this.buildSubtree(e[1],t,n),a=new Ll;return a.leftChild=r,a.rightChild=i,a.minX=Math.min(r.minX,i.minX),a.minY=Math.min(r.minY,i.minY),a.minZ=Math.min(r.minZ,i.minZ),a.maxX=Math.max(r.maxX,i.maxX),a.maxY=Math.max(r.maxY,i.maxY),a.maxZ=Math.max(r.maxZ,i.maxZ),a}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},Ll=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Rl=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};qt();var zl=Pt(`bvh`),Bl=1073741824,Vl=1073741826,Hl=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),Ul=1073741824;function Wl(e,t){if(e>=Ul)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${Ul}`);return e}var Gl=null;function Kl(e){Gl=e}var ql={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},Jl=ql.FLOATS_PER_TRIANGLE,Yl=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),Xl=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},Zl=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=Yl(this.triangles),n=ql.POSITION_A_OFFSET,r=ql.POSITION_B_OFFSET,i=ql.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Jl,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Jl*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&Gl&&typeof Worker<`u`?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;zl.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Jl*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(Gl())}catch(i){zl.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Jl*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new Il(this.traversalCost,this.intersectionCost);t.setTreeletSize(e),t.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let i=n?t=>{n(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{t.optimizeBVH(c,i)}catch(t){zl.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=t.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let i=performance.now()-r;this.splitStats.treeletOptimizationTime=i;let a=t.getStatistics();this.splitStats.treeletsProcessed=a.treeletsProcessed,this.splitStats.treeletsImproved=a.treeletsImproved,this.splitStats.averageSAHImprovement=a.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new Rl(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=n?e=>{n(e)}:null;try{e.optimizeBVH(c,t)}catch(e){zl.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let l=performance.now();this.applySAOrdering(c),this.splitStats.saOrderTime=performance.now()-l;let u=performance.now(),d=this.triangles,f=r||new d.constructor(a*Jl);for(let e=0;e<a;e++){let t=this.indices[e]*Jl,n=e*Jl;f.set(d.subarray(t,t+Jl),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return zl.debug(`${Y.n(a)} tris → ${Y.n(this.totalNodes)} nodes in ${Y.ms(m)} | SAH ${h.sahSplits} objMed ${h.objectMedianSplits} spatMed ${h.spatialMedianSplits} failed ${h.failedSplits}`+(h.treeletsProcessed?` | treelets ${h.treeletsImproved}/${h.treeletsProcessed} improved`:``)+(h.reinsertionsApplied?` | reinsertions ${h.reinsertionsApplied}`:``)),n&&n(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,c}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new Xl;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new Xl;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Wl(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=Hl(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=Bl}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}Wl(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=Hl(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=Vl,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=Bl}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;Wl(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=Hl(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<Bl&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Ql={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},$l=Ql.FLOATS_PER_TRIANGLE,eu=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),tu=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),nu=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):tu(e)}},ru=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,iu=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,au=(e,t)=>e.chunked?e.chunked.baseOf(t):t*cu,ou=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):eu(e),u:t?e:tu(e)}};function su(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}var cu=16,lu=1073741824,uu=1073741825,du=1e-12;function fu(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=du*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,ee=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>ee&&(ee=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=ee}var pu=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length,i=ou(e);for(let e=0;e<r;e++){let r=n[e],a=i.chunked?i.f.chunkFor(e):i.f,o=i.chunked?i.u.chunkFor(e):i.u,s=i.chunked?i.chunked.baseOf(e):e*$l,c=r*9,l=t[c],u=t[c+1],d=t[c+2],f=t[c+3],p=t[c+4],m=t[c+5],h=t[c+6],g=t[c+7],_=t[c+8];a[s+Ql.POSITION_A_OFFSET]=l,a[s+Ql.POSITION_A_OFFSET+1]=u,a[s+Ql.POSITION_A_OFFSET+2]=d,a[s+Ql.POSITION_B_OFFSET]=f,a[s+Ql.POSITION_B_OFFSET+1]=p,a[s+Ql.POSITION_B_OFFSET+2]=m,a[s+Ql.POSITION_C_OFFSET]=h,a[s+Ql.POSITION_C_OFFSET+1]=g,a[s+Ql.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=su(y*C-b*S,b*x-v*C,v*S-y*x);o[s+Ql.NORMAL_A_PACKED_OFFSET]=w,o[s+Ql.NORMAL_B_PACKED_OFFSET]=w,o[s+Ql.NORMAL_C_PACKED_OFFSET]=w}}refitRange(e,t,n,r){let i=ou(t);r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let a=this._bounds,o=n+r,s=nu(e);for(let e=o-1;e>=n;e--){let t=ru(s,e),r=iu(s,e),o=au(s,e),c=(e-n)*6;if(r[o+3]===lu){let e=r[o],t=r[o+1],n=1/0,s=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let r=0;r<t;r++){let t=e+r,a=i.chunked?i.f.chunkFor(t):i.f,o=i.chunked?i.chunked.baseOf(t):t*$l,c=a[o+Ql.POSITION_A_OFFSET],p=a[o+Ql.POSITION_A_OFFSET+1],m=a[o+Ql.POSITION_A_OFFSET+2],h=a[o+Ql.POSITION_B_OFFSET],g=a[o+Ql.POSITION_B_OFFSET+1],_=a[o+Ql.POSITION_B_OFFSET+2],v=a[o+Ql.POSITION_C_OFFSET],y=a[o+Ql.POSITION_C_OFFSET+1],b=a[o+Ql.POSITION_C_OFFSET+2];n=Math.min(n,c,h,v),s=Math.min(s,p,g,y),l=Math.min(l,m,_,b),u=Math.max(u,c,h,v),d=Math.max(d,p,g,y),f=Math.max(f,m,_,b)}a[c]=n,a[c+1]=s,a[c+2]=l,a[c+3]=u,a[c+4]=d,a[c+5]=f}else{let e=r[o+3],i=r[o+7],s=(e-n)*6,l=(i-n)*6,u=a[s],d=a[s+1],f=a[s+2],p=a[s+3],m=a[s+4],h=a[s+5],g=a[l],_=a[l+1],v=a[l+2],y=a[l+3],b=a[l+4],x=a[l+5];t[o]=u,t[o+1]=d,t[o+2]=f,t[o+4]=p,t[o+5]=m,t[o+6]=h,t[o+8]=g,t[o+9]=_,t[o+10]=v,t[o+12]=y,t[o+13]=b,t[o+14]=x,a[c]=Math.min(u,g),a[c+1]=Math.min(d,_),a[c+2]=Math.min(f,v),a[c+3]=Math.max(p,y),a[c+4]=Math.max(m,b),a[c+5]=Math.max(h,x)}}}refit(e,t,n){let r=ou(t);n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let i=this._bounds,a=nu(e);for(let e=n-1;e>=0;e--){let t=ru(a,e),n=iu(a,e),o=au(a,e),s=e*6,c=n[o+3];if(c===lu){let e=n[o],t=n[o+1],a=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let n=0;n<t;n++){let t=e+n,i=r.chunked?r.f.chunkFor(t):r.f,o=r.chunked?r.chunked.baseOf(t):t*$l,s=i[o+Ql.POSITION_A_OFFSET],p=i[o+Ql.POSITION_A_OFFSET+1],m=i[o+Ql.POSITION_A_OFFSET+2],h=i[o+Ql.POSITION_B_OFFSET],g=i[o+Ql.POSITION_B_OFFSET+1],_=i[o+Ql.POSITION_B_OFFSET+2],v=i[o+Ql.POSITION_C_OFFSET],y=i[o+Ql.POSITION_C_OFFSET+1],b=i[o+Ql.POSITION_C_OFFSET+2];a=Math.min(a,s,h,v),c=Math.min(c,p,g,y),l=Math.min(l,m,_,b),u=Math.max(u,s,h,v),d=Math.max(d,p,g,y),f=Math.max(f,m,_,b)}i[s]=a,i[s+1]=c,i[s+2]=l,i[s+3]=u,i[s+4]=d,i[s+5]=f}else if(c===uu)fu(t,o,i,n[o]*6,i,s);else{let e=n[o+3],r=n[o+7],a=e*6,c=r*6,l=i[a],u=i[a+1],d=i[a+2],f=i[a+3],p=i[a+4],m=i[a+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];t[o]=l,t[o+1]=u,t[o+2]=d,t[o+4]=f,t[o+5]=p,t[o+6]=m,t[o+8]=h,t[o+9]=g,t[o+10]=_,t[o+12]=v,t[o+13]=y,t[o+14]=b,i[s]=Math.min(l,h),i[s+1]=Math.min(u,g),i[s+2]=Math.min(d,_),i[s+3]=Math.max(f,v),i[s+4]=Math.max(p,y),i[s+5]=Math.max(m,b)}}}},mu="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}function b(e){e&&e in r&&(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e])}const x=y(`bvh`),S=1073741824,C=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),w=1073741824;function T(e,t){if(e>=w)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${w}`);return e}const E={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},D=E.FLOATS_PER_TRIANGLE,O=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var k=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},A=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=O(this.triangles),n=E.POSITION_A_OFFSET,r=E.POSITION_B_OFFSET,i=E.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*D,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(D*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(D*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){x.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){x.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*D);for(let e=0;e<s;e++){let t=this.indices[e]*D,n=e*D;m.set(p.subarray(t,t+D),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return x.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new k;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new k;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}T(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=C(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=S}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}T(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=C(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=S}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;T(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=C(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<S&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const j=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?M(t):n===`assemble`?N(t):P(t)};function M(e){let{sharedTriangleData:t,sharedCentroids:n,sharedBMin:r,sharedBMax:i,sharedIndices:a,sharedMortonCodes:o,triangleCount:s,depth:c,parallelDepth:l,reportProgress:u,treeletOptimization:d}=e;try{let e=new A;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Uint32Array(t),e.centroids=new Float32Array(n),e.bMin=new Float32Array(r),e.bMax=new Float32Array(i),e.indices=new Uint32Array(a),e.mortonCodes=new Uint32Array(o),e.totalTriangles=s,e.totalNodes=0,e.processedTriangles=0,e.lastProgressUpdate=performance.now(),e.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let p=performance.now(),m=performance.now();e.initializeTriangleArrays(),e.splitStats.initTime=performance.now()-m,e.sortTrianglesByMortonCode(),e.frontierTasks=[];let h=performance.now(),g=e.buildNodeRecursiveToDepth(0,s,c,l,f);e.splitStats.sahBuildTime=performance.now()-h,e.applySAOrdering(g);let v=performance.now(),{flatData:y,frontierMap:b,nodeCount:x}=e.flattenBVHWithFrontier(g),S=performance.now()-v,C=performance.now()-p;j.debug(`phase 1 ${_.ms(C)} (init ${_.ms(e.splitStats.initTime)} · morton ${_.ms(e.splitStats.mortonSortTime)} · SAH ${_.ms(e.splitStats.sahBuildTime)} · flatten ${_.ms(S)}) · ${e.frontierTasks.length} frontier tasks`),self.postMessage({type:`phase1Result`,topFlatData:y,topNodeCount:x,frontierTasks:e.frontierTasks,frontierMap:b,splitStats:e.splitStats},[y.buffer])}catch(e){j.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function N(e){let{topFlatData:t,topNodeCount:n,frontierMap:r,subtreeResults:i,sharedTriangleData:a,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c}=e;try{let e=performance.now(),l=new A().assembleParallelBVH(t,n,r,i),u=new Uint32Array(o),d=new Uint32Array(a),f=new Uint32Array(s);for(let e=0;e<c;e++){let t=u[e]*20,n=e*20;f.set(d.subarray(t,t+20),n)}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[u[e]]=e;let m=performance.now()-e;j.debug(`phase 3 assemble + reorder ${_.ms(m)} (${_.mb(l.byteLength)} BVH)`),self.postMessage({type:`assembleResult`,bvhData:l,originalToBvh:p,triangleCount:c},[l.buffer,p.buffer])}catch(e){j.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function P(e){let{triangleData:t,triangleByteOffset:n,triangleByteLength:r,depth:i,reportProgress:a,treeletOptimization:o,reinsertionOptimization:s,sharedReorderBuffer:c,maxLeafSize:l,numBins:u,maxBins:d,minBins:f}=e,p=new A;l!==void 0&&(p.maxLeafSize=l),u!==void 0&&(p.numBins=u),d!==void 0&&(p.maxBins=d),f!==void 0&&(p.minBins=f);try{o&&p.setTreeletConfig(o),s&&p.setReinsertionConfig(s);let e=a?e=>{self.postMessage({progress:e})}:null,l=n===void 0?new Uint32Array(t):new Uint32Array(t,n,r/4),u=c?new Uint32Array(c):null,d=p.buildSync(l,i,e,u),f=performance.now(),m=p.flattenBVH(d),h=performance.now()-f;j.debug(`flatten ${_.ms(h)} (${_.mb(m.byteLength)})`);let g=p.originalToBvhMap||null;if(c){let e=[m.buffer];g&&e.push(g.buffer),self.postMessage({bvhData:m,originalToBvh:g,triangleCount:l.length/20,treeletStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/80,n=[m.buffer,e.buffer];g&&n.push(g.buffer),self.postMessage({bvhData:m,triangles:e,originalToBvh:g,triangleCount:t,treeletStats:p.splitStats},n)}}catch(e){j.error(`build failed:`,e),self.postMessage({error:e.message})}}",hu=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,mu],{type:`text/javascript;charset=utf-8`});function gu(e){let t;try{if(t=hu&&(self.URL||self.webkitURL).createObjectURL(hu),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(mu),{type:`module`,name:e?.name})}}var _u="var e=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.maxTreeletLeaves=7,this.minImprovement=.02,this.topologyCache=new Map;for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.set(e,this.generateTopologies(e));this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0}}generateTopologies(e){if(e===1)return[0];if(e===2)return[[0,1]];let t=[];for(let n=1;n<e;n++){let r=this.generateTopologies(n),i=this.generateTopologies(e-n);for(let e of r)for(let r of i)t.push([e,this.offsetTopology(r,n)])}return t}offsetTopology(e,t){return typeof e==`number`?e+t:[this.offsetTopology(e[0],t),this.offsetTopology(e[1],t)]}optimizeBVH(e){let t=performance.now();this.stats={treeletsProcessed:0,treeletsImproved:0,totalSAHImprovement:0,averageSAHImprovement:0,optimizationTime:0};let n=this.identifyTreeletRoots(e);for(let e=0;e<n.length;e++){if(performance.now()-t>3e4){console.warn(`TreeletOptimizer: timeout after ${e}/${n.length} treelets`);break}this.optimizeTreelet(n[e])}return this.stats.optimizationTime=performance.now()-t,this.stats.averageSAHImprovement=this.stats.treeletsProcessed>0?this.stats.totalSAHImprovement/this.stats.treeletsProcessed:0,e}identifyTreeletRoots(e){let t=[],n=new Set,r=[{node:e,visited:!1}];for(;r.length>0;){let e=r[r.length-1];if(e.visited){r.pop();let i=e.node;if(i.triangleCount>0||n.has(i))continue;let a=this.countLeaves(i);a>=3&&a<=this.maxTreeletLeaves&&(t.push(i),this.markSubtree(i,n))}else{e.visited=!0;let t=e.node;if(t.triangleCount>0)continue;t.rightChild&&r.push({node:t.rightChild,visited:!1}),t.leftChild&&r.push({node:t.leftChild,visited:!1})}}return t}countLeaves(e){return e?e.triangleCount>0?1:this.countLeaves(e.leftChild)+this.countLeaves(e.rightChild):0}markSubtree(e,t){e&&(t.add(e),!(e.triangleCount>0)&&(this.markSubtree(e.leftChild,t),this.markSubtree(e.rightChild,t)))}optimizeTreelet(e){let t=[];this.extractLeaves(e,t);let n=t.length;if(n<3||n>this.maxTreeletLeaves)return;this.stats.treeletsProcessed++;let r=this.evaluateSubtreeSAH(e),i=this.topologyCache.get(n);if(!i||i.length===0)return;let a=r,o=null,s=null;if(n<=5){let e=this.generatePermutations(n);for(let n of i)for(let r of e){let e=this.evaluateTopology(n,t,r);e<a&&(a=e,o=n,s=r)}}else{let e=Array.from({length:n},(e,t)=>t);for(let n of i){let r=this.evaluateTopology(n,t,e);r<a&&(a=r,o=n,s=e);let i=this.greedySwapOptimize(n,t,e,r);i.cost<a&&(a=i.cost,o=n,s=i.perm)}}let c=(r-a)/r;o&&c>this.minImprovement&&(this.reconstructTreelet(e,o,t,s),this.stats.treeletsImproved++,this.stats.totalSAHImprovement+=c)}extractLeaves(e,t){if(e){if(e.triangleCount>0){t.push({minX:e.minX,minY:e.minY,minZ:e.minZ,maxX:e.maxX,maxY:e.maxY,maxZ:e.maxZ,triangleOffset:e.triangleOffset,triangleCount:e.triangleCount});return}this.extractLeaves(e.leftChild,t),this.extractLeaves(e.rightChild,t)}}evaluateSubtreeSAH(e){if(!e)return 0;if(e.triangleCount>0)return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*e.triangleCount*this.intersectionCost;let t=this.evaluateSubtreeSAH(e.leftChild),n=this.evaluateSubtreeSAH(e.rightChild);return this.surfaceAreaFlat(e.minX,e.minY,e.minZ,e.maxX,e.maxY,e.maxZ)*this.traversalCost+t+n}evaluateTopology(e,t,n){return this.evalTopoRecursive(e,t,n).cost}evalTopoRecursive(e,t,n){if(typeof e==`number`){let r=t[n[e]];return{cost:this.surfaceAreaFlat(r.minX,r.minY,r.minZ,r.maxX,r.maxY,r.maxZ)*r.triangleCount*this.intersectionCost,minX:r.minX,minY:r.minY,minZ:r.minZ,maxX:r.maxX,maxY:r.maxY,maxZ:r.maxZ}}let r=this.evalTopoRecursive(e[0],t,n),i=this.evalTopoRecursive(e[1],t,n),a=Math.min(r.minX,i.minX),o=Math.min(r.minY,i.minY),s=Math.min(r.minZ,i.minZ),c=Math.max(r.maxX,i.maxX),l=Math.max(r.maxY,i.maxY),u=Math.max(r.maxZ,i.maxZ);return{cost:this.surfaceAreaFlat(a,o,s,c,l,u)*this.traversalCost+r.cost+i.cost,minX:a,minY:o,minZ:s,maxX:c,maxY:l,maxZ:u}}surfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}generatePermutations(e){let t=[],n=Array.from({length:e},(e,t)=>t),r=i=>{if(i===e){t.push([...n]);return}for(let t=i;t<e;t++)[n[i],n[t]]=[n[t],n[i]],r(i+1),[n[i],n[t]]=[n[t],n[i]]};return r(0),t}greedySwapOptimize(e,t,n,r){let i=[...n],a=r,o=!0;for(;o;){o=!1;for(let n=0;n<i.length-1;n++)for(let r=n+1;r<i.length;r++){[i[n],i[r]]=[i[r],i[n]];let s=this.evaluateTopology(e,t,i);s<a?(a=s,o=!0):[i[n],i[r]]=[i[r],i[n]]}}return{perm:i,cost:a}}reconstructTreelet(e,t,n,r){let i=this.buildSubtree(t,n,r);e.minX=i.minX,e.minY=i.minY,e.minZ=i.minZ,e.maxX=i.maxX,e.maxY=i.maxY,e.maxZ=i.maxZ,e.leftChild=i.leftChild,e.rightChild=i.rightChild,e.triangleOffset=i.triangleOffset,e.triangleCount=i.triangleCount}buildSubtree(e,n,r){if(typeof e==`number`){let i=n[r[e]],a=new t;return a.minX=i.minX,a.minY=i.minY,a.minZ=i.minZ,a.maxX=i.maxX,a.maxY=i.maxY,a.maxZ=i.maxZ,a.triangleOffset=i.triangleOffset,a.triangleCount=i.triangleCount,a}let i=this.buildSubtree(e[0],n,r),a=this.buildSubtree(e[1],n,r),o=new t;return o.leftChild=i,o.rightChild=a,o.minX=Math.min(i.minX,a.minX),o.minY=Math.min(i.minY,a.minY),o.minZ=Math.min(i.minZ,a.minZ),o.maxX=Math.max(i.maxX,a.maxX),o.maxY=Math.max(i.maxY,a.maxY),o.maxZ=Math.max(i.maxZ,a.maxZ),o}setTreeletSize(e){this.maxTreeletLeaves=Math.max(3,Math.min(7,e));for(let e=3;e<=this.maxTreeletLeaves;e++)this.topologyCache.has(e)||this.topologyCache.set(e,this.generateTopologies(e))}setMinImprovement(e){this.minImprovement=Math.max(.001,e)}getStatistics(){return{...this.stats}}},t=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},n=class{constructor(e,t){this.traversalCost=e,this.intersectionCost=t,this.batchSizeRatio=.02,this.maxIterations=2,this.timeBudgetMs=15e3,this.stats={reinsertionsApplied:0,iterations:0,timeMs:0}}setBatchSizeRatio(e){this.batchSizeRatio=Math.max(.005,Math.min(.1,e))}setMaxIterations(e){this.maxIterations=Math.max(1,Math.min(5,e))}getStatistics(){return{...this.stats}}surfaceArea(e){let t=e.maxX-e.minX,n=e.maxY-e.minY,r=e.maxZ-e.minZ;return t*n+n*r+r*t}buildParentMap(e){let t=new Map;t.set(e,{parent:null,isLeft:!1});let n=[e];for(;n.length>0;){let e=n.pop();e.triangleCount>0||(e.leftChild&&(t.set(e.leftChild,{parent:e,isLeft:!0}),n.push(e.leftChild)),e.rightChild&&(t.set(e.rightChild,{parent:e,isLeft:!1}),n.push(e.rightChild)))}return t}findCandidates(e,t,n){let r=[],i=[e];for(;i.length>0;){let a=i.pop();if(a!==e&&n.get(a).parent!==e){let e=this.surfaceArea(a);r.length<t?(r.push({node:a,cost:e}),r.length===t&&this._heapify(r)):e>r[0].cost&&(r[0]={node:a,cost:e},this._siftDown(r,0))}a.triangleCount===0&&(a.leftChild&&i.push(a.leftChild),a.rightChild&&i.push(a.rightChild))}return r}_heapify(e){for(let t=(e.length>>1)-1;t>=0;t--)this._siftDown(e,t)}_siftDown(e,t){let n=e.length;for(;;){let r=t,i=2*t+1,a=2*t+2;if(i<n&&e[i].cost<e[r].cost&&(r=i),a<n&&e[a].cost<e[r].cost&&(r=a),r===t)break;let o=e[t];e[t]=e[r],e[r]=o,t=r}}findReinsertion(e,t,n){let r=n.get(e),i=r.parent;if(!i)return null;let a=r.isLeft?i.rightChild:i.leftChild,o=this.surfaceArea(e),s=this.surfaceArea(i),c=null,l=0,u=s,d=a.minX,f=a.minY,p=a.minZ,m=a.maxX,h=a.maxY,g=a.maxZ,_=a,v=i,y=[];do{for(y.length=0,y.push(u,_);y.length>0;){let t=y.pop(),n=y.pop();if(n-o<=l)continue;let r=Math.min(t.minX,e.minX),i=Math.min(t.minY,e.minY),a=Math.min(t.minZ,e.minZ),s=Math.max(t.maxX,e.maxX),u=Math.max(t.maxY,e.maxY),d=Math.max(t.maxZ,e.maxZ),f=s-r,p=u-i,m=d-a,h=n-(f*p+p*m+m*f);if(h>l&&(c=t,l=h),t.triangleCount===0&&t.leftChild&&t.rightChild){let e=h+this.surfaceArea(t);y.push(e,t.leftChild),y.push(e,t.rightChild)}}let t=n.get(v);if(!t||t.parent===null)break;if(v!==i){d=Math.min(d,_.minX),f=Math.min(f,_.minY),p=Math.min(p,_.minZ),m=Math.max(m,_.maxX),h=Math.max(h,_.maxY),g=Math.max(g,_.maxZ);let e=m-d,t=h-f,n=g-p,r=e*t+t*n+n*e;u+=this.surfaceArea(v)-r}let r=t.parent;_=t.isLeft?r.rightChild:r.leftChild,v=r}while(n.get(v).parent!==null);return c===a||c===i?null:c?{from:e,to:c,areaDiff:l}:null}getConflicts(e,t,n){let r=n.get(e);return[t,e,r.isLeft?r.parent.rightChild:r.parent.leftChild,n.get(t).parent,r.parent]}reinsertNode(e,t,n){let r=n.get(e),i=r.parent,a=r.isLeft?i.rightChild:i.leftChild,o=n.get(i),s=o.parent,c=n.get(t),l=c.parent;o.isLeft?s.leftChild=a:s.rightChild=a,i.leftChild=e,i.rightChild=t,i.triangleOffset=0,i.triangleCount=0,i.minX=Math.min(e.minX,t.minX),i.minY=Math.min(e.minY,t.minY),i.minZ=Math.min(e.minZ,t.minZ),i.maxX=Math.max(e.maxX,t.maxX),i.maxY=Math.max(e.maxY,t.maxY),i.maxZ=Math.max(e.maxZ,t.maxZ),c.isLeft?l.leftChild=i:l.rightChild=i,n.set(a,{parent:s,isLeft:o.isLeft}),n.set(i,{parent:l,isLeft:c.isLeft}),n.set(e,{parent:i,isLeft:!0}),n.set(t,{parent:i,isLeft:!1}),this.refitFrom(s,n),this.refitFrom(l,n)}refitFrom(e,t){let n=e;for(;n;){if(n.triangleCount===0&&n.leftChild&&n.rightChild){let e=n.leftChild,t=n.rightChild;n.minX=Math.min(e.minX,t.minX),n.minY=Math.min(e.minY,t.minY),n.minZ=Math.min(e.minZ,t.minZ),n.maxX=Math.max(e.maxX,t.maxX),n.maxY=Math.max(e.maxY,t.maxY),n.maxZ=Math.max(e.maxZ,t.maxZ)}let e=t.get(n);n=e?e.parent:null}}optimizeBVH(e,t){let n=performance.now();this.stats={reinsertionsApplied:0,iterations:0,timeMs:0};for(let r=0;r<this.maxIterations&&!(performance.now()-n>this.timeBudgetMs);r++){let i=this.buildParentMap(e),a=i.size,o=Math.max(1,Math.floor(a*this.batchSizeRatio));t&&t(`Reinsertion iter ${r+1}/${this.maxIterations}: selecting ${o} candidates`);let s=this.findCandidates(e,o,i),c=[];for(let t=0;t<s.length&&!(performance.now()-n>this.timeBudgetMs);t++){let n=this.findReinsertion(s[t].node,e,i);n&&n.areaDiff>0&&c.push(n)}c.sort((e,t)=>t.areaDiff-e.areaDiff);let l=new Set,u=0;for(let e of c){let t=this.getConflicts(e.from,e.to,i);if(!t.some(e=>l.has(e))){for(let e of t)l.add(e);this.reinsertNode(e.from,e.to,i),u++}}if(this.stats.reinsertionsApplied+=u,this.stats.iterations=r+1,t&&t(`Reinsertion iter ${r+1}: applied ${u} reinsertions`),u===0)break}return this.stats.timeMs=performance.now()-n,this.stats}};const r={silent:0,error:1,warn:2,info:3,debug:4},i=`info`,a=`rayzeeLogLevel`,o=`rayzeeLogNamespaces`,s=`color:#7c8494`,c=`color:inherit`;let l=null,u=null;function d(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function f(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function p(){if(l!==null)return l;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in r?(l=r[e],l):(l=r[d(a)]??r[i],l)}function m(){if(u!==null)return u;let e=globalThis.__RAYZEE_LOG_NS__??d(o);return u=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],u}function h(e,t){if(t<r.debug)return!0;let n=m();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function g(e,t,n){if(e>p()||!h(t,e))return;let i=e===r.error?console.error:e===r.warn?console.warn:console.log,a=`[${t}]`;typeof n[0]==`string`?i(`%c${a}%c ${n[0]}`,s,c,...n.slice(1)):i(`%c${a}`,s,...n)}const _={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${_.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},v={levels:r,setLevel(e){return e in r?(globalThis.__RAYZEE_LOG_LEVEL__=e,l=r[e],f(a,e===i?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(r).join(`, `)}`),this.getLevel())},getLevel(){let e=p();return Object.keys(r).find(t=>r[t]===e)},isEnabled(e){return(r[e]??r.debug)<=p()},only(...e){let t=e.flat().filter(Boolean);return u=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),f(o,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return l=null,u=null,this.getLevel()}};function y(e){return{namespace:e,error:(...t)=>g(r.error,e,t),warn:(...t)=>g(r.warn,e,t),info:(...t)=>g(r.info,e,t),debug:(...t)=>g(r.debug,e,t),isEnabled:e=>v.isEnabled(e),summary(t,n=[]){let i=n.filter(Boolean);if(i.length===0||!console.groupCollapsed){g(r.info,e,[t]),i.forEach(t=>g(r.debug,e,[t]));return}r.info>p()||((p()>=r.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,s,c),i.forEach(e=>console.log(e)),console.groupEnd())}}}const b=y(`bvh`),x=1073741824,S=e=>new Uint32Array(e.buffer,e.byteOffset,e.length),C=1073741824;function w(e,t){if(e>=C)throw RangeError(`${t} is ${e}, at or past the BVH index limit of ${C}`);return e}const T={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8},E=T.FLOATS_PER_TRIANGLE,D=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length);var O=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.triangleOffset=0,this.triangleCount=0}},k=class{constructor(){this.useWorker=!0,this.maxLeafSize=8,this.numBins=32,this.minBins=8,this.maxBins=64,this.totalNodes=0,this.processedTriangles=0,this.totalTriangles=0,this.lastProgressUpdate=0,this.progressUpdateInterval=100,this.traversalCost=1,this.intersectionCost=2.5,this.useMortonCodes=!0,this.mortonBits=10,this.mortonClusterThreshold=128,this.enableObjectMedianFallback=!0,this.enableSpatialMedianFallback=!0,this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0},this.enableTreeletOptimization=!1,this.treeletSize=5,this.treeletOptimizationPasses=1,this.treeletMinImprovement=.02,this.treeletComplexityThreshold=5e4,this.enableReinsertionOptimization=!0,this.reinsertionBatchSizeRatio=.02,this.reinsertionMaxIterations=2,this.initializeBinArrays(),this._partResult={mid:0,lMinX:0,lMinY:0,lMinZ:0,lMaxX:0,lMaxY:0,lMaxZ:0,rMinX:0,rMinY:0,rMinZ:0,rMaxX:0,rMaxY:0,rMaxZ:0},this.centroids=null,this.bMin=null,this.bMax=null,this.indices=null,this.mortonCodes=null,this.triangles=null,this.reorderedTriangleData=null}initializeBinArrays(){let e=this.maxBins;this.binBoundsMin=new Float32Array(e*3),this.binBoundsMax=new Float32Array(e*3),this.binCounts=new Uint32Array(e),this.leftPrefixMin=new Float32Array(e*3),this.leftPrefixMax=new Float32Array(e*3),this.leftPrefixCount=new Uint32Array(e),this.rightPrefixMin=new Float32Array(e*3),this.rightPrefixMax=new Float32Array(e*3),this.rightPrefixCount=new Uint32Array(e)}getOptimalBinCount(e){return e<=16?this.minBins:e<=64?16:e<=256?32:e<=1024?48:this.maxBins}setAdaptiveBinConfig(e){e.minBins!==void 0&&(this.minBins=Math.max(4,e.minBins)),e.maxBins!==void 0&&(this.maxBins=Math.min(128,e.maxBins)),e.baseBins!==void 0&&(this.numBins=e.baseBins),e.maxBins!==void 0&&this.initializeBinArrays()}setMortonConfig(e){e.enabled!==void 0&&(this.useMortonCodes=e.enabled),e.bits!==void 0&&(this.mortonBits=Math.max(6,Math.min(10,e.bits))),e.threshold!==void 0&&(this.mortonClusterThreshold=Math.max(16,e.threshold))}setFallbackConfig(e){e.objectMedian!==void 0&&(this.enableObjectMedianFallback=e.objectMedian),e.spatialMedian!==void 0&&(this.enableSpatialMedianFallback=e.spatialMedian)}setTreeletConfig(e){e.enabled!==void 0&&(this.enableTreeletOptimization=e.enabled),e.size!==void 0&&(this.treeletSize=Math.max(3,Math.min(12,e.size))),e.passes!==void 0&&(this.treeletOptimizationPasses=Math.max(1,Math.min(3,e.passes))),e.minImprovement!==void 0&&(this.treeletMinImprovement=Math.max(.001,e.minImprovement)),e.complexityThreshold!==void 0&&(this.treeletComplexityThreshold=e.complexityThreshold)}disableTreeletOptimization(){this.enableTreeletOptimization=!1}setReinsertionConfig(e){e.enabled!==void 0&&(this.enableReinsertionOptimization=e.enabled),e.batchSizeRatio!==void 0&&(this.reinsertionBatchSizeRatio=Math.max(.005,Math.min(.1,e.batchSizeRatio))),e.maxIterations!==void 0&&(this.reinsertionMaxIterations=Math.max(1,Math.min(5,e.maxIterations)))}initializeTriangleArrays(){let e=this.totalTriangles,t=D(this.triangles),n=T.POSITION_A_OFFSET,r=T.POSITION_B_OFFSET,i=T.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*E,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){if(this.totalTriangles=e.byteLength/(E*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),!(this.useWorker&&null))return new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(t,r=30,i=null,a=null){let o=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=t,this.totalTriangles=t.byteLength/(E*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let s=this.totalTriangles,c=performance.now();this.centroids=new Float32Array(s*3),this.bMin=new Float32Array(s*3),this.bMax=new Float32Array(s*3),this.indices=new Uint32Array(s),this.mortonCodes=new Uint32Array(s),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-c,this.sortTrianglesByMortonCode();let l=performance.now(),u=this.buildNodeRecursive(0,s,r,i);if(this.splitStats.sahBuildTime=performance.now()-l,this.enableTreeletOptimization&&this.totalTriangles>1e3){let t=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,n=new e(this.traversalCost,this.intersectionCost);n.setTreeletSize(t),n.setMinImprovement(this.treeletMinImprovement);let r=performance.now();for(let e=0;e<this.treeletOptimizationPasses;e++){let t=i?t=>{i(`Treelet optimization pass ${e+1}/${this.treeletOptimizationPasses}: ${t}`)}:null;try{n.optimizeBVH(u,t)}catch(t){b.error(`treelet optimizer failed in pass ${e+1}:`,t);break}let a=n.getStatistics(),o=performance.now()-r;if(a.treeletsImproved===0&&e>0||o>15e3)break}let a=performance.now()-r;this.splitStats.treeletOptimizationTime=a;let o=n.getStatistics();this.splitStats.treeletsProcessed=o.treeletsProcessed,this.splitStats.treeletsImproved=o.treeletsImproved,this.splitStats.averageSAHImprovement=o.averageSAHImprovement}if(this.enableReinsertionOptimization&&this.totalTriangles>1e3){let e=new n(this.traversalCost,this.intersectionCost);e.setBatchSizeRatio(this.reinsertionBatchSizeRatio),e.setMaxIterations(this.reinsertionMaxIterations);let t=i?e=>{i(e)}:null;try{e.optimizeBVH(u,t)}catch(e){b.error(`reinsertion optimizer failed:`,e)}let r=e.getStatistics();this.splitStats.reinsertionOptimizationTime=r.timeMs,this.splitStats.reinsertionsApplied=r.reinsertionsApplied,this.splitStats.reinsertionIterations=r.iterations}let d=performance.now();this.applySAOrdering(u),this.splitStats.saOrderTime=performance.now()-d;let f=performance.now(),p=this.triangles,m=a||new p.constructor(s*E);for(let e=0;e<s;e++){let t=this.indices[e]*E,n=e*E;m.set(p.subarray(t,t+E),n)}this.reorderedTriangleData=m;let h=new Uint32Array(s);for(let e=0;e<s;e++)h[this.indices[e]]=e;this.originalToBvhMap=h,this.splitStats.reorderTime=performance.now()-f,this.splitStats.totalBuildTime=performance.now()-o;let g=this.splitStats.totalBuildTime,v=this.splitStats;return b.debug(`${_.n(s)} tris → ${_.n(this.totalNodes)} nodes in ${_.ms(g)} | SAH ${v.sahSplits} objMed ${v.objectMedianSplits} spatMed ${v.spatialMedianSplits} failed ${v.failedSplits}`+(v.treeletsProcessed?` | treelets ${v.treeletsImproved}/${v.treeletsProcessed} improved`:``)+(v.reinsertionsApplied?` | reinsertions ${v.reinsertionsApplied}`:``)),i&&i(100),this.centroids=null,this.bMin=null,this.bMax=null,this.mortonCodes=null,u}updateProgress(e,t){if(!t)return;this.processedTriangles+=e;let n=performance.now();n-this.lastProgressUpdate<this.progressUpdateInterval||(this.lastProgressUpdate=n,t(Math.min(Math.floor(this.processedTriangles/this.totalTriangles*100),99)))}buildNodeRecursiveToDepth(e,t,n,r,i,a,o,s,c,l,u){let d=new O;this.totalNodes++;let f=t-e;if(a===void 0?this.updateNodeBounds(d,e,t):(d.minX=a,d.minY=o,d.minZ=s,d.maxX=c,d.maxY=l,d.maxZ=u),f<=this.maxLeafSize||n<=0)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;if(r<=0&&f>this.maxLeafSize*16){let r=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=r,this.frontierTasks.push({taskId:r,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}let p=this.findBestSplitPositionSAH(e,t,d);if(!p.success){if(this.splitStats.failedSplits++,r>0||f<=this.maxLeafSize*16)return d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d;let a=this.frontierTasks.length;return d.triangleOffset=e,d.triangleCount=f,d.isFrontier=!0,d.frontierTaskId=a,this.frontierTasks.push({taskId:a,start:e,end:t,depth:n,preMinX:d.minX,preMinY:d.minY,preMinZ:d.minZ,preMaxX:d.maxX,preMaxY:d.maxY,preMaxZ:d.maxZ}),d}p.method===`SAH`?this.splitStats.sahSplits++:p.method===`object_median`?this.splitStats.objectMedianSplits++:p.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,p.axis,p.pos);let m=this._partResult,h=m.mid,g=m.lMinX,_=m.lMinY,v=m.lMinZ,y=m.lMaxX,b=m.lMaxY,x=m.lMaxZ,S=m.rMinX,C=m.rMinY,w=m.rMinZ,T=m.rMaxX,E=m.rMaxY,D=m.rMaxZ;return h===e||h===t?(d.triangleOffset=e,d.triangleCount=f,this.updateProgress(f,i),d):(d.leftChild=this.buildNodeRecursiveToDepth(e,h,n-1,r-1,i,g,_,v,y,b,x),d.rightChild=this.buildNodeRecursiveToDepth(h,t,n-1,r-1,i,S,C,w,T,E,D),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new O;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}w(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=S(r);for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,i[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,i[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else i[a]=n.triangleOffset,i[a+1]=n.triangleCount,i[a+3]=x}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}w(t.length,`BLAS node count`);let r=new Float32Array(t.length*16),i=[],a=S(r);for(let e=0;e<t.length;e++){let n=t[e],o=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[o]=e.minX,r[o+1]=e.minY,r[o+2]=e.minZ,a[o+3]=e._flatIndex,r[o+4]=e.maxX,r[o+5]=e.maxY,r[o+6]=e.maxZ,a[o+7]=t._flatIndex,r[o+8]=t.minX,r[o+9]=t.minY,r[o+10]=t.minZ,r[o+12]=t.maxX,r[o+13]=t.maxY,r[o+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+2]=t,a[o+3]=1073741826,i.push({taskId:t,flatIndex:e})}else a[o]=n.triangleOffset,a[o+1]=n.triangleCount,a[o+3]=x}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;w(a,`assembled BLAS node count`);let o=new Float32Array(a*16),s=S(o);o.set(e);let c=new Map;for(let e of n)c.set(e.taskId,e.flatIndex);let l=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=l*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;s[t+3]<x&&(s[t+3]+=l,s[t+7]+=l)}let u=c.get(t.taskId);if(u!==void 0){let e=u*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}l+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};self.onmessage=function(t){let{tasks:r,sharedTriangleData:i,sharedCentroids:a,sharedBMin:o,sharedBMax:s,sharedIndices:c,triangleCount:l,maxLeafSize:u,numBins:d,maxBins:f,minBins:p,treeletConfig:m,reinsertionConfig:h,reportProgress:g}=t.data;for(let t=0;t<r.length;t++){let _=r[t];try{let t=new k;t.maxLeafSize=u,t.numBins=d,t.maxBins=f,t.minBins=p,t.triangles=new Float32Array(i),t.centroids=new Float32Array(a),t.bMin=new Float32Array(o),t.bMax=new Float32Array(s),t.indices=new Uint32Array(c),t.totalTriangles=l,t.totalNodes=0,t.processedTriangles=0,t.lastProgressUpdate=performance.now(),t.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,initTime:0,sahBuildTime:0,reorderTime:0};let r=g?e=>{self.postMessage({type:`progress`,taskId:_.taskId,progress:e})}:null,v=performance.now(),y=t.buildNodeRecursive(_.start,_.end,_.depth,r,_.preMinX,_.preMinY,_.preMinZ,_.preMaxX,_.preMaxY,_.preMaxZ);if(m&&m.enabled&&_.end-_.start>1e3){let n=_.end-_.start>5e4,r=n?3:m.size||5,i=n?10:20,a=new e(t.traversalCost,t.intersectionCost);a.setTreeletSize(r),a.setMinImprovement(m.minImprovement||.02),a.setMaxTreelets(i);let o=m.passes||1;for(let e=0;e<o;e++)try{a.optimizeBVH(y,null)}catch(t){console.error(`[BVHSubtreeWorker] Treelet pass ${e+1} error:`,t);break}}if(h&&h.enabled&&_.end-_.start>1e3){let e=new n(t.traversalCost,t.intersectionCost);h.batchSizeRatio&&e.setBatchSizeRatio(h.batchSizeRatio),h.maxIterations&&e.setMaxIterations(h.maxIterations);try{e.optimizeBVH(y,null)}catch(e){console.error(`[BVHSubtreeWorker] Reinsertion error:`,e)}}t.applySAOrdering(y);let b=t.flattenBVH(y),x=b.length/16,S=performance.now()-v;console.log(`[BVHSubtreeWorker] Task ${_.taskId}: ${(_.end-_.start).toLocaleString()} triangles, ${x} nodes, ${Math.round(S)}ms`),self.postMessage({type:`subtreeResult`,taskId:_.taskId,flatData:b,nodeCount:x},[b.buffer])}catch(e){console.error(`[BVHSubtreeWorker] Task ${_.taskId} error:`,e),self.postMessage({type:`error`,taskId:_.taskId,error:e.message})}}};",vu=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,_u],{type:`text/javascript;charset=utf-8`});function yu(e){let t;try{if(t=vu&&(self.URL||self.webkitURL).createObjectURL(vu),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(_u),{type:`module`,name:e?.name})}}qt(),Kl(()=>new gu);var bu=Pt(`bvh`),xu=20,Su=5e4,Cu=8;function wu(e,t,n,r){let i=e.byteLength/(xu*4),a=Math.min(navigator.hardwareConcurrency||4,Cu),o=Math.ceil(Math.log2(a*2.5+1));return bu.debug(`parallel build ${Y.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let c=new SharedArrayBuffer(e.byteLength);new Uint32Array(c).set(e),e=null;let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*xu*4),h=new gu,g=null,_=[h],v={id:null},y=!1,b=()=>{v.id&&=(clearTimeout(v.id),null);for(let e of _)try{e.terminate()}catch{}},x=e=>{if(y)return;y=!0,bu.warn(`parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Uint32Array(i).set(new Uint32Array(c)),s(Eu(new Uint32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,Tu(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r).catch(e=>x(e.message));return}if(t.type===`assembleResult`){y=!0,b();let e=new Uint32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{bu.warn(`parallel build setup failed:`,e),c(e)})})}async function Tu(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g){let{topFlatData:_,topNodeCount:v,frontierTasks:y,frontierMap:b}=e;if(!y||y.length===0){bu.debug(`no frontier tasks, assembling with top-level tree only`),u.postMessage({type:`assemble`,topFlatData:_,topNodeCount:v,frontierMap:[],subtreeResults:[],sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},[_.buffer]);return}bu.debug(`phase 2 distributing ${y.length} tasks across ${t} workers`);let x=[...y].sort((e,t)=>t.end-t.start-(e.end-e.start)),S=Array.from({length:Math.min(t,x.length)},()=>[]),C=Array(S.length).fill(0);for(let e of x){let t=0;for(let e=1;e<C.length;e++)C[e]<C[t]&&(t=e);S[t].push(e),C[t]+=e.end-e.start}let w=[],T=0,E=y.length,D=y.reduce((e,t)=>e+(t.end-t.start),0),O=0;h.id=setTimeout(()=>{p(`Phase 2 timeout (30s)`)},3e4);let k=()=>{clearTimeout(h.id),h.id=null,l&&l(85);let t=[];e.topFlatData&&e.topFlatData.buffer&&t.push(e.topFlatData.buffer);for(let e of w)e.flatData&&e.flatData.buffer&&t.push(e.flatData.buffer);u.postMessage({type:`assemble`,topFlatData:e.topFlatData,topNodeCount:v,frontierMap:b,subtreeResults:w,sharedTriangleData:n,sharedIndices:o,sharedReorderBuffer:s,triangleCount:c},t)},A=S.length;for(let e=0;e<A;e++){let t=S[e];if(t.length===0)continue;let s=new yu;d.push(s),s.onerror=e=>{p(`subtree worker error: ${e.message}`)},s.onmessage=e=>{let t=e.data;if(t.type===`error`){p(`subtree task ${t.taskId} error: ${t.error}`);return}if(t.type===`progress`&&l){let e=30+Math.floor(O/D*55);l(Math.min(e,85));return}if(t.type===`subtreeResult`){w.push({taskId:t.taskId,flatData:t.flatData,nodeCount:t.nodeCount});let e=y.find(e=>e.taskId===t.taskId);if(e&&(O+=e.end-e.start),T++,l){let e=30+Math.floor(O/D*55);l(Math.min(e,85))}if(T===E){for(let e of d)if(e!==u)try{e.terminate()}catch{}k()}}},s.postMessage({tasks:t,sharedTriangleData:n,sharedCentroids:r,sharedBMin:i,sharedBMax:a,sharedIndices:o,triangleCount:c,maxLeafSize:g.maxLeafSize,numBins:g.numBins,maxBins:g.maxBins,minBins:g.minBins,treeletConfig:g.treeletOptimization,reinsertionConfig:g.reinsertionOptimization,reportProgress:!!l})}}function Eu(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=new gu,s=e.byteLength/(xu*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*xu*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Uint32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])})().catch(e=>{bu.warn(`single worker fallback failed:`,e),a(e)})})}function Du(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Su}var Ou=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function ku(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function Au(e,t,n){let r=ku(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(Ou),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function ju(e,t,n,r){for(let i=0;i<4;i++){let a=n+i*4,o=t[a],s=t[a+1],c=t[a+2],l=t[a+3];for(let t=0;t<4;t++)r[i*4+t]=e[t]*o+e[4+t]*s+e[8+t]*c+e[12+t]*l}return r}function Mu(e){for(let t=0;t<16;t++)if(e[t]!==Ou[t])return!1;return!0}function Nu(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=0;i<8;i++){let a=e[t+(i&1?3:0)],f=e[t+(i&2?4:1)],p=e[t+(i&4?5:2)],m=n[r]*a+n[r+4]*f+n[r+8]*p+n[r+12],h=n[r+1]*a+n[r+5]*f+n[r+9]*p+n[r+13],g=n[r+2]*a+n[r+6]*f+n[r+10]*p+n[r+14];m<o&&(o=m),m>l&&(l=m),h<s&&(s=h),h>u&&(u=h),g<c&&(c=g),g>d&&(d=g)}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}function Pu(e,t){for(let n=0;n<16;n++)if(e[t+n]!==Ou[n])return!1;return!0}var Fu=class{constructor(){this.count=0,this.templateCount=0,this.totalBLASNodes=0,this.tlasNodeCount=0,this.allocate(0)}allocate(e,t=e,n=null,r=null){this.count=e,this.templateCount=t,this.isSet=new Uint8Array(e),this.sourceMesh=r&&r.length>=e?r:new Int32Array(e),this.tlasLeafIndex=new Int32Array(e).fill(-1),this.visible=new Uint8Array(e).fill(1),this.flipWinding=new Uint8Array(e),this.tplBakeInverse=null,n&&n.length>=e*16?(this.world=n,this.worldPooled=!0):(this.world=new Float32Array(e*16),this.worldPooled=!1),this.tplTriOffset=new Int32Array(t),this.tplTriCount=new Int32Array(t),this.tplExpandedStart=new Int32Array(t),this.tplNodeCount=new Int32Array(t),this.tplBlasOffset=new Int32Array(t),this.tplOwner=new Int32Array(t).fill(-1),this.tplObjectAABB=new Float32Array(t*6),this._placementRuns=null,this.originalToBvhMap=new Map,this.bvhToOriginal=new Map,this.blasData=new Map}_place(e,t,n,r){this.isSet[e]=1,this.sourceMesh[e]=t;let i=e*16;if(!n){this.world.set(Ou,i),this.flipWinding[e]=0;return}if(n!==this.world)for(let e=0;e<16;e++)this.world[i+e]=n[r+e];this.flipWinding[e]=+(ku(this.world,i)<0)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a,matrixWorld:o=null,matrixOffset:s=0,expandedStart:c=null,sourceMesh:l=null}){let u=l??e;this._place(e,u,o,s),this.tplTriOffset[u]=n,this.tplTriCount[u]=r,this.tplExpandedStart[u]=c??n,this.tplNodeCount[u]=t,this.tplOwner[u]=e,i&&this.originalToBvhMap.set(u,i),a&&this.blasData.set(u,a)}setAlias(e,t,n=null,r=null,i=null,a=0){if(!this.isSet[t])throw Error(`InstanceTable.setAlias: owner ${t} not built`);let o=i??e,s=this.sourceMesh[t];this._place(e,o,n,a),o!==s&&(this.tplTriOffset[o]=this.tplTriOffset[s],this.tplTriCount[o]=this.tplTriCount[s],this.tplNodeCount[o]=this.tplNodeCount[s],this.tplExpandedStart[o]=r??this.tplExpandedStart[s],this.tplOwner[o]=this.tplOwner[s])}get setCount(){let e=0;for(let t=0;t<this.count;t++)e+=this.isSet[t];return e}setPlacementMatrix(e,t,n=0){this._place(e,this.sourceMesh[e],t,n)}placementRunOf(e){if(!this._placementRuns){let e=this._placementRuns=new Map;for(let t=0;t<this.count;t++){let n=this.sourceMesh[t],r=e.get(n);r?r.count++:e.set(n,{start:t,count:1})}}return this._placementRuns.get(e)??null}isOwner(e){return this.tplOwner[this.sourceMesh[e]]===e}triOffsetOf(e){return this.tplTriOffset[this.sourceMesh[e]]}triCountOf(e){return this.tplTriCount[this.sourceMesh[e]]}expandedStartOf(e){return this.tplExpandedStart[this.sourceMesh[e]]}blasOffsetOf(e){return this.tplBlasOffset[this.sourceMesh[e]]}blasNodeCountOf(e){return this.tplNodeCount[this.sourceMesh[e]]}setBlasNodeCount(e,t){this.tplNodeCount[this.sourceMesh[e]]=t}setBvhToOriginal(e,t){this.bvhToOriginal.set(this.sourceMesh[e],t)}bvhToOriginalOf(e){let t=this.sourceMesh[e],n=this.bvhToOriginal.get(t);if(n)return n;let r=this.tplOwner[t];return(r>=0?this.bvhToOriginal.get(this.sourceMesh[r]):null)||null}matrixWorldOf(e){return this.world.subarray(e*16,e*16+16)}matrixInverseOf(e){return Au(this.world,e*16,new Float64Array(16))}writeWorldAABB(e,t,n){if(!this.isSet[e]){for(let e=0;e<6;e++)t[n+e]=0;return}Nu(this.tplObjectAABB,this.sourceMesh[e]*6,this.world,e*16,t,n)}writeWorldAABBs(e){let t=this.tplObjectAABB,n=this.world,r=this.sourceMesh,i=this.isSet;for(let a=0;a<this.count;a++){let o=a*6;if(!i[a]){e[o]=0,e[o+1]=0,e[o+2]=0,e[o+3]=0,e[o+4]=0,e[o+5]=0;continue}Nu(t,r[a]*6,n,a*16,e,o)}}entryAt(e){if(!this.isSet[e])return null;let t=this.sourceMesh[e],n=this.tplOwner[t];return{meshIndex:e,blasOffset:this.tplBlasOffset[t],blasNodeCount:this.tplNodeCount[t],triOffset:this.tplTriOffset[t],triCount:this.tplTriCount[t],expandedStart:this.tplExpandedStart[t],sourceMesh:t,sharedFrom:n===e?null:n,matrixWorld:this.matrixWorldOf(e),matrixInverse:this.matrixInverseOf(e),flipWinding:!!this.flipWinding[e],bvhToOriginal:this.bvhToOriginal.get(t)||null,visible:!!this.visible[e],tlasLeafIndex:this.tlasLeafIndex[e]}}setVisibility(e,t){this.isSet[e]&&(this.visible[e]=+!!t)}computeAABBs(e){for(let t=0;t<this.templateCount;t++){if(this.tplOwner[t]<0)continue;let n=this.blasData.get(t);n&&this._readRootAABB(n,t,e,this.tplObjectAABB,t*6)}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0||this.blasData.has(e))continue;let n=this.sourceMesh[t];n!==e&&this.tplObjectAABB.copyWithin(e*6,n*6,n*6+6)}}recomputeAABB(e,t,n){let r=this.sourceMesh[e],i=this.tplBlasOffset[r],a=t.chunks?t.chunkFor(i).subarray(t.baseOf(i),t.baseOf(i)+16):t.subarray(i*16,i*16+16);this._readRootAABB(a,r,n,this.tplObjectAABB,r*6)}_readRootAABB(e,t,n,r,i){if(!e||lt(e)[3]===ct.TRIANGLE_LEAF){this._computeAABBFromTriangles(t,n,r,i);return}r[i]=Math.min(e[0],e[8]),r[i+1]=Math.min(e[1],e[9]),r[i+2]=Math.min(e[2],e[10]),r[i+3]=Math.max(e[4],e[12]),r[i+4]=Math.max(e[5],e[13]),r[i+5]=Math.max(e[6],e[14])}_computeAABBFromTriangles(e,t,n,r){let i=$e.FLOATS_PER_TRIANGLE,a=t&&t.chunks?t.viewAs(Float32Array):null,o=a?null:t instanceof Float32Array?t:new Float32Array(t.buffer,t.byteOffset,t.length),s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0,p=this.tplTriOffset[e],m=this.tplTriCount[e];for(let e=0;e<m;e++){let t=p+e,n=a?a.chunkFor(t):o,r=a?a.baseOf(t):t*i;for(let e=0;e<=8;e+=4){let t=n[r+e],i=n[r+e+1],a=n[r+e+2];t<s&&(s=t),i<c&&(c=i),a<l&&(l=a),t>u&&(u=t),i>d&&(d=i),a>f&&(f=a)}}n[r]=s,n[r+1]=c,n[r+2]=l,n[r+3]=u,n[r+4]=d,n[r+5]=f}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e=0;e<this.templateCount;e++){let n=this.tplOwner[e];n<0||this.sourceMesh[n]!==e||(this.tplBlasOffset[e]=t,t+=this.tplNodeCount[e])}for(let e=0;e<this.templateCount;e++){let t=this.tplOwner[e];if(t<0)continue;let n=this.sourceMesh[t];n!==e&&(this.tplBlasOffset[e]=this.tplBlasOffset[n])}this.totalBLASNodes=t-e,ut(t,`combined TLAS + BLAS node count`)}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}clear(){this.allocate(0),this.totalBLASNodes=0,this.tlasNodeCount=0}},Iu=16,Lu=32,Ru=e=>e<Lu?e:Lu,zu=8,Bu=64,Vu=new Float64Array(16),Hu=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(Lu*3),this._binBounds=new Float64Array(Lu*6*3),this._binSuffix=new Float64Array(Lu),this._binSuffixCount=new Int32Array(Lu),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let r=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};ut(r,`TLAS node count`);let i=r*Iu;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer,o=lt(a);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let s=this._order;for(let e=0;e<n;e++)s[e]=e;this._ensureStack(Bu);let c=0,l=0,u=0,d=n,f=this._bounds;this._rangeBounds(t,s,u,d,f,0);let p=f[0],m=f[1],h=f[2],g=f[3],_=f[4],v=f[5];for(;;){if(d-u===1){let e=l*Iu;o[e]=0,o[e+1]=s[u],a[e+2]=0,o[e+3]=ct.BLAS_POINTER_LEAF}else{let e=this._partition(t,s,u,d,p,m,h,g,_,v),n=e-u,r=l+1,i=r+(n*2-1),y=l*Iu;a[y]=f[0],a[y+1]=f[1],a[y+2]=f[2],o[y+3]=r,a[y+4]=f[3],a[y+5]=f[4],a[y+6]=f[5],o[y+7]=i,a[y+8]=f[6],a[y+9]=f[7],a[y+10]=f[8],a[y+11]=0,a[y+12]=f[9],a[y+13]=f[10],a[y+14]=f[11],a[y+15]=0;let b=n<=d-e,x=b?0:6,S=b?6:0;c=this._push(c,b?i:r,b?e:u,b?d:e,f,S),l=b?r:i,b?d=e:u=e,p=f[x],m=f[x+1],h=f[x+2],g=f[x+3],_=f[x+4],v=f[x+5];continue}if(c===0)break;c--;let e=c*3,n=c*6;l=this._stackI[e],u=this._stackI[e+1],d=this._stackI[e+2],p=this._stackB[n],m=this._stackB[n+1],h=this._stackB[n+2],g=this._stackB[n+3],_=this._stackB[n+4],v=this._stackB[n+5]}return{data:a.subarray(0,i),nodeCount:r}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,r){let i=r.world,a=r.sourceMesh,o=r.tplBlasOffset,s=r.visible,c=r.tlasLeafIndex,l=lt(t);for(let r=0;r<n;r++){let n=r*Iu;if(l[n+3]!==ct.BLAS_POINTER_LEAF)continue;let u=l[n+1]&st;l[n]=o[a[u]],t[n+2]=+!!s[u],e.writeLeafMatrix(t,l,n,i,u),c[u]=r}}static writeLeafMatrix(e,t,n,r,i){let a=Vu;Au(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(Pu(r,i*16)?ot:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=zu)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let u=this._surfaceArea(i,a,o,s,c,l);if(!(u>0)||!isFinite(u))return n;let d=1/0,f=1/0,p=1/0,m=-1/0,h=-1/0,g=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<d&&(d=r),r>m&&(m=r),a<f&&(f=a),a>h&&(h=a),o<p&&(p=o),o>g&&(g=o)}let _=this._extent,v=this._cMin;_[0]=m-d,_[1]=h-f,_[2]=g-p,v[0]=d,v[1]=f,v[2]=p;let y=1/0,b=-1,x=-1,S=this._binCounts,C=this._binBounds,w=_[0]>1e-12,T=_[1]>1e-12,E=_[2]>1e-12;if(!w&&!T&&!E)return n;let D=Ru(r-n),O=w?D/_[0]:0,k=T?D/_[1]:0,A=E?D/_[2]:0;S.fill(0,0,D*3);for(let e=0;e<D*3;e++){let t=e*6;C[t]=C[t+1]=C[t+2]=1/0,C[t+3]=C[t+4]=C[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?O:e===1?k:A;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-v[e])*t|0;n<0?n=0:n>=D&&(n=D-1),n+=e*D,S[n]++;let i=n*6;r<C[i]&&(C[i]=r),a<C[i+1]&&(C[i+1]=a),o<C[i+2]&&(C[i+2]=o),s>C[i+3]&&(C[i+3]=s),c>C[i+4]&&(C[i+4]=c),l>C[i+5]&&(C[i+5]=l)}}for(let e=0;e<3;e++){if(!(_[e]>1e-12))continue;let t=e*D,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,d=0;for(let e=D-1;e>=1;e--){let u=(t+e)*6;C[u]<i&&(i=C[u]),C[u+1]<a&&(a=C[u+1]),C[u+2]<o&&(o=C[u+2]),C[u+3]>s&&(s=C[u+3]),C[u+4]>c&&(c=C[u+4]),C[u+5]>l&&(l=C[u+5]),d+=S[t+e],n[e]=d?this._surfaceArea(i,a,o,s,c,l):0,r[e]=d}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,v=-1/0,w=0;for(let i=1;i<D;i++){let a=(t+i-1)*6;if(C[a]<f&&(f=C[a]),C[a+1]<p&&(p=C[a+1]),C[a+2]<m&&(m=C[a+2]),C[a+3]>h&&(h=C[a+3]),C[a+4]>g&&(g=C[a+4]),C[a+5]>v&&(v=C[a+5]),w+=S[t+i-1],w===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,v)*w+n[i]*r[i])/u;o<y&&(y=o,b=e,x=i)}}if(b<0)return n;let j=D/_[b],M=v[b],N=this._bounds;N[0]=N[1]=N[2]=N[6]=N[7]=N[8]=1/0,N[3]=N[4]=N[5]=N[9]=N[10]=N[11]=-1/0;let P=n,F=r-1;for(;P<=F;){let n=t[P]*6,r=((e[n+b]+e[n+3+b])*.5-M)*j|0;r<0?r=0:r>=D&&(r=D-1);let i=r<x?0:6;if(e[n]<N[i]&&(N[i]=e[n]),e[n+1]<N[i+1]&&(N[i+1]=e[n+1]),e[n+2]<N[i+2]&&(N[i+2]=e[n+2]),e[n+3]>N[i+3]&&(N[i+3]=e[n+3]),e[n+4]>N[i+4]&&(N[i+4]=e[n+4]),e[n+5]>N[i+5]&&(N[i+5]=e[n+5]),i===0)P++;else{let e=t[P];t[P]=t[F],t[F]=e,F--}}return P}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Uu=$e.FLOATS_PER_TRIANGLE*4,Wu=64,Gu=.9,Ku=64,qu=4,Ju=7040*1024*1024,Yu=9216*1024*1024,Xu=1.15,Zu=12*1024*1024*1024;function Qu({triangles:e,placements:t,geometryBytes:n=0}){let r={triangles:e*Uu,bvh:Math.ceil(e*Gu)*Wu,geometry:n,placements:t*Ku,orderMaps:e*qu};return r.total=r.triangles+r.bvh+r.geometry+r.placements+r.orderMaps,r}function $u(e,{chunkBytes:t=pn,shared:n=!1,allocate:r=null}={}){let i=Math.min(e,Zu),a=r??(n?e=>new SharedArrayBuffer(e):e=>new ArrayBuffer(e)),o=[],s=0;try{for(;s<i;){let e=Math.min(t,i-s);o.push(a(e)),s+=e}}catch{}for(let e=o.length-1;e>=0;e--)o[e]=null;return o.length=0,{placed:s,want:i,exhausted:s<i,capped:e>i}}var ed=class{constructor(){this.reset()}reset(){this.phase=`idle`,this.events=[],this.samples=[],this.allocatedBytes=0,this.peakLiveBytes=0,this.byPhase=Object.create(null)}mark(e){return this.phase=e,this.byPhase[e]??={allocated:0,chunks:0},this}alloc(e,t=`chunk`){if(!(e>0))return;let n=this.byPhase[this.phase]??={allocated:0,chunks:0};n.allocated+=e,n.chunks++,this.allocatedBytes+=e,this.events.push({phase:this.phase,bytes:e,what:t,at:performance.now()})}sample(e,t){let n=0;for(let e in t)n+=t[e]||0;return n>this.peakLiveBytes&&(this.peakLiveBytes=n),this.samples.push({label:e,phase:this.phase,total:n,parts:t,at:performance.now()}),n}get report(){return{allocatedBytes:this.allocatedBytes,peakLiveBytes:this.peakLiveBytes,byPhase:{...this.byPhase},samples:this.samples.slice()}}},td="let e,t;const n={MAX_BYTES_PER_TEXTURE:256*1024*1024,MAX_TEXTURE_DIMENSION:8192,CHUNK_SIZE:8,ADAPTIVE_CHUNK_SIZE:!0,MEMORY_SAFETY_FACTOR:.8};self.onmessage=async function(t){let{textures:n,maxTextureSize:a,method:o=`direct-transfer`}=t.data;try{e||r(a);let t=await i(n,a,o);self.postMessage(t,[t.data])}catch(e){console.error(`Worker processing failed:`,e),self.postMessage({error:e.message})}};function r(r){let i=Math.min(r,n.MAX_TEXTURE_DIMENSION);e=new OffscreenCanvas(i,i),t=e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0})}async function i(e,t,r){let i=h(e,t),o=i.maxWidth*i.maxHeight*e.length*4;if(o>n.MAX_BYTES_PER_TEXTURE)return console.log(`Large texture array detected (${(o/1024/1024).toFixed(2)}MB), using chunked processing`),await a(e,t,r);switch(r){case`direct-transfer`:return await d(e,t);case`offscreen-optimized`:return await p(e,t);case`imageBitmap-batch`:return await m(e,t);default:return await d(e,t)}}async function a(e,t,n){let{maxWidth:r,maxHeight:i}=h(e,t),a=e.length,c=o(r,i,a),l=Math.ceil(a/c);console.log(`Processing ${a} textures in ${l} chunks of up to ${c} textures each`),console.log(`Texture dimensions: ${r}x${i}, Est. memory per chunk: ${(r*i*c*4/1024/1024).toFixed(2)}MB`);let u;try{u=new Uint8Array(r*i*a*4)}catch{return console.warn(`Failed to allocate full texture array, reducing dimensions`),await f(e,g(e,t),n)}let d=r*i*c*4,p;try{p=new Uint8Array(d)}catch{return console.warn(`Failed to allocate chunk buffer, reducing dimensions`),await f(e,g(e,t),n)}for(let t=0;t<l;t++){let n=t*c,o=Math.min(n+c,a),l=o-n,d=await s(e.slice(n,o),r,i,p.subarray(0,r*i*l*4)),f=n*r*i*4,m=l*r*i*4;u.set(new Uint8Array(d.data.slice(0,m)),f),t%2==1&&await new Promise(e=>setTimeout(e,0))}return{data:u.buffer,width:r,height:i,depth:a}}function o(e,t,r){if(!n.ADAPTIVE_CHUNK_SIZE)return Math.min(n.CHUNK_SIZE,r);let i=e*t*4/(1024*1024),a;return a=i<=1?16:i<=4?8:i<=16?4:2,Math.min(a,r,n.CHUNK_SIZE*2)}async function s(n,r,i,a){(e.width!==r||e.height!==i)&&(e.width=r,e.height=i);let o=r*i*4;t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await c(t,a,e*o,r,i)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=e*o;a.fill(0,n,n+o)}}return{data:a.buffer,width:r,height:i,depth:n.length}}async function c(e,n,r,i,a){let o;if(e.isDirect&&e.bitmap)o=e.bitmap;else if(e.isImageData&&e.data){let t=new ImageData(new Uint8ClampedArray(e.data),e.width,e.height);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else if(e.isBlob){let t=new Blob([e.data]);o=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:`high`})}else throw Error(`Unknown texture data format`);t.clearRect(0,0,i,a),t.drawImage(o,0,0,i,a);let s=t.getImageData(0,0,i,a);n.set(s.data,r),(e.isImageData||e.isBlob)&&o.close()}async function l(e,t,n){let r;try{r=new Uint8Array(t*n*e.length*4)}catch(r){console.warn(`Failed to allocate texture array in processTextureChunk, reducing dimensions`);let i=Math.max(1,Math.floor(t/2)),a=Math.max(1,Math.floor(n/2));if(i===t&&a===n)throw r;return await l(e,i,a)}return await s(e,t,n,r)}async function u(e,t,n,r,i){await c(e,n,r*i*4*t,r,i)}async function d(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`direct-transfer`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let t=n[e];try{await u(t,e,c,i,o)}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function f(e,t,n){let{maxWidth:r,maxHeight:i}=t;return console.log(`Using reduced dimensions: ${r}x${i}`),await l(e,r,i,n)}async function p(n,r){let{maxWidth:i,maxHeight:o}=h(n,r);(e.width!==i||e.height!==o)&&(e.width=i,e.height=o);let s=n.length,c;try{c=new Uint8Array(i*o*s*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`offscreen-optimized`)}t.imageSmoothingEnabled=!0,t.imageSmoothingQuality=`high`;for(let e=0;e<n.length;e++){let r=n[e];try{let n;if(r.isBlob){let e=new Blob([r.data]);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(r.data),r.width,r.height);n=await createImageBitmap(e,{resizeWidth:i,resizeHeight:o,resizeQuality:`high`})}t.clearRect(0,0,i,o),t.drawImage(n,0,0);let a=t.getImageData(0,0,i,o),s=i*o*4*e;c.set(a.data,s),n.close()}catch(t){console.warn(`Failed to process texture ${e}:`,t);let n=i*o*4*e;c.fill(0,n,n+i*o*4)}}return{data:c.buffer,width:i,height:o,depth:s}}async function m(n,r){let{maxWidth:i,maxHeight:s}=h(n,r),c=n.length,l;try{l=new Uint8Array(i*s*c*4)}catch(e){return console.error(`Failed to allocate texture array:`,e),await a(n,r,`imageBitmap-batch`)}let u=Math.min(o(i,s,n.length),n.length);for(let r=0;r<n.length;r+=u){let a=Math.min(r+u,n.length),o=[];for(let e=r;e<a;e++){let t=n[e],r;if(t.isBlob){let e=new Blob([t.data]);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}else{let e=new ImageData(new Uint8ClampedArray(t.data),t.width,t.height);r=createImageBitmap(e,{resizeWidth:i,resizeHeight:s,resizeQuality:`high`})}o.push(r.then(t=>({bitmap:t,index:e})))}let c=await Promise.all(o);e.width=i,e.height=s,t.imageSmoothingEnabled=!1;for(let{bitmap:e,index:n}of c){t.clearRect(0,0,i,s),t.drawImage(e,0,0);let r=t.getImageData(0,0,i,s),a=i*s*4*n;l.set(r.data,a),e.close()}}return{data:l.buffer,width:i,height:s,depth:c}}function h(e,t){let r=0,i=0;for(let t of e)r=Math.max(r,t.width||0),i=Math.max(i,t.height||0);let a=Math.min(t,n.MAX_TEXTURE_DIMENSION),o=Math.max(r,i);if(o>a){let e=a/o;r=Math.round(r*e),i=Math.round(i*e)}return r=Math.min(a,Math.max(4,Math.ceil(Math.max(1,r)/64)*64)),{maxWidth:r,maxHeight:Math.max(1,i)}}function g(e,t){let n=h(e,t);return{maxWidth:Math.max(64,Math.ceil(n.maxWidth/128)*64),maxHeight:Math.max(1,Math.floor(n.maxHeight/2))}}",nd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,td],{type:`text/javascript;charset=utf-8`});function rd(e){let t;try{if(t=nd&&(self.URL||self.webkitURL).createObjectURL(nd),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(td),{type:`module`,name:e?.name})}}ca();var id=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),ad=new Map;function od(){ad.clear();for(let e of oa.values())ad.set(e.id,id(e.cpu))}od(),Ui(od);function sd(e){return Wi(e)?.outputEncoded===!0}var cd=1/2.2;function ld(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function ud(e,t){let n=Wi(t);return n?n.appliesExposure?e:1:t===r.NoToneMapping?1:e}var dd=.2126,fd=.7152,pd=.0722;function md(e,t){if(t===1)return;let n=e[0]*dd+e[1]*fd+e[2]*pd;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function hd(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=ad.get(n)??ad.get(r.NoToneMapping),s=ud(t,n),c=sd(n),l=new Uint8ClampedArray(e.length),u=[0,0,0];for(let t=0;t<e.length;t+=4)u[0]=e[t]*s,u[1]=e[t+1]*s,u[2]=e[t+2]*s,md(u,i),o(u[0],u[1],u[2],1,u),c?(l[t]=u[0]*255+.5,l[t+1]=u[1]*255+.5,l[t+2]=u[2]*255+.5):(l[t]=ld(u[0])*255+.5,l[t+1]=ld(u[1])*255+.5,l[t+2]=ld(u[2])*255+.5),l[t+3]=a?e[t+3]*255+.5:255;return l}qt();var gd=Pt(`textures`),_d={toSRGB:null,toLinear:null};function vd(e){if(!_d[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?ld(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}_d[e]=t}return _d[e]}var yd=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=dt.CANVAS_POOL_SIZE}getCanvasWithContext(e,t,n=!1,r={}){let i={willReadFrequently:!0,alpha:!0,desynchronized:!0,...r},a=this.canvasContextPairs.pop();if(!a){let r;r=n&&typeof OffscreenCanvas<`u`?new OffscreenCanvas(e,t):document.createElement(`canvas`);let o=r.getContext(`2d`,i);a={canvas:r,context:o}}return a.canvas.width=e,a.canvas.height=t,a}releaseCanvasWithContext(e){this.canvasContextPairs.length<this.maxPoolSize&&(e.context.globalAlpha=1,e.context.globalCompositeOperation=`source-over`,e.context.imageSmoothingEnabled=!0,e.context.clearRect(0,0,e.canvas.width,e.canvas.height),e.canvas.width=1,e.canvas.height=1,this.canvasContextPairs.push(e))}getCanvas(e,t,n=!1){return this.getCanvasWithContext(e,t,n).canvas}getContext(e,t={}){let n=this.canvasContextPairs.find(t=>t.canvas===e);return n?n.context:e.getContext(`2d`,{willReadFrequently:!0,alpha:!0,desynchronized:!0,...t})}dispose(){this.canvasContextPairs=[]}},bd=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||Dt.MAX_BUFFER_MEMORY,this.allocatedBuffers=new WeakMap,this.sizeStrategy=e.sizeStrategy||`adaptive`}getOptimalSize(e){switch(this.sizeStrategy){case`exact`:return e;case`power2`:return 2**Math.ceil(Math.log2(e));default:return e<1024?e:e<1024*1024?Math.ceil(e/1024)*1024:2**Math.ceil(Math.log2(e))}}getBuffer(e,t=Float32Array){let n=this.getOptimalSize(e),r=`${t.name}-${n}`,i=(this.pools.get(r)||[]).pop();if(!i)try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch{this.cleanup();try{i=new t(n),this.memoryUsage+=i.byteLength,this.allocatedBuffers.set(i,!0)}catch(e){let r=n*t.BYTES_PER_ELEMENT/(1024*1024),i=this.memoryUsage/(1024*1024);throw Error(`Buffer allocation failed: requested ${r.toFixed(1)}MB, current usage: ${i.toFixed(1)}MB, max: ${(this.maxMemoryUsage/(1024*1024)).toFixed(1)}MB. Original error: ${e.message}`)}}return this.memoryUsage>this.maxMemoryUsage*Dt.CLEANUP_THRESHOLD&&this.cleanup(),this.checkMemoryHealth(),i.byteOffset+e*t.BYTES_PER_ELEMENT>i.buffer.byteLength&&(i=new t(e),this.memoryUsage+=i.byteLength),new t(i.buffer,i.byteOffset,e)}releaseBuffer(e,t=Float32Array){let n=(e.buffer.byteLength-e.byteOffset)/t.BYTES_PER_ELEMENT,r=this.getOptimalSize(n),i=`${t.name}-${r}`,a=this.pools.get(i)||[];a.length<dt.BUFFER_POOL_SIZE?(a.push(new t(e.buffer,e.byteOffset,n)),this.pools.set(i,a)):this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}cleanup(){let e=Array.from(this.pools.entries());e.slice(0,Math.floor(e.length/2)).forEach(([e,t])=>{t.forEach(e=>{this.allocatedBuffers.has(e)&&(this.memoryUsage-=e.byteLength,this.allocatedBuffers.delete(e))}),this.pools.delete(e)})}dispose(){this.pools.forEach(e=>{e.forEach(e=>{this.allocatedBuffers.has(e)&&this.allocatedBuffers.delete(e)})}),this.pools.clear(),this.memoryUsage=0}getMemoryStats(){return{currentUsage:this.memoryUsage,maxUsage:this.maxMemoryUsage,utilizationPercentage:this.memoryUsage/this.maxMemoryUsage*100,poolCount:this.pools.size,allocatedBufferCount:this.allocatedBuffers&&this.allocatedBuffers.size||0}}checkMemoryHealth(){let e=this.getMemoryStats();return e.utilizationPercentage>90?(console.warn(`Memory pool critical: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`critical`):e.utilizationPercentage>70?(console.warn(`Memory pool high: ${e.utilizationPercentage.toFixed(1)}% used (${(e.currentUsage/(1024*1024)).toFixed(1)}MB / ${(e.maxUsage/(1024*1024)).toFixed(1)}MB)`),`high`):`normal`}},xd=class{constructor(e=dt.CACHE_SIZE_LIMIT){this.cache=new Map,this.accessOrder=[],this.maxSize=e}generateHash(e){let t=``;for(let n of e)if(n?.image){let e=n.image.width||0,r=n.image.height||0,i=n.image.src||n.uuid||``,a=n.flipY===!1?`n`:`f`,o=`${n.colorSpace??``}|${n.userData?.ocioColorSpace??``}`;t+=`${e}x${r}_${i.slice(-8)}_${a}_${o}_`}return t+e.length}get(e){if(this.cache.has(e)){let t=this.cache.get(e);if(t?.userData&&t.userData.buffer===null){this.cache.delete(e);let t=this.accessOrder.indexOf(e);return t>-1&&this.accessOrder.splice(t,1),null}let n=this.accessOrder.indexOf(e);return n>-1&&this.accessOrder.splice(n,1),this.accessOrder.push(e),t}return null}set(e,t){if(this.cache.has(e)){let t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)}else this.cache.size>=this.maxSize&&this.evictLRU();this.cache.set(e,t),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){let e=this.accessOrder.shift(),t=this.cache.get(e);t&&t.dispose&&t.dispose(),this.cache.delete(e)}}dispose(){this.cache.forEach(e=>{e&&e.dispose&&e.dispose()}),this.cache.clear(),this.accessOrder=[]}},Sd=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=dt.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??dt.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new yd,this.bufferPool=new bd({maxMemory:e.maxBufferMemory||Dt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new xd,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){this._issues?.record(ln.TEXTURE_BUILD_FAILED,`${e} texture array failed to build — those surfaces render untextured`,{map:e,cause:String(t?.message??t)})}_clampTextureSize(e){let t=Math.floor(Number(e)||dt.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(dt.MIN_TEXTURE_WIDTH,Math.min(t,dt.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new xd,this.maxTextureSize)}detectCapabilities(){return{offscreenCanvas:typeof OffscreenCanvas<`u`,imageBitmap:typeof createImageBitmap<`u`,workers:typeof Worker<`u`,hardwareConcurrency:navigator.hardwareConcurrency||4}}selectOptimalMethod(){return this.capabilities.workers&&this.capabilities.offscreenCanvas?`worker-offscreen`:this.capabilities.imageBitmap?`imageBitmap`:`canvas`}_applyColorManagement(e,t,n,i=new Set){let a=so();if(!a?.hasConfig)return;let o=e?.image?.data;if(!o||!n)return;let s=t.filter(e=>e?.image),c=e.image.width*e.image.height*4,l=0,u=0,d=[];for(let e=0;e<s.length;e++){let t=e*c,n=Math.min(t+c,o.length);if(t>=o.length)break;let f=s[e],p=o.subarray(t,n),m=null;try{m=a.resolveTexture(f)}catch(t){gd.warn(`could not resolve the colour space of layer ${e}: ${t.message}`)}let h=m&&m.via!==`three`?m.colorSpace:null,g=f.type===r.FloatType||f.type===r.HalfFloatType;h&&(i.has(e)||g)&&(d.push(`${f.name||`layer ${e}`} (${h})`),h=null);try{a.convertTextureBytes(p,{space:h,encoding:`srgb`})&&(h?l++:u++)}catch(t){this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`colour conversion failed for layer ${e} — left in its original space`,{cause:String(t?.message??t),space:h})}}d.length&&this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`${d.length} colour map(s) name a colour space their stored bytes are no longer in (re-encoded or quantized on the way in); converted by primaries only`,{textures:d.slice(0,8)}),l+u!==0&&(e.needsUpdate=!0,gd.info(`colour maps into ${a.workingSpace}: ${l} by named space, ${u} by primaries, of ${s.length}`))}_harmonizeTransfer(e,t,n){let i=new Set,a=e?.image?.data;if(!a)return i;let o=t.filter(e=>e?.image),s=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,c=e.image.width*e.image.height*4,l=[];for(let e=0;e<o.length;e++){let t=o[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===s)continue;let u=vd(n?`toSRGB`:`toLinear`),d=e*c,f=Math.min(d+c,a.length);for(let e=d;e<f;e+=4)a[e]=u[a[e]],a[e+1]=u[a[e+1]],a[e+2]=u[a[e+2]];l.push(o[e].name||o[e].source?.uuid?.slice(0,8)||`layer ${e}`),i.add(e)}if(l.length===0)return i;e.needsUpdate=!0;let u=l.slice(0,4).join(`, `)+(l.length>4?`, +${l.length-4} more`:``);return n?gd.info(`re-encoded ${l.length}/${o.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${u}`):gd.warn(`decoded ${l.length}/${o.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${u}`),i}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=so()?.inputKey??`-`,r=`${t?`s`:`l`}:${n}:${this.textureCache.generateHash(e)}`,i=this.textureCache.get(r);if(i)return i;let{normalized:a,bitmapsToClose:o}=await this._normalizeTexturesForProcessing(e),s=this.selectProcessingStrategy(a),c;try{switch(s.method){case`worker-direct`:c=await this.processWithWorkerDirect(a);break;case`main-batch`:c=await this.processOnMainThreadBatch(a,s.batchSize);break;case`main-streaming`:c=await this.processOnMainThreadStreaming(a);break;default:c=await this.processOnMainThreadSync(a)}if(c){let n=this._harmonizeTransfer(c,e,t);this._applyColorManagement(c,e,t,n),this.textureCache.set(r,c)}return c}catch(n){this._issues?.warn(ln.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(a),i=this._harmonizeTransfer(r,e,t);return this._applyColorManagement(r,e,t,i),r}finally{for(let e of o)e.close()}}selectProcessingStrategy(e){let t=e.reduce((e,t)=>e+(t.image?.width||0)*(t.image?.height||0),0),n=t*4;return this.capabilities.workers&&n>Dt.MAX_TEXTURE_MEMORY?{method:`main-streaming`}:this.capabilities.workers&&t>2097152?{method:`worker-direct`}:t>524288?{method:`main-batch`,batchSize:Math.min(4,e.length)}:e.length>8?{method:`main-streaming`}:{method:`main-sync`}}async processWithWorkerDirect(e){for(;this.activeWorkers>=this.maxConcurrentWorkers;)await new Promise(e=>setTimeout(e,10));this.activeWorkers++;try{let t=new rd,n=await this.prepareTexturesForWorkerDirect(e),r=await new Promise((e,r)=>{t.onmessage=t=>{t.data.error?r(Error(t.data.error)):e(t.data)},t.onerror=r;let i=[];n.forEach(e=>{e.data instanceof ArrayBuffer?i.push(e.data):e.bitmap&&i.push(e.bitmap)}),t.postMessage({textures:n,maxTextureSize:this.maxTextureSize,method:`direct-transfer`},i)});return t.terminate(),this.createDataArrayTextureFromResult(r)}finally{this.activeWorkers--}}async prepareTexturesForWorkerDirect(e){let t=[];for(let n of e){if(!n?.image)continue;let e=n.flipY!==!1;try{let r=n.image;if(typeof createImageBitmap<`u`&&(r instanceof HTMLImageElement||typeof ImageBitmap<`u`&&r instanceof ImageBitmap||typeof HTMLCanvasElement<`u`&&r instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&r instanceof OffscreenCanvas)){let r=await createImageBitmap(n.image,{imageOrientation:e?`flipY`:`none`});t.push({bitmap:r,width:n.image.width,height:n.image.height,isDirect:!0})}else{let r=n.image.width,i=n.image.height,a=await createImageBitmap(n.image,{imageOrientation:e?`flipY`:`none`}),o=this.canvasPool.getCanvasWithContext(r,i);o.context.drawImage(a,0,0),a.close();let s=o.context.getImageData(0,0,r,i);t.push({data:s.data.buffer,width:r,height:i,isImageData:!0}),this.canvasPool.releaseCanvasWithContext(o)}}catch(e){console.warn(`Failed to prepare texture for worker:`,e)}}return t}async processOnMainThreadBatch(e,t){let n=e.filter(e=>e?.image);if(n.length===0)return this.createFallbackTexture();let{maxWidth:r,maxHeight:i}=this.calculateOptimalDimensions(n),a=n.length,o=this.bufferPool.getBuffer(r*i*a*4,Uint8Array);for(let e=0;e<n.length;e+=t){let a=Math.min(e+t,n.length),s=[];for(let t=e;t<a;t++){let e=n[t],a=e.flipY!==!1,o=createImageBitmap(e.image,{resizeWidth:r,resizeHeight:i,resizeQuality:`high`,imageOrientation:a?`flipY`:`none`});s.push(o.then(e=>({bitmap:e,index:t})))}let c=await Promise.all(s),l=this.canvasPool.getCanvasWithContext(r,i);l.context.imageSmoothingEnabled=!1;for(let{bitmap:e,index:t}of c){l.context.clearRect(0,0,r,i),l.context.drawImage(e,0,0);let n=l.context.getImageData(0,0,r,i),a=r*i*4*t;o.set(n.data,a),e.close()}this.canvasPool.releaseCanvasWithContext(l)}return this.createDataArrayTextureFromBuffer(o,r,i,a)}async processOnMainThreadStreaming(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l),e%Dt.STREAM_BATCH_SIZE===0&&await new Promise(e=>setTimeout(e,0))}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}async processOnMainThreadSync(e){let t=e.filter(e=>e?.image);if(t.length===0)return this.createFallbackTexture();let{maxWidth:n,maxHeight:r}=this.calculateOptimalDimensions(t),i=t.length,a=this.bufferPool.getBuffer(n*r*i*4,Uint8Array),o=this.canvasPool.getCanvasWithContext(n,r);o.context.imageSmoothingEnabled=!0,o.context.imageSmoothingQuality=`high`;for(let e=0;e<t.length;e++){let i=t[e],s=await createImageBitmap(i.image,{resizeWidth:n,resizeHeight:r,resizeQuality:`high`,imageOrientation:i.flipY===!1?`none`:`flipY`});o.context.clearRect(0,0,n,r),o.context.drawImage(s,0,0),s.close();let c=o.context.getImageData(0,0,n,r),l=n*r*4*e;a.set(c.data,l)}return this.canvasPool.releaseCanvasWithContext(o),this.createDataArrayTextureFromBuffer(a,n,r,i)}createMaterialRawData(e){let t=q.FLOATS_PER_MATERIAL,n=new Float32Array(e.length*t);for(let r=0;r<e.length;r++)cn(n,r*t,e[r]);return n}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=dt.VEC4_PER_BVH_NODE*dt.FLOATS_PER_VEC4;ut(t.length,`BVH node count`);let i=t.length*r,a=new Float32Array(i),o=lt(a);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,s=t[e],c=t[r];a[n]=s.boundsMin.x,a[n+1]=s.boundsMin.y,a[n+2]=s.boundsMin.z,o[n+3]=e,a[n+4]=s.boundsMax.x,a[n+5]=s.boundsMax.y,a[n+6]=s.boundsMax.z,o[n+7]=r,a[n+8]=c.boundsMin.x,a[n+9]=c.boundsMin.y,a[n+10]=c.boundsMin.z,a[n+12]=c.boundsMax.x,a[n+13]=c.boundsMax.y,a[n+14]=c.boundsMax.z}else o[n]=i.triangleOffset,o[n+1]=i.triangleCount,o[n+3]=ct.TRIANGLE_LEAF}return a}async createMaterialTextures(e){let{materials:t,maps:n,normalMaps:i,bumpMaps:a,roughnessMaps:o,metalnessMaps:s,emissiveMaps:c,displacementMaps:l}=e;console.log(`[TextureCreator] Creating material textures only`);let u=performance.now();try{if(!t||t.length===0)throw Error(`No materials provided for texture creation`);this.textureCache.dispose(),this.textureCache=new xd;let e=[];for(let[t,r]of[[`albedo`,n],[`normal`,i],[`bump`,a],[`roughness`,o],[`metalness`,s],[`emissive`,c],[`displacement`,l]])!r||r.length===0||e.push(this.createTexturesToDataTexture(r).then(e=>({type:t,texture:e})).catch(e=>(this._reportTextureFailure(t,e),{type:t,texture:null})));let d=await Promise.allSettled(e),f=d.find(e=>e.status===`rejected`);if(f)throw f.reason;let p={};d.forEach(e=>{if(e.status===`fulfilled`&&e.value){let{type:t,texture:n}=e.value;if(n)switch(t){case`albedo`:n.colorSpace=r.SRGBColorSpace,p.albedoTexture=n;break;case`normal`:p.normalTexture=n;break;case`bump`:p.bumpTexture=n;break;case`roughness`:p.roughnessTexture=n;break;case`metalness`:p.metalnessTexture=n;break;case`emissive`:n.colorSpace=r.SRGBColorSpace,p.emissiveTexture=n;break;case`displacement`:p.displacementTexture=n;break}}});let m=performance.now()-u;return console.log(`[TextureCreator] Material texture creation complete (${m.toFixed(2)}ms)`),p}catch(e){throw console.error(`[TextureCreator] Material texture creation error:`,e),Error(`Material texture creation failed: ${e.message}`)}}calculateOptimalDimensions(e){let t=0,n=0;for(let r of e)t=Math.max(t,r.image.width),n=Math.max(n,r.image.height);let r=Math.max(t,n);if(r>this.maxTextureSize){let e=this.maxTextureSize/r;t=Math.round(t*e),n=Math.round(n*e)}return{maxWidth:pt(t,this.maxTextureSize),maxHeight:Math.max(1,n)}}createDataArrayTextureFromResult(e){let t=(e.data instanceof ArrayBuffer,new Uint8Array(e.data));return this.createDataArrayTextureFromBuffer(t,e.width,e.height,e.depth)}createDataArrayTextureFromBuffer(e,t,n,i){let a=new r.DataArrayTexture(e,t,n,i);a.minFilter=r.LinearFilter,a.magFilter=r.LinearFilter,a.wrapS=r.RepeatWrapping,a.wrapT=r.RepeatWrapping,a.format=r.RGBAFormat,a.type=r.UnsignedByteType,a.needsUpdate=!0,a.generateMipmaps=!1,a.userData={buffer:e,bufferType:Uint8Array};let o=a.dispose.bind(a);return a.dispose=()=>{a.userData.buffer&&(this.bufferPool.releaseBuffer(a.userData.buffer,a.userData.bufferType),a.userData.buffer=null),o()},a}async _normalizeTexturesForProcessing(e){let t=[],n=[],i=[];for(let n of e)if(n?.image){if(n.isCompressedTexture&&n.format===r.RGBAFormat&&n.mipmaps?.[0]?.data){let e=n.mipmaps[0],r=t.length;t.push(null),i.push({index:r,flipY:n.flipY,promise:Cd(e.data,e.width,e.height)});continue}if(n.isCompressedTexture){console.warn(`[TextureCreator] GPU-compressed texture in mixed group — using placeholder`),t.push(null);continue}if(n.image.data&&!(n.image instanceof HTMLImageElement)&&!(n.image instanceof HTMLCanvasElement)&&!(typeof ImageBitmap<`u`&&n.image instanceof ImageBitmap)){let e=t.length;t.push(null),i.push({index:e,flipY:n.flipY,promise:Cd(n.image.data,n.image.width,n.image.height)});continue}t.push(n)}if(i.length>0){let e=await Promise.allSettled(i.map(e=>e.promise));for(let r=0;r<i.length;r++){let{index:a,flipY:o}=i[r],s=e[r];if(s.status===`fulfilled`){let e=s.value;n.push(e),t[a]={image:e,flipY:o}}else console.warn(`[TextureCreator] Failed to create ImageBitmap:`,s.reason)}}for(let e=0;e<t.length;e++)if(t[e]===null){let r=new Uint8ClampedArray([255,255,255,255]),i=await createImageBitmap(new ImageData(r,1,1));n.push(i),t[e]={image:i,flipY:!1}}return{normalized:t,bitmapsToClose:n}}createFallbackTexture(){let e=new r.DataArrayTexture(new Uint8Array([255,255,255,255]),1,1,1);return e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e.format=r.RGBAFormat,e.type=r.UnsignedByteType,e.needsUpdate=!0,e.generateMipmaps=!1,e}dispose(){this.canvasPool.dispose(),this.bufferPool.dispose(),this.textureCache.dispose()}};function Cd(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var wd=class{constructor(){this.maxLeafSize=8}build(e){let t=e.length;if(t===0){let e=new Float32Array(16);return e[7]=1,e[14]=1,e[15]=-1,{nodeData:e,nodeCount:1,sortedPerm:new Int32Array,bitTrails:new Float32Array}}let n=new Int32Array(t);for(let e=0;e<t;e++)n[e]=e;let r=2*t+4,i=new Float32Array(r*16),a=0,o=new Float32Array(t),s=(t,r,c,l)=>{let u=a++,d=u*16,f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,v=0,y=1/0,b=1/0,x=1/0,S=-1/0,C=-1/0,w=-1/0;for(let i=t;i<r;i++){let t=e[n[i]];f=Math.min(f,t.bMinX),p=Math.min(p,t.bMinY),m=Math.min(m,t.bMinZ),h=Math.max(h,t.bMaxX),g=Math.max(g,t.bMaxY),_=Math.max(_,t.bMaxZ),v+=t.power,y=Math.min(y,t.cx),b=Math.min(b,t.cy),x=Math.min(x,t.cz),S=Math.max(S,t.cx),C=Math.max(C,t.cy),w=Math.max(w,t.cz)}i[d+0]=f,i[d+1]=p,i[d+2]=m,i[d+3]=v,i[d+4]=h,i[d+5]=g,i[d+6]=_;let T=r-t,E;if(T<=this.maxLeafSize){i[d+7]=1,i[d+8]=t,i[d+9]=T,i[d+10]=0,i[d+11]=0,E=null;for(let i=t;i<r;i++){let t=e[n[i]];E=Ed(E,Td(t)),o[i]=c}E||={ax:0,ay:0,az:1,cosO:-1}}else{let a=S-y,o=C-b,u=w-x,f;f=a>=o&&a>=u?0:o>=u?1:2;let p=[`cx`,`cy`,`cz`][f],m=t+r>>1;this._nthElement(n,e,t,r,m,p),i[d+7]=0;let h=s(t,m,c,l+1),g=s(m,r,c+2**l,l+1);i[d+8]=h.nodeIndex,i[d+9]=g.nodeIndex,i[d+10]=0,i[d+11]=0,E=Ed(h.cone,g.cone)}return i[d+12]=E.ax,i[d+13]=E.ay,i[d+14]=E.az,i[d+15]=E.cosO,{nodeIndex:u,cone:E}};s(0,t,0,0);let c=new Int32Array(t);for(let e=0;e<t;e++)c[e]=n[e];let l=new Float32Array(a*16);return l.set(i.subarray(0,a*16)),console.log(`[LightBVHBuilder] Built BVH: ${a} nodes for ${t} emissive triangles`),{nodeData:l,nodeCount:a,sortedPerm:c,bitTrails:o}}_nthElement(e,t,n,r,i,a){for(;n<r-1;){let o=n+r>>1,s=t[e[o]][a],c=e[o];e[o]=e[r-1],e[r-1]=c;let l=n;for(let i=n;i<r-1;i++)t[e[i]][a]<s&&(c=e[i],e[i]=e[l],e[l]=c,l++);if(c=e[l],e[l]=e[r-1],e[r-1]=c,l===i)return;l<i?n=l+1:r=l}}};function Td(e){return e.twoSided?{ax:e.nx,ay:e.ny,az:e.nz,cosO:-1}:{ax:e.nx,ay:e.ny,az:e.nz,cosO:1}}function Ed(e,t){if(!e)return t;if(!t||e.cosO<=-1)return e;if(t.cosO<=-1)return t;let n=Math.min(Math.max(e.cosO,-1),1),r=Math.min(Math.max(t.cosO,-1),1),i=Math.acos(n),a=Math.acos(r),o=Math.min(Math.max(e.ax*t.ax+e.ay*t.ay+e.az*t.az,-1),1),s=Math.acos(o);if(Math.min(s+a,Math.PI)<=i)return e;if(Math.min(s+i,Math.PI)<=a)return t;let c=(i+a+s)*.5;if(c>=Math.PI)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};let l=c-i,u=e.ay*t.az-e.az*t.ay,d=e.az*t.ax-e.ax*t.az,f=e.ax*t.ay-e.ay*t.ax,p=Math.sqrt(u*u+d*d+f*f);if(p<1e-8)return{ax:e.ax,ay:e.ay,az:e.az,cosO:-1};u/=p,d/=p,f/=p;let m=Math.cos(l),h=Math.sin(l),g=u*e.ax+d*e.ay+f*e.az,_=d*e.az-f*e.ay,v=f*e.ax-u*e.az,y=u*e.ay-d*e.ax,b=e.ax*m+_*h+u*g*(1-m),x=e.ay*m+v*h+d*g*(1-m),S=e.az*m+y*h+f*g*(1-m),C=Math.sqrt(b*b+x*x+S*S)||1;return{ax:b/C,ay:x/C,az:S/C,cosO:Math.cos(c)}}qt();var Dd=Object.freeze({r:0,g:0,b:0});function Od(e){if(!e)return Dd;if(!Ln())return e;let t=[e.r,e.g,e.b];return zn(t),{r:t[0],g:t[1],b:t[2]}}var kd=Pt(`emissive`),Ad=class{constructor(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}extractEmissiveTriangles(e,t,n,r=null){this.emissiveTriangles=[],this._emissiveMeshes=null,this.totalEmissivePower=0,this._totalTriangleCount=n;let i=$e.FLOATS_PER_TRIANGLE,a=$e.MATERIAL_FLAGS_OFFSET,o=$e.MESH_INDEX_OFFSET,s=e&&e.chunks?e:null,c=s?s.viewAs(Float32Array):null,l=s?null:e,u=s?null:new Float32Array(e.buffer,e.byteOffset,e.length),d=new Map;for(let e=0;e<n;e++){let n=s?s.chunkFor(e):l,f=s?c.chunkFor(e):u,p=s?s.baseOf(e):e*i,m=n[p+a]&et,h=n[p+o],g=t[m];if(!g)continue;let _=d.get(g);_===void 0&&(_=Od(g.emissive),d.set(g,_));let v=g.emissiveIntensity||0;if(v>0&&(_.r>0||_.g>0||_.b>0)){let t=r?.placementRunOf?.(h)?.start??-1,n=t>=0&&r.isSet[t],i=n?r.world:null,a=n?t*16:0,o=(e,t,n)=>i?i[a]*e+i[a+4]*t+i[a+8]*n+i[a+12]:e,s=(e,t,n)=>i?i[a+1]*e+i[a+5]*t+i[a+9]*n+i[a+13]:t,c=(e,t,n)=>i?i[a+2]*e+i[a+6]*t+i[a+10]*n+i[a+14]:n,l=f[p+0],u=f[p+1],d=f[p+2],y=f[p+4],b=f[p+5],x=f[p+6],S=f[p+8],C=f[p+9],w=f[p+10],T=o(l,u,d),E=s(l,u,d),D=c(l,u,d),O=o(y,b,x),k=s(y,b,x),A=c(y,b,x),j=o(S,C,w),M=s(S,C,w),N=c(S,C,w),P=this._calculateTriangleArea(T,E,D,O,k,A,j,M,N),F=(.2126*_.r+.7152*_.g+.0722*_.b)*v*P,I=(k-E)*(N-D)-(A-D)*(M-E),L=(A-D)*(j-T)-(O-T)*(N-D),R=(O-T)*(M-E)-(k-E)*(j-T),ee=Math.sqrt(I*I+L*L+R*R)||1,te=g.side===1?-1:1;I=I/ee*te,L=L/ee*te,R=R/ee*te;let z=g.side===2,ne=(T+O+j)/3,B=(E+k+M)/3,re=(D+A+N)/3,ie=Math.min(T,O,j),ae=Math.min(E,k,M),oe=Math.min(D,A,N),se=Math.max(T,O,j),ce=Math.max(E,k,M),le=Math.max(D,A,N);this.emissiveTriangles.push({triangleIndex:e,materialIndex:m,meshIndex:h,sideSign:te,instanceLeaf:n?r.tlasLeafIndex[t]:-1,power:F,area:P,emissive:{r:_.r,g:_.g,b:_.b},emissiveIntensity:v,cx:ne,cy:B,cz:re,bMinX:ie,bMinY:ae,bMinZ:oe,bMaxX:se,bMaxY:ce,bMaxZ:le,nx:I,ny:L,nz:R,twoSided:z}),this.totalEmissivePower+=F}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&kd.debug(`${Y.n(this.emissiveCount)} emissive tris (${(this.emissiveCount/n*100).toFixed(2)}%) · total power ${this.totalEmissivePower.toFixed(2)}`),this._buildDataArrays(),this.emissiveCount}get emissiveMeshes(){return this._emissiveMeshes??=new Set(this.emissiveTriangles.map(e=>e.meshIndex))}refreshTransforms(e,t){let n=e&&e.chunks?e:null,r=n?n.viewAs(Float32Array):null,i=n?null:new Float32Array(e.buffer,e.byteOffset,e.length),a=$e.FLOATS_PER_TRIANGLE,o=t.world;this.totalEmissivePower=0;for(let e of this.emissiveTriangles){let s=n?r.chunkFor(e.triangleIndex):i,c=n?n.baseOf(e.triangleIndex):e.triangleIndex*a,l=[s[c],s[c+1],s[c+2],s[c+4],s[c+5],s[c+6],s[c+8],s[c+9],s[c+10]],u=t.placementRunOf?.(e.meshIndex)?.start??-1;if(u>=0&&t.isSet[u]){let e=u*16;for(let t=0;t<9;t+=3){let n=l[t],r=l[t+1],i=l[t+2];l[t]=o[e]*n+o[e+4]*r+o[e+8]*i+o[e+12],l[t+1]=o[e+1]*n+o[e+5]*r+o[e+9]*i+o[e+13],l[t+2]=o[e+2]*n+o[e+6]*r+o[e+10]*i+o[e+14]}}let[d,f,p,m,h,g,_,v,y]=l,b=this._calculateTriangleArea(d,f,p,m,h,g,_,v,y),x=e.emissive;e.power=(.2126*x.r+.7152*x.g+.0722*x.b)*e.emissiveIntensity*b,e.area=b;let S=(h-f)*(y-p)-(g-p)*(v-f),C=(g-p)*(_-d)-(m-d)*(y-p),w=(m-d)*(v-f)-(h-f)*(_-d),T=(Math.sqrt(S*S+C*C+w*w)||1)/e.sideSign;e.nx=S/T,e.ny=C/T,e.nz=w/T,e.cx=(d+m+_)/3,e.cy=(f+h+v)/3,e.cz=(p+g+y)/3,e.bMinX=Math.min(d,m,_),e.bMinY=Math.min(f,h,v),e.bMinZ=Math.min(p,g,y),e.bMaxX=Math.max(d,m,_),e.bMaxY=Math.max(f,h,v),e.bMaxZ=Math.max(p,g,y),this.totalEmissivePower+=e.power}this._buildDataArrays()}_calculateTriangleArea(e,t,n,r,i,a,o,s,c){let l=r-e,u=i-t,d=a-n,f=o-e,p=s-t,m=c-n,h=u*m-d*p,g=d*f-l*m,_=l*p-u*f;return Math.sqrt(h*h+g*g+_*_)*.5}_buildDataArrays(){this.emissiveIndicesArray=new Int32Array(this.emissiveCount),this.emissivePowerArray=new Float32Array(this.emissiveCount);for(let e=0;e<this.emissiveCount;e++)this.emissiveIndicesArray[e]=this.emissiveTriangles[e].triangleIndex,this.emissivePowerArray[e]=this.emissiveTriangles[e].power;this._buildCDF()}_buildCDF(){if(this.emissiveCount===0){this.cdfArray=new Float32Array(1),this.cdfArray[0]=0;return}this.cdfArray=new Float32Array(this.emissiveCount);let e=0;for(let t=0;t<this.emissiveCount;t++)e+=this.emissivePowerArray[t],this.cdfArray[t]=e;if(e>0)for(let t=0;t<this.emissiveCount;t++)this.cdfArray[t]/=e}sampleCDF(e){if(this.emissiveCount===0)return-1;if(this.emissiveCount===1)return 0;let t=0,n=this.emissiveCount-1;for(;t<n;){let r=Math.floor((t+n)/2);this.cdfArray[r]<e?t=r+1:n=r}return t}getGPUData(){return{emissiveIndices:this.emissiveIndicesArray,emissivePower:this.emissivePowerArray,emissiveCDF:this.cdfArray,emissiveCount:this.emissiveCount,totalPower:this.totalEmissivePower}}createEmissiveTexture(){if(this.emissiveCount===0)return new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);let e=new Float32Array(this.emissiveCount*4);for(let t=0;t<this.emissiveCount;t++){let n=t*4;e[n+0]=this.emissiveIndicesArray[t],e[n+1]=this.emissivePowerArray[t],e[n+2]=this.cdfArray[t],e[n+3]=0}let t=Math.ceil(Math.sqrt(this.emissiveCount)),n=Math.ceil(this.emissiveCount/t),i=t*n*4,a=new Float32Array(i);a.set(e);let o=new r.DataTexture(a,t,n,r.RGBAFormat,r.FloatType);return o.needsUpdate=!0,o.generateMipmaps=!1,o.minFilter=r.NearestFilter,o.magFilter=r.NearestFilter,kd.debug(`emissive texture ${Y.px(t,n)} · ${Y.n(this.emissiveCount)} entries`),o}createEmissiveRawData(){if(this.emissiveCount===0)return new Float32Array(8);let e=new Float32Array(this.emissiveCount*8);for(let t=0;t<this.emissiveCount;t++){let n=this.emissiveTriangles[t],r=t*8;e[r+0]=n.triangleIndex,e[r+1]=n.power,e[r+2]=this.cdfArray[t],e[r+3]=n.instanceLeaf,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return kd.debug(`emissive raw data ${Y.n(this.emissiveCount)} entries (${Y.mb(e.byteLength)})`),e}getStats(){if(this.emissiveCount===0)return{count:0,totalPower:0,averagePower:0,minPower:0,maxPower:0};let e=1/0,t=-1/0;for(let n=0;n<this.emissiveCount;n++){let r=this.emissivePowerArray[n];e=Math.min(e,r),t=Math.max(t,r)}return{count:this.emissiveCount,totalPower:this.totalEmissivePower,averagePower:this.totalEmissivePower/this.emissiveCount,minPower:e,maxPower:t}}updateMaterialEmissive(e,t,n,r,i){let a=Od(t.emissive),o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.2126*a.r+.7152*a.g+.0722*a.b;for(let t of this.emissiveTriangles)t.materialIndex===e&&(t.power=c*o*t.area,t.emissive={r:a.r,g:a.g,b:a.b},t.emissiveIntensity=o);return!0}setHiddenMeshes(e){let t=new Set;for(let e of this.emissiveTriangles)t.add(e.meshIndex);let n=new Set;for(let r of e)t.has(r)&&n.add(r);let r=this._hiddenMeshes,i=n.size!==r.size;if(!i){for(let e of n)if(!r.has(e)){i=!0;break}}return this._hiddenMeshes=n,i}buildLightBVH(){let e=this._hiddenMeshes.size===0?this.emissiveTriangles:this.emissiveTriangles.filter(e=>!this._hiddenMeshes.has(e.meshIndex));this.emissiveCount=e.length,this.totalEmissivePower=0;for(let t of e)this.totalEmissivePower+=t.power;if(e.length===0)return this.lightBVHNodeData=new Float32Array(16),this.lightBVHNodeData[7]=1,this.lightBVHNodeData[14]=1,this.lightBVHNodeData[15]=-1,this.lightBVHNodeCount=1,this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1),this.emissiveIndicesArray=new Int32Array,this.emissivePowerArray=new Float32Array,this._buildCDF(),this.emissiveTriangleData=new Float32Array(8),1;let{nodeData:t,nodeCount:n,sortedPerm:r,bitTrails:i}=new wd().build(e);this.lightBVHNodeData=t,this.lightBVHNodeCount=n,this._rebuildSortedEmissiveData(r,e),this.emissiveBitTrailMap=new Float32Array(Math.max(this._totalTriangleCount,1)).fill(-1);for(let t=0;t<r.length;t++){let n=e[r[t]].triangleIndex;this.emissiveBitTrailMap[n]=i[t]}return n}_rebuildSortedEmissiveData(e,t){let n=e.length;this.emissiveIndicesArray=new Int32Array(n),this.emissivePowerArray=new Float32Array(n);for(let r=0;r<n;r++){let n=e[r];this.emissiveIndicesArray[r]=t[n].triangleIndex,this.emissivePowerArray[r]=t[n].power}this._buildCDF();let r=new Float32Array(n*8);for(let i=0;i<n;i++){let n=t[e[i]],a=i*8;r[a+0]=n.triangleIndex,r[a+1]=n.power,r[a+2]=this.cdfArray[i],r[a+3]=n.instanceLeaf,r[a+4]=n.emissive.r*n.emissiveIntensity,r[a+5]=n.emissive.g*n.emissiveIntensity,r[a+6]=n.emissive.b*n.emissiveIntensity,r[a+7]=n.area}this.emissiveTriangleData=r,kd.debug(`rebuilt sorted emissive data · ${Y.n(n)} entries`)}clear(){this.emissiveTriangles=[],this.emissiveCount=0,this.totalEmissivePower=0,this.emissiveIndicesArray=null,this.emissivePowerArray=null,this.cdfArray=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._totalTriangleCount=0,this._hiddenMeshes=new Set}};qt();var jd=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=Pt(t),this.entries=new Map,this.order=[],this.totalStart=performance.now()}start(e){return this.entries.set(e,{start:performance.now(),end:null}),this.order.includes(e)||this.order.push(e),this}end(e){let t=this.entries.get(e);return t&&(t.end=performance.now(),t.duration=t.end-t.start),this}getDuration(e){return this.entries.get(e)?.duration??0}print(e=[]){let t=performance.now()-this.totalStart,n=this.order.map(e=>{let t=this.entries.get(e)?.duration??0;return t>=1?`${e} ${Math.round(t)}ms`:null}).filter(Boolean),r=Y.list([this.label,...e,Y.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(Y.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Md="const e={FLOATS_PER_TRIANGLE:20,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_PACKED_OFFSET:3,NORMAL_B_PACKED_OFFSET:7,NORMAL_C_PACKED_OFFSET:11},t=e.FLOATS_PER_TRIANGLE,n=e=>e instanceof Float32Array?e:new Float32Array(e.buffer,e.byteOffset,e.length),r=e=>e instanceof Uint32Array?e:new Uint32Array(e.buffer,e.byteOffset,e.length),i=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:e,idx:t?e.viewAs(Uint32Array):r(e)}},a=(e,t)=>e.chunked?e.f.chunkFor(t):e.f,o=(e,t)=>e.chunked?e.idx.chunkFor(t):e.idx,s=(e,t)=>e.chunked?e.chunked.baseOf(t):t*u,c=e=>{let t=e&&e.chunks?e:null;return{chunked:t,f:t?t.viewAs(Float32Array):n(e),u:t?e:r(e)}};function l(e,t,n){let r=Math.sqrt(e*e+t*t+n*n);r>0?(e/=r,t/=r,n/=r):(e=0,t=0,n=1);let i=Math.abs(e)+Math.abs(t)+Math.abs(n),a=e/i,o=t/i;if(n<0){let e=a,t=o;a=(1-Math.abs(t))*(e>=0?1:-1),o=(1-Math.abs(e))*(t>=0?1:-1)}let s=Math.round(Math.min(1,Math.max(-1,a))*32767)&65535;return((Math.round(Math.min(1,Math.max(-1,o))*32767)&65535)<<16|s)>>>0}const u=16,d=1073741824;function f(e,t,n,r,i,a){let o=e[t+4],s=e[t+5],c=e[t+6],l=e[t+7],u=e[t+8],d=e[t+9],f=e[t+10],p=e[t+11],m=e[t+12],h=e[t+13],g=e[t+14],_=e[t+15],v=d*g-f*h,y=f*m-u*g,b=u*h-d*m,x=o*v+s*y+c*b,S=o===1&&d===1&&g===1&&s===0&&c===0&&u===0&&f===0&&m===0&&h===0&&l===0&&p===0&&_===0,C=(Math.abs(o)+Math.abs(s)+Math.abs(c))*(Math.abs(u)+Math.abs(d)+Math.abs(f))*(Math.abs(m)+Math.abs(h)+Math.abs(g));if(S||!Number.isFinite(x)||Math.abs(x)<=1e-12*C){for(let e=0;e<6;e++)i[a+e]=n[r+e];return}let w=1/x,T=v*w,E=y*w,D=b*w,O=(c*h-s*g)*w,k=(o*g-c*m)*w,A=(s*m-o*h)*w,j=(s*f-c*d)*w,M=(c*u-o*f)*w,N=(o*d-s*u)*w,P=1/0,F=1/0,I=1/0,L=-1/0,R=-1/0,z=-1/0;for(let e=0;e<8;e++){let t=(e&1?n[r+3]:n[r])-l,i=(e&2?n[r+4]:n[r+1])-p,a=(e&4?n[r+5]:n[r+2])-_,o=T*t+O*i+j*a,s=E*t+k*i+M*a,c=D*t+A*i+N*a;o<P&&(P=o),o>L&&(L=o),s<F&&(F=s),s>R&&(R=s),c<I&&(I=c),c>z&&(z=c)}i[a]=P,i[a+1]=F,i[a+2]=I,i[a+3]=L,i[a+4]=R,i[a+5]=z}var p=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(n,r,i){let a=i.length,o=c(n);for(let n=0;n<a;n++){let a=i[n],s=o.chunked?o.f.chunkFor(n):o.f,c=o.chunked?o.u.chunkFor(n):o.u,u=o.chunked?o.chunked.baseOf(n):n*t,d=a*9,f=r[d],p=r[d+1],m=r[d+2],h=r[d+3],g=r[d+4],_=r[d+5],v=r[d+6],y=r[d+7],b=r[d+8];s[u+e.POSITION_A_OFFSET]=f,s[u+e.POSITION_A_OFFSET+1]=p,s[u+e.POSITION_A_OFFSET+2]=m,s[u+e.POSITION_B_OFFSET]=h,s[u+e.POSITION_B_OFFSET+1]=g,s[u+e.POSITION_B_OFFSET+2]=_,s[u+e.POSITION_C_OFFSET]=v,s[u+e.POSITION_C_OFFSET+1]=y,s[u+e.POSITION_C_OFFSET+2]=b;let x=h-f,S=g-p,C=_-m,w=v-f,T=y-p,E=b-m,D=l(S*E-C*T,C*w-x*E,x*T-S*w);c[u+e.NORMAL_A_PACKED_OFFSET]=D,c[u+e.NORMAL_B_PACKED_OFFSET]=D,c[u+e.NORMAL_C_PACKED_OFFSET]=D}}refitRange(n,r,l,u){let f=c(r);u>this._boundsNodeCount&&(this._bounds=new Float32Array(u*6),this._boundsNodeCount=u);let p=this._bounds,m=l+u,h=i(n);for(let n=m-1;n>=l;n--){let r=a(h,n),i=o(h,n),c=s(h,n),u=(n-l)*6;if(i[c+3]===d){let n=i[c],r=i[c+1],a=1/0,o=1/0,s=1/0,l=-1/0,d=-1/0,m=-1/0;for(let i=0;i<r;i++){let r=n+i,c=f.chunked?f.f.chunkFor(r):f.f,u=f.chunked?f.chunked.baseOf(r):r*t,p=c[u+e.POSITION_A_OFFSET],h=c[u+e.POSITION_A_OFFSET+1],g=c[u+e.POSITION_A_OFFSET+2],_=c[u+e.POSITION_B_OFFSET],v=c[u+e.POSITION_B_OFFSET+1],y=c[u+e.POSITION_B_OFFSET+2],b=c[u+e.POSITION_C_OFFSET],x=c[u+e.POSITION_C_OFFSET+1],S=c[u+e.POSITION_C_OFFSET+2];a=Math.min(a,p,_,b),o=Math.min(o,h,v,x),s=Math.min(s,g,y,S),l=Math.max(l,p,_,b),d=Math.max(d,h,v,x),m=Math.max(m,g,y,S)}p[u]=a,p[u+1]=o,p[u+2]=s,p[u+3]=l,p[u+4]=d,p[u+5]=m}else{let e=i[c+3],t=i[c+7],n=(e-l)*6,a=(t-l)*6,o=p[n],s=p[n+1],d=p[n+2],f=p[n+3],m=p[n+4],h=p[n+5],g=p[a],_=p[a+1],v=p[a+2],y=p[a+3],b=p[a+4],x=p[a+5];r[c]=o,r[c+1]=s,r[c+2]=d,r[c+4]=f,r[c+5]=m,r[c+6]=h,r[c+8]=g,r[c+9]=_,r[c+10]=v,r[c+12]=y,r[c+13]=b,r[c+14]=x,p[u]=Math.min(o,g),p[u+1]=Math.min(s,_),p[u+2]=Math.min(d,v),p[u+3]=Math.max(f,y),p[u+4]=Math.max(m,b),p[u+5]=Math.max(h,x)}}}refit(n,r,l){let u=c(r);l!==this._boundsNodeCount&&(this._bounds=new Float32Array(l*6),this._boundsNodeCount=l);let p=this._bounds,m=i(n);for(let n=l-1;n>=0;n--){let r=a(m,n),i=o(m,n),c=s(m,n),l=n*6,h=i[c+3];if(h===d){let n=i[c],r=i[c+1],a=1/0,o=1/0,s=1/0,d=-1/0,f=-1/0,m=-1/0;for(let i=0;i<r;i++){let r=n+i,c=u.chunked?u.f.chunkFor(r):u.f,l=u.chunked?u.chunked.baseOf(r):r*t,p=c[l+e.POSITION_A_OFFSET],h=c[l+e.POSITION_A_OFFSET+1],g=c[l+e.POSITION_A_OFFSET+2],_=c[l+e.POSITION_B_OFFSET],v=c[l+e.POSITION_B_OFFSET+1],y=c[l+e.POSITION_B_OFFSET+2],b=c[l+e.POSITION_C_OFFSET],x=c[l+e.POSITION_C_OFFSET+1],S=c[l+e.POSITION_C_OFFSET+2];a=Math.min(a,p,_,b),o=Math.min(o,h,v,x),s=Math.min(s,g,y,S),d=Math.max(d,p,_,b),f=Math.max(f,h,v,x),m=Math.max(m,g,y,S)}p[l]=a,p[l+1]=o,p[l+2]=s,p[l+3]=d,p[l+4]=f,p[l+5]=m}else if(h===1073741825)f(r,c,p,i[c]*6,p,l);else{let e=i[c+3],t=i[c+7],n=e*6,a=t*6,o=p[n],s=p[n+1],u=p[n+2],d=p[n+3],f=p[n+4],m=p[n+5],h=p[a],g=p[a+1],_=p[a+2],v=p[a+3],y=p[a+4],b=p[a+5];r[c]=o,r[c+1]=s,r[c+2]=u,r[c+4]=d,r[c+5]=f,r[c+6]=m,r[c+8]=h,r[c+9]=g,r[c+10]=_,r[c+12]=v,r[c+13]=y,r[c+14]=b,p[l]=Math.min(o,h),p[l+1]=Math.min(s,g),p[l+2]=Math.min(u,_),p[l+3]=Math.max(d,v),p[l+4]=Math.max(f,y),p[l+5]=Math.max(m,b)}}}};const m=64*1024*1024;function h(e,t,n){return n?new e(new SharedArrayBuffer(t*e.BYTES_PER_ELEMENT)):new e(t)}var g=class e{constructor(e,t,n,r=m,i=!1){let a=t*n.BYTES_PER_ELEMENT,o=Math.max(1,Math.floor(r/a));this.recordCount=e,this.lanesPerRecord=t,this.LaneType=n,this.recordsPerChunk=e<=o?Math.max(e,1):o,this.shared=i,this.chunks=[];let s=e;for(;s>0;){let e=Math.min(s,this.recordsPerChunk);this.chunks.push(h(n,e*t,i)),s-=e}this.chunks.length===0&&this.chunks.push(h(n,0,i))}static adopt(t,n,r,i){let a=Object.create(e.prototype);return a.recordCount=n,a.lanesPerRecord=r,a.LaneType=t[0]?.constructor??null,a.recordsPerChunk=i,a.chunks=t,a.shared=typeof SharedArrayBuffer<`u`&&t[0]?.buffer instanceof SharedArrayBuffer,a}static lazy(t,n,r,i=m,a=!1){let o=Math.max(1,Math.floor(i/(n*r.BYTES_PER_ELEMENT))),s=Object.create(e.prototype);return s.recordCount=t,s.lanesPerRecord=n,s.LaneType=r,s.recordsPerChunk=t<=o?Math.max(t,1):o,s.shared=a,s.chunks=Array(Math.max(1,Math.ceil(t/s.recordsPerChunk))),s._views=[],s}_materialize(e){if(this._owner)return this._owner._materialize(e),this.chunks[e];let t=e*this.recordsPerChunk,n=Math.min(this.recordsPerChunk,this.recordCount-t)*this.lanesPerRecord,r=this.chunks[e]=h(this.LaneType,n,this.shared);for(let t of this._views)t.chunks[e]=new t.LaneType(r.buffer,r.byteOffset,r.byteLength/t.LaneType.BYTES_PER_ELEMENT);return r}materializeAll(){for(let e=0;e<this.chunks.length;e++)this.chunks[e]||this._materialize(e);return this}get chunkCount(){return this.chunks.length}get single(){return this.chunks.length===1?this.chunks[0]:null}get byteLength(){let e=0;for(let t of this.chunks)t&&(e+=t.byteLength);return e}chunkFor(e){let t=e/this.recordsPerChunk|0;return this.chunks[t]??this._materialize(t)}baseOf(e){return e%this.recordsPerChunk*this.lanesPerRecord}isContiguous(e,t){return t<=0?!0:(e/this.recordsPerChunk|0)==((e+t-1)/this.recordsPerChunk|0)}slice(e,t){let n=this.baseOf(e),r=t*this.lanesPerRecord;if(this.isContiguous(e,t))return this.chunkFor(e).subarray(n,n+r);let i=new this.LaneType(r);return this.readRecords(e,t,i),i}readRecords(e,t,n){let r=0;for(;r<t;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,t-r);n.set(a.subarray(o,o+c*this.lanesPerRecord),r*this.lanesPerRecord),r+=c}return n}setRecords(e,t){let n=t.length/this.lanesPerRecord,r=0;for(;r<n;){let i=e+r,a=this.chunkFor(i),o=this.baseOf(i),s=this.recordsPerChunk-i%this.recordsPerChunk,c=Math.min(s,n-r);a.set(t.subarray(r*this.lanesPerRecord,(r+c)*this.lanesPerRecord),o),r+=c}}copyOf(e,t){return this.readRecords(e,t,new this.LaneType(t*this.lanesPerRecord))}trimTo(t){let n=Math.max(1,Math.ceil(t/this.recordsPerChunk)),r=this.chunks.slice(0,n),i=(t-(n-1)*this.recordsPerChunk)*this.lanesPerRecord,a=r[n-1];return a.length>i&&(r[n-1]=a.subarray(0,Math.max(0,i))),e.adopt(r,t,this.lanesPerRecord,this.recordsPerChunk)}viewAs(t){let n=e=>new t(e.buffer,e.byteOffset,e.byteLength/t.BYTES_PER_ELEMENT),r=e.adopt(this.chunks.map(e=>e?n(e):void 0),this.recordCount,this.lanesPerRecord,this.recordsPerChunk);return r.LaneType=t,this._views&&(r._owner=this,this._views.push(r)),r}};const _=new p;let v=null,y=null,b=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){v=g.adopt(e.data.sharedBvhBufs.map(e=>new Float32Array(e)),e.data.bvhRecordCount,16,e.data.bvhRecordsPerChunk),y=g.adopt(e.data.sharedTriBufs.map(e=>new Uint32Array(e)),e.data.triRecordCount,e.data.triLanesPerRecord,e.data.triRecordsPerChunk),b=v.recordCount;return}if(t===`refit`)try{let e=performance.now();_.refit(v,y,b),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-e})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Nd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Md],{type:`text/javascript;charset=utf-8`});function Pd(e){let t;try{if(t=Nd&&(self.URL||self.webkitURL).createObjectURL(Nd),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Md),{type:`module`,name:e?.name})}}var Fd="const e=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:0,toneMapping:6,saturation:1}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})}),t={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:e.viewer.toneMapping,exposure:1,saturation:e.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:e.viewer.environmentRotation,groundProjectionEnabled:!1,groundProjectionRadius:100,groundProjectionHeight:15,groundProjectionLevel:0,enableGroundCatcher:!1,groundCatcherHeight:0,globalIlluminationIntensity:1,environmentMode:`hdri`,gradientZenithColor:`#0077BE`,gradientHorizonColor:`#87CEEB`,gradientGroundColor:`#654321`,solidSkyColor:`#87CEEB`,skySunAzimuth:90,skySunElevation:20,skySunIntensity:15,skyRayleighDensity:.9,skyTurbidity:.8,skyMieAnisotropy:.76,skyPreset:`clearMorning`,cameraProjection:`perspective`,panoramaLonRange:[-180,180],panoramaLatRange:[-90,90],panoramaLevelHorizon:!0,enableDOF:!1,fov:55,focusDistance:.8,aperture:5.6,focalLength:50,apertureScale:1,anamorphicRatio:1,autoFocusMode:`auto`,afScreenPoint:{x:.5,y:.5},afSmoothingFactor:.15,enablePathTracer:!0,enableAccumulation:!0,pauseRendering:!1,maxSamples:60,bounces:3,transmissiveBounces:5,maxSubsurfaceSteps:8,maxTransparentBounces:32,useAdaptiveSampling:!0,noiseThreshold:.1,adaptiveMinSamples:8,adaptiveStopFraction:.9,usePixelFreeze:!0,pixelFreezeThreshold:.02,pixelFreezeStability:8,convergenceOverlay:!1,samplingTechnique:2,enableEmissiveTriangleSampling:!1,emissiveBoost:1,fireflyThreshold:3,shadowTerminatorOffset:.1,wavefrontSortMaterials:!0,renderLimitMode:`frames`,renderTimeLimit:30,renderMode:0,enableAlphaShadows:!1,tilesHelper:!0,showLightHelper:!1,directionalLightIntensity:0,directionalLightColor:`#ffffff`,directionalLightPosition:[1,1,1],directionalLightAngle:0,filterStrength:1,edgeAtrousIterations:5,edgePhiLuminance:4,edgePhiNormal:64,edgePhiDepth:.1,enableOIDN:!1,oidnQuality:`fast`,continuousDenoise:!1,continuousDenoiseInterval:8,oidnTemporalHistory:!0,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,interactionRenderScale:.5,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,asvgfGradientStrength:1,asvgfGradientSigmaScale:2,asvgfGradientNoiseFloor:0,asvgfDebugMode:0,asvgfQualityPreset:`medium`,showAsvgfHeatmap:!1,nrdQualityPreset:`medium`,nrdDebugMode:0,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5};t.fov,t.focusDistance,t.aperture,t.focalLength,n({color:[1,1,1],emissive:[0,0,0],emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:0,attenuationColor:[1,1,1],attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:[0,0,0],specularIntensity:1,specularColor:[1,1,1],clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:[1,1],bumpScale:1,displacementScale:1,transparent:0,alphaTest:0,alphaMode:0,side:0,depthWrite:1,subsurface:0,subsurfaceColor:[1,1,1],subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0});function n(e){for(let t of Object.values(e))typeof t==`object`&&Object.freeze(t);return Object.freeze(e)}const r={TRIANGLE_LEAF:1073741824,BLAS_POINTER_LEAF:1073741825,FRONTIER:1073741826};function i(e){return new Uint32Array(e.buffer,e.byteOffset,e.length)}function a(e,t){if(e>=1073741824)throw RangeError(`${t} is ${e.toLocaleString()}, at or past the BVH index limit of ${1073741824 .toLocaleString()}. Node indices are stored as u32 bit patterns and the leaf tags occupy everything above that.`);return e}Math.min(typeof navigator<`u`&&navigator.hardwareConcurrency||4,6),t.maxSamples,t.bounces,t.renderMode,t.enableAlphaShadows,t.maxSubsurfaceSteps;const o=Float64Array.from([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);function s(e,t){return e[t]*(e[t+5]*e[t+10]-e[t+6]*e[t+9])-e[t+4]*(e[t+1]*e[t+10]-e[t+2]*e[t+9])+e[t+8]*(e[t+1]*e[t+6]-e[t+2]*e[t+5])}function c(e,t,n){let r=s(e,t);if(!Number.isFinite(r)||Math.abs(r)<1e-20)return n.set(o),n;let i=1/r;return n[0]=(e[t+5]*e[t+10]-e[t+6]*e[t+9])*i,n[1]=(e[t+2]*e[t+9]-e[t+1]*e[t+10])*i,n[2]=(e[t+1]*e[t+6]-e[t+2]*e[t+5])*i,n[3]=0,n[4]=(e[t+6]*e[t+8]-e[t+4]*e[t+10])*i,n[5]=(e[t]*e[t+10]-e[t+2]*e[t+8])*i,n[6]=(e[t+2]*e[t+4]-e[t]*e[t+6])*i,n[7]=0,n[8]=(e[t+4]*e[t+9]-e[t+5]*e[t+8])*i,n[9]=(e[t+1]*e[t+8]-e[t]*e[t+9])*i,n[10]=(e[t]*e[t+5]-e[t+1]*e[t+4])*i,n[11]=0,n[12]=-(n[0]*e[t+12]+n[4]*e[t+13]+n[8]*e[t+14]),n[13]=-(n[1]*e[t+12]+n[5]*e[t+13]+n[9]*e[t+14]),n[14]=-(n[2]*e[t+12]+n[6]*e[t+13]+n[10]*e[t+14]),n[15]=1,n}function l(e,t){for(let n=0;n<16;n++)if(e[t+n]!==o[n])return!1;return!0}const u=e=>e<32?e:32,d=new Float64Array(16);var f=class e{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0,this._binCounts=new Int32Array(96),this._binBounds=new Float64Array(576),this._binSuffix=new Float64Array(32),this._binSuffixCount=new Int32Array(32),this._order=null,this._stackI=null,this._stackB=null,this._stackFrames=0,this._sortScratch=[],this._suffix=null,this._bounds=new Float64Array(12),this._extent=new Float64Array(3),this._cMin=new Float64Array(3)}static nodeCountFor(e){return e>0?e*2-1:0}releaseFlattenBuffer(){this._flatBuffer=null,this._flatBufferCapacity=0}build(t){let n=new Float64Array(t.count*6);t.writeWorldAABBs(n);let r=this.buildStructure(n,t.count);return e.fillLeaves(r.data,r.nodeCount,t),r}buildStructure(t,n){let o=e.nodeCountFor(n);if(n===0)return{data:new Float32Array,nodeCount:0};a(o,`TLAS node count`);let s=o*16;s>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(s),this._flatBufferCapacity=s);let c=this._flatBuffer,l=i(c);(!this._order||this._order.length<n)&&(this._order=new Int32Array(n));let u=this._order;for(let e=0;e<n;e++)u[e]=e;this._ensureStack(64);let d=0,f=0,p=0,m=n,h=this._bounds;this._rangeBounds(t,u,p,m,h,0);let g=h[0],_=h[1],v=h[2],y=h[3],b=h[4],x=h[5];for(;;){if(m-p===1){let e=f*16;l[e]=0,l[e+1]=u[p],c[e+2]=0,l[e+3]=r.BLAS_POINTER_LEAF}else{let e=this._partition(t,u,p,m,g,_,v,y,b,x),n=e-p,r=f+1,i=r+(n*2-1),a=f*16;c[a]=h[0],c[a+1]=h[1],c[a+2]=h[2],l[a+3]=r,c[a+4]=h[3],c[a+5]=h[4],c[a+6]=h[5],l[a+7]=i,c[a+8]=h[6],c[a+9]=h[7],c[a+10]=h[8],c[a+11]=0,c[a+12]=h[9],c[a+13]=h[10],c[a+14]=h[11],c[a+15]=0;let o=n<=m-e,s=o?0:6,S=o?6:0;d=this._push(d,o?i:r,o?e:p,o?m:e,h,S),f=o?r:i,o?m=e:p=e,g=h[s],_=h[s+1],v=h[s+2],y=h[s+3],b=h[s+4],x=h[s+5];continue}if(d===0)break;d--;let e=d*3,n=d*6;f=this._stackI[e],p=this._stackI[e+1],m=this._stackI[e+2],g=this._stackB[n],_=this._stackB[n+1],v=this._stackB[n+2],y=this._stackB[n+3],b=this._stackB[n+4],x=this._stackB[n+5]}return{data:c.subarray(0,s),nodeCount:o}}_push(e,t,n,r,i,a){e>=this._stackFrames&&this._ensureStack(this._stackFrames*2);let o=e*3,s=e*6;this._stackI[o]=t,this._stackI[o+1]=n,this._stackI[o+2]=r;for(let e=0;e<6;e++)this._stackB[s+e]=i[a+e];return e+1}_ensureStack(e){if(this._stackFrames>=e)return;let t=new Int32Array(e*3),n=new Float64Array(e*6);this._stackI&&(t.set(this._stackI),n.set(this._stackB)),this._stackI=t,this._stackB=n,this._stackFrames=e}static fillLeaves(t,n,a){let o=a.world,s=a.sourceMesh,c=a.tplBlasOffset,l=a.visible,u=a.tlasLeafIndex,d=i(t);for(let i=0;i<n;i++){let n=i*16;if(d[n+3]!==r.BLAS_POINTER_LEAF)continue;let a=d[n+1]&1073741823;d[n]=c[s[a]],t[n+2]=+!!l[a],e.writeLeafMatrix(t,d,n,o,a),u[a]=i}}static writeLeafMatrix(e,t,n,r,i){let a=d;c(r,i*16,a),e[n+4]=a[0],e[n+5]=a[4],e[n+6]=a[8],e[n+7]=a[12],e[n+8]=a[1],e[n+9]=a[5],e[n+10]=a[9],e[n+11]=a[13],e[n+12]=a[2],e[n+13]=a[6],e[n+14]=a[10],e[n+15]=a[14],t[n+1]=(i|(l(r,i*16)?1073741824:0))>>>0}_partition(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=0;if(u===2)d=n+1;else if(u<=8)d=n+(u>>1),this._insertionSortRange(e,t,n,r,this._widestCentroidAxis(e,t,n,r));else{if(d=this._binnedSplit(e,t,n,r,i,a,o,s,c,l),d>n&&d<r)return d;if(d=this._sweepSplit(e,t,n,r,i,a,o,s,c,l),!(d>n&&d<r)){let f=s-i,p=c-a,m=l-o,h=p>f&&p>m?1:m>f?2:0;this._sortRange(e,t,n,r,h),d=n+(u>>1)}}let f=this._bounds;return this._rangeBounds(e,t,n,d,f,0),this._rangeBounds(e,t,d,r,f,6),d}_binnedSplit(e,t,n,r,i,a,o,s,c,l){let d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0;for(let i=n;i<r;i++){let n=t[i]*6,r=(e[n]+e[n+3])*.5,a=(e[n+1]+e[n+4])*.5,o=(e[n+2]+e[n+5])*.5;r<f&&(f=r),r>h&&(h=r),a<p&&(p=a),a>g&&(g=a),o<m&&(m=o),o>_&&(_=o)}let v=this._extent,y=this._cMin;v[0]=h-f,v[1]=g-p,v[2]=_-m,y[0]=f,y[1]=p,y[2]=m;let b=1/0,x=-1,S=-1,C=this._binCounts,w=this._binBounds,T=v[0]>1e-12,E=v[1]>1e-12,D=v[2]>1e-12;if(!T&&!E&&!D)return n;let O=u(r-n),k=T?O/v[0]:0,A=E?O/v[1]:0,j=D?O/v[2]:0;C.fill(0,0,O*3);for(let e=0;e<O*3;e++){let t=e*6;w[t]=w[t+1]=w[t+2]=1/0,w[t+3]=w[t+4]=w[t+5]=-1/0}for(let i=n;i<r;i++){let n=t[i]*6,r=e[n],a=e[n+1],o=e[n+2],s=e[n+3],c=e[n+4],l=e[n+5];for(let e=0;e<3;e++){let t=e===0?k:e===1?A:j;if(t===0)continue;let n=((e===0?(r+s)*.5:e===1?(a+c)*.5:(o+l)*.5)-y[e])*t|0;n<0?n=0:n>=O&&(n=O-1),n+=e*O,C[n]++;let i=n*6;r<w[i]&&(w[i]=r),a<w[i+1]&&(w[i+1]=a),o<w[i+2]&&(w[i+2]=o),s>w[i+3]&&(w[i+3]=s),c>w[i+4]&&(w[i+4]=c),l>w[i+5]&&(w[i+5]=l)}}for(let e=0;e<3;e++){if(!(v[e]>1e-12))continue;let t=e*O,n=this._binSuffix,r=this._binSuffixCount,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0,u=0;for(let e=O-1;e>=1;e--){let d=(t+e)*6;w[d]<i&&(i=w[d]),w[d+1]<a&&(a=w[d+1]),w[d+2]<o&&(o=w[d+2]),w[d+3]>s&&(s=w[d+3]),w[d+4]>c&&(c=w[d+4]),w[d+5]>l&&(l=w[d+5]),u+=C[t+e],n[e]=u?this._surfaceArea(i,a,o,s,c,l):0,r[e]=u}let f=1/0,p=1/0,m=1/0,h=-1/0,g=-1/0,_=-1/0,y=0;for(let i=1;i<O;i++){let a=(t+i-1)*6;if(w[a]<f&&(f=w[a]),w[a+1]<p&&(p=w[a+1]),w[a+2]<m&&(m=w[a+2]),w[a+3]>h&&(h=w[a+3]),w[a+4]>g&&(g=w[a+4]),w[a+5]>_&&(_=w[a+5]),y+=C[t+i-1],y===0||r[i]===0)continue;let o=1+(this._surfaceArea(f,p,m,h,g,_)*y+n[i]*r[i])/d;o<b&&(b=o,x=e,S=i)}}if(x<0)return n;let M=O/v[x],N=y[x],P=this._bounds;P[0]=P[1]=P[2]=P[6]=P[7]=P[8]=1/0,P[3]=P[4]=P[5]=P[9]=P[10]=P[11]=-1/0;let F=n,I=r-1;for(;F<=I;){let n=t[F]*6,r=((e[n+x]+e[n+3+x])*.5-N)*M|0;r<0?r=0:r>=O&&(r=O-1);let i=r<S?0:6;if(e[n]<P[i]&&(P[i]=e[n]),e[n+1]<P[i+1]&&(P[i+1]=e[n+1]),e[n+2]<P[i+2]&&(P[i+2]=e[n+2]),e[n+3]>P[i+3]&&(P[i+3]=e[n+3]),e[n+4]>P[i+4]&&(P[i+4]=e[n+4]),e[n+5]>P[i+5]&&(P[i+5]=e[n+5]),i===0)F++;else{let e=t[F];t[F]=t[I],t[I]=e,I--}}return F}_sweepSplit(e,t,n,r,i,a,o,s,c,l){let u=r-n,d=this._surfaceArea(i,a,o,s,c,l);if(!(d>0)||!isFinite(d))return n;let f=this._suffixBuffer(u),p=1/0,m=-1,h=-1;for(let i=0;i<3;i++){this._sortRange(e,t,n,r,i);let a=1/0,o=1/0,s=1/0,c=-1/0,l=-1/0,g=-1/0;for(let r=u-1;r>=1;r--){let i=t[n+r]*6;e[i]<a&&(a=e[i]),e[i+1]<o&&(o=e[i+1]),e[i+2]<s&&(s=e[i+2]),e[i+3]>c&&(c=e[i+3]),e[i+4]>l&&(l=e[i+4]),e[i+5]>g&&(g=e[i+5]);let u=r*6;f[u]=a,f[u+1]=o,f[u+2]=s,f[u+3]=c,f[u+4]=l,f[u+5]=g}let _=1/0,v=1/0,y=1/0,b=-1/0,x=-1/0,S=-1/0;for(let r=1;r<u;r++){let a=t[n+r-1]*6;e[a]<_&&(_=e[a]),e[a+1]<v&&(v=e[a+1]),e[a+2]<y&&(y=e[a+2]),e[a+3]>b&&(b=e[a+3]),e[a+4]>x&&(x=e[a+4]),e[a+5]>S&&(S=e[a+5]);let o=r*6,s=this._surfaceArea(_,v,y,b,x,S),c=this._surfaceArea(f[o],f[o+1],f[o+2],f[o+3],f[o+4],f[o+5]),l=1+(s*r+c*(u-r))/d;l<p&&(p=l,m=i,h=r)}}return m<0||h<=0?n:(m!==2&&this._sortRange(e,t,n,r,m),n+h)}_widestCentroidAxis(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=t[u]*6,r=(e[n]+e[n+3])*.5,d=(e[n+1]+e[n+4])*.5,f=(e[n+2]+e[n+5])*.5;r<i&&(i=r),r>s&&(s=r),d<a&&(a=d),d>c&&(c=d),f<o&&(o=f),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o;return d>u&&d>f?1:f>u?2:0}_insertionSortRange(e,t,n,r,i){let a=i,o=3+i;for(let i=n+1;i<r;i++){let r=t[i],s=e[r*6+a]+e[r*6+o],c=i-1;for(;c>=n&&e[t[c]*6+a]+e[t[c]*6+o]>s;)t[c+1]=t[c],c--;t[c+1]=r}}_sortRange(e,t,n,r,i){let a=r-n,o=this._sortScratch;o.length=a;for(let e=0;e<a;e++)o[e]=t[n+e];let s=i,c=3+i;o.sort((t,n)=>e[t*6+s]+e[t*6+c]-(e[n*6+s]+e[n*6+c]));for(let e=0;e<a;e++)t[n+e]=o[e]}_suffixBuffer(e){let t=e*6;return(!this._suffix||this._suffix.length<t)&&(this._suffix=new Float64Array(t)),this._suffix}_rangeBounds(e,t,n,r,i,a){let o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let i=n;i<r;i++){let n=t[i]*6;e[n]<o&&(o=e[n]),e[n+1]<s&&(s=e[n+1]),e[n+2]<c&&(c=e[n+2]),e[n+3]>l&&(l=e[n+3]),e[n+4]>u&&(u=e[n+4]),e[n+5]>d&&(d=e[n+5])}i[a]=o,i[a+1]=s,i[a+2]=c,i[a+3]=l,i[a+4]=u,i[a+5]=d}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const p={silent:0,error:1,warn:2,info:3,debug:4},m=`info`,h=`rayzeeLogLevel`,g=`rayzeeLogNamespaces`,_=`color:#7c8494`,v=`color:inherit`;let y=null,b=null;function x(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function S(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function C(){if(y!==null)return y;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in p?(y=p[e],y):(y=p[x(h)]??p[m],y)}function w(){if(b!==null)return b;let e=globalThis.__RAYZEE_LOG_NS__??x(g);return b=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],b}function T(e,t){if(t<p.debug)return!0;let n=w();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function E(e,t,n){if(e>C()||!T(t,e))return;let r=e===p.error?console.error:e===p.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,_,v,...n.slice(1)):r(`%c${i}`,_,...n)}const D={n:e=>Number(e).toLocaleString(`en-US`),ms:e=>e<10?`${Number(e).toFixed(1)} ms`:`${Math.round(e)} ms`,mb:e=>{let t=e/(1024*1024);return t<10?`${t.toFixed(1)} MB`:`${Math.round(t)} MB`},px:(e,t)=>`${e}×${t}`,count:(e,t,n=`${t}s`)=>`${D.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},O={levels:p,setLevel(e){return e in p?(globalThis.__RAYZEE_LOG_LEVEL__=e,y=p[e],S(h,e===m?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(p).join(`, `)}`),this.getLevel())},getLevel(){let e=C();return Object.keys(p).find(t=>p[t]===e)},isEnabled(e){return(p[e]??p.debug)<=C()},only(...e){let t=e.flat().filter(Boolean);return b=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),S(g,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return y=null,b=null,this.getLevel()}};function k(e){return{namespace:e,error:(...t)=>E(p.error,e,t),warn:(...t)=>E(p.warn,e,t),info:(...t)=>E(p.info,e,t),debug:(...t)=>E(p.debug,e,t),isEnabled:e=>O.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){E(p.info,e,[t]),r.forEach(t=>E(p.debug,e,[t]));return}p.info>C()||((C()>=p.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,_,v),r.forEach(e=>console.log(e)),console.groupEnd())}}}function A(e){e&&e in p&&(globalThis.__RAYZEE_LOG_LEVEL__=e,y=p[e])}const j=k(`bvh`);self.onmessage=function(e){let{aabbs:t,count:n,logLevel:r}=e.data;A(r);try{let e=performance.now(),{data:r,nodeCount:i}=new f().buildStructure(new Float64Array(t),n);j.debug(`TLAS ${D.n(i)} nodes in ${D.ms(performance.now()-e)}`),self.postMessage({tlasData:r,nodeCount:i},[r.buffer])}catch(e){j.error(`TLAS build failed:`,e),self.postMessage({error:e.message})}};",Id=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Fd],{type:`text/javascript;charset=utf-8`});function Ld(e){let t;try{if(t=Id&&(self.URL||self.webkitURL).createObjectURL(Id),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Fd),{type:`module`,name:e?.name})}}qt();var Rd=5e4,zd=Pt(`scene`),Bd=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:dt.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),maxSceneBytes:Yu,enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,...e},this.triangleData=null,this.triangleFloats=null,this.triangleCount=0,this.materials=[],this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.materialData=null,this.instanceTable=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.srgbBucketTextures=null,this.linearBucketTextures=null,this.emissiveTriangleData=null,this.emissiveTriangleCount=0,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this._initProcessors(),this.isProcessing=!1,this.processingStage=null,this.memory=new ed,this.memoryPreflight=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Nn({issues:this.config.issues}),this.bvhBuilder=new Zl,this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold}),this.textureCreator=new Sd({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Ad,this.tlasBuilder=new Hu,this._tlasWorker=null,this._tlasWorkerFailed=!1}_log(e,t){t===void 0?zd.debug(e):zd.debug(e,t)}_preflightMemory(e){let t=this.config.maxSceneBytes??9663676416,n=this.geometryExtractor.surveyScene(e),r=Qu(n),i={...n,estimate:r,safeBytes:Ju,maxBytes:t,fits:r.total<=Ju};if(this.memoryPreflight=i,r.total<1610612736)return i;if(zd.debug(Y.list([`memory preflight: ${Y.mb(r.total)} estimated`,`triangles ${Y.mb(r.triangles)} · bvh ${Y.mb(r.bvh)} · geometry ${Y.mb(r.geometry)}`,`${Y.n(n.triangles)} tris · ${Y.n(n.placements)} placements`])),r.total>t){let e=`Scene needs about ${Y.mb(r.total)} of CPU memory, past the ${Y.mb(t)} a browser tab can hold — loading it would crash the tab rather than fail. Reduce the scene (it has ${Y.n(n.triangles)} triangles), or raise maxSceneBytes to try anyway.`;throw this.config.issues?.record(ln.SCENE_MEMORY_BUDGET,e,{...n,estimate:r,maxBytes:t}),Error(e)}return i.fits||this.config.issues?.warn(ln.SCENE_MEMORY_BUDGET,`Scene needs about ${Y.mb(r.total)} of CPU memory, above the ${Y.mb(Ju)} a fresh browser session can usually place. It may still load, but a long-running session will probably fail during BVH assembly; restarting the browser recovers the address space.`,{...n,estimate:r,safeBytes:Ju}),i}_checkAssemblyHeadroom(e){let t=e*64;if(t<1610612736)return!0;let n=$u(Math.ceil(t*Xu),{shared:mn});return this.memoryPreflight&&(this.memoryPreflight.assemblyProbed=n.placed),n.exhausted&&this.config.issues?.warn(ln.SCENE_MEMORY_BUDGET,`BVH assembly needs ${Y.mb(t)} but only ${Y.mb(n.placed)} could be allocated. Restarting the browser usually recovers the address space.`,{totalNodes:e,need:t,placeable:n.placed}),!n.exhausted}_liveMemoryParts(){let e=this.instanceTable,t={triangles:this.triangles?.byteLength??0,bvh:this.bvh?.byteLength??0,geometry:this._geometryBytes??this.memoryPreflight?.geometryBytes??0,placements:e?.world?.byteLength??0,blasScratch:0,orderMaps:0};if(e){for(let n of e.blasData.values())t.blasScratch+=n?.byteLength??0;for(let n of e.bvhToOriginal.values())t.orderMaps+=n?.byteLength??0;for(let n of e.originalToBvhMap.values())t.orderMaps+=n?.byteLength??0}return t}sceneBounds(){if(!this.bvh||this.bvh.recordCount===0)return null;let e=this.bvh.chunkFor(0),t=this.bvh.baseOf(0),n=[],r=[];for(let i=0;i<3;i++)n.push(Math.min(e[t+i],e[t+8+i])),r.push(Math.max(e[t+4+i],e[t+12+i]));return{min:n,max:r}}_sampleMemory(e){this.memory.sample(e,this._liveMemoryParts())}_logMemoryReport(){let{allocatedBytes:e,peakLiveBytes:t,byPhase:n}=this.memory;if(e===0)return;let r=Object.keys(n).filter(e=>n[e].allocated>0).map(e=>`${e} ${Y.mb(n[e].allocated)}`),i=this.memoryPreflight?.estimate?.total;zd.debug(Y.list([`memory: peak live ${Y.mb(t)}`,`allocated ${Y.mb(e)}`,i?`predicted ${Y.mb(i)}`:null,r.join(` · `)]))}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`,this.memory.reset(),this._geometryBytes=0,gn(e=>this.memory.alloc(e));let t=new jd(e.name??``,{namespace:`scene`});try{this._reset(),this._log(`Starting scene processing`),this.memory.mark(`preflight`),this._preflightMemory(e),this.processingStage=`extraction`,this.memory.mark(`extraction`),t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this._geometryBytes=Dn(e),this._sampleMemory(`after extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,U({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||U({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvh&&this._setBVHData(this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,U({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,zd.error(`processing failed:`,e),U({status:`Error: ${e.message}`,failed:!0,progress:100}),e}finally{gn(null),this._sampleMemory(`at ${this.processingStage}`),this._logMemoryReport(),this.isProcessing=!1}}async _extractGeometry(e){U({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this._setTriangleData(n.triangleData),this.triangleCount=ut(n.triangleCount,`triangle count`),this.expandedTriangleCount=n.expandedTriangleCount??n.triangleCount,this.instanceSource=n.instanceSource||null,this.instanceMatrices=n.instanceMatrices||null,this.instanceCount=n.instanceCount||0,this.bakeInverse=n.bakeInverse||null,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangles.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.materialTriangleCounts=n.materialTriangleCounts,this.meshes=n.meshes,this.meshTriangleRanges=n.meshTriangleRanges,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,this.anisotropyMaps=n.anisotropyMaps,this.transmissionMaps=n.transmissionMaps,this.clearcoatMaps=n.clearcoatMaps,this.clearcoatRoughnessMaps=n.clearcoatRoughnessMaps,this.sheenColorMaps=n.sheenColorMaps,this.sheenRoughnessMaps=n.sheenRoughnessMaps,this.iridescenceMaps=n.iridescenceMaps,this.iridescenceThicknessMaps=n.iridescenceThicknessMaps,this.specularIntensityMaps=n.specularIntensityMaps,this.specularColorMaps=n.specularColorMaps,this.directionalLights=n.directionalLights,this.cameras=n.cameras;let r=performance.now()-t;this._log(`Geometry extraction complete (${r.toFixed(2)}ms)`,{triangleCount:this.triangleCount,materials:this.materials.length}),U({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw zd.error(`geometry extraction failed:`,e),U({status:`Extraction error: ${e.message}`,failed:!0,progress:25}),e}}async _buildBVH(){if(U({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`),this.memory.mark(`blas`);let e=performance.now();try{let t=this.meshTriangleRanges;if(!t||t.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);let n=this.instanceCount>0,r=n?this.instanceCount:t.length,i=this.instanceSource,a=n?this.instanceMatrices:null,o=e=>n?i[e]:e;this.instanceTable=new Fu,this.instanceTable.allocate(r,t.length,a,n?i:null),this.instanceTable.tplBakeInverse=this.bakeInverse;let s=this.config.enableTreeletOptimization,c=[],l=[],u=new Map,d=new Map;for(let e=0;e<r;e++){let n=t[o(e)];if(!n||n.count===0)continue;let r=d.get(n.start);if(r!==void 0){u.set(e,r);continue}d.set(n.start,e),n.count>=2e5&&Du(n.count)?l.push({m:e,range:n}):c.push({m:e,range:n})}let f={depth:this.config.bvhDepth,treeletOptimization:{enabled:s!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations},maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,logLevel:It()},p=c.length+l.length,m=0,h=()=>{m++,U({status:`Building BLAS ${m}/${p}...`,progress:25+Math.floor(m/p*45)})},g=this._buildBLASesWithPool(c,f,h),_=[],v=(async()=>{for(let{m:e,range:t}of l){let n=await wu(this.triangles.copyOf(t.start,t.count),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...f});n.reorderedTriangles&&(this.triangles.setRecords(t.start,n.reorderedTriangles),delete n.reorderedTriangles),_.push({m:e,range:t,result:n}),h()}})(),[y]=await Promise.all([g,v]),b={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:t,result:r}of[...y,..._]){let i=r.splitStats;i&&(b.sah+=i.sahSplits??0,b.objMed+=i.objectMedianSplits??0,b.spatMed+=i.spatialMedianSplits??0,b.failed+=i.failedSplits??0,b.treeletsImproved+=i.treeletsImproved??0,b.treeletsProcessed+=i.treeletsProcessed??0,this.performanceMetrics.blasWorkerTime+=i.totalBuildTime??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:t.start,triCount:t.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData,matrixWorld:n?a:this.meshes?.[e]?.matrixWorld?.elements??null,matrixOffset:n?e*16:0,expandedStart:t.expandedStart,sourceMesh:o(e)})}for(let[e,r]of u)this.instanceTable.setAlias(e,r,n?a:this.meshes?.[e]?.matrixWorld?.elements??null,t[o(e)].expandedStart,o(e),n?e*16:0);U({status:`Built all BLASes`,progress:70}),this.performanceMetrics.blasBuildTime=performance.now()-e,U({status:`Building TLAS...`,progress:72}),this._sampleMemory(`BLASes built`),this.memory.mark(`tlas`);let x=performance.now(),S=this.instanceTable;this.instanceTable.computeAABBs(this.triangles),this.instanceTable.assignOffsets(Hu.nodeCountFor(S.count));let C=this.instanceTable.totalNodeCount,w=await this._buildTLAS(S);this.performanceMetrics.tlasBuildTime=performance.now()-x,this.memory.mark(`assemble`);let T=performance.now();this._checkAssemblyHeadroom(C),this._setBVHData(vn.lazy(C,16,Float32Array,void 0,mn)),this.bvh.setRecords(0,w),w=null,this.tlasBuilder.releaseFlattenBuffer();let E=Math.max(1,Math.ceil(S.templateCount/32));for(let e=0;e<S.templateCount;e++){let t=S.blasData.get(e);if(!t)continue;let n=S.tplBlasOffset[e];this.bvh.setRecords(n,t),this._offsetBLASInPlace(n,t.length/16,n,S.tplTriOffset[e]),S.blasData.delete(e),e%E===0&&this._sampleMemory(`assembling ${e}/${S.templateCount}`)}this._setBVHData(this.bvh.materializeAll()),this._buildBvhToOriginalMaps(),this.performanceMetrics.bvhAssembleTime=performance.now()-T,S.originalToBvhMap.clear(),S.blasData.clear(),this.bvhRoot=!0,this._disposeRefitWorker();let D=performance.now()-e;zd.debug(Y.list([`${Y.n(S.setCount)} BLASes + TLAS`,`${Y.n(this.bvh.recordCount)} nodes`,`SAH ${Y.n(b.sah)} · objMed ${b.objMed} · spatMed ${b.spatMed} · failed ${b.failed}`,b.treeletsProcessed?`treelets ${b.treeletsImproved}/${b.treeletsProcessed} improved`:null,Y.ms(D)])),U({status:`BVH construction complete`,progress:75})}catch(e){throw zd.error(`BVH build failed:`,e),U({status:`BVH error: ${e.message}`,failed:!0,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){let i=this.bvhIndexChunks;for(let a=0;a<t;a++){let t=e+a,o=i.chunkFor(t),s=i.baseOf(t);o[s+3]===ct.TRIANGLE_LEAF?o[s]+=r:(o[s+3]+=n,o[s+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),i=[],a=0,o=0;return new Promise((s,c)=>{let l=[],u=n=>{if(a>=e.length){n.terminate(),l.splice(l.indexOf(n),1),l.length===0&&s(i);return}let{m:r,range:o}=e[a++],c=this.triangles.copyOf(o.start,o.count),u=o.count,d=u<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:r,range:o},n.postMessage({triangleData:c.buffer,triangleByteOffset:c.byteOffset,triangleByteLength:c.byteLength,triangleCount:u,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:d,reinsertionOptimization:t.reinsertionOptimization,maxLeafSize:t.maxLeafSize,numBins:t.numBins,maxBins:t.maxBins,minBins:t.minBins,logLevel:t.logLevel},[c.buffer])},d=(e,t)=>{let r=t.data;if(r.error){l.forEach(e=>e.terminate()),c(Error(r.error));return}if(r.progress!==void 0)return;let{m:a,range:s}=e._currentTask;r.triangles&&this.triangles.setRecords(s.start,r.triangles),i.push({m:a,range:s,result:{bvhData:r.bvhData,originalToBvh:r.originalToBvh||null,splitStats:r.treeletStats||null}}),o++,n?.(o),u(e)};(async()=>{for(let e=0;e<r;e++){let e;try{e=new gu}catch(e){c(e);return}e.onmessage=t=>d(e,t),e.onerror=e=>{l.forEach(e=>e.terminate()),c(e)},l.push(e),u(e)}})().catch(c)})}_buildBvhToOriginalMaps(){let e=this.instanceTable;for(let t=0;t<e.count;t++){if(!e.isSet[t]||!e.isOwner(t))continue;let n=e.sourceMesh[t],r=e.tplTriCount[n],i=e.originalToBvhMap.get(n),a=new Uint32Array(r);if(i)for(let e=0;e<r;e++)a[i[e]]=e;else for(let e=0;e<r;e++)a[e]=e;e.bvhToOriginal.set(n,a),e.originalToBvhMap.delete(n)}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{let{srgbLists:e,linearLists:t,remap:n}=this._bucketTextures();this._remapMaterialTextureIndices(n),this.materials?.length&&(this.materialData=this.textureCreator.createMaterialRawData(this.materials));let i=(e,t)=>e.length===0?Promise.resolve(null):this.textureCreator.createTexturesToDataTexture(e,{srgbPool:t}).then(e=>(e&&t&&(e.colorSpace=r.SRGBColorSpace),e)),[a,o]=await Promise.all([Promise.all(e.map(e=>i(e,!0))),Promise.all(t.map(e=>i(e,!1)))]);this.srgbBucketTextures=a,this.linearBucketTextures=o,this._log(`Material textures complete`,{materialData:!!this.materialData,srgbBuckets:a.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`),linearBuckets:o.map(e=>e?`${e.image.width}x${e.image.height}x${e.image.depth}`:`-`).join(`,`)})}catch(e){throw zd.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=dt.MATERIAL_BUCKET_COUNT,n=dt.BUCKET_LAYER_STRIDE,r=e=>{let t=new Set,n=[];for(let r of e)for(let e of r||[]){if(!e?.image)continue;let r=e.source?.uuid??e.uuid;t.has(r)||(t.add(r),n.push({width:e.image.width,height:e.image.height}))}return n},i=[this.maps,this.emissiveMaps,this.sheenColorMaps,this.specularColorMaps],a=[this.normalMaps,this.bumpMaps,this.roughnessMaps,this.metalnessMaps,this.displacementMaps,this.anisotropyMaps,this.transmissionMaps,this.clearcoatMaps,this.clearcoatRoughnessMaps,this.sheenRoughnessMaps,this.iridescenceMaps,this.iridescenceThicknessMaps,this.specularIntensityMaps],o=bt(r(i),e,t),s=bt(r(a),e,t);this._srgbBucketShapes=o,this._linearBucketShapes=s;let c=Array.from({length:t},()=>[]),l=Array.from({length:t},()=>[]),u=Array.from({length:t},()=>new Map),d=Array.from({length:t},()=>new Map);this._srgbTexPacked=new Map,this._linearTexPacked=new Map;let f=!1,p=!1,m=(e,t,r,i,a)=>{if(!e)return-1;if(!e.image)return p||this.config.issues?.record(ln.TEXTURE_BUILD_FAILED,`a material map had not finished decoding when the scene was packed; it renders untextured`,{texture:e.name||e.source?.uuid||e.uuid}),p=!0,-1;let o=xt(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return St(o,c);if(t[o].length>=n)return zd.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(ln.TEXTURE_LIMIT_EXCEEDED,`texture bucket ${o} full (${n} layers); the rest render untextured`,{bucket:o,limit:n}),f=!0,-1;t[o].push(e);let l=t[o].length-1;r[o].set(s,l);let u=St(o,l);return i.set(s,u),u},h=(e,t,n,r,i)=>(e||[]).map(e=>m(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:h(this.maps,c,u,this._srgbTexPacked,o),emissive:h(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:h(this.normalMaps,l,d,this._linearTexPacked,s),bump:h(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:h(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:h(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:h(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:h(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:h(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:h(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:h(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:h(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:h(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:h(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:h(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:h(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:h(this.specularColorMaps,c,u,this._srgbTexPacked,o)}}}_remapMaterialTextureIndices(e){let t=(e,t)=>e>=0&&e<t.length?t[e]:-1;for(let n of this.materials)n.map=t(n.map,e.albedo),n.emissiveMap=t(n.emissiveMap,e.emissive),n.normalMap=t(n.normalMap,e.normal),n.bumpMap=t(n.bumpMap,e.bump),n.roughnessMap=t(n.roughnessMap,e.roughness),n.metalnessMap=t(n.metalnessMap,e.metalness),n.displacementMap=t(n.displacementMap,e.displacement),n.anisotropyMap=t(n.anisotropyMap,e.anisotropy),n.transmissionMap=t(n.transmissionMap,e.transmission),n.clearcoatMap=t(n.clearcoatMap,e.clearcoat),n.clearcoatRoughnessMap=t(n.clearcoatRoughnessMap,e.clearcoatRoughness),n.sheenColorMap=t(n.sheenColorMap,e.sheenColor),n.sheenRoughnessMap=t(n.sheenRoughnessMap,e.sheenRoughness),n.iridescenceMap=t(n.iridescenceMap,e.iridescence),n.iridescenceThicknessMap=t(n.iridescenceThicknessMap,e.iridescenceThickness),n.specularIntensityMap=t(n.specularIntensityMap,e.specularIntensity),n.specularColorMap=t(n.specularColorMap,e.specularColor)}_buildEmissiveData(){this.emissiveTriangleCount=this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this._setTriangleData(null),this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.anisotropyMaps=[],this.transmissionMaps=[],this.clearcoatMaps=[],this.clearcoatRoughnessMaps=[],this.sheenColorMaps=[],this.sheenRoughnessMaps=[],this.iridescenceMaps=[],this.iridescenceThicknessMaps=[],this.specularIntensityMaps=[],this.specularColorMaps=[],this.directionalLights=[],this.cameras=[],this.spheres=[],this.bvhRoot=null,this.bvh=null,this.bvhData=null,this.bvhIndexChunks=null,this.bvhIndex=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,blasBuildTime:0,blasWorkerTime:0,tlasBuildTime:0,bvhAssembleTime:0,totalProcessingTime:0}}_disposeTextures(){this._disposeBucketTextures()}_disposeBucketTextures(){for(let e of[`srgbBucketTextures`,`linearBucketTextures`]){let t=this[e];if(t){for(let n of t)if(n&&typeof n.dispose==`function`)try{n.dispose()}catch(t){zd.warn(`error disposing ${e}:`,t)}this[e]=null}}}async rebuildMaterials(e){if(this.isProcessing)throw Error(`Already processing. Cannot rebuild materials during processing.`);this._log(`Rebuilding materials and textures`);let t=performance.now();try{this.isProcessing=!0;let n=this.geometryExtractor.extractMaterialsOnly(e);this._disposeMaterialTextures(),this.materials=n.materials,this.meshes=n.meshes,this.maps=n.maps,this.normalMaps=n.normalMaps,this.bumpMaps=n.bumpMaps,this.roughnessMaps=n.roughnessMaps,this.metalnessMaps=n.metalnessMaps,this.emissiveMaps=n.emissiveMaps,this.displacementMaps=n.displacementMaps,await this._createMaterialTextures();let r=performance.now()-t;return this._log(`Material rebuild complete (${r.toFixed(2)}ms)`,{materials:this.materials.length,textures:this.maps.length}),this}catch(e){throw zd.error(`material rebuild failed:`,e),e}finally{this.isProcessing=!1}}_disposeMaterialTextures(){this._disposeBucketTextures(),this.textureCreator&&this.textureCreator.textureCache&&(this.textureCreator.textureCache.dispose(),this.textureCreator.textureCache=new this.textureCreator.textureCache.constructor)}getStatistics(){let e={triangleCount:this.triangleCount,materialCount:this.materials.length,textureCount:this.maps.length,lightCount:this.directionalLights.length,cameraCount:this.cameras.length,processingComplete:this.processingStage===`complete`,hasBVH:!!this.bvhRoot,hasTextures:!!this.materialData&&!!this.bvh,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangles?(this.triangles.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}_adoptSharedChunks(e,t){let n=this[e];if(n.shared)return;let r=n.chunks.map(e=>{let n=new t(new SharedArrayBuffer(e.byteLength));return n.set(e),n}),i=vn.adopt(r,n.recordCount,n.lanesPerRecord,n.recordsPerChunk);e===`bvh`?this._setBVHData(i):this._setTriangleData(i)}_meshSource(e,t){if(e==null)return null;let n=this.instanceTable;if(typeof e==`function`)return r=>{let i=n.sourceMesh[r],a=e(i,n.triCountOf(r)),o=n.triCountOf(r)*9;if(a&&a.length!==o)throw Error(`SceneProcessor: ${t}s for mesh ${i} must be ${o} floats (${n.triCountOf(r)} triangles × 9), got ${a.length}.`);return a??null};let r=(this.expandedTriangleCount??this.triangleCount)*9;if(e.length!==r)throw Error(`SceneProcessor: expected ${r} ${t} floats (${r/9} triangles × 9, full scene), got ${e.length}. Pass a per-mesh callback instead to avoid building one array for the whole scene.`);return t=>{let r=n.expandedStartOf(t)*9;return e.subarray(r,r+n.triCountOf(t)*9)}}async refitBVH(e,t){if(!this.bvh||!this.triangles||!this.instanceTable)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this._meshSource(e,`position`),r=this._meshSource(t,`normal`);if(!n)throw Error(`SceneProcessor.refitBVH: positions are required.`);if(this._refitWorker||=new Pd,!this._refitSharedBuffers){this._adoptSharedChunks(`bvh`,Float32Array),this._adoptSharedChunks(`triangles`,Uint32Array);let e=this.bvh.chunks.map(e=>e.buffer),t=this.triangles.chunks.map(e=>e.buffer);this._refitSharedBuffers={bvhBufs:e,triBufs:t},this._refitWorker.postMessage({type:`init`,sharedBvhBufs:e,bvhRecordCount:this.bvh.recordCount,bvhRecordsPerChunk:this.bvh.recordsPerChunk,sharedTriBufs:t,triRecordCount:this.triangles.recordCount,triLanesPerRecord:this.triangles.lanesPerRecord,triRecordsPerChunk:this.triangles.recordsPerChunk})}let i=this.instanceTable;for(let e=0;e<i.count;e++){if(!i.isSet[e]||!i.isOwner(e))continue;let t=n(e);if(t&&(this._updateMeshTrianglePositions(e,t),r)){let t=r(e);t&&this._patchMeshSmoothNormals(e,t)}}return new Promise((e,t)=>{this._refitWorker.onmessage=n=>{let r=n.data;r.type===`refitComplete`?e({refitTimeMs:r.refitTimeMs}):r.type===`error`&&t(Error(r.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){let t=this.instanceTable;if(t)for(let n=0;n<t.count;n++){if(!t.isSet[n]||!t.isOwner(n))continue;let r=e(n);r&&this._patchMeshSmoothNormals(n,r)}}_placementOf(e){return this.instanceTable?.placementRunOf(e)?.start??-1}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvh||!this.triangles)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this._meshSource(t,`position`),i=this._meshSource(n,`normal`);if(!r)throw Error(`SceneProcessor.refitBLASes: positions are required.`);let a=performance.now();this._blasRefitter||=new pu;let o=this.instanceTable;for(let t of e){let e=this._placementOf(t);if(e<0||!o.isSet[e])continue;if(!o.isOwner(e)){let n=o.tplOwner[o.sourceMesh[e]];this.config.issues?.record(ln.REFIT_SHARED_GEOMETRY,`mesh ${t} shares its triangles with another placement; deforming it would move every copy, so it was skipped`,{meshIndex:t,owner:o.sourceMesh[n]??n});continue}let n=r(e);if(n){if(this._updateMeshTrianglePositions(e,n),i){let t=i(e);t&&this._patchMeshSmoothNormals(e,t)}this._blasRefitter.refitRange(this.bvh,this.triangles,o.blasOffsetOf(e),o.blasNodeCountOf(e)),this.instanceTable.recomputeAABB(e,this.bvh,this.triangles)}}return this._refitTLAS(),{refitTimeMs:performance.now()-a}}updateMeshTransforms(e){if(!this.instanceTable||!this.bvh)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let t=performance.now(),n=this.instanceTable,r=this._transformScratch??=new Float32Array(16),i=0;for(let t of e){let e=this.meshes?.[t],a=n.placementRunOf(t);if(!e||!a)continue;e.updateMatrixWorld(!0);let o=e.matrixWorld.elements,s=e.isInstancedMesh?this._ownInstanceMatrices(e):null,c=n.tplBakeInverse?.get(n.sourceMesh[a.start])??null;for(let e=0;e<a.count;e++){let t=a.start+e;n.isSet[t]&&(s?(ju(o,s,e*16,r),n.setPlacementMatrix(t,r)):c?(ju(o,c,0,r),n.setPlacementMatrix(t,r)):n.setPlacementMatrix(t,o),this._writeLeafMatrix(t),i++)}}return this._refitTLAS(),{refitTimeMs:performance.now()-t,placements:i}}_ownInstanceMatrices(e){let t=e.instanceMatrix;return t?.array?(t.array.buffer===this.instanceTable.world.buffer&&(t.array=t.array.slice(),t.needsUpdate=!0),t.array):null}_writeLeafMatrix(e){let t=this.instanceTable.tlasLeafIndex[e];t<0||Hu.writeLeafMatrix(this.bvh.chunkFor(t),this.bvhIndexChunks.chunkFor(t),this.bvh.baseOf(t),this.instanceTable.world,e)}computeTLASDirtyRange(){return{offset:0,count:this.instanceTable.tlasNodeCount*16}}computeBLASDirtyRanges(e){let t=$e.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable,a=this._placementOf(i);a<0||!e.isSet[a]||(n.push({offset:e.triOffsetOf(a)*t,count:e.triCountOf(a)*t}),r.push({offset:e.blasOffsetOf(a)*16,count:e.blasNodeCountOf(a)*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangles?(e.setTriangleData(this.triangles,this.triangleCount),this.bvh?(e.setBVHData(this.bvh),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData,this.materials.map(e=>e.sources)):zd.warn(`no material data, using defaults`),r&&e.environment.setEnvironmentTexture(r),e.materialData.setMaterialTextures({srgbBuckets:this.srgbBucketTextures,linearBuckets:this.linearBucketTextures}),e.materialData.setTexturePackMaps?.(this._srgbTexPacked,this._linearTexPacked),this.emissiveTriangleData&&e.setEmissiveTriangleData(this.emissiveTriangleData,this.emissiveTriangleCount,this.emissiveTotalPower,this.emissiveBitTrailMap),this.lightBVHNodeData&&e.setLightBVHData(this.lightBVHNodeData,this.lightBVHNodeCount),t.transferSceneLights(n),!0):(zd.error(`failed to get BVH data`),!1)):(zd.error(`failed to get triangle data`),!1)}updateMaterialEmissive(e,t,n){if(!this.emissiveTriangleBuilder)return null;let r=this.materials[e];return!r||(t===`emissive`?r.emissive=n:t===`emissiveIntensity`&&(r.emissiveIntensity=n),!this.emissiveTriangleBuilder.updateMaterialEmissive(e,r,this.triangles,this.materials,this.triangleCount))?null:this._collectEmissivePayload()}rebuildEmissiveColors(){return!this.emissiveTriangleBuilder||!this.triangleCount?null:(this.emissiveTriangleBuilder.extractEmissiveTriangles(this.triangles,this.materials,this.triangleCount,this.instanceTable??null),this.emissiveTriangleBuilder.createEmissiveRawData(),this._collectEmissivePayload())}rebuildEmissiveForVisibility(e,t=!1){return!this.emissiveTriangleBuilder||!this.emissiveTriangleBuilder.setHiddenMeshes(e)&&!t?null:this._collectEmissivePayload()}movesEmitters(e){let t=this.emissiveTriangleBuilder?.emissiveMeshes;return!!t?.size&&e.some(e=>t.has(e))}refreshEmissiveTransforms(){let e=this.emissiveTriangleBuilder;return!e?.emissiveTriangles.length||!this.instanceTable||!this.triangles?null:(e.refreshTransforms(this.triangles,this.instanceTable),this._collectEmissivePayload())}_collectEmissivePayload(){return this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,{rawData:this.emissiveTriangleData,emissiveCount:this.emissiveTriangleCount,totalPower:this.emissiveTotalPower,bitTrailMap:this.emissiveBitTrailMap,lightBVHNodeData:this.lightBVHNodeData,lightBVHNodeCount:this.lightBVHNodeCount}}async _buildTLAS(e){let t=e.count;if(t>=Rd&&!this._tlasWorkerFailed)try{let n=new Float64Array(t*6);e.writeWorldAABBs(n);let{tlasData:r,nodeCount:i}=await this._runTLASWorker(n,t);return Hu.fillLeaves(r,i,e),r}catch(e){this._tlasWorkerFailed=!0,zd.warn(`TLAS worker unavailable (${e.message}); building on the main thread`)}return this.tlasBuilder.build(e).data}_runTLASWorker(e,t){this._tlasWorker||=new Ld;let n=this._tlasWorker;return new Promise((r,i)=>{let a=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),e.data?.error?i(Error(e.data.error)):r(e.data)},o=e=>{n.removeEventListener(`message`,a),n.removeEventListener(`error`,o),i(Error(e.message||`worker error`))};n.addEventListener(`message`,a),n.addEventListener(`error`,o),n.postMessage({aabbs:e.buffer,count:t,logLevel:It()},[e.buffer])})}_setBVHData(e){let t=e?e instanceof vn?e:vn.adopt([e],e.length/16,16,e.length/16):null;this.bvh=t,this.bvhIndexChunks=t?t.viewAs(Uint32Array):null,this.bvhData=t?t.single:null,this.bvhIndex=this.bvhIndexChunks?this.bvhIndexChunks.single:null}_setTriangleData(e){let t=$e.FLOATS_PER_TRIANGLE,n=e?e instanceof vn?e:vn.adopt([e],e.length/t,t,e.length/t):null;this.triangles=n,this.triangleFloatChunks=n?n.viewAs(Float32Array):null,this.triangleData=n?n.single:null,this.triangleFloats=this.triangleFloatChunks?this.triangleFloatChunks.single:null}_updateMeshTrianglePositions(e,t){let n=$e.POSITION_A_OFFSET,r=$e.POSITION_B_OFFSET,i=$e.POSITION_C_OFFSET,a=$e.NORMAL_A_PACKED_OFFSET,o=$e.NORMAL_B_PACKED_OFFSET,s=$e.NORMAL_C_PACKED_OFFSET,c=this.triangles,l=this.triangleFloatChunks,u=this.instanceTable,d=u.bvhToOriginalOf(e),f=u.triOffsetOf(e),p=u.triCountOf(e),m=u.matrixInverseOf(e),h=Mu(m);for(let e=0;e<p;e++){let u=d?d[e]:e,p=f+e,g=l.chunkFor(p),_=c.chunkFor(p),v=c.baseOf(p),y=u*9,b=t[y],x=t[y+1],S=t[y+2],C=t[y+3],w=t[y+4],T=t[y+5],E=t[y+6],D=t[y+7],O=t[y+8];if(!h){let e=(e,t,n)=>m[0]*e+m[4]*t+m[8]*n+m[12],t=(e,t,n)=>m[1]*e+m[5]*t+m[9]*n+m[13],n=(e,t,n)=>m[2]*e+m[6]*t+m[10]*n+m[14],r=[e(b,x,S),t(b,x,S),n(b,x,S)],i=[e(C,w,T),t(C,w,T),n(C,w,T)],a=[e(E,D,O),t(E,D,O),n(E,D,O)];b=r[0],x=r[1],S=r[2],C=i[0],w=i[1],T=i[2],E=a[0],D=a[1],O=a[2]}g[v+n]=b,g[v+n+1]=x,g[v+n+2]=S,g[v+r]=C,g[v+r+1]=w,g[v+r+2]=T,g[v+i]=E,g[v+i+1]=D,g[v+i+2]=O;let k=C-b,A=w-x,j=T-S,M=E-b,N=D-x,P=O-S,F=nt(A*P-j*N,j*M-k*P,k*N-A*M);_[v+a]=F,_[v+o]=F,_[v+s]=F}}_patchMeshSmoothNormals(e,t){let n=this.instanceTable;this._patchNormalsRange(t,n.triOffsetOf(e),n.triCountOf(e),n.matrixWorldOf(e),n.bvhToOriginalOf(e))}_patchNormalsRange(e,t,n,r,i){let a=$e.NORMAL_A_PACKED_OFFSET,o=$e.NORMAL_B_PACKED_OFFSET,s=$e.NORMAL_C_PACKED_OFFSET,c=r,l=!c||Mu(c),u=[a,o,s];for(let r=0;r<n;r++){let n=t+r,a=this.triangles.chunkFor(n),o=this.triangles.baseOf(n),s=(i?i[r]:r)*9;for(let t=0;t<3;t++){let n=s+t*3,r=e[n],i=e[n+1],d=e[n+2],f=r,p=i,m=d;if(!l){f=c[0]*r+c[1]*i+c[2]*d,p=c[4]*r+c[5]*i+c[6]*d,m=c[8]*r+c[9]*i+c[10]*d;let e=Math.hypot(f,p,m)||1;f/=e,p/=e,m/=e}a[o+u[t]]=nt(f,p,m)}}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6));let t=this.instanceTable;for(let n=e-1;n>=0;n--){let e=this.bvhIndexChunks.chunkFor(n),r=this.bvh.chunkFor(n),i=this.bvh.baseOf(n),a=e[i+3];if(a===ct.BLAS_POINTER_LEAF){let r=e[i+1]&st;r<t.count&&t.writeWorldAABB(r,this._tlasBounds,n*6)}else if(a<ct.TRIANGLE_LEAF){let t=a,o=e[i+7],s=t*6,c=o*6,l=this._tlasBounds;r[i]=l[s],r[i+1]=l[s+1],r[i+2]=l[s+2],r[i+4]=l[s+3],r[i+5]=l[s+4],r[i+6]=l[s+5],r[i+8]=l[c],r[i+9]=l[c+1],r[i+10]=l[c+2],r[i+12]=l[c+3],r[i+13]=l[c+4],r[i+14]=l[c+5];let u=n*6;l[u]=Math.min(l[s],l[c]),l[u+1]=Math.min(l[s+1],l[c+1]),l[u+2]=Math.min(l[s+2],l[c+2]),l[u+3]=Math.max(l[s+3],l[c+3]),l[u+4]=Math.max(l[s+4],l[c+4]),l[u+5]=Math.max(l[s+5],l[c+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangles)return;this._rebuildGeneration++;let n=this._rebuildGeneration,r=(e,r,i)=>{let a=this.triangles.copyOf(r.triOffset,r.triCount);this._pendingRebuilds.set(e,i),i.onmessage=a=>{let o=a.data;if(i.terminate(),this._pendingRebuilds.delete(e),o.error){zd.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}n===this._rebuildGeneration&&this._swapBLAS(e,r,o,t)},i.onerror=t=>{zd.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),i.terminate(),this._pendingRebuilds.delete(e)};let o=r.triCount>500;i.postMessage({triangleData:a.buffer,triangleByteOffset:a.byteOffset,triangleByteLength:a.byteLength,triangleCount:r.triCount,depth:this.config.bvhDepth,maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:o,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[a.buffer])};for(let t of e){let e=this._placementOf(t);if(e<0)continue;let n=this.instanceTable.entryAt(e);if(!n||!this.instanceTable.isOwner(e))continue;let i=this._pendingRebuilds.get(e);i&&i.terminate(),r(e,n,new gu)}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a>t.blasNodeCount){zd.warn(`background rebuild does not fit for mesh ${e} (${a} nodes vs ${t.blasNodeCount} reserved), skipping swap`);return}this.bvh.setRecords(t.blasOffset,i),this._offsetBLASInPlace(t.blasOffset,a,t.blasOffset,t.triOffset);let o=n.triangles;o&&this.triangles.setRecords(t.triOffset,o),this.instanceTable.setBlasNodeCount(e,a);let s=n.originalToBvh;if(s){let n=this.instanceTable.bvhToOriginalOf(e),r=new Uint32Array(t.triCount);for(let e=0;e<t.triCount;e++)r[s[e]]=n?n[e]:e;this.instanceTable.setBvhToOriginal(e,r)}this.instanceTable.recomputeAABB(e,this.bvh,this.triangles),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.(this.instanceTable.sourceMesh[e]??e)}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}_disposeTLASWorker(){this._tlasWorker&&=(this._tlasWorker.terminate(),null)}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTLASWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},Vd=[[1619.19106,-.00205010916,5.02995757],[2488.45471,-.00111330907,3.22621544],[3341.43193,-.000486551192,1.76486769],[4094.61742,-.000127446582,.725731635],[4670.28036,291258199e-13,.126703442],[4595.09185,287495649e-13,.15034502],[3787.1745,935907826e-14,.399075871]],Hd=[[-488.999748,.000604330754,-.0755807526],[-755.994277,.000316730098,.478306139],[-1023.63977,.00012022347,.936662319],[-1265.71316,487340896e-14,1.27054498],[-1425.29332,-401150431e-13,1.43972784],[-1175.54822,-216378048e-13,1.30408023],[-500.799571,-459832026e-14,1.09098763]],Ud=[[596945309e-19,-4.85742887e-8,-970622247e-13,-.00407936148],[240430366e-19,5.55021075e-8,-.000198503712,.0289312858],[-140949732e-19,1.89878968e-7,-.000356632824,.0910767778],[-361460868e-19,2.84822009e-7,-.000493211319,.15672344],[-197075738e-19,1.75359352e-7,-.000250542825,-.0222783266],[-161997957e-21,-1.64216008e-8,.000386216271,-.738077418],[672650283e-21,-2.73078809e-8,.000424098264,-.752335691]];function Wd(e){let t,n,r;if(e>=12e3)t=.8262954810464208,n=.9945080501520986,r=1.566307710274283;else if(e<800)t=5.413294490189271,n=-.20319390035873933,r=-.0822535242887164;else{let i=e>=6365?6:e>=3315?5:e>=1902?4:e>=1449?3:e>=1167?2:+(e>=965),a=Vd[i],o=Hd[i],s=Ud[i],c=1/e;t=a[0]*c+a[1]*e+a[2],n=o[0]*c+o[1]*e+o[2],r=((s[0]*e+s[1])*e+s[2])*e+s[3]}return[Math.max(0,t),Math.max(0,n),Math.max(0,r)]}var Gd=1/(4*Math.PI);function Kd(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=[e.color.r,e.color.g,e.color.b];if(t.useTemperature){let[e,n,r]=Wd(t.temperature??6500);i[0]*=e,i[1]*=n,i[2]*=r}return zn(i),{r:i[0],g:i[1],b:i[2],intensity:r}}var qd=class{constructor(){this.lightData={directional:[],rectArea:[],point:[],spot:[]},this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}clear(){this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache=[],this.areaLightCache=[],this.pointLightCache=[],this.spotLightCache=[]}calculateLightImportance(e,t=`directional`){let n=.2126*e.color.r+.7152*e.color.g+.0722*e.color.b,r=e.intensity*n;if(t===`area`){let t=e.width*e.height;r*=Math.sqrt(t)}else if(t===`point`)r*=Math.sqrt(e.distance||100);else if(t===`spot`){let t=Math.sin(e.angle||Math.PI/4);r*=Math.sqrt(e.distance||100)*t}return r}addDirectionalLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n;if(e.target){e.target.updateMatrixWorld();let i=e.target.getWorldPosition(new r.Vector3);n=t.sub(i).normalize()}else n=t.normalize();let i=this.calculateLightImportance(e,`directional`),a=e.userData.angle||e.angle||0,o=Kd(e),s=e.userData?.gobo,c=s&&Number.isInteger(s.index)?s.index:-1,l=s&&typeof s.intensity==`number`?s.intensity:1,u=s&&s.inverted?-Math.abs(l):Math.abs(l),d=s&&typeof s.scale==`number`?s.scale:5;this.directionalLightCache.push({data:[n.x,n.y,n.z,o.r,o.g,o.b,o.intensity,a,c,u,d,0],importance:i,light:e})}addRectAreaLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=e.getWorldQuaternion(new r.Quaternion),i=e.getWorldScale(new r.Vector3),a=e.width*i.x*.5,o=e.height*i.y*.5,s=new r.Vector3(a,0,0).applyQuaternion(n),c=new r.Vector3(0,-o,0).applyQuaternion(n),l=this.calculateLightImportance(e,`area`),u=e.userData?.normalize??!0?1:0,d=Number.isFinite(e.userData?.spread)?e.userData.spread:Math.PI,f=+(e.userData?.shape===`ellipse`||e.userData?.shape===`disk`||e.userData?.shape===1),p=Kd(e);this.areaLightCache.push({data:[t.x,t.y,t.z,s.x,s.y,s.z,c.x,c.y,c.z,p.r,p.g,p.b,p.intensity,u,d,f],importance:l,light:e})}addPointLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=this.calculateLightImportance(e,`point`),i=Kd(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*Gd,e.distance||0,e.decay===void 0?2:e.decay],importance:n,light:e})}addSpotLight(e){if(!e.visible||e.intensity<=0)return;e.updateMatrixWorld();let t=e.getWorldPosition(new r.Vector3),n=(e.target?e.target.getWorldPosition(new r.Vector3):new r.Vector3(0,0,-1)).sub(t).normalize(),i=this.calculateLightImportance(e,`spot`),a=e.userData?.gobo,o=a&&Number.isInteger(a.index)?a.index:-1,s=a&&typeof a.intensity==`number`?a.intensity:1,c=a&&a.inverted?-Math.abs(s):Math.abs(s),l=e.userData?.ies,u=l&&Number.isInteger(l.index)?l.index:-1,d=l&&typeof l.intensity==`number`?l.intensity:1,f=Kd(e);this.spotLightCache.push({data:[t.x,t.y,t.z,n.x,n.y,n.z,f.r,f.g,f.b,f.intensity*Gd,e.angle||Math.PI/4,e.penumbra||0,e.distance||0,e.decay===void 0?2:e.decay,o,c,u,d,0,0],importance:i,light:e})}preprocessLights(){this.directionalLightCache.sort((e,t)=>t.importance-e.importance),this.areaLightCache.sort((e,t)=>t.importance-e.importance),this.pointLightCache.sort((e,t)=>t.importance-e.importance),this.spotLightCache.sort((e,t)=>t.importance-e.importance),this.lightData.directional=[],this.lightData.rectArea=[],this.lightData.point=[],this.lightData.spot=[],this.directionalLightCache.forEach(e=>{this.lightData.directional.push(...e.data)}),this.areaLightCache.forEach(e=>{this.lightData.rectArea.push(...e.data)}),this.pointLightCache.forEach(e=>{this.lightData.point.push(...e.data)}),this.spotLightCache.forEach(e=>{this.lightData.spot.push(...e.data)}),this.areaLightCache.length>0&&console.log(`Preprocessed ${this.areaLightCache.length} area lights by importance`),this.pointLightCache.length>0&&console.log(`Preprocessed ${this.pointLightCache.length} point lights by importance`),this.spotLightCache.length>0&&console.log(`Preprocessed ${this.spotLightCache.length} spot lights by importance`)}updateShaderUniforms(e){let t=Math.floor(this.lightData.directional.length/12),n=Math.floor(this.lightData.rectArea.length/16),r=Math.floor(this.lightData.point.length/9),i=Math.floor(this.lightData.spot.length/20);e.defines.MAX_DIRECTIONAL_LIGHTS=t,e.defines.MAX_AREA_LIGHTS=n,e.defines.MAX_POINT_LIGHTS=r,e.defines.MAX_SPOT_LIGHTS=i,e.uniforms.directionalLights.value=new Float32Array(this.lightData.directional),e.uniforms.areaLights.value=new Float32Array(this.lightData.rectArea),e.uniforms.pointLights.value=new Float32Array(this.lightData.point),e.uniforms.spotLights.value=new Float32Array(this.lightData.spot),e.needsUpdate=!0}processSceneLights(e,t){this.clear(),e.traverse(e=>{e.isDirectionalLight?this.addDirectionalLight(e):e.isRectAreaLight?this.addRectAreaLight(e):e.isPointLight?this.addPointLight(e):e.isSpotLight&&this.addSpotLight(e)}),this.preprocessLights(),this.updateShaderUniforms(t)}getLightStatistics(){return{directionalLights:this.directionalLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color})),areaLights:this.areaLightCache.map(e=>({intensity:e.light.intensity,importance:e.importance,color:e.light.color,size:e.light.width*e.light.height}))}}};Ar(),qt();var Jd=Pt(`pathtracer`),Yd=100,Xd=4,Zd=class extends V{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:ye.ALWAYS});let a=i.width||1920,o=i.height||1080;this.camera=n,this.width=a,this.height=o,this.renderer=e,this.scene=t,this.sdfs=new Bd,this.lightSerializer=new qd,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Fe(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new Zt(0,0),this.uniforms=new $t(a,o),this._defineUniformGetters(),this.materialData=new Jn(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this.triangleStorageAttr?.array,records:this._triangleRecords,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleStorageAttr&&(this._triangleRecords?w(this.renderer,this.triangleStorageAttr,this._triangleRecords.chunks):this.triangleStorageAttr.needsUpdate=!0)},this.environment=new _o(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new Fl,this._initRenderingState(),this.setupBlueNoise(),this.tempVector2=new r.Vector2,this.lastCameraMatrix=new r.Matrix4,this.lastProjectionMatrix=new r.Matrix4,this._seedTick=0,this._pinSeedToFrame=!1,this.tracedFrames=0,this.resetCount=0,this.lastRenderMode=-1,this.renderModeChangeTimeout=null,this.renderModeChangeDelay=50,this.pendingRenderMode=null,this.lastInteractionModeState=!1,this.cameraChanged=!1,this._lastViewChangeAt=-1/0,this.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this._triangleRecords=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.goboMaps=null,this.iesProfiles=null,this.stbnScalarTexture=null,this.stbnVec2Texture=null,this.blueNoiseReady=Promise.resolve(),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(new Float32Array(16),4),this.lightStorageNode=(0,n.storage)(this.lightStorageAttr,`vec4`,1).toReadOnly(),this._lightBufferRealloc=!1,this._lbvhDataCache=null,this._emissiveDataCache=null,this._bitTrailMapCache=null,this._instanceTable=null,this.spheres=[]}_defineUniformGetters(){let e=this.uniforms;for(let t of e.keys())Object.defineProperty(this,t,{get:()=>e.get(t),configurable:!0});let t=e.getLightBufferNodes();for(let[e,n]of Object.entries(t))Object.defineProperty(this,`${e}LightsBufferNode`,{get:()=>n,configurable:!0})}_initRenderingState(){this.isReady=!1,this.frameCount=0}_initCameraOptimizer(){let e=this;this.cameraOptimizer=new be(this.renderer,{uniforms:{enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},fireflyThreshold:{get value(){return e.fireflyThreshold.value},set value(t){e.fireflyThreshold.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:W.interactionModeEnabled,qualitySettings:{enableAccumulation:!1,fireflyThreshold:e=>e*8},onEnter:()=>this.emit(`pathtracer:interactionStart`),onExit:()=>this.emit(`pathtracer:interactionEnd`),onReset:()=>{this.reset(),this.emit(`pathtracer:viewpointChanged`)}})}setupBlueNoise(){let e=new r.TextureLoader;e.setCrossOrigin(`anonymous`);let t=e=>(e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e.wrapS=r.RepeatWrapping,e.wrapT=r.RepeatWrapping,e.generateMipmaps=!1,e),{stbnScalarAtlas:n,stbnVec2Atlas:i}=Or(),a=e.loadAsync(n).then(e=>{this.stbnScalarTexture=t(e),L.value=e,Jd.debug(`STBN scalar atlas ${Y.px(e.image.width,e.image.height)}`)}),o=e.loadAsync(i).then(e=>{this.stbnVec2Texture=t(e),R.value=e,Jd.debug(`STBN vec2 atlas ${Y.px(e.image.width,e.image.height)}`)});this.blueNoiseReady=Promise.allSettled([a,o]).then(e=>{for(let t of e)t.status===`rejected`&&Jd.warn(`STBN atlas failed to load`,t.reason)})}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()}),this.on(`pipeline:resize`,e=>{e&&e.width&&e.height&&this.setSize(e.width,e.height)}),this.on(`pathtracer:setCompletionThreshold`,e=>{e&&e.threshold!==void 0&&(this.completionThreshold=e.threshold)})}async build(e){this.dispose(),this.scene=e,await this.sdfs.buildBVH(e),this.cameras=this.sdfs.cameras,this.updateSceneUniforms(),this.updateLights(),this._initCameraOptimizer(),this.setupMaterial()}updateSceneUniforms(){this.setTriangleData(this.sdfs.triangleData,this.sdfs.triangleCount),this.setBVHData(this.sdfs.bvhData),this.setInstanceTable(this.sdfs.instanceTable),this.materialData.setMaterialData(this.sdfs.materialData,this.sdfs.materials?.map(e=>e.sources)),this.materialData.loadTexturesFromSdfs(),this.sdfs.emissiveTriangleData?this.setEmissiveTriangleData(this.sdfs.emissiveTriangleData,this.sdfs.emissiveTriangleCount||0):this.emissiveTriangleCount.value=0,this.sdfs.lightBVHNodeData?this.setLightBVHData(this.sdfs.lightBVHNodeData,this.sdfs.lightBVHNodeCount||0):this.lightBVHNodeCount.value=0,this._meshRefs=this._collectMeshRefs(this.scene),this.setMeshVisibilityData(this._meshRefs),this.spheres=this.sdfs.spheres||[]}updateLights(){let e={uniforms:{directionalLights:{value:null},pointLights:{value:null},spotLights:{value:null},areaLights:{value:null}},defines:{}};if(this.lightSerializer.processSceneLights(this.scene,e),this.directionalLightsData=e.uniforms.directionalLights.value,this.pointLightsData=e.uniforms.pointLights.value,this.spotLightsData=e.uniforms.spotLights.value,this.areaLightsData=e.uniforms.areaLights.value,this.hasSun.value){let t=this.environment.envParams.skySunIntensity*950,n={intensity:t,color:{r:1,g:1,b:1},userData:{angle:this.sunAngularSize.value},updateMatrixWorld:()=>{},getWorldPosition:e=>{let t=this.sunDirection.value;return e.set(t.x,t.y,t.z).multiplyScalar(1e10)}};this.lightSerializer.addDirectionalLight(n),this.lightSerializer.preprocessLights(),this.lightSerializer.updateShaderUniforms(e),this.directionalLightsData=e.uniforms.directionalLights.value,Jd.debug(`sun added as directional light · intensity ${t.toFixed(2)}`)}this._updateLightBufferNodes()}_updateLightBufferNodes(){this.directionalLightsData&&this.directionalLightsData.length>0?(this.directionalLightsBufferNode.array=Array.from(this.directionalLightsData),this.numDirectionalLights.value=Math.floor(this.directionalLightsData.length/12)):this.numDirectionalLights.value=0,this.areaLightsData&&this.areaLightsData.length>0?(this.areaLightsBufferNode.array=Array.from(this.areaLightsData),this.numAreaLights.value=Math.floor(this.areaLightsData.length/16)):this.numAreaLights.value=0,this.pointLightsData&&this.pointLightsData.length>0?(this.pointLightsBufferNode.array=Array.from(this.pointLightsData),this.numPointLights.value=Math.floor(this.pointLightsData.length/9)):this.numPointLights.value=0,this.spotLightsData&&this.spotLightsData.length>0?(this.spotLightsBufferNode.array=Array.from(this.spotLightsData),this.numSpotLights.value=Math.floor(this.spotLightsData.length/20)):this.numSpotLights.value=0}reset(){this.resetCount++,this.frameCount=0,this.frame.value=0,this.hasPreviousAccumulated.value=0,this.storageTextures.currentTarget=0,this.updateCompletionThreshold(),this.isComplete=!1,this.performanceMonitor?.reset(),this.lastInteractionModeState=!1,this._pinSeedToFrame&&(this._seedTick=0)}setSize(e,t){this.width=e,this.height=t,this.resolution.value.set(e,t),this.createStorageTextures(e,t)}setAccumulationEnabled(e){this.accumulationEnabled=e,this.enableAccumulation.value=+!!e}enterInteractionMode(){this.cameraOptimizer?.enterInteractionMode()}setInteractionModeEnabled(e){this.cameraOptimizer?.setInteractionModeEnabled(e)}get interactionMode(){return this.cameraOptimizer?.isInInteractionMode()??!1}get viewIsChanging(){return this.interactionMode||performance.now()-this._lastViewChangeAt<Yd}noteViewChanged(){this._lastViewChangeAt=performance.now()}setTriangleData(e,r){if(!e)return;let i=e.chunks&&e.chunks.length>1?e:null,a=i?null:e.chunks?e.chunks[0]:e,o=(i?i.recordCount*i.lanesPerRecord:a.length)/4,s=()=>i?S(o,4,Uint32Array):new t.StorageInstancedBufferAttribute(a,4);this.triangleStorageNode?(this.triangleStorageAttr=s(),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=o):(this.triangleStorageAttr=s(),this.triangleStorageNode=(0,n.storage)(this.triangleStorageAttr,`uvec4`,o).toReadOnly()),this._triangleRecords=i,i&&w(this.renderer,this.triangleStorageAttr,i.chunks),this.triangleCount=r,Jd.debug(`${Y.n(this.triangleCount)} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let r=e.chunks&&e.chunks.length>1?e:null,i=r?null:e.chunks?e.chunks[0]:e,a=(r?r.recordCount*r.lanesPerRecord:i.length)/4,o=()=>r?S(a,4,Float32Array):new t.StorageInstancedBufferAttribute(i,4);this.bvhStorageNode?(this.bvhStorageAttr=o(),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=a):(this.bvhStorageAttr=o(),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,a).toReadOnly()),this._bvhRecords=r,r&&w(this.renderer,this.bvhStorageAttr,r.chunks),this.bvhNodeCount=Math.floor(a/Xd),Jd.debug(`${Y.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){!e||e.length===0||!this._instanceTable||(this._patchVisibilityFromMeshes(e),this._flushBVHEdits())}_patchVisibilityFromMeshes(e){let t=this._instanceTable,n=new Map;for(let r=0;r<t.count;r++){if(!t.isSet[r])continue;let i=t.sourceMesh[r],a=n.get(i);a===void 0&&n.set(i,a=this._isWorldVisible(e[i])),this._patchTLASLeafVisibility(r,a)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this._flushBVHEdits()}updateAllMeshVisibility(){!this._meshRefs||!this._instanceTable||(this._patchVisibilityFromMeshes(this._meshRefs),this._flushBVHEdits())}_patchTLASLeafVisibility(e,t){let n=this._instanceTable;if(!n||!n.isSet?.[e]||!this.bvhStorageAttr)return!1;let r=n.tlasLeafIndex[e];return r<0?!1:(n.visible[e]=+!!t,this._bvhRecords?this._bvhRecords.chunkFor(r)[this._bvhRecords.baseOf(r)+2]=+!!t:this.bvhStorageAttr.array[r*16+2]=+!!t,this._dirtyBVHLeaves??=new Set,this._dirtyBVHLeaves.add(r),!0)}_flushBVHEdits(){if(this.bvhStorageAttr){if(!this._bvhRecords){let e=1/0,t=-1;for(let n of this._dirtyBVHLeaves??[])n<e&&(e=n),n>t&&(t=n);t>=0&&(this.bvhStorageAttr.addUpdateRange(e*16,(t-e+1)*16),this.bvhStorageAttr.version++),this._dirtyBVHLeaves?.clear();return}for(let e of this._dirtyBVHLeaves??[])T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e*16,16);this._dirtyBVHLeaves?.clear()}}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){if(this._triangleRecords){w(this.renderer,this.triangleStorageAttr,this._triangleRecords.chunks);return}this._updateStorageBuffer(this.triangleStorageAttr,e?.chunks?e.chunks[0]:e)}updateBVHData(e){if(this._bvhRecords){w(this.renderer,this.bvhStorageAttr,this._bvhRecords.chunks);return}this._updateStorageBuffer(this.bvhStorageAttr,e?.chunks?e.chunks[0]:e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0)if(this._triangleRecords)for(let t of e)T(this.renderer,this.triangleStorageAttr,this._triangleRecords,t.offset,t.count);else{this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0)if(this._bvhRecords)for(let e of t)T(this.renderer,this.bvhStorageAttr,this._bvhRecords,e.offset,e.count);else{this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){Jd.error(`triangle data required`);return}if(!this.bvhStorageNode){Jd.error(`BVH data required`);return}if(this.isReady&&this.shaderBuilder.getSceneTextureNodes()){this.shaderBuilder.updateSceneTextures(this);return}this._ensureStorageTextures(),this.shaderBuilder.createSceneTextureNodes(this,this.storageTextures),this.isReady=!0}_ensureStorageTextures(){let e=this.renderer.domElement,t=Math.max(1,e.width||this.width),n=Math.max(1,e.height||this.height);this.storageTextures.ensureSize(t,n)&&this.resolution.value.set(t,n)}_handleResize(){let{width:e,height:t}=this.renderer.domElement;(e!==this.storageTextures.renderWidth||t!==this.storageTextures.renderHeight)&&(this.createStorageTextures(e,t),this.frameCount=0),this.resolution.value.set(e,t)}_matricesApproxEqual(e,t,n=1e-10){let r=e.elements,i=t.elements;for(let e=0;e<16;e++)if(Math.abs(r[e]-i[e])>n)return!1;return!0}_updateCameraUniforms(){return!this._matricesApproxEqual(this.lastCameraMatrix,this.camera.matrixWorld)||!this._matricesApproxEqual(this.lastProjectionMatrix,this.camera.projectionMatrixInverse)?(this.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.cameraViewMatrix.value.copy(this.camera.matrixWorldInverse),this.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.lastCameraMatrix.copy(this.camera.matrixWorld),this.lastProjectionMatrix.copy(this.camera.projectionMatrixInverse),!0):!1}_updateAccumulationUniforms(e,t){let n=this.cameraOptimizer?.isInInteractionMode()??!1;this.lastInteractionModeState=n,this.accumulationEnabled?n?(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0):(this.accumulationAlpha.value=Pe(e),this.hasPreviousAccumulated.value=+(e>0)):(this.accumulationAlpha.value=1,this.hasPreviousAccumulated.value=0)}_publishTexturesToContext(e,t){e.setTexture(`pathtracer:color`,t.color),e.setTexture(`pathtracer:normalDepth`,t.normalDepth),e.setTexture(`pathtracer:albedo`,t.albedo),e.setState(`pathtracer:samples`,this.frameCount),e.setState(`interactionMode`,this.cameraOptimizer?.isInInteractionMode()??!1),e.setState(`renderMode`,this.renderMode.value)}_emitStateEvents(){this.emit(`pathtracer:frameComplete`,{frame:this.frameCount,isComplete:this.isComplete}),this.cameraChanged&&=(this.emit(`camera:moved`),!1)}updateCompletionThreshold(){this.completionThreshold=Ne(this.renderMode.value,this.maxSamples.value)}setRenderLimitMode(e){this.renderLimitMode=e,this.updateCompletionThreshold()}manageASVGFForRenderMode(e){e!==this.lastRenderMode&&(this.renderModeChangeTimeout&&clearTimeout(this.renderModeChangeTimeout),this.pendingRenderMode=e,this.renderModeChangeTimeout=setTimeout(()=>{this.pendingRenderMode!==null&&this.pendingRenderMode!==this.lastRenderMode&&(this.lastRenderMode=this.pendingRenderMode,this.emit(`asvgf:reset`),this.emit(`denoiser:reset`)),this.renderModeChangeTimeout=null,this.pendingRenderMode=null},this.renderModeChangeDelay))}setUniform(e,t){this.uniforms.set(e,t)}setBlueNoiseTexture(e){this.stbnScalarTexture=e,e&&(L.value=e)}_rebuildLightBuffer(){let e=this._lbvhDataCache,n=this._emissiveDataCache,r=this._bitTrailMapCache,i=e?e.length:0,a=n?n.length:0,o=r?Math.ceil(r.length/4)*4:0,s=Math.max(i+a+o,4);if(this.lightStorageAttr&&s<=this.lightStorageAttr.array.length){let t=this.lightStorageAttr.array;e&&t.set(e,0),n&&t.set(n,i),r&&t.set(r,i+a),this.lightStorageAttr.needsUpdate=!0}else{let o=new Float32Array(s);e&&o.set(e,0),n&&o.set(n,i),r&&o.set(r,i+a),this.lightStorageAttr=new t.StorageInstancedBufferAttribute(o,4),this.lightStorageNode.value=this.lightStorageAttr,this.lightStorageNode.bufferCount=o.length/4,this._lightBufferRealloc=!0}this.emissiveVec4Offset.value=(this.lightBVHNodeCount.value||0)*4,this.reverseMapVec4Offset.value=(i+a)/4}setEmissiveTriangleData(e,t,n=0,r=null){e&&(this._emissiveDataCache=e,r&&(this._bitTrailMapCache=r),this.emissiveTriangleCount.value=t,this.emissiveTotalPower.value=n,this._rebuildLightBuffer(),Jd.debug(`${Y.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),Jd.debug(`light BVH ${Y.n(t)} nodes`))}updateUniforms(e){let t=!1;for(let[n,r]of Object.entries(e))this[n]&&this[n].value!==void 0&&this[n].value!==r&&(this[n].value=r,t=!0);t&&this.reset()}async rebuildMaterials(e){if(!this.sdfs)throw Error(`Scene not built yet. Call build() first.`);try{Jd.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),Jd.debug(`material rebuild complete`)}catch(e){Jd.error(`material rebuild failed:`,e);try{Jd.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){Jd.error(`recovery failed:`,e)}throw e}}dispose(){this.renderModeChangeTimeout&&=(clearTimeout(this.renderModeChangeTimeout),null),this.cameraOptimizer?.dispose(),this.materialData?.dispose(),this.environment?.dispose(),this.shaderBuilder?.dispose(),this.uniforms?.dispose(),this.storageTextures?.dispose(),this.stbnScalarTexture?.dispose(),this.stbnVec2Texture?.dispose(),this.placeholderTexture?.dispose(),this.triangleStorageAttr=null,this._triangleRecords=null,this.triangleStorageNode=null,this.bvhStorageAttr=null,this._bvhRecords=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}};qt();var Qd=Pt(`gpu`),$d={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},ef={DIST_TRI_BARY:0,NORMAL_MAT:1},tf=0,nf=(e,t)=>t===0?e:e.add(t*tf);function rf(e,t){t&&e?._attributes?.delete?.(t)}var af=class{constructor(e=0,t=null){this.capacity=0,this._renderer=t,this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,tf=e;let t=e*7,r=S(t,4);this._attrs.ray=r,this.rayBuffer={rw:(0,n.storage)(r,`vec4`),ro:(0,n.storage)(r,`vec4`).toReadOnly()};let i=S(e,1,Uint32Array);this._attrs.rng=i,this.rngBuffer={rw:(0,n.storage)(i,`uint`),ro:(0,n.storage)(i,`uint`).toReadOnly()};let a=e*2,o=S(a,4,Uint32Array);this._attrs.hit=o,this.hitBuffer={rw:(0,n.storage)(o,`uvec4`),ro:(0,n.storage)(o,`uvec4`).toReadOnly()},this.rayBytes=t*16+e*4,this.hitBytes=a*16,this.totalBytes=this.rayBytes+this.hitBytes,Qd.debug(`ray pool capacity ${Y.n(e)} · ${Y.mb(this.totalBytes)} (rays ${Y.mb(this.rayBytes)} · hits ${Y.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){rf(this._renderer,this._attrs.ray),rf(this._renderer,this._attrs.rng),rf(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,this.capacity=0}},of=(e,t)=>e.element(nf(t,$d.ORIGIN_META)).xyz,sf=(e,t)=>e.element(nf(t,$d.DIR_FLAGS)).xyz,cf=(e,t)=>(0,n.floatBitsToUint)(e.element(nf(t,$d.DIR_FLAGS)).w),lf=(e,t)=>e.element(nf(t,$d.THROUGHPUT_PDF)).xyz,uf=(e,t)=>e.element(nf(t,$d.THROUGHPUT_PDF)).w,df=(e,t)=>e.element(nf(t,$d.RADIANCE_ALPHA)),ff=e=>(0,n.uint)(e).mul(1),pf=(e,t,r,i,a,o=null)=>{let s=ff(t),c=o===null?(0,n.unpackUnorm2x16)(e.element(s).w).y:(0,n.float)(o);return e.element(s).assign((0,n.uvec4)((0,n.packSnorm2x16)((0,n.vec2)(r.x,r.y)),(0,n.packSnorm2x16)((0,n.vec2)(r.z,i)),(0,n.packUnorm2x16)((0,n.vec2)(a.x,a.y)),(0,n.packUnorm2x16)((0,n.vec2)(a.z,c))))},mf=(e,t,r)=>{let i=ff(t),a=e.element(i).toVar();return e.element(i).assign((0,n.uvec4)(a.x,a.y,a.z,(0,n.packUnorm2x16)((0,n.vec2)((0,n.unpackUnorm2x16)(a.w).x,r))))},hf=(e,t)=>e.element(ff(t)),gf=e=>(0,n.unpackUnorm2x16)(e.w).y,_f=e=>{let t=(0,n.unpackSnorm2x16)(e.x),r=(0,n.unpackSnorm2x16)(e.y);return(0,n.vec4)((0,n.vec3)(t.x,t.y,r.x).mul(.5).add(.5),r.y)},vf=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),yf=e=>{let t=(0,n.clamp)((0,n.floor)((0,n.log2)((0,n.max)(e,1e-6))),-8,7),r=(0,n.clamp)((0,n.float)(e).mul((0,n.exp2)(t.negate())).sub(1).mul(64),0,63);return(0,n.select)((0,n.float)(e).lessThan(.004),(0,n.uint)(0),(0,n.uint)(t.add(8)).shiftLeft(6).bitOr((0,n.uint)(r)))},bf=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(22),i=(0,n.float)(r.shiftRight(6).bitAnd((0,n.uint)(15))).sub(8),a=(0,n.float)(r.bitAnd((0,n.uint)(63))).div(64).add(1);return(0,n.select)(r.equal((0,n.uint)(0)),(0,n.float)(0),a.mul((0,n.exp2)(i)))},xf=(e,t,r,i,a,o=(0,n.uint)(0),s=null)=>{let c=(0,n.uint)(i).bitAnd((0,n.uint)(255)).bitOr((0,n.uint)(a).bitAnd((0,n.uint)(255)).shiftLeft(8)).bitOr((0,n.uint)(o).bitAnd((0,n.uint)(63)).shiftLeft(16));return s!==null&&(c=c.bitOr(yf(s).shiftLeft(22))),e.element(nf(t,$d.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Sf=(e,t,r,i)=>e.element(nf(t,$d.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Cf=(e,t,r,i)=>e.element(nf(t,$d.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),wf=(e,t,n)=>e.element(nf(t,$d.RADIANCE_ALPHA)).assign(n),Tf=(e,t)=>(0,n.uintBitsToFloat)(e.element(nf(t,ef.DIST_TRI_BARY)).x),Ef=(e,t)=>e.element(nf(t,ef.DIST_TRI_BARY)).y,Df=(e,t)=>(0,n.uintBitsToFloat)(e.element(nf(t,ef.DIST_TRI_BARY)).zw),Of=(e,t)=>ss(e.element(nf(t,ef.NORMAL_MAT)).x),kf=(e,t)=>(0,n.uint)(e.element(nf(t,ef.NORMAL_MAT)).y),Af=(e,t)=>(0,n.int)(e.element(nf(t,ef.NORMAL_MAT)).z).sub((0,n.int)(1)),jf=(e,t)=>e.element(nf(t,ef.NORMAL_MAT)).w,Mf=(e,t,r,i,a,o,s,c,l,u=(0,n.uint)(0))=>{e.element(nf(t,ef.DIST_TRI_BARY)).assign((0,n.uvec4)((0,n.floatBitsToUint)(r),i,(0,n.floatBitsToUint)(a),(0,n.floatBitsToUint)(o))),e.element(nf(t,ef.NORMAL_MAT)).assign((0,n.uvec4)(os(s),c,l,u))},Nf=(e,t)=>{let r=e.element(nf(t,$d.MEDIUM_STACK)),i=(0,n.floatBitsToUint)(r.x);return{stackDepth:i.bitAnd(255),transTraversals:i.shiftRight(8).bitAnd(255),wavelength:i.shiftRight(16).bitAnd(65535),ior1:r.y,ior2:r.z,ior3:r.w}},Pf=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(nf(t,$d.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),Ff=(e,t)=>e.element(nf(t,$d.MEDIUM_SIGMA_A)).xyz,If=(e,t,r)=>{let i=e.element(nf(t,$d.MEDIUM_SIGMA_A)).w.toVar();e.element(nf(t,$d.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},Lf=e=>{let t=(0,n.clamp)(e,(0,n.vec3)(0),(0,n.vec3)(1)).mul(1023).add(.5);return(0,n.uint)(t.x).bitOr((0,n.uint)(t.y).shiftLeft(10)).bitOr((0,n.uint)(t.z).shiftLeft(20))},Rf=e=>(0,n.vec3)((0,n.float)(e.bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(10).bitAnd((0,n.uint)(1023))),(0,n.float)(e.shiftRight(20).bitAnd((0,n.uint)(1023)))).div(1023),zf=(e,t)=>Rf((0,n.floatBitsToUint)(e.element(nf(t,$d.MEDIUM_SIGMA_A)).w)),Bf=(e,t,r)=>{let i=e.element(nf(t,$d.MEDIUM_SIGMA_A)).xyz.toVar();e.element(nf(t,$d.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(Lf(r))))},Vf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).bitAnd(255)),Hf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),Uf=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(nf(t,$d.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),Wf=(e,t)=>{let n=e.element(nf(t,$d.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},Gf=(e,t,r,i)=>e.element(nf(t,$d.SSS_SIGMA_S)).assign((0,n.vec4)(r,i));qt();var Kf=Pt(`gpu`),$={ACTIVE_RAY_COUNT:0,ENTERING_COUNT:1,CONVERGED_COUNT:2,RESERVED_3:3,ACTIVE_PIXEL_COUNT:4,GEOMETRY_COUNT:5,CONVERGED_GEOMETRY_COUNT:6,ACTIVE_ENERGY:7,COUNT:8},qf=65535,Jf={BOUNCE_MASK:255,ACTIVE:256,SPECULAR:512,INSIDE_MEDIUM:1024,RAY_TYPE_SHIFT:11,RAY_TYPE_MASK:63488,HAS_HIT_OPAQUE:65536,AUX_LOCKED:1<<17,REDIRECTED:1<<18},Yf=class{constructor(e=0,t=null){this._renderer=t,this.capacity=0,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.pingPong=0,e>0&&this.allocate(e)}allocate(e){this.dispose(),this.capacity=e,this._countersAttr=new t.StorageInstancedBufferAttribute(new Uint32Array($.COUNT),1),this.counters=(0,n.storage)(this._countersAttr,`uint`).toAtomic(),this.MAX_BOUNCE_SNAPSHOTS=32,this._bounceCountsAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(2*this.MAX_BOUNCE_SNAPSHOTS),1),this.bounceCounts=(0,n.storage)(this._bounceCountsAttr,`uint`);let r=S(e,1,Uint32Array),i=S(e,1,Uint32Array);this._attrA=r,this._attrB=i,this.activeIndices={a:(0,n.storage)(r,`uint`),b:(0,n.storage)(i,`uint`)},this.activeIndicesRO={a:(0,n.storage)(r,`uint`).toReadOnly(),b:(0,n.storage)(i,`uint`).toReadOnly()};let a=S(e,1,Uint32Array);this._sortAttr=a,this.sortedIndices=(0,n.storage)(a,`uint`),this.sortedIndicesRO=(0,n.storage)(a,`uint`).toReadOnly(),this._sortGlobalHistAttr=new t.StorageInstancedBufferAttribute(new Uint32Array(256),1),this.sortGlobalHistogram=(0,n.storage)(this._sortGlobalHistAttr,`uint`).toAtomic(),this.pingPong=0,this.totalBytes=$.COUNT*4+e*4*3,Kf.debug(`queues capacity ${Y.n(e)} · ${Y.mb(this.totalBytes)}`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}getCounters(){return this.counters}getActiveReadRO(){return this.pingPong===0?this.activeIndicesRO.a:this.activeIndicesRO.b}getActiveRead(){return this.pingPong===0?this.activeIndices.a:this.activeIndices.b}getActiveWrite(){return this.pingPong===0?this.activeIndices.b:this.activeIndices.a}getSortedRW(){return this.sortedIndices}getSortedRO(){return this.sortedIndicesRO}getSortGlobalHistogram(){return this.sortGlobalHistogram}getCountersAttribute(){return this._countersAttr}getBounceCounts(){return this.bounceCounts}getBounceCountsAttribute(){return this._bounceCountsAttr}swap(){this.pingPong=1-this.pingPong}resetPingPong(){this.pingPong=0}dispose(){rf(this._renderer,this._countersAttr),rf(this._renderer,this._bounceCountsAttr),rf(this._renderer,this._attrA),rf(this._renderer,this._attrB),rf(this._renderer,this._sortAttr),rf(this._renderer,this._sortGlobalHistAttr),this._countersAttr=this._bounceCountsAttr=null,this._attrA=this._attrB=this._sortAttr=this._sortGlobalHistAttr=null,this.counters=null,this.activeIndices=null,this.activeIndicesRO=null,this.sortedIndices=null,this.sortedIndicesRO=null,this.sortGlobalHistogram=null,this.capacity=0}},Xf={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},Zf={[r.FloatType]:4,[r.HalfFloatType]:2,[r.UnsignedByteType]:1,[r.ByteType]:1,[r.UnsignedShortType]:2,[r.ShortType]:2,[r.UnsignedIntType]:4,[r.IntType]:4};function Qf(e){return(Xf[e.format]??4)*(Zf[e.type]??4)}function $f(e){return e?.gpuByteLength??e?.array?.byteLength??0}function ep(e){if(!e)return 0;if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&(a+=n*r*i*Qf(e));return a}let t=e.image||{},n=t.width??e.width??0,r=t.height??e.height??0,i=t.depth??1;return n*r*i*Qf(e)}var tp=class{constructor(e=null){this._providers=[],this._renderer=e,this.current=0,this.peak=0,this.byCategory={}}setRenderer(e){this._renderer=e}register(e,t){this._providers.push({category:e,fn:t})}measure(){let e=new WeakSet,t={},n=0;for(let{category:r,fn:i}of this._providers){let a;try{a=i()}catch{a=null}if(!a)continue;let o=0;for(let t of Array.isArray(a)?a:[a])o+=this._resourceBytes(t,e);t[r]=(t[r]||0)+o,n+=o}return this.byCategory=t,this.current=n,n>this.peak&&(this.peak=n),{current:n,peak:this.peak,byCategory:t}}_resourceBytes(e,t){return e?typeof e.bytes==`number`&&!e.isTexture&&!e.isRenderTarget?e.bytes:e.gpuByteLength==null?e.array&&e.array.byteLength!=null?t.has(e.array)?0:(t.add(e.array),e.array.byteLength):e.isRenderTarget||e.isTexture?t.has(e)?0:(t.add(e),this._residentTextureBytes(e)):0:t.has(e)?0:(t.add(e),e.gpuByteLength):0}_isResident(e){let t=this._renderer?.backend;if(!t||typeof t.get!=`function`)return!0;if(typeof t.has==`function`&&!t.has(e))return!1;let n=t.get(e);return!!(n&&(n.texture||n.gpuTexture))}_residentTextureBytes(e){if(e.isRenderTarget){let t=e.textures?.length?e.textures:[e.texture],n=e.width||0,r=e.height||0,i=e.depth||1,a=0;for(let e of t)e&&this._isResident(e)&&(a+=n*r*i*Qf(e));return a}return this._isResident(e)?ep(e):0}resetPeak(){this.peak=this.current}getReport(){let e=e=>(e/1048576).toFixed(1),t=Object.entries(this.byCategory).map(([t,n])=>`${t}=${e(n)}`);return`VRAM current=${e(this.current)}MB peak=${e(this.peak)}MB [${t.join(` `)}]`}};qt();var np=Pt(`wavefront`),rp=class{constructor(e){this.renderer=e,this.kernels=new Map,this.timing=new Map,this.profiling=!1,this.profile=new Map,this._firstDispatches=[],this._firstDispatchFlush=null}_recordFirstDispatch(e,t){this._firstDispatches.push({name:e,ms:t}),clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=setTimeout(()=>this._flushFirstDispatches(),0)}_flushFirstDispatches(){let e=this._firstDispatches;if(this._firstDispatches=[],this._firstDispatchFlush=null,e.length===0)return;let t=e.reduce((e,t)=>e+t.ms,0),n=[...e].sort((e,t)=>t.ms-e.ms);np.info(Y.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${Y.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${Y.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>np.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${Y.ms(e.ms)}`))}register(e,t){this.kernels.set(e,t),this.timing.set(e,{compiledOnce:!1,lastDispatchMs:0})}dispatch(e){let t=this.kernels.get(e);if(!t)throw Error(`KernelManager: Unknown kernel '${e}'`);let n=this.timing.get(e);if(n&&!n.compiledOnce){let r=performance.now();this.renderer.compute(t);let i=performance.now();n.compiledOnce=!0,n.lastDispatchMs=i-r,this._recordFirstDispatch(e,i-r)}else if(this.profiling){let n=performance.now();this.renderer.compute(t);let r=performance.now(),i=this.profile.get(e);i||(i={calls:0,totalMs:0},this.profile.set(e,i)),i.calls++,i.totalMs+=r-n}else this.renderer.compute(t)}setDispatchForCount(e,t){let n=this.kernels.get(e);n&&(n.dispatchSize=[Math.ceil(t/n.workgroupSize[0]),1,1])}setDispatchForGrid(e,t,n){let r=this.kernels.get(e);if(!r)return;let i=r.workgroupSize;r.dispatchSize=[Math.ceil(t/i[0]),Math.ceil(n/i[1]),1]}has(e){return this.kernels.has(e)}get(e){return this.kernels.get(e)}getTimingReport(){let e={};for(let[t,n]of this.timing)e[t]={...n};return e}enableProfiling(e){this.profiling=e,e&&this.profile.clear()}getProfileReport(){let e=[],t=0;for(let[n,{calls:r,totalMs:i}]of this.profile)t+=i,e.push({name:n,calls:r,totalMs:+i.toFixed(2),avgMs:+(i/r).toFixed(3)});return e.sort((e,t)=>t.totalMs-e.totalMs),e.push({name:`TOTAL`,calls:e.reduce((e,t)=>e+t.calls,0),totalMs:+t.toFixed(2),avgMs:null}),e}dispose(){clearTimeout(this._firstDispatchFlush),this._firstDispatchFlush=null,this._firstDispatches=[],this.kernels.clear(),this.timing.clear(),this.profile.clear()}},ip=(0,n.Fn)(([e,t,r,i,a,o,s])=>{let c=(0,n.vec3)(0).toVar();return(0,n.If)(i.equal((0,n.int)(1)),()=>{let r=(0,n.mix)(a.x,a.y,e.x).toVar(),i=(0,n.mix)(o.y,o.x,e.y).toVar(),l=(0,n.cos)(i).toVar(),u=(0,n.vec3)(0).toVar(),d=(0,n.vec3)(0).toVar(),f=(0,n.vec3)(0).toVar();(0,n.If)(s.equal((0,n.int)(1)),()=>{let e=(0,n.vec3)(t[2].x,0,t[2].z).toVar();(0,n.If)((0,n.dot)(e,e).lessThan((0,n.float)(1e-8)),()=>{e.assign((0,n.vec3)(t[1].x,0,t[1].z))}),f.assign((0,n.normalize)(e)),d.assign((0,n.vec3)(0,1,0)),u.assign((0,n.cross)(d,f))}).Else(()=>{u.assign((0,n.normalize)((0,n.vec3)(t[0]))),d.assign((0,n.normalize)((0,n.vec3)(t[1]))),f.assign((0,n.normalize)((0,n.vec3)(t[2])))}),c.assign((0,n.normalize)(u.mul((0,n.sin)(r).mul(l)).add(d.mul((0,n.sin)(i))).sub(f.mul((0,n.cos)(r).mul(l)))))}).Else(()=>{let i=(0,n.vec3)(e.x.mul(2).sub(1),(0,n.float)(1).sub(e.y.mul(2)),1),a=r.mul((0,n.vec4)(i,1));c.assign((0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))))}),c}),ap=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h])=>{let g=(0,n.vec3)(r[3]).toVar(),_=ip(e,r,i,a,o,s,c).toVar(),v=g.toVar(),y=_.toVar();return(0,n.If)(l.and(u.greaterThan(0)).and(d.lessThan(64)).and(f.greaterThan(.001)),()=>{let e=u.div(d).mul(.001).mul(p).mul(m),i=ie(t),o=i.x.mul(h.max(.01)),s=i.y,c=(0,n.vec3)(0).toVar();(0,n.If)(a.equal((0,n.int)(1)),()=>{c.assign($o({N:_}).mul((0,n.vec3)(o,s,0)))}).Else(()=>{let e=(0,n.normalize)((0,n.vec3)(r[0])),t=(0,n.normalize)((0,n.vec3)(r[1]));c.assign(e.mul(o).add(t.mul(s)))}),v.assign(g.add(c.mul(e))),y.assign((0,n.normalize)(g.add(_.mul(f)).sub(v)))}),vo({origin:v,direction:y})});function op(e){let{rayBufferRW:t,rngBufferRW:r,gBufferRW:i,resolution:a,frame:o,cameraWorldMatrix:s,cameraProjectionMatrixInverse:c,cameraProjection:l,panoLonRange:u,panoLatRange:d,panoLevelHorizon:f,enableDOF:p,focalLength:m,aperture:h,focusDistance:g,sceneScale:_,apertureScale:v,anamorphicRatio:y,renderWidth:b,chunkRowBase:x,chunkRows:S,transmissiveBounces:C,transparentBackground:w,auxGBufferEnabled:T,listDriven:E=!1,activeIndicesRO:D=null,counters:O=null}=e,k=T.greaterThan((0,n.uint)(0)),A=(e,b,x)=>{let S=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(b).add(.5)),w=z({state:ve({pixelCoord:S,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),T=_e(S,(0,n.int)(1),(0,n.int)(1),w,a,o).toVar().sub(.5),E=(0,n.vec2)(S.x.add(T.x),S.y.sub(T.y)).div(a),D=vo.wrap(ap(E,w,s,c,l,u,d,f,p,m,h,g,_,v,y));xf(t,x,D.origin,(0,n.int)(0),(0,n.int)(0)),Sf(t,x,D.direction,(0,n.uint)(Jf.ACTIVE)),Cf(t,x,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),wf(t,x,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(k,()=>{pf(i,x,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),Bf(t,x,(0,n.vec3)(1))}),Pf(t,x,(0,n.uint)(0),(0,n.uint)(C),(0,n.float)(1),(0,n.float)(1),(0,n.float)(1)),r.element(x).assign(w)};return(0,n.Fn)(()=>{if(E){let e=n.instanceIndex;(0,n.If)(e.lessThan((0,n.atomicLoad)(O.element((0,n.uint)($.ENTERING_COUNT)))),()=>{let t=(0,n.int)(D.element(e)),r=t.add(x.mul(b));A(r.mod(b),r.div(b),(0,n.uint)(t))})}else{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),t=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(b).and(t.lessThan(S)),()=>{A(e,t.add(x),(0,n.uint)(t.mul(b).add(e)))})}})}var sp=32,cp=4096,lp=4,up=1e8,dp=()=>(0,n.array)(`int`,sp).toVar(),fp=e=>{let t=(0,n.mix)((0,n.vec3)(1),(0,n.sign)(e),(0,n.notEqual)(e,(0,n.vec3)(0)));return(0,n.mix)((0,n.vec3)(1).div(e),(0,n.vec3)(up).mul(t),(0,n.lessThan)((0,n.abs)(e),(0,n.vec3)(1e-8)))},pp=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t).add(e[0].w),e[1].xyz.dot(t).add(e[1].w),e[2].xyz.dot(t).add(e[2].w)),mp=(e,t)=>(0,n.vec3)(e[0].xyz.dot(t),e[1].xyz.dot(t),e[2].xyz.dot(t)),hp=(0,n.wgslFn)(`
716
716
  fn RayTriangleGeometry( rayOrigin: vec3f, rayDir: vec3f, pA: vec3f, pB: vec3f, pC: vec3f, closestHitDst: f32, woopParams: vec4f ) -> vec4f {
717
717
 
718
718
  // Returns vec4(t, u, v, hit) where hit > 0.5 means intersection.
@@ -892,7 +892,7 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
892
892
  let ndcDepth = clipPos.z / clipPos.w * 0.5f + 0.5f;
893
893
  return clamp( ndcDepth, 0.0f, 1.0f );
894
894
  }
895
- `),qm=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=vo({origin:e,direction:t}),y=Co.wrap(bp(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=Np({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Uo).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=yo.wrap(ls(y.materialIndex,a)).toVar(),r=Ao.wrap(tl(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(Gm({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Km({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Wm({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=z({state:ne({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=cc({N:d,xi:(0,n.vec2)(re(p).toVar(),re(p).toVar())}).toVar(),h=vo({origin:Po(y.hitPoint,d),direction:m}),v=Co.wrap(bp(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(Np({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=yo.wrap(ls(v.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=Np({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=Np({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=Np({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function Jm(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,sceneScale:b,apertureScale:x,anamorphicRatio:S,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:E,environmentMatrix:D,environmentIntensity:O,enableEnvironmentLight:k,visMode:A,debugVisScale:j,frame:M}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),N=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(N.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(N).add(.5)),s=z({state:(0,n.uint)(N.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),P=vo.wrap(ap(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S)),F=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(A.equal((0,n.int)(9)),()=>{let e=_e(o,(0,n.int)(0),(0,n.int)(1),s,a,M);F.assign((0,n.vec4)(e,1,1))}).Else(()=>{F.assign(qm(P.origin,P.direction,C,w,T,E,D,O,k,A,j,o,a,u,d,M))});let I=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(N));(0,n.textureStore)(t,I,F).toWriteOnly(),(0,n.textureStore)(r,I,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,I,(0,n.vec4)(F.xyz,1)).toWriteOnly()})})}function Ym({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function Xm({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)($.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(kf(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function Zm({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function Qm({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)($.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(kf(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}qt();var $m=Pt(`wavefront`),eh=256,th=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],nh=class extends Zd{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this._chunkRows=0,this._numChunks=1,this.vramTracker=new tp(this.renderer),this._registerVRAMProviders(),$m.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(t,n);let i=this._updateAuxAccumulationUniforms(t);this.frame.value=t,this.seedFrame.value=this._seedTick++,this._setWfDispatch();let a=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=a.color,this.shaderBuilder.prevAlbedoTexNode.value=a.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=a.normalDepth),this._refreshWfTextureNodes();let o=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){o.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}let s=this.maxBounces.value,c=this._bounceLoopBound(),l=this._wfRenderHeight.value,u=this._chunkRows,d=this._numChunks<=1;c>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let f=this._lastBounceCounts,p=s<=this._lastBounceCountsBudget&&c<=this._lastBounceCountsLoopBound,m=d&&f?p?c+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0;for(let e=0,n=0;n<l;n+=u,e++){let r=Math.min(u,l-n),i=this._setChunk(n,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,s=d&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(s*1.5)+1024);o.setDispatchForCount(`generateList`,e),o.dispatch(`resetFrameCounters`),o.dispatch(`buildActivePixels`),o.dispatch(`seedEnter`),o.dispatch(`generateList`)}else o.dispatch(`generate`),o.dispatch(`initActiveIndices`);e===0&&t>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&o.dispatch(`countConvergedDilated`);let p=this._lastBounceEnergy,h=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=c;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(d&&e>0&&this._curveSizingValid){let n=e-1,r;n<m&&f[n]!==void 0?r=f[n]:m>0&&(r=f[m-1]),t=r>0?r:i}else e===0&&a&&(t=s);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of th)o.setDispatchForCount(e,n)}else{o.dispatch(`enterFull`);for(let e of th)o.setDispatchForCount(e,i)}if(o.dispatch(`extend`),this._sortMaterials&&(o.dispatch(`resetGlobalHist`),o.dispatch(`globalHist`),o.dispatch(`globalPrefix`),o.dispatch(`globalScatter`)),o.dispatch(`shade`),o.dispatch(`compact`),t?o.dispatch(`compactCopyback`):o.dispatch(`snapshotBounceCount`),h>=0&&e<m&&e<c&&p?.[e]!==void 0&&p[e]<=h)break}o.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let h=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,h),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=i?this._auxSamples+1:1),this._auxSeedPending=!1,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value}_maybeReadbackCounters(){if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS;if(this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration){let t=new Uint32Array(e.slice(0));this._lastBounceCounts=t.subarray(0,i),this._lastBounceEnergy=t.subarray(i,2*i),this._lastBounceCountsBudget=n,this._lastBounceCountsLoopBound=r,this._curveSizingValid=!0}this._readbackPending=!1}).catch(e=>{$m.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration&&n>0){let t=new Uint32Array(e);this._convergedFraction=t[$.CONVERGED_COUNT]/n;let r=t[$.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?t[$.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=t[$.ACTIVE_PIXEL_COUNT]}this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(Bc(e.srgbBuckets,n.srgbBuckets),Bc(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=(typeof navigator<`u`&&navigator.deviceMemory||4)*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/176),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,G),t=Math.min(this.storageTextures.renderHeight||1,G);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t;this._packedBuffers?this._packedBuffers.resize(i):this._packedBuffers=new af(i,this.renderer);let o=i*1;rf(this.renderer,this._gBufferAttr),this._gBufferAttr=S(o,4,Uint32Array);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),l=G*G;(!this._m2Attr||this._m2Attr.count<l)&&(rf(this.renderer,this._m2Attr),this._m2Attr=S(l,1),rf(this.renderer,this._streakAttr),this._streakAttr=S(l,1,Uint32Array),rf(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=S(l,1,Uint32Array));let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Yf(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new rp(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,v=this.shaderBuilder.prevAlbedoTexNode,y=this.shaderBuilder.prevNormalDepthTexNode,b=this.storageTextures.getWriteTextures(),x=g.getCounters(),C=g.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),C.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=g.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*t/eh),1,1],[eh,1,1]));let O={rayBufferRW:h.rayBuffer.rw,rngBufferRW:h.rngBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=op(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*t/eh),1,1],[eh,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(t*r/eh),1,1],[eh,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e),(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=op({...O,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:x});this._kernelManager.register(`generateList`,F().compute([Math.ceil(a/eh),1,1],[eh,1,1]));let I=this.bvhStorageNode,L=this.triangleStorageNode,R=this.materialData.materialStorageNode,ee=(0,n.texture)(this.environment.envCDFTexture),te=this.lightStorageNode,z=this.materialData,ne=this.environment,B=zc(z.srgbBuckets),re=zc(z.linearBuckets);Nc(B,re),il(B);let ie=ne.environmentTexture?(0,n.texture)(ne.environmentTexture):e.envTex;this._wfTexNodes={envTex:ie,envCDFTex:ee,srgbBuckets:B,linearBuckets:re},this._sortMaterials=(W.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let ae=Op({bvhBuffer:I,triangleBuffer:L,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:x,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ae().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,Ym({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,Xm({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,Zm({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,Qm({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let oe=Rm({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envCDFTexture:ee,lightBuffer:te,rayBufferRW:h.rayBuffer.rw,rngBufferRW:h.rngBuffer.rw,hitBufferRO:h.hitBuffer.ro,counters:x,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:ie,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let se=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=se;let ce=(se?Vm:Bm)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:x,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ce().compute([Math.ceil(a/256),1,1],[256,1,1]));let le=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,le().compute([1,1,1],[1,1,1]));let ue=g.activeIndicesRO.b,de=g.activeIndices.a,fe=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),C.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),de.element(e).assign(ue.element(e))});this._kernelManager.register(`compactCopyback`,fe().compute([Math.ceil(a/eh),1,1],[eh,1,1]));let pe=Um({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:_,prevAlbedoTexture:v,prevNormalDepthTexture:y,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,pe().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let me=Jm({writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envTexture:ie,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,me().compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1])),this._wavefrontReady=!0;let he=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);$m.info(Y.list([Y.px(t,r),`${Y.mb(he)} wavefront buffers`,`budget ${Y.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},rh=class extends V{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:ye.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(G,G),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(G,G),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`uvec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&Bc(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=zc(this.pathTracer?.materialData?.linearBuckets),Nc(zc(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let u=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),d=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(u.lessThan((0,n.int)(o)).and(d.lessThan((0,n.int)(s))),()=>{let f=ip((0,n.vec2)((0,n.float)(u).add(.5).div(o),(0,n.float)(d).add(.5).div(s)),i,a,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon),p=vo({origin:(0,n.vec3)(i[3]),direction:f}),m=Co.wrap(yp(p,t,e)),h=m.normal.mul(.5).add(.5),g=(0,n.min)(m.dst,(0,n.float)(65504)),_=m.didHit.select((0,n.vec4)(h,g),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),_).toWriteOnly();let v=m.normal.toVar(),y=(0,n.float)(1).toVar();(0,n.If)(m.didHit,()=>{let i=yo.wrap(ls(m.materialIndex,r)).toVar(),a=Mo.wrap(Gc(m.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(Yc(e,m.triangleIndex,m.normal,i.normalTransform,t,m.instanceLeaf))});let s=Xc(m.normal,i,a,o).toVar();v.assign(Zc(s,i,a)),y.assign(qc(i,a).y.clamp(.05,1))});let b=m.didHit.select((0,n.vec4)(v.mul(.5).add(.5),y),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(u),(0,n.uint)(d)),b).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraProjection.value=t.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(t.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(t.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=t.uniforms.get(`panoLevelHorizon`).value),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(G,G);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._computeBuilt=!1}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},ih=class extends V{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:ye.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(G,G),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(G,G),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(G,G);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},ah=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),oh=e=>(0,n.vec3)(ah(e.x),ah(e.y),ah(e.z)),sh=class extends V{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:ye.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(G,G),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(G,G),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(G,G),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(G,G),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(G,G),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Xo(oh(m.div((0,n.max)(_,(0,n.vec3)(Ve))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Xo(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ve)),T=oh(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),te=I.add(L).add(R).add(ee);(0,n.If)(te.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(te),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=oh((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Xo(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},ch=1e-6,lh=1.5/255,uh=.01,dh=3,fh=2,ph=2,mh=3,hh=2,gh=38,_h=.1,vh=4,yh=Math.cos(89*Math.PI/180),bh=.5,xh=16,Sh={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Ch=.25*Math.SQRT2,wh=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Ch,Ch,.5],[Ch,Ch,.5],[Ch,-Ch,.5],[-Ch,-Ch,.5]],Th=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),Eh=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-dh);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Dh=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Oh=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),kh=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(ch)))),Ah=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(kh(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(lh));return(0,n.float)(1).div(a)},jh=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(uh),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Mh=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},Nh=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},Ph=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Fh=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Ih=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Lh=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Rh=(e,t)=>t.add(ch).div(e.add(ch)),zh=(e,t)=>(0,n.vec4)(e.xyz.mul(Rh(e.x,t)),e.w),Bh=e=>(0,n.vec4)(Ih(Lh(e.xyz)),(0,n.saturate)(e.w)),Vh=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),Hh=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Uh=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Wh(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var Gh=class extends V{constructor(e,i={}){super(`NRD`,{...i,executionMode:ye.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ge,...i.settings||{}};let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/xh),this._dispatchY=Math.ceil(o/xh),this._buildKernels()}_allocStorage(){let e=()=>Yt(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in Ge&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,r,i){let a=ip(e,r,i,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon);return(0,n.vec3)(r[3]).add(a.mul(t))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=bh,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[xh,xh,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Sh[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(Ih(Ko(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ve))))),Go(r.w,Wo).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Re),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Re).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,(0,n.normalize)(_.sub(f))).abs().toVar(),p=this.minRectDimMulUnproject.mul(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=Oh(k,.5).toVar(),D=A.mul(Be).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=Ph(a.planeDistSensitivity,p,f,O).toVar(),ee=Ah(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),te=jh(k,a.roughnessFraction.mul(i)).toVar(),z=Nh(M,T).toVar(),ne=a.minHitDistanceWeight.mul(i).mul(E);t||(ne=ne.mul(T)),ne=ne.toVar();let B=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;B=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),B=B.div((0,n.max)(B.x,B.y))}let re=B.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ie=(0,n.float)(1).toVar();for(let t=0;t<wh.length;t++){let r=wh[t],i=e.add(Hh(m,(0,n.vec2)(r[0],r[1])).mul(re)),a=Fh(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=Dh((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(Th(g,ee,(0,n.float)(0))),u.mulAssign(Th(h.w,te.x,te.y)),u.mulAssign(Th((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Re),(0,n.float)(0),u));let _=Uh(u,x(d));u.mulAssign(ne.add(Eh(_.w,z.x,z.y))),ie.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ie,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Re),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,(0,n.normalize)(m.sub(M))).abs().toVar(),F=this.minRectDimMulUnproject.mul(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Re);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),te=this._bilinear(R),z=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(ch).toVar(),ne=(0,n.float)(1).sub(y),B=[],re=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,te.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(yh),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(z),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Re),(0,n.float)(1),(0,n.float)(0));B.push(r.mul(i).mul(a).mul(te.inScreen[e]).mul(ne).toVar()),re.push((0,n.textureLoad)(c,te.taps[e]).x)}let ie=te.customWeights(B).map(e=>e.toVar()),ae=B[0].add(B[1]).add(B[2]).add(B[3]).greaterThan(3.5).toVar(),oe=B[0].add(B[1].mul(2)).add(B[2].mul(4)).add(B[3].mul(8)),se=this._applyCustomWeights(re,ie,(0,n.float)(0)).toVar(),ce=(0,n.dot)(k,(0,n.normalize)(h.sub(M))).abs().add(.001).div(P.add(.001)).toVar();ce.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ce.mul(ce))));let le=(0,n.sqrt)((0,n.saturate)(te.filter(B))).mul(ce).toVar();se.assign(se.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(se.add(1))))),se.assign((0,n.min)(se,E));let ue=Bh(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,te,ie,ae)).toVar(),de=(0,n.max)(this._applyCustomWeights(te.taps.map(e=>(0,n.textureLoad)(s,e).x),ie,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=se.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(Oh(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(gh).div(se.add(1))).toVar(),ye=se.mul(e.maxBlurRadius).mul(_h).toVar();ye.assign(ye.div(ye.add(1)).mul((0,n.float)(1).sub(pe)));let V=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),ye);_e.assign(zh(_e,V));let be=(0,n.float)(1.2).add((0,n.float)(1).div(se.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(be)),ye))),(0,n.textureStore)(u,_,_e).toWriteOnly();let H=(0,n.min)(se,D).mul((0,n.float)(1).sub(pe)),xe=fe.div(fe.add(H)),Se=(0,n.mix)(de,T.x,xe).toVar(),Ce=(0,n.min)(Se,ue.x.mul(ve).mul(vh));Se.assign((0,n.mix)(Se,Ce,ye)),(0,n.textureStore)(d,_,(0,n.vec4)(Se,se,oe,(0,n.select)(ae,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(Re),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this.minRectDimMulUnproject.mul(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Be).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/fh).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=Ah(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=Ph(e.planeDistSensitivity,k,D,w).toVar(),c=Nh(P,j).toVar(),d=Mh(T.mul(T),(0,n.sqrt)(e.roughnessFraction),uh).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-fh;e<=fh;e++)for(let h=-fh;h<=fh;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===fh*2)continue;let g=Fh(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=Eh(Dh((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(Eh(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(Th((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Re),(0,n.float)(0),x));let S=Uh(x,(0,n.textureLoad)(i,_));x.mulAssign(Eh(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,ch))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),te=R.mul(R).toVar(),z=(0,n.float)(0).toVar(),ne=(0,n.float)(0).toVar(),B=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(Re),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=ph&&Math.abs(r)<=ph&&(ee.addAssign(c),te.addAssign(c.mul(c))),i&&(z.addAssign(c),ne.addAssign(c.mul(c)))},re=e.antiFirefly.greaterThan(.5);for(let e=-ph;e<=ph;e++)for(let t=-ph;t<=ph;t++)t===0&&e===0||B(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(re,()=>{for(let e=-mh;e<=mh;e++)for(let t=-mh;t<=mh;t++)Math.abs(t)<=ph&&Math.abs(e)<=ph||B(t,e,!0)}),(0,n.If)(re,()=>{let e=1/((mh*2+1)**2-9),t=z.mul(e),r=Vh(t,ne.mul(e)).mul(hh);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(ph*2+1)**2,r=ee.mul(t),i=Vh(r,te.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,zh(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(Re),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(Re),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=Vh(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),te=R.mul(t.antilag.x),z=t.antilag.y.mul(4),ne=ee.clamp(I.sub(te),I.add(te)),B=ee.sub(ne).abs().div((0,n.max)(ee,ne).add(ch)),re=(0,n.float)(1).div((0,n.float)(1).add(B.mul(D.mul(N)).div(z))).toVar(),ie=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ie,D,re));let ae=h.add(1),oe=this._handover(ae),se=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(oe)).div(ae)))).mul(re).toVar(),ce=(0,n.float)(1).add(se.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(ce)),I.add(R.mul(ce))),(0,n.min)(se,le)).toVar();P.assign(zh(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(Lh(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ve))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[xh,xh,1])}setupEventListeners(){this.on(`denoiser:reset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.cameraProjection.value=e.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(e.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(e.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=e.uniforms.get(`panoLevelHorizon`).value,this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=Wh(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/xh),this._dispatchY=Math.ceil(t/xh);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}},Kh=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),qh=(0,n.wgslFn)(`
895
+ `),qm=(0,n.Fn)(([e,t,r,i,a,o,s,c,l,u,d,f,p,m,h,g])=>{let _=(0,n.vec4)(1,0,1,1).toVar(),v=vo({origin:e,direction:t}),y=Co.wrap(bp(v,r,i).toVar());return(0,n.If)(u.equal((0,n.int)(7)),()=>{let e=(0,n.float)(y.triTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(8)),()=>{let e=(0,n.float)(y.boxTests).div(d);_.assign((0,n.select)(e.lessThan(1),(0,n.vec4)((0,n.vec3)(e),1),(0,n.vec4)(1,0,0,1)))}),(0,n.If)(u.equal((0,n.int)(10)),()=>{(0,n.If)(l,()=>{let e=Np({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).toVar(),r=(0,n.dot)(e.xyz,Uo).toVar(),i=r,a=(0,n.max)(d.mul(.1),.001),u=r.div(a),m=(0,n.log)(r.add(1e-6)).add(10).div(10),h=(0,n.select)(d.greaterThan(1),u,m).toVar(),g=(0,n.vec3)(0).toVar();(0,n.If)(h.lessThan(.2),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,0),(0,n.vec3)(0,0,.5),h.mul(5)))}).ElseIf(h.lessThan(.4),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,.5),(0,n.vec3)(0,0,1),h.sub(.2).mul(5)))}).ElseIf(h.lessThan(.6),()=>{g.assign((0,n.mix)((0,n.vec3)(0,0,1),(0,n.vec3)(0,1,0),h.sub(.4).mul(5)))}).ElseIf(h.lessThan(.8),()=>{g.assign((0,n.mix)((0,n.vec3)(0,1,0),(0,n.vec3)(1,1,0),h.sub(.6).mul(5)))}).ElseIf(h.lessThan(1),()=>{g.assign((0,n.mix)((0,n.vec3)(1,1,0),(0,n.vec3)(1,0,0),h.sub(.8).mul(5)))}).Else(()=>{g.assign((0,n.mix)((0,n.vec3)(1,0,0),(0,n.vec3)(1,1,1),(0,n.min)(h.sub(1),1)))});let v=f.div(p);(0,n.If)(v.x.lessThan(.1).and(v.y.lessThan(.1)),()=>{let e=i.mul(1);g.assign((0,n.vec3)(e))}).ElseIf(v.x.greaterThan(.9).and(v.y.lessThan(.1)),()=>{g.assign(e.xyz.mul(1))}),_.assign((0,n.vec4)(g,1))}).Else(()=>{_.assign((0,n.vec4)(1,0,1,1))})}),(0,n.If)(u.equal((0,n.int)(4)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let t=yo.wrap(ls(y.materialIndex,a)).toVar(),r=Ao.wrap(tl(t,y.uv,y.normal,(0,n.vec4)(0))).toVar().emissive.toVar(),i=(0,n.length)(r).toVar();(0,n.If)(i.greaterThan(0),()=>{let t=r.div((0,n.max)(i.mul(.1),.001)).toVar(),a=(0,n.length)(e.sub(y.hitPoint)),o=(0,n.clamp)((0,n.float)(1).sub(a.div(10)),0,1),s=(0,n.mix)(t,t.mul((0,n.vec3)(1,.8,.6)),o.mul(.3));_.assign((0,n.vec4)(s,1))}).Else(()=>{_.assign((0,n.vec4)(0,0,.1,1))})})}),(0,n.If)(u.equal((0,n.int)(1)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(.5,.5,1,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=(0,n.normalize)(Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().normal);_.assign((0,n.vec4)(Gm({normal:t}),1))})}),(0,n.If)(u.equal((0,n.int)(2)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)((0,n.vec3)(1),1))}).Else(()=>{let e=Km({worldPos:y.hitPoint,cameraProjectionMatrix:m,cameraViewMatrix:h});_.assign((0,n.vec4)(Wm({depth:e}),1))})}),(0,n.If)(u.equal((0,n.int)(3)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar().albedo.rgb;_.assign((0,n.vec4)(t,1))})}),(0,n.If)(u.equal((0,n.int)(5)),()=>{(0,n.If)(y.didHit.not(),()=>{_.assign((0,n.vec4)(0,0,0,1))}).Else(()=>{let e=yo.wrap(ls(y.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,y.uv,y.normal,(0,n.vec4)(0))).toVar(),u=t.albedo.rgb,d=(0,n.normalize)(t.normal).toVar(),p=z({state:ne({seed:(0,n.uint)(f.x).mul((0,n.uint)(1973)).add((0,n.uint)(f.y).mul((0,n.uint)(9277))).add(g.mul((0,n.uint)(26699)))})}).toVar(),m=cc({N:d,xi:(0,n.vec2)(re(p).toVar(),re(p).toVar())}).toVar(),h=vo({origin:Po(y.hitPoint,d),direction:m}),v=Co.wrap(bp(h,r,i).toVar()),b=(0,n.vec3)(0).toVar();(0,n.If)(v.didHit.not(),()=>{(0,n.If)(l,()=>{b.assign(Np({tex:o,samp:(0,n.sampler)(o),direction:m,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz)})}).Else(()=>{let e=yo.wrap(ls(v.materialIndex,a)).toVar(),t=Ao.wrap(tl(e,v.uv,v.normal,(0,n.vec4)(0))).toVar();b.assign(t.emissive),(0,n.If)(l,()=>{let e=(0,n.normalize)(t.normal).toVar(),r=Np({tex:o,samp:(0,n.sampler)(o),direction:e,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz;b.addAssign(t.albedo.rgb.mul(r))})});let x=u.mul(b);_.assign((0,n.vec4)(x,1))})}),(0,n.If)(u.equal((0,n.int)(6)),()=>{(0,n.If)(y.didHit,()=>{let e=y.normal.toVar(),r=(0,n.normalize)(t.sub(e.mul((0,n.dot)(t,e).mul(2)))).toVar(),i=Np({tex:o,samp:(0,n.sampler)(o),direction:r,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,a=i.div(i.add(1));_.assign((0,n.vec4)(a,1))}).Else(()=>{let e=Np({tex:o,samp:(0,n.sampler)(o),direction:t,environmentMatrix:s,environmentIntensity:c,enableEnvironmentLight:l}).xyz,r=e.div(e.add(1));_.assign((0,n.vec4)(r,1))})}),_});function Jm(e){let{writeColorTex:t,writeNDTex:r,writeAlbedoTex:i,resolution:a,renderWidth:o,renderHeight:s,cameraWorldMatrix:c,cameraProjectionMatrixInverse:l,cameraProjectionMatrix:u,cameraViewMatrix:d,cameraProjection:f,panoLonRange:p,panoLatRange:m,panoLevelHorizon:h,enableDOF:g,focalLength:_,aperture:v,focusDistance:y,sceneScale:b,apertureScale:x,anamorphicRatio:S,bvhBuffer:C,triangleBuffer:w,materialBuffer:T,envTexture:E,environmentMatrix:D,environmentIntensity:O,enableEnvironmentLight:k,visMode:A,debugVisScale:j,frame:M}=e;return(0,n.Fn)(()=>{let e=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),N=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(e.lessThan(o).and(N.lessThan(s)),()=>{let o=(0,n.vec2)((0,n.float)(e).add(.5),(0,n.float)(N).add(.5)),s=z({state:(0,n.uint)(N.mul((0,n.int)(a.x)).add(e)).add((0,n.uint)(1))}).toVar(),P=vo.wrap(ap(o.div(a),s,c,l,f,p,m,h,g,_,v,y,b,x,S)),F=(0,n.vec4)(1,0,1,1).toVar();(0,n.If)(A.equal((0,n.int)(9)),()=>{let e=_e(o,(0,n.int)(0),(0,n.int)(1),s,a,M);F.assign((0,n.vec4)(e,1,1))}).Else(()=>{F.assign(qm(P.origin,P.direction,C,w,T,E,D,O,k,A,j,o,a,u,d,M))});let I=(0,n.uvec2)((0,n.uint)(e),(0,n.uint)(N));(0,n.textureStore)(t,I,F).toWriteOnly(),(0,n.textureStore)(r,I,(0,n.vec4)(.5,.5,1,1)).toWriteOnly(),(0,n.textureStore)(i,I,(0,n.vec4)(F.xyz,1)).toWriteOnly()})})}function Ym({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.lessThan((0,n.uint)(t)),()=>{(0,n.atomicStore)(e.element(n.instanceIndex),(0,n.uint)(0))})})}function Xm({hitBufferRO:e,activeIndicesReadRO:t,sortGlobalHistogram:r,counters:i,bins:a=256}){return(0,n.Fn)(()=>{let o=n.instanceIndex,s=n.localId.x,c=(0,n.workgroupArray)(`uint`,a).toAtomic();(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{(0,n.atomicStore)(c.element(s),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let l=(0,n.atomicLoad)(i.element((0,n.uint)($.ENTERING_COUNT)));(0,n.If)(o.lessThan(l),()=>{let r=(0,n.uint)(kf(e,t.element(o))).clamp((0,n.uint)(0),(0,n.uint)(a-1));(0,n.atomicAdd)(c.element(r),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(s.lessThan((0,n.uint)(a)),()=>{let e=(0,n.atomicLoad)(c.element(s));(0,n.If)(e.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicAdd)(r.element(s),e)})})})}function Zm({sortGlobalHistogram:e,bins:t=256}){return(0,n.Fn)(()=>{(0,n.If)(n.instanceIndex.equal((0,n.uint)(0)),()=>{let r=(0,n.uint)(0).toVar();(0,n.Loop)({start:(0,n.uint)(0),end:(0,n.uint)(t),type:`uint`},({i:t})=>{let i=e.element(t),a=(0,n.atomicLoad)(i);(0,n.atomicStore)(i,r),r.addAssign(a)})})})}function Qm({hitBufferRO:e,activeIndicesReadRO:t,sortedIndicesRW:r,sortGlobalHistogram:i,counters:a,bins:o=256}){return(0,n.Fn)(()=>{let s=n.instanceIndex,c=n.localId.x,l=(0,n.workgroupArray)(`uint`,o).toAtomic();(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{(0,n.atomicStore)(l.element(c),(0,n.uint)(0))}),(0,n.workgroupBarrier)();let u=(0,n.atomicLoad)(a.element((0,n.uint)($.ENTERING_COUNT))),d=s.lessThan(u),f=(0,n.uint)(0).toVar(),p=(0,n.uint)(0).toVar();(0,n.If)(d,()=>{f.assign(t.element(s)),p.assign((0,n.uint)(kf(e,f)).clamp((0,n.uint)(0),(0,n.uint)(o-1))),(0,n.atomicAdd)(l.element(p),(0,n.uint)(1))}),(0,n.workgroupBarrier)(),(0,n.If)(c.lessThan((0,n.uint)(o)),()=>{let e=l.element(c),t=(0,n.atomicLoad)(e);(0,n.If)(t.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(e,(0,n.atomicAdd)(i.element(c),t))})}),(0,n.workgroupBarrier)(),(0,n.If)(d,()=>{r.element((0,n.atomicAdd)(l.element(p),(0,n.uint)(1))).assign(f)})})}qt();var $m=Pt(`wavefront`),eh=256,th=[`extend`,`shade`,`globalHist`,`globalScatter`,`compact`,`compactCopyback`],nh=class extends Zd{constructor(e,t,r,i={}){super(e,t,r,i),this.name=`PathTracer`,this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._dilateFrozenUniform=(0,n.uniform)(1,`int`),this._wavefrontReady=!1,this._auxGBufferEnabled=!1,this._auxGBufferUniform=(0,n.uniform)(0,`uint`),this._cleanAuxNormalEnabled=!1,this._cleanAuxNormalUniform=(0,n.uniform)(0,`uint`),this._auxSamples=0,this._auxSeedPending=!1,this._useDynamicDispatch=!0,this._sortMaterials=!1,this._useSubgroupCompact=!1,this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1,this._readbackPending=!1,this._readbackEveryNFrames=4,this._readbackFrameCounter=0,this._readbackGeneration=0,this._curveSizingValid=!1,this._bounceEarlyExitThreshold=1e-4,this._convergedFraction=0,this._convergedGeometryFraction=0,this._geometryPixelCount=0,this._convergedReadbackPending=!1,this._lastActivePixelCount=0,this._wfRenderWidth=(0,n.uniform)(1920,`int`),this._wfRenderHeight=(0,n.uniform)(1080,`int`),this._wfMaxRayCount=(0,n.uniform)(0,`uint`),this._wfCurrentBounce=(0,n.uniform)(0,`int`),this._wfChunkRowBase=(0,n.uniform)(0,`int`),this._wfChunkRows=(0,n.uniform)(0,`int`),this._wfIsFirstChunk=(0,n.uniform)(1,`uint`),this._pathBudget=0,this._pathBudgetOverride=0,this._chunkRows=0,this._numChunks=1,this.vramTracker=new tp(this.renderer),this._registerVRAMProviders(),$m.debug(`initialized (wavefront)`)}_registerVRAMProviders(){let e=this.vramTracker;e.register(`rays`,()=>{let e=this._packedBuffers?._attrs;return e?[e.ray,e.rng,e.hit]:null}),e.register(`queues`,()=>{let e=this._queueManager;return e?[e._countersAttr,e._bounceCountsAttr,e._attrA,e._attrB,e._sortAttr]:null}),e.register(`gbuffer`,()=>{let e=[];return this._gBufferAttr&&e.push(this._gBufferAttr),this._m2Attr&&e.push(this._m2Attr),this._streakAttr&&e.push(this._streakAttr),this._frozenMaskAttr&&e.push(this._frozenMaskAttr),e.length?e:null}),e.register(`accum`,()=>{let e=this.storageTextures;return e?[e.writeColor,e.writeNormalDepth,e.writeAlbedo,e.readTarget]:null}),e.register(`geometry`,()=>[this.triangleStorageAttr,this.bvhStorageAttr,this.lightStorageAttr]),e.register(`materials`,()=>{let e=this.materialData;return e?[e.materialStorageAttr,...(e.srgbBuckets||[]).filter(Boolean),...(e.linearBuckets||[]).filter(Boolean)]:null}),e.register(`environment`,()=>{let e=this.environment;return e?[e.environmentTexture,e.envCDFTexture]:null})}setupMaterial(){super.setupMaterial(),this.materialData?.materialCount>0&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}render(e){if(!this.isReady||!this._wavefrontReady||this._lightBufferRealloc&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels(),!this._wavefrontReady))return;if(this.isComplete||this.frameCount>=this.completionThreshold||this._isConvergedComplete())if(this._auxSeedPending)this.isComplete=!1;else{this.isComplete||=!0;return}this.performanceMonitor?.start();let t=this.frameCount,n=this.renderMode.value,r=null;n===1&&t===0&&(r=this.maxBounces.value,this.maxBounces.value=1),this._handleResize(),this.manageASVGFForRenderMode(n),e&&e.setState(`tileRenderingComplete`,!0),this.cameraChanged=this._updateCameraUniforms(),this.cameraOptimizer?.updateInteractionMode(this.cameraChanged),this.cameraChanged&&(this._curveSizingValid=!1,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0),this._updateAccumulationUniforms(t,n);let i=this._updateAuxAccumulationUniforms(t);this.frame.value=t,this.seedFrame.value=this._seedTick++,this.tracedFrames++,this._setWfDispatch();let a=this.storageTextures.getReadTextures();this.shaderBuilder.prevColorTexNode&&(this.shaderBuilder.prevColorTexNode.value=a.color,this.shaderBuilder.prevAlbedoTexNode.value=a.albedo,this.shaderBuilder.prevNormalDepthTexNode.value=a.normalDepth),this._refreshWfTextureNodes();let o=this._kernelManager;if((this.visMode?.value|0)>0&&this.visMode.value!==11){o.dispatch(`debug`),this.storageTextures.copyToReadTargets(this.renderer);let t=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,t),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end();return}let s=this.maxBounces.value,c=this._bounceLoopBound(),l=this._wfRenderHeight.value,u=this._chunkRows,d=this._numChunks<=1;c>this._lastBounceCountsLoopBound&&(this._curveSizingValid=!1);let f=this._lastBounceCounts,p=s<=this._lastBounceCountsBudget&&c<=this._lastBounceCountsLoopBound,m=d&&f?p?c+1:Math.min(this._lastBounceCountsBudget,this._lastBounceCountsLoopBound):0;for(let e=0,n=0;n<l;n+=u,e++){let r=Math.min(u,l-n),i=this._setChunk(n,r,e),a=this.usePixelFreeze.value>0&&!this._auxSeedPending,s=d&&a&&this._curveSizingValid&&this._lastActivePixelCount>0?this._lastActivePixelCount:i;if(a){let e=Math.min(i,Math.ceil(s*1.5)+1024);o.setDispatchForCount(`generateList`,e),o.dispatch(`resetFrameCounters`),o.dispatch(`buildActivePixels`),o.dispatch(`seedEnter`),o.dispatch(`generateList`)}else o.dispatch(`generate`),o.dispatch(`initActiveIndices`);e===0&&t>0&&this.useAdaptiveSampling.value>0&&this._willReadCountersThisFrame()&&o.dispatch(`countConvergedDilated`);let p=this._lastBounceEnergy,h=this._bounceEarlyExitThreshold>=0?this._bounceEarlyExitThreshold*i*64:-1;for(let e=0;e<=c;e++){this._wfCurrentBounce.value=e;let t=this._useDynamicDispatch;if(t){let t=i;if(d&&e>0&&this._curveSizingValid){let n=e-1,r;n<m&&f[n]!==void 0?r=f[n]:m>0&&(r=f[m-1]),t=r>0?r:i}else e===0&&a&&(t=s);let n=Math.min(i,Math.ceil(t*1.5)+1024);for(let e of th)o.setDispatchForCount(e,n)}else{o.dispatch(`enterFull`);for(let e of th)o.setDispatchForCount(e,i)}if(o.dispatch(`extend`),this._sortMaterials&&(o.dispatch(`resetGlobalHist`),o.dispatch(`globalHist`),o.dispatch(`globalPrefix`),o.dispatch(`globalScatter`)),o.dispatch(`shade`),o.dispatch(`compact`),t?o.dispatch(`compactCopyback`):o.dispatch(`snapshotBounceCount`),h>=0&&e<m&&e<c&&p?.[e]!==void 0&&p[e]<=h)break}o.dispatch(`finalWrite`)}this._maybeReadbackCounters(),this.storageTextures.copyToReadTargets(this.renderer,this._auxGBufferEnabled);let h=this.storageTextures.getReadTextures();e&&this._publishTexturesToContext(e,h),this._emitStateEvents(),this.cameraOptimizer?.isInInteractionMode()||this.frameCount++,this._auxGBufferEnabled&&(this._auxSamples=i?this._auxSamples+1:1),this._auxSeedPending=!1,r!==null&&(this.maxBounces.value=r),this.performanceMonitor?.end()}_isConvergedComplete(){return this.useAdaptiveSampling.value>0&&this.frameCount>=this.adaptiveMinSamples.value&&this._convergedFraction>=this.adaptiveStopFraction.value&&this._convergedGeometryFraction>=this.adaptiveStopFraction.value}reset(){super.reset(),this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._auxSamples=0,this._auxSeedPending=!1}getConvergenceDebugSource(){return!this._m2Attr||!this._frozenMaskAttr?null:(this._convDebugSource?.m2===this._m2Attr&&this._convDebugSource.frozenMask===this._frozenMaskAttr||(this._convDebugSource={m2:this._m2Attr,frozenMask:this._frozenMaskAttr,frame:this.frame,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,noiseThreshold:this.noiseThreshold,pixelFreezeThreshold:this.pixelFreezeThreshold,usePixelFreeze:this.usePixelFreeze,adaptiveMinSamples:this.adaptiveMinSamples}),this._convDebugSource)}getConvergenceStats(){let e=this._wfRenderWidth.value*this._wfRenderHeight.value;return{converged:this._convergedFraction,convergedGeometry:this._convergedGeometryFraction,geometryPixels:this._geometryPixelCount,activePixels:this._lastActivePixelCount,totalPixels:e,frame:this.frameCount}}_handleResize(){let e=this.storageTextures.renderWidth,t=this.storageTextures.renderHeight;super._handleResize(),this._rebuildKernelsIfResized(e,t)}setAuxGBufferEnabled(e){e=!!e,this._auxGBufferEnabled!==e&&(this._auxGBufferEnabled=e,this._auxGBufferUniform.value=+!!e,this.restartAuxAccumulation())}setCleanAuxNormal(e){e=!!e,this._cleanAuxNormalEnabled!==e&&(this._cleanAuxNormalEnabled=e,this._cleanAuxNormalUniform.value=+!!e,this.restartAuxAccumulation())}restartAuxAccumulation(){this._auxSamples=0,this._auxSeedPending=this._auxGBufferEnabled}_updateAuxAccumulationUniforms(e){let t=this.accumulationEnabled&&!this.cameraIsMoving.value&&e>0&&this.hasPreviousAccumulated.value>0&&this.visMode.value!==11,n=this._auxGBufferEnabled&&t&&!this._auxSeedPending&&this._auxSamples>0;return this.hasPreviousAux.value=+!!n,this.auxAccumulationAlpha.value=n?1/(this._auxSamples+1):1,n}setSize(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;super.setSize(e,t),this._rebuildKernelsIfResized(n,r)}_willReadCountersThisFrame(){return this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()||this._readbackPending||this._convergedReadbackPending?!1:this._readbackFrameCounter+1>=this._readbackEveryNFrames}_bounceLoopBound(){return this.maxBounces.value+this.transmissiveBounces.value+this.maxSubsurfaceSteps.value}_maybeReadbackCounters(){if(this.cameraChanged||this.cameraOptimizer?.isInInteractionMode()){this._readbackFrameCounter=this._readbackEveryNFrames;return}if(this._readbackPending||((this.maxBounces.value!==this._lastBounceCountsBudget||this._bounceLoopBound()!==this._lastBounceCountsLoopBound)&&(this._readbackFrameCounter=this._readbackEveryNFrames),this._readbackFrameCounter++,this._readbackFrameCounter<this._readbackEveryNFrames))return;this._readbackFrameCounter=0;let e=this._queueManager?.getBounceCountsAttribute();if(!e)return;this._readbackPending=!0;let t=this._readbackGeneration,n=this.maxBounces.value,r=this._bounceLoopBound(),i=this._queueManager.MAX_BOUNCE_SNAPSHOTS;if(this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration){let t=new Uint32Array(e.slice(0));this._lastBounceCounts=t.subarray(0,i),this._lastBounceEnergy=t.subarray(i,2*i),this._lastBounceCountsBudget=n,this._lastBounceCountsLoopBound=r,this._curveSizingValid=!0}this._readbackPending=!1}).catch(e=>{$m.warn(`bounceCounts readback failed:`,e),this._readbackPending=!1}),!this._convergedReadbackPending){let e=this._queueManager?.getCountersAttribute();if(e){this._convergedReadbackPending=!0;let t=this._readbackGeneration,n=this._wfRenderWidth.value*this._wfRenderHeight.value;this.renderer.getArrayBufferAsync(e).then(e=>{if(t===this._readbackGeneration&&n>0){let t=new Uint32Array(e);this._convergedFraction=t[$.CONVERGED_COUNT]/n;let r=t[$.GEOMETRY_COUNT];this._geometryPixelCount=r,this._convergedGeometryFraction=r>0?t[$.CONVERGED_GEOMETRY_COUNT]/r:1,this._lastActivePixelCount=t[$.ACTIVE_PIXEL_COUNT]}this._convergedReadbackPending=!1}).catch(()=>{this._convergedReadbackPending=!1})}}}_refreshWfTextureNodes(){let e=this._wfTexNodes;if(!e)return;let t=this.environment?.environmentTexture;t&&e.envTex&&(e.envTex.value=t),this.environment?.envCDFTexture&&e.envCDFTex&&(e.envCDFTex.value=this.environment.envCDFTexture);let n=this.materialData;n&&(Bc(e.srgbBuckets,n.srgbBuckets),Bc(e.linearBuckets,n.linearBuckets))}_rebuildKernelsIfResized(e,t){let n=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;if(!(n===e&&r===t||!(this.materialData?.materialCount>0))){if(this._lastBounceCounts&&this._numChunks<=1&&e>0&&t>0){let i=n*r/(e*t),a=e=>Math.min(4294967295,Math.round(e*i));this._lastBounceCounts=this._lastBounceCounts.map(a),this._lastBounceEnergy=this._lastBounceEnergy.map(a)}else this._lastBounceCounts=null,this._lastBounceEnergy=null,this._lastBounceCountsBudget=-1,this._lastBounceCountsLoopBound=-1;this._curveSizingValid=!1,this._readbackFrameCounter=0,this._readbackGeneration++,this._convergedFraction=0,this._convergedGeometryFraction=0,this._lastActivePixelCount=0,this._packedBuffers?this._resizeWavefrontInPlace(n,r):(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}}_resizeWavefrontInPlace(e,t){this._wfRenderWidth.value=e,this._wfRenderHeight.value=t,this._updateChunkLayout()}_computePathBudget(){if(this._pathBudgetOverride>0)return this._pathBudgetOverride;let e=this.renderer?.backend?.device?.limits,t=e?.maxStorageBufferBindingSize||128*1024*1024,n=e?.maxBufferSize||t,r=Math.floor(t*.9/112),i=(typeof navigator<`u`&&navigator.deviceMemory||4)*1024*1024*1024,a=Math.min(i*.25,n*4),o=Math.floor(a/176),s=Math.min(r,o,2048*2048);return s=Math.max(262144,s),s}_updateChunkLayout(){let e=Math.max(1,this.storageTextures.renderWidth),t=this.storageTextures.renderHeight,n=this._pathBudget||e*t;this._chunkRows=Math.max(1,Math.min(Math.floor(n/e),t)),this._numChunks=Math.max(1,Math.ceil(t/this._chunkRows))}reallocateReservedStorage(){if(!this.storageTextures.writeColor)return;let e=Math.min(this.storageTextures.renderWidth||1,G),t=Math.min(this.storageTextures.renderHeight||1,G);this.storageTextures.create(e,t),this.resolution.value.set(e,t),!(!this._packedBuffers||!(this.materialData?.materialCount>0))&&(this._kernelManager&&this._kernelManager.dispose(),this._wavefrontReady=!1,this._buildWavefrontKernels())}_buildWavefrontKernels(){let e=this.shaderBuilder.getSceneTextureNodes();if(!e)return;this._lightBufferRealloc=!1;let t=this.storageTextures.renderWidth,r=this.storageTextures.renderHeight;this._pathBudget||=this._computePathBudget();let i=this._pathBudget;this._updateChunkLayout();let a=this._chunkRows*t;this._packedBuffers?this._packedBuffers.resize(i):this._packedBuffers=new af(i,this.renderer);let o=i*1;rf(this.renderer,this._gBufferAttr),this._gBufferAttr=S(o,4,Uint32Array);let s=(0,n.storage)(this._gBufferAttr,`uvec4`),c=(0,n.storage)(this._gBufferAttr,`uvec4`).toReadOnly(),l=G*G;(!this._m2Attr||this._m2Attr.count<l)&&(rf(this.renderer,this._m2Attr),this._m2Attr=S(l,1),rf(this.renderer,this._streakAttr),this._streakAttr=S(l,1,Uint32Array),rf(this.renderer,this._frozenMaskAttr),this._frozenMaskAttr=S(l,1,Uint32Array));let u=(0,n.storage)(this._m2Attr,`float`),d=(0,n.storage)(this._streakAttr,`uint`),f=(0,n.storage)(this._streakAttr,`uint`).toReadOnly(),p=(0,n.storage)(this._frozenMaskAttr,`uint`),m=(0,n.storage)(this._frozenMaskAttr,`uint`).toReadOnly();this._queueManager?this._queueManager.resize(this._packedBuffers.capacity):this._queueManager=new Yf(this._packedBuffers.capacity,this.renderer),this._kernelManager||=new rp(this.renderer);let h=this._packedBuffers,g=this._queueManager;this._wfRenderWidth.value=t,this._wfRenderHeight.value=r,this._wfMaxRayCount.value=Math.min(i,this._chunkRows*t);let _=this.shaderBuilder.prevColorTexNode,v=this.shaderBuilder.prevAlbedoTexNode,y=this.shaderBuilder.prevNormalDepthTexNode,b=this.storageTextures.getWriteTextures(),x=g.getCounters(),C=g.getBounceCounts(),w=this._wfCurrentBounce,T=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT))),t=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(t).assign(e),C.element(t.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e)});this._kernelManager.register(`snapshotBounceCount`,T().compute([1,1,1],[1,1,1]));let E=g.activeIndices.a,D=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{E.element(e).assign(e)}),(0,n.If)(e.equal((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),this._wfMaxRayCount),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})})});this._kernelManager.register(`initActiveIndices`,D().compute([Math.ceil(this._chunkRows*t/eh),1,1],[eh,1,1]));let O={rayBufferRW:h.rayBuffer.rw,rngBufferRW:h.rngBuffer.rw,gBufferRW:s,resolution:this.resolution,frame:this.seedFrame,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows,transmissiveBounces:this.transmissiveBounces,transparentBackground:this.transparentBackground,auxGBufferEnabled:this._auxGBufferUniform},k=op(O);this._kernelManager.register(`generate`,k().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let A=this.pixelFreezeStability,j=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(0)),(0,n.If)(this._wfIsFirstChunk.greaterThan((0,n.uint)(0)),()=>{(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(0)),(0,n.atomicStore)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(0))})});this._kernelManager.register(`resetFrameCounters`,j().compute([1,1,1],[1,1,1]));let M=(0,n.Fn)(()=>{let e=n.instanceIndex;(0,n.If)(e.lessThan(this._wfMaxRayCount),()=>{let t=(0,n.uint)((0,n.int)(e).add(this._wfChunkRowBase.mul(this._wfRenderWidth))).toVar(),r=(0,n.uint)(0).toVar();(0,n.If)(this.frame.greaterThan((0,n.uint)(0)).and(f.element(t).bitAnd((0,n.uint)(1073741823)).greaterThanEqual((0,n.uint)(A))),()=>{r.assign((0,n.uint)(1)),(0,n.If)(this._dilateFrozenUniform.greaterThan((0,n.int)(0)),()=>{let e=(0,n.int)(t).mod(this._wfRenderWidth),i=(0,n.int)(t).div(this._wfRenderWidth);for(let[t,a]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let o=e.add((0,n.int)(t)),s=i.add((0,n.int)(a));(0,n.If)(o.greaterThanEqual((0,n.int)(0)).and(o.lessThan(this._wfRenderWidth)).and(s.greaterThanEqual((0,n.int)(0))).and(s.lessThan(this._wfRenderHeight)),()=>{(0,n.If)(f.element((0,n.uint)(s.mul(this._wfRenderWidth).add(o))).bitAnd((0,n.uint)(1073741823)).lessThan((0,n.uint)(A)),()=>{r.assign((0,n.uint)(0))})})}})}),p.element(t).assign(r),(0,n.If)(r.equal((0,n.uint)(0)),()=>{let t=(0,n.atomicAdd)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)),(0,n.uint)(1));E.element(t).assign(e)})})});this._kernelManager.register(`buildActivePixels`,M().compute([Math.ceil(this._chunkRows*t/eh),1,1],[eh,1,1]));let N=(0,n.Fn)(()=>{let e=n.instanceIndex,t=this._wfRenderWidth,r=this._wfRenderHeight;(0,n.If)(e.lessThan((0,n.uint)(t.mul(r))),()=>{let i=(0,n.int)(e).mod(t),a=(0,n.int)(e).div(t),o=(0,n.uint)(2147483648),s=(0,n.uint)(1073741824),c=f.element(e).toVar(),l=c.bitAnd(s).notEqual((0,n.uint)(0)),u=c.bitAnd(o).notEqual((0,n.uint)(0)).toVar();(0,n.If)(u,()=>{for(let[e,s]of[[-1,-1],[0,-1],[1,-1],[-1,0],[1,0],[-1,1],[0,1],[1,1]]){let c=i.add((0,n.int)(e)),l=a.add((0,n.int)(s));(0,n.If)(c.greaterThanEqual((0,n.int)(0)).and(c.lessThan(t)).and(l.greaterThanEqual((0,n.int)(0))).and(l.lessThan(r)),()=>{(0,n.If)(f.element((0,n.uint)(l.mul(t).add(c))).bitAnd(o).equal((0,n.uint)(0)),()=>{u.assign(!1)})})}}),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_COUNT)),(0,n.uint)(1))}),(0,n.If)(l,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.GEOMETRY_COUNT)),(0,n.uint)(1)),(0,n.If)(u,()=>{(0,n.atomicAdd)(x.element((0,n.uint)($.CONVERGED_GEOMETRY_COUNT)),(0,n.uint)(1))})})})});this._kernelManager.register(`countConvergedDilated`,N().compute([Math.ceil(t*r/eh),1,1],[eh,1,1]));let P=(0,n.Fn)(()=>{let e=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),e),(0,n.atomicStore)(x.element((0,n.uint)($.ACTIVE_PIXEL_COUNT)),e)});this._kernelManager.register(`seedEnter`,P().compute([1,1,1],[1,1,1]));let F=op({...O,listDriven:!0,activeIndicesRO:g.activeIndicesRO.a,counters:x});this._kernelManager.register(`generateList`,F().compute([Math.ceil(a/eh),1,1],[eh,1,1]));let I=this.bvhStorageNode,L=this.triangleStorageNode,R=this.materialData.materialStorageNode,ee=(0,n.texture)(this.environment.envCDFTexture),te=this.lightStorageNode,z=this.materialData,ne=this.environment,B=zc(z.srgbBuckets),re=zc(z.linearBuckets);Nc(B,re),il(B);let ie=ne.environmentTexture?(0,n.texture)(ne.environmentTexture):e.envTex;this._wfTexNodes={envTex:ie,envCDFTex:ee,srgbBuckets:B,linearBuckets:re},this._sortMaterials=(W.wavefrontSortMaterials??!1)&&(this.materialData?.materialCount??0)>8;let ae=Op({bvhBuffer:I,triangleBuffer:L,rayBufferRO:h.rayBuffer.ro,hitBufferRW:h.hitBuffer.rw,activeIndicesRO:g.getActiveReadRO(),counters:x,maxRayCount:this._wfMaxRayCount,shadowTerminatorOffset:this.shadowTerminatorOffset});if(this._kernelManager.register(`extend`,ae().compute([Math.ceil(a/256),1,1],[256,1,1])),this._sortMaterials){let e=g.getSortGlobalHistogram(),t=Math.min(256,this.materialData?.materialCount??256);this._kernelManager.register(`resetGlobalHist`,Ym({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[256,1,1])),this._kernelManager.register(`globalHist`,Xm({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1])),this._kernelManager.register(`globalPrefix`,Zm({sortGlobalHistogram:e,bins:t})().compute([1,1,1],[1,1,1])),this._kernelManager.register(`globalScatter`,Qm({hitBufferRO:h.hitBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),sortedIndicesRW:g.getSortedRW(),sortGlobalHistogram:e,counters:x,bins:t})().compute([Math.ceil(a/256),1,1],[256,1,1]))}let oe=Rm({gBufferRW:s,envCompensationDelta:this.envCompensationDelta,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envCDFTexture:ee,lightBuffer:te,rayBufferRW:h.rayBuffer.rw,rngBufferRW:h.rngBuffer.rw,hitBufferRO:h.hitBuffer.ro,counters:x,activeIndicesRO:this._sortMaterials?g.getSortedRO():g.getActiveReadRO(),envTexture:ie,environmentIntensity:this.environmentIntensity,envMatrix:this.environmentMatrix,enableEnvironmentLight:this.enableEnvironment,groundProjectionEnabled:this.groundProjectionEnabled,groundProjectionRadius:this.groundProjectionRadius,groundProjectionHeight:this.groundProjectionHeight,groundProjectionLevel:this.groundProjectionLevel,enableGroundCatcher:this.enableGroundCatcher,groundCatcherHeight:this.groundCatcherHeight,envTotalSum:this.envTotalSum,envResolution:this.envResolution,directionalLightsBuffer:this.directionalLightsBufferNode,numDirectionalLights:this.numDirectionalLights,areaLightsBuffer:this.areaLightsBufferNode,numAreaLights:this.numAreaLights,pointLightsBuffer:this.pointLightsBufferNode,numPointLights:this.numPointLights,spotLightsBuffer:this.spotLightsBufferNode,numSpotLights:this.numSpotLights,maxBounceCount:this.maxBounces,maxSubsurfaceSteps:this.maxSubsurfaceSteps,maxTransparentBounces:this.maxTransparentBounces,transparentBackground:this.transparentBackground,backgroundIntensity:this.backgroundIntensity,backgroundColor:this.backgroundColor,backgroundBlurriness:this.backgroundBlurriness,backgroundBlurSamples:this.backgroundBlurSamples,showBackground:this.showBackground,globalIlluminationIntensity:this.globalIlluminationIntensity,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,fireflyThreshold:this.fireflyThreshold,shadowTerminatorOffset:this.shadowTerminatorOffset,frame:this.seedFrame,accumFrame:this.frame,resolution:this.resolution,emissiveTriangleCount:this.emissiveTriangleCount,emissiveVec4Offset:this.emissiveVec4Offset,emissiveTotalPower:this.emissiveTotalPower,emissiveBoost:this.emissiveBoost,totalTriangleCount:this.totalTriangleCount,enableEmissiveTriangleSampling:this.enableEmissiveTriangleSampling,lightBVHNodeCount:this.lightBVHNodeCount,reverseMapVec4Offset:this.reverseMapVec4Offset,currentBounce:this._wfCurrentBounce,maxRayCount:this._wfMaxRayCount,chunkRowBase:this._wfChunkRowBase,auxGBufferEnabled:this._auxGBufferUniform});this._kernelManager.register(`shade`,oe().compute([Math.ceil(a/256),1,1],[256,1,1]));let se=this._useSubgroupCompact&&(this.renderer.hasFeature?this.renderer.hasFeature(`subgroups`):!1);this._compactIsSubgroup=se;let ce=(se?Vm:Bm)({rayBufferRO:h.rayBuffer.ro,activeIndicesReadRO:g.getActiveReadRO(),activeIndicesWriteRW:g.getActiveWrite(),counters:x,currentActiveCount:this._wfMaxRayCount});this._kernelManager.register(`compact`,ce().compute([Math.ceil(a/256),1,1],[256,1,1]));let le=(0,n.Fn)(()=>{(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),this._wfMaxRayCount)});this._kernelManager.register(`enterFull`,le().compute([1,1,1],[1,1,1]));let ue=g.activeIndicesRO.b,de=g.activeIndices.a,fe=(0,n.Fn)(()=>{let e=n.instanceIndex,t=(0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_RAY_COUNT)));(0,n.If)(e.equal((0,n.uint)(0)),()=>{let e=(0,n.uint)(w).clamp((0,n.uint)(0),(0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS-1));C.element(e).assign(t),C.element(e.add((0,n.uint)(g.MAX_BOUNCE_SNAPSHOTS))).assign((0,n.atomicLoad)(x.element((0,n.uint)($.ACTIVE_ENERGY)))),(0,n.atomicStore)(x.element((0,n.uint)($.ENTERING_COUNT)),t)}),(0,n.If)(e.greaterThanEqual(t),()=>{(0,n.Return)()}),de.element(e).assign(ue.element(e))});this._kernelManager.register(`compactCopyback`,fe().compute([Math.ceil(a/eh),1,1],[eh,1,1]));let pe=Um({rayBufferRO:h.rayBuffer.ro,gBufferRO:c,writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,frame:this.frame,enableAccumulation:this.enableAccumulation,hasPreviousAccumulated:this.hasPreviousAccumulated,accumulationAlpha:this.accumulationAlpha,hasPreviousAux:this.hasPreviousAux,auxAccumulationAlpha:this.auxAccumulationAlpha,cameraIsMoving:this.cameraIsMoving,transparentBackground:this.transparentBackground,prevAccumTexture:_,prevAlbedoTexture:v,prevNormalDepthTexture:y,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,visMode:this.visMode,auxGBufferEnabled:this._auxGBufferUniform,cleanAuxNormalEnabled:this._cleanAuxNormalUniform,m2BufferRW:u,useAdaptiveSampling:this.useAdaptiveSampling,noiseThreshold:this.noiseThreshold,adaptiveMinSamples:this.adaptiveMinSamples,usePixelFreeze:this.usePixelFreeze,pixelFreezeThreshold:this.pixelFreezeThreshold,streakBufferRW:d,frozenMaskRO:m,convergenceOverlay:this.convergenceOverlay,chunkRowBase:this._wfChunkRowBase,chunkRows:this._wfChunkRows});this._kernelManager.register(`finalWrite`,pe().compute([Math.ceil(t/16),Math.ceil(this._chunkRows/16),1],[16,16,1]));let me=Jm({writeColorTex:b.color,writeNDTex:b.normalDepth,writeAlbedoTex:b.albedo,resolution:this.resolution,renderWidth:this._wfRenderWidth,renderHeight:this._wfRenderHeight,cameraWorldMatrix:this.cameraWorldMatrix,cameraProjectionMatrixInverse:this.cameraProjectionMatrixInverse,cameraProjectionMatrix:this.cameraProjectionMatrix,cameraViewMatrix:this.cameraViewMatrix,cameraProjection:this.cameraProjection,panoLonRange:this.panoLonRange,panoLatRange:this.panoLatRange,panoLevelHorizon:this.panoLevelHorizon,enableDOF:this.enableDOF,focalLength:this.focalLength,aperture:this.aperture,focusDistance:this.focusDistance,sceneScale:this.sceneScale,apertureScale:this.apertureScale,anamorphicRatio:this.anamorphicRatio,bvhBuffer:I,triangleBuffer:L,materialBuffer:R,envTexture:ie,environmentMatrix:this.environmentMatrix,environmentIntensity:this.environmentIntensity,enableEnvironmentLight:this.enableEnvironment,visMode:this.visMode,debugVisScale:this.debugVisScale,frame:this.frame});this._kernelManager.register(`debug`,me().compute([Math.ceil(t/16),Math.ceil(r/16),1],[16,16,1])),this._wavefrontReady=!0;let he=(this._packedBuffers?.totalBytes??0)+(this._queueManager?.totalBytes??0);$m.info(Y.list([Y.px(t,r),`${Y.mb(he)} wavefront buffers`,`budget ${Y.n(i)} paths`,this._numChunks>1?`${this._numChunks} chunks of ≤${this._chunkRows} rows`:null]))}_setWfDispatch(){let e=this._wfRenderWidth.value,t=this._wfRenderHeight.value;this._kernelManager.setDispatchForGrid(`debug`,e,t),this._kernelManager.setDispatchForCount(`countConvergedDilated`,e*t)}_setChunk(e,t,n){let r=this._wfRenderWidth.value,i=t*r;this._wfChunkRowBase.value=e,this._wfChunkRows.value=t,this._wfIsFirstChunk.value=+(n===0),this._wfMaxRayCount.value=i;let a=this._kernelManager;return a.setDispatchForGrid(`generate`,r,t),a.setDispatchForGrid(`finalWrite`,r,t),a.setDispatchForCount(`initActiveIndices`,i),a.setDispatchForCount(`buildActivePixels`,i),i}dispose(){super.dispose(),this._packedBuffers?.dispose(),this._queueManager?.dispose(),this._kernelManager?.dispose(),this._gBufferAttr?.dispose?.(),this._m2Attr?.dispose?.(),this._streakAttr?.dispose?.(),this._frozenMaskAttr?.dispose?.(),this._packedBuffers=null,this._queueManager=null,this._kernelManager=null,this._gBufferAttr=null,this._m2Attr=null,this._streakAttr=null,this._frozenMaskAttr=null,this._convDebugSource=null,this._wavefrontReady=!1}},rh=class extends V{constructor(e,i={}){super(`NormalDepth`,{...i,executionMode:ye.ALWAYS}),this.renderer=e,this.pathTracer=i.pathTracer,this._dirty=!0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.resolutionWidth=(0,n.uniform)(i.width||1),this.resolutionHeight=(0,n.uniform)(i.height||1);let a=i.width||1,o=i.height||1;this._outputStorageTex=new t.StorageTexture(G,G),this._outputStorageTex.type=r.HalfFloatType,this._outputStorageTex.format=r.RGBAFormat,this._outputStorageTex.minFilter=r.NearestFilter,this._outputStorageTex.magFilter=r.NearestFilter,this._shadingStorageTex=new t.StorageTexture(G,G),this._shadingStorageTex.type=r.HalfFloatType,this._shadingStorageTex.format=r.RGBAFormat,this._shadingStorageTex.minFilter=r.NearestFilter,this._shadingStorageTex.magFilter=r.NearestFilter,this._shadingRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._leafStorageTex=null,this._leafRT=null,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let s={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._rtA=new t.RenderTarget(a,o,s),this._rtB=new t.RenderTarget(a,o,s),this._currentIdx=0,this._hasHistory=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._lastTriAttr=null,this._lastBvhAttr=null,this._lastMatAttr=null,this._computeNode=null,this._computeBuilt=!1,this._linearBuckets=null}setupEventListeners(){this.on(`camera:moved`,()=>{this._dirty=!0}),this.on(`pipeline:reset`,()=>{this._dirty=!0})}_syncStorageBuffers(){let e=this.pathTracer;if(!e)return!1;let t=e.materialData?.materialStorageAttr,r=e.triangleStorageAttr&&e.triangleStorageAttr!==this._lastTriAttr,i=e.bvhStorageAttr&&e.bvhStorageAttr!==this._lastBvhAttr,a=t&&t!==this._lastMatAttr;return(r||i||a)&&(this._computeNode?.dispose?.(),this._computeNode=null,this._computeBuilt=!1,this._triStorageNode=null,this._bvhStorageNode=null,this._matStorageNode=null,this._dirty=!0,this._hasHistory=!1),e.triangleStorageAttr&&!this._triStorageNode&&(this._triStorageNode=(0,n.storage)(e.triangleStorageAttr,`uvec4`,e.triangleStorageAttr.count).toReadOnly()),e.bvhStorageAttr&&!this._bvhStorageNode&&(this._bvhStorageNode=(0,n.storage)(e.bvhStorageAttr,`vec4`,e.bvhStorageAttr.count).toReadOnly()),t&&!this._matStorageNode&&(this._matStorageNode=(0,n.storage)(t,`vec4`,t.count).toReadOnly()),this._linearBuckets&&Bc(this._linearBuckets,e.materialData?.linearBuckets),this._lastTriAttr=e.triangleStorageAttr||this._lastTriAttr,this._lastBvhAttr=e.bvhStorageAttr||this._lastBvhAttr,this._lastMatAttr=t||this._lastMatAttr,!!(this._triStorageNode&&this._bvhStorageNode&&this._matStorageNode)}_buildCompute(){let e=this._triStorageNode,t=this._bvhStorageNode,r=this._matStorageNode;this._linearBuckets=zc(this.pathTracer?.materialData?.linearBuckets),Nc(zc(null),this._linearBuckets);let i=this.cameraWorldMatrix,a=this.cameraProjectionMatrixInverse,o=this.resolutionWidth,s=this.resolutionHeight,c=this._outputStorageTex,l=this._shadingStorageTex,u=this._leafStorageTex;this._computeNode=(0,n.Fn)(([i,a])=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(o)).and(f.lessThan((0,n.int)(s))),()=>{let p=ip((0,n.vec2)((0,n.float)(d).add(.5).div(o),(0,n.float)(f).add(.5).div(s)),i,a,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon),m=vo({origin:(0,n.vec3)(i[3]),direction:p}),h=Co.wrap(yp(m,t,e)),g=h.normal.mul(.5).add(.5),_=(0,n.min)(h.dst,(0,n.float)(65504)),v=h.didHit.select((0,n.vec4)(g,_),(0,n.vec4)(0,0,0,(0,n.float)(65504)));(0,n.textureStore)(c,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),v).toWriteOnly(),u&&(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),(0,n.uvec4)((0,n.uint)(h.instanceLeaf.add(1)),0,0,0)).toWriteOnly();let y=h.normal.toVar(),b=(0,n.float)(1).toVar();(0,n.If)(h.didHit,()=>{let i=yo.wrap(ls(h.materialIndex,r)).toVar(),a=Mo.wrap(Gc(h.uv,i)).toVar(),o=(0,n.vec4)(0).toVar();(0,n.If)(i.normalMapIndex.greaterThanEqual((0,n.int)(0)),()=>{o.assign(Yc(e,h.triangleIndex,h.normal,i.normalTransform,t,h.instanceLeaf))});let s=Xc(h.normal,i,a,o).toVar();y.assign(Zc(s,i,a)),b.assign(qc(i,a).y.clamp(.05,1))});let x=h.didHit.select((0,n.vec4)(y.mul(.5).add(.5),b),(0,n.vec4)(0,0,0,1));(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),x).toWriteOnly()})})(i,a).compute([this._dispatchX,this._dispatchY,1],[8,8,1]),this._computeBuilt=!0}render(e){if(!this.enabled||!this._syncStorageBuffers())return;this._computeBuilt||this._buildCompute();let t=this.pathTracer;if(t&&(this.cameraWorldMatrix.value.copy(t.uniforms.get(`cameraWorldMatrix`).value),this.cameraProjectionMatrixInverse.value.copy(t.uniforms.get(`cameraProjectionMatrixInverse`).value),this.cameraProjection.value=t.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(t.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(t.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=t.uniforms.get(`panoLevelHorizon`).value),!this._dirty&&this._hasHistory){let t=this._currentIdx===0?this._rtA:this._rtB;e.setTexture(`pathtracer:normalDepth`,t.texture),e.setTexture(`pathtracer:prevNormalDepth`,t.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e);return}let n=e.getTexture(`pathtracer:color`);if(n&&n.image){let e=n.image;e.width>0&&e.height>0&&(e.width!==this._rtA.width||e.height!==this._rtA.height)&&this.setSize(e.width,e.height)}this._hasHistory&&(this._currentIdx=1-this._currentIdx);let r=this._currentIdx===0?this._rtA:this._rtB,i=this._currentIdx===0?this._rtB:this._rtA;this.renderer.compute(this._computeNode),this._srcRegion.max.set(r.width,r.height),this.renderer.copyTextureToTexture(this._outputStorageTex,r.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._shadingStorageTex,this._shadingRT.texture,this._srcRegion),this._leafRT&&this.renderer.copyTextureToTexture(this._leafStorageTex,this._leafRT.texture,this._srcRegion),this._hasHistory||=(this.renderer.copyTextureToTexture(this._outputStorageTex,i.texture,this._srcRegion),!0),e.setTexture(`pathtracer:normalDepth`,r.texture),e.setTexture(`pathtracer:prevNormalDepth`,i.texture),e.setTexture(`pathtracer:shadingNormal`,this._shadingRT.texture),this._publishLeaf(e),this._dirty=!1}releaseGPUMemory(){this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._leafStorageTex?.dispose(),this.reset(),this._hasHistory=!1}reset(){this._dirty=!0}setSize(e,t){this._rtA.setSize(e,t),this._rtA.texture.needsUpdate=!0,this._rtB.setSize(e,t),this._rtB.texture.needsUpdate=!0,this._shadingRT.setSize(e,t),this._shadingRT.texture.needsUpdate=!0,this._leafRT&&(this._leafRT.setSize(e,t),this._leafRT.texture.needsUpdate=!0),this._hasHistory=!1,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._computeNode&&(this._computeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._dirty=!0}reallocateReservedStorage(){this._computeNode?.dispose(),this._computeNode=null,this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(G,G);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._outputStorageTex=e(),this._shadingStorageTex=e(),this._leafStorageTex&&=(this._leafStorageTex.dispose(),this._makeLeafStorage()),this._computeBuilt=!1}setInstanceLeafOutput(e){e=!!e,e!==!!this._leafStorageTex&&(this._computeNode?.dispose(),this._computeNode=null,this._computeBuilt=!1,this._dirty=!0,e?(this._leafStorageTex=this._makeLeafStorage(),this._leafRT=new t.RenderTarget(this._rtA.width,this._rtA.height,{type:r.UnsignedIntType,format:r.RedIntegerFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1})):(this._leafStorageTex.dispose(),this._leafRT.dispose(),this._leafStorageTex=null,this._leafRT=null))}_publishLeaf(e){this._leafRT?e.setTexture(`pathtracer:instanceLeaf`,this._leafRT.texture):e.getTexture(`pathtracer:instanceLeaf`)&&e.removeTexture(`pathtracer:instanceLeaf`)}_makeLeafStorage(){let e=new t.StorageTexture(G,G);return e.type=r.UnsignedIntType,e.format=r.RedIntegerFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e}dispose(){this._computeNode?.dispose(),this._outputStorageTex?.dispose(),this._shadingStorageTex?.dispose(),this._shadingRT?.dispose(),this._leafStorageTex?.dispose(),this._leafRT?.dispose(),this._rtA?.dispose(),this._rtB?.dispose()}},ih=class extends V{constructor(e,i,a={}){super(`MotionVector`,{...a,executionMode:ye.ALWAYS}),this.renderer=e,this.camera=i,this.pathTracer=a.pathTracer||null;let o=a.width||1,s=a.height||1;this.prevViewProjectionMatrix=new r.Matrix4,this.currentViewProjectionMatrix=new r.Matrix4,this.matricesInitialized=!1,this.isFirstFrame=!0,this.frameCount=0,this.cameraWorldMatrix=(0,n.uniform)(new r.Matrix4,`mat4`),this.cameraProjectionMatrixInverse=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevVP=(0,n.uniform)(new r.Matrix4,`mat4`),this.isFirstFrameU=(0,n.uniform)(1),this.deltaTime=(0,n.uniform)(1/60),this.velocityScale=(0,n.uniform)(1),this.resolutionWidth=(0,n.uniform)(o),this.resolutionHeight=(0,n.uniform)(s),this._normalDepthTexNode=new t.TextureNode,this._screenSpaceStorageTex=new t.StorageTexture(G,G),this._screenSpaceStorageTex.type=r.HalfFloatType,this._screenSpaceStorageTex.format=r.RGBAFormat,this._screenSpaceStorageTex.minFilter=r.NearestFilter,this._screenSpaceStorageTex.magFilter=r.NearestFilter,this._worldSpaceStorageTex=new t.StorageTexture(G,G),this._worldSpaceStorageTex.type=r.HalfFloatType,this._worldSpaceStorageTex.format=r.RGBAFormat,this._worldSpaceStorageTex.minFilter=r.NearestFilter,this._worldSpaceStorageTex.magFilter=r.NearestFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0));let c={type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this.screenSpaceTarget=new t.RenderTarget(o,s,c),this.worldSpaceTarget=new t.RenderTarget(o,s,c),this._dispatchX=Math.ceil(o/16),this._dispatchY=Math.ceil(s/16),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}_buildScreenSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.resolutionWidth,o=this.resolutionHeight,s=this._screenSpaceStorageTex;this._screenSpaceComputeNode=(0,n.Fn)(([t,r])=>{let c=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),l=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(c.lessThan((0,n.int)(a)).and(l.lessThan((0,n.int)(o))),()=>{let u=(0,n.textureLoad)(e,(0,n.ivec2)(c,l)).w,d=(0,n.vec2)((0,n.float)(c).add(.5).div(a),(0,n.float)(l).add(.5).div(o)),f=(0,n.vec4)(0,0,u,1).toVar();(0,n.If)(u.lessThan((0,n.float)(6e4)),()=>{let e=(0,n.vec3)((0,n.float)(c).add(.5).div(a).mul(2).sub(1),(0,n.float)(l).add(.5).div(o).mul(2).sub(1).negate(),1),s=r.mul((0,n.vec4)(e,1)),p=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(s.xyz.div(s.w))),m=(0,n.vec3)(t[3]).add(p.mul(u)),h=i.mul((0,n.vec4)(m,1)),g=h.xy.div(h.w),_=(0,n.vec2)(g.x.mul(.5).add(.5),g.y.mul(-.5).add(.5)),v=d.sub(_),y=_.x.greaterThanEqual(0).and(_.x.lessThanEqual(1)).and(_.y.greaterThanEqual(0)).and(_.y.lessThanEqual(1));f.assign(y.select((0,n.vec4)(v,u,1),(0,n.vec4)((0,n.float)(1e3),(0,n.float)(1e3),u,0)))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(c),(0,n.uint)(l)),f).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_buildWorldSpaceCompute(){let e=this._normalDepthTexNode,t=this.cameraWorldMatrix,r=this.cameraProjectionMatrixInverse,i=this.prevVP,a=this.isFirstFrameU,o=this.deltaTime,s=this.velocityScale,c=this.resolutionWidth,l=this.resolutionHeight,u=this._worldSpaceStorageTex;this._worldSpaceComputeNode=(0,n.Fn)(([t,r])=>{let d=(0,n.int)(n.workgroupId.x).mul(16).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(16).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(c)).and(f.lessThan((0,n.int)(l))),()=>{let p=(0,n.textureLoad)(e,(0,n.ivec2)(d,f)).w,m=(0,n.vec4)(0,0,0,0).toVar();(0,n.If)(a.lessThan(.5).and(p.lessThan((0,n.float)(6e4))),()=>{let e=(0,n.vec3)((0,n.float)(d).add(.5).div(c).mul(2).sub(1),(0,n.float)(f).add(.5).div(l).mul(2).sub(1).negate(),1),a=r.mul((0,n.vec4)(e,1)),u=(0,n.normalize)((0,n.mat3)(t[0].xyz,t[1].xyz,t[2].xyz).mul(a.xyz.div(a.w))),h=(0,n.vec3)(t[3]).add(u.mul(p)),g=(0,n.vec2)((0,n.float)(d).add(.5).div(c),(0,n.float)(f).add(.5).div(l)),_=i.mul((0,n.vec4)(h,1)),v=_.xy.div(_.w),y=(0,n.vec2)(v.x.mul(.5).add(.5),v.y.mul(-.5).add(.5)),b=y.x.greaterThanEqual(0).and(y.x.lessThanEqual(1)).and(y.y.greaterThanEqual(0)).and(y.y.lessThanEqual(1)),x=g.sub(y),S=(0,n.vec3)(x.x.div(o).mul(s),x.y.div(o).mul(s),0);m.assign(b.select((0,n.vec4)(S,1),(0,n.vec4)(0,0,0,.5)))}),(0,n.textureStore)(u,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})(t,r).compute([this._dispatchX,this._dispatchY,1],[16,16,1])}_updateCameraMatrices(){let e=this.pathTracer,t,n,r,i;if(e&&e.uniforms)t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrix`).value,i=e.uniforms.get(`cameraProjectionMatrixInverse`).value;else{let e=this.camera;if(!e)return;t=e.matrixWorld,n=e.matrixWorldInverse,r=e.projectionMatrix,i=e.projectionMatrixInverse}this.matricesInitialized?this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix):(this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.prevViewProjectionMatrix.copy(this.currentViewProjectionMatrix),this.matricesInitialized=!0),this.currentViewProjectionMatrix.multiplyMatrices(r,n),this.cameraWorldMatrix.value.copy(t),this.cameraProjectionMatrixInverse.value.copy(i),this.prevVP.value.copy(this.prevViewProjectionMatrix)}setupEventListeners(){this.on(`pipeline:reset`,()=>{this.reset()})}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:normalDepth`);if(!t)return;this._updateCameraMatrices(),this.isFirstFrameU.value=+!!this.isFirstFrame,this.frameCount++;let n=t.image;n&&n.width>0&&n.height>0&&(n.width!==this.screenSpaceTarget.width||n.height!==this.screenSpaceTarget.height)&&this.setSize(n.width,n.height),this._normalDepthTexNode.value=t,this.renderer.compute(this._screenSpaceComputeNode),this.renderer.compute(this._worldSpaceComputeNode),this._srcRegion.max.set(this.screenSpaceTarget.width,this.screenSpaceTarget.height),this.renderer.copyTextureToTexture(this._screenSpaceStorageTex,this.screenSpaceTarget.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._worldSpaceStorageTex,this.worldSpaceTarget.texture,this._srcRegion),e.setTexture(`motionVector:screenSpace`,this.screenSpaceTarget.texture),e.setTexture(`motionVector:worldSpace`,this.worldSpaceTarget.texture),e.setTexture(`motionVector:motion`,this.screenSpaceTarget.texture),this.emit(`motionvector:computed`,{frame:this.frameCount,isFirstFrame:this.isFirstFrame}),this.isFirstFrame=!1}releaseGPUMemory(){this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.reset()}reset(){this.matricesInitialized||(this.isFirstFrame=!0),this.frameCount=0}setSize(e,t){this.screenSpaceTarget.setSize(e,t),this.screenSpaceTarget.texture.needsUpdate=!0,this.worldSpaceTarget.setSize(e,t),this.worldSpaceTarget.texture.needsUpdate=!0,this.resolutionWidth.value=e,this.resolutionHeight.value=t,this._dispatchX=Math.ceil(e/16),this._dispatchY=Math.ceil(t/16),this._screenSpaceComputeNode&&(this._screenSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]),this._worldSpaceComputeNode&&(this._worldSpaceComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1])}setVelocityScale(e){this.velocityScale.value=e}setDeltaTime(e){this.deltaTime.value=e}reallocateReservedStorage(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose();let e=()=>{let e=new t.StorageTexture(G,G);return e.type=r.HalfFloatType,e.format=r.RGBAFormat,e.minFilter=r.NearestFilter,e.magFilter=r.NearestFilter,e};this._screenSpaceStorageTex=e(),this._worldSpaceStorageTex=e(),this._buildScreenSpaceCompute(),this._buildWorldSpaceCompute()}dispose(){this._screenSpaceComputeNode?.dispose(),this._worldSpaceComputeNode?.dispose(),this._screenSpaceStorageTex?.dispose(),this._worldSpaceStorageTex?.dispose(),this.screenSpaceTarget?.dispose(),this.worldSpaceTarget?.dispose(),this._normalDepthTexNode?.dispose()}},ah=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),oh=e=>(0,n.vec3)(ah(e.x),ah(e.y),ah(e.z)),sh=class extends V{constructor(e,i={}){super(`ASVGF`,{...i,executionMode:ye.PER_CYCLE}),this.renderer=e,this.temporalAlpha=(0,n.uniform)(i.temporalAlpha??0),this.gradientStrength=(0,n.uniform)(i.gradientStrength??1),this.gradientSigmaScale=(0,n.uniform)(i.gradientSigmaScale??2),this.gradientNoiseFloor=(0,n.uniform)(i.gradientNoiseFloor??0),this.maxAccumFrames=(0,n.uniform)(i.maxAccumFrames??32),this.resW=(0,n.uniform)(i.width||1),this.resH=(0,n.uniform)(i.height||1),this.temporalEnabledU=(0,n.uniform)(1),this.forceResetU=(0,n.uniform)(0),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._normalDepthTexNode=new t.TextureNode,this._prevNormalDepthTexNode=new t.TextureNode,this._readTemporalTexNode=new t.TextureNode,this._gradientReadTexNode=new t.TextureNode;let a=i.width||1,o=i.height||1;this._temporalTexA=new t.StorageTexture(G,G),this._temporalTexA.type=r.FloatType,this._temporalTexA.format=r.RGBAFormat,this._temporalTexA.minFilter=r.LinearFilter,this._temporalTexA.magFilter=r.LinearFilter,this._temporalTexB=new t.StorageTexture(G,G),this._temporalTexB.type=r.FloatType,this._temporalTexB.format=r.RGBAFormat,this._temporalTexB.minFilter=r.LinearFilter,this._temporalTexB.magFilter=r.LinearFilter,this._outputModulatedTex=new t.StorageTexture(G,G),this._outputModulatedTex.type=r.FloatType,this._outputModulatedTex.format=r.RGBAFormat,this._outputModulatedTex.minFilter=r.LinearFilter,this._outputModulatedTex.magFilter=r.LinearFilter,this._gradientStorageTex=new t.StorageTexture(G,G),this._gradientStorageTex.type=r.HalfFloatType,this._gradientStorageTex.format=r.RGBAFormat,this._gradientStorageTex.minFilter=r.LinearFilter,this._gradientStorageTex.magFilter=r.LinearFilter,this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this._demodulatedRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._outputRT=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._gradientRT=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this.currentMoments=0,this._compiled=!1,this._needsWarmReset=!1,this._dispatchX=Math.ceil(a/8),this._dispatchY=Math.ceil(o/8),this._buildGradientCompute(),this._buildTemporalCompute(),this.showHeatmap=!1,this.debugMode=(0,n.uniform)(0,`int`),this._heatmapStorageTex=new t.StorageTexture(G,G),this._heatmapStorageTex.type=r.FloatType,this._heatmapStorageTex.format=r.RGBAFormat,this._heatmapStorageTex.minFilter=r.NearestFilter,this._heatmapStorageTex.magFilter=r.NearestFilter,this.heatmapTarget=new t.RenderTarget(a,o,{type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1}),this._heatmapRawColorTexNode=new t.TextureNode,this._heatmapColorTexNode=new t.TextureNode,this._heatmapTemporalTexNode=new t.TextureNode,this._heatmapNDTexNode=new t.TextureNode,this._heatmapMotionTexNode=new t.TextureNode,this._heatmapGradientTexNode=new t.TextureNode,this._buildHeatmapCompute()}_buildGradientCompute(){let e=this._colorTexNode,t=this._albedoTexNode,r=this._motionTexNode,i=this._readTemporalTexNode,a=this.gradientNoiseFloor,o=this.gradientSigmaScale,s=this._gradientStorageTex,c=this.resW,l=this.resH,u=(0,n.workgroupArray)(`float`,144),d=(0,n.workgroupArray)(`float`,144);this._gradientNode=(0,n.Fn)(()=>{let f=n.localId.x,p=n.localId.y,m=p.mul(8).add(f),h=(0,n.int)(n.workgroupId.x).mul(8).sub(2).toVar(),g=(0,n.int)(n.workgroupId.y).mul(8).sub(2).toVar(),_=a=>{let o=a.mod((0,n.uint)(12)),s=a.div((0,n.uint)(12)),f=h.add((0,n.int)(o)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),p=g.add((0,n.int)(s)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),m=(0,n.textureLoad)(e,(0,n.ivec2)(f,p)).xyz,_=(0,n.textureLoad)(t,(0,n.ivec2)(f,p)).xyz,v=Xo(oh(m.div((0,n.max)(_,(0,n.vec3)(Ve))))).toVar();u.element(a).assign(v);let y=(0,n.textureLoad)(r,(0,n.ivec2)(f,p)),b=(0,n.float)(f).sub(y.x.mul(c)),x=(0,n.float)(p).sub(y.y.mul(l)),S=(0,n.int)(b.add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),C=(0,n.int)(x.add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),w=y.w.greaterThan(.5),T=(0,n.textureLoad)(i,(0,n.ivec2)(S,C)).xyz,E=w.select(Xo(T),v);d.element(a).assign(E)};_(m);let v=m.add((0,n.uint)(64));(0,n.If)(v.lessThan((0,n.uint)(144)),()=>{_(v)});let y=m.add((0,n.uint)(128));(0,n.If)(y.lessThan((0,n.uint)(144)),()=>{_(y)}),(0,n.workgroupBarrier)();let b=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(f)),x=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(p));(0,n.If)(b.lessThan((0,n.int)(c)).and(x.lessThan((0,n.int)(l))),()=>{let e=(0,n.float)(0).toVar(),t=(0,n.float)(0).toVar();for(let r=-2;r<=2;r++)for(let i=-2;i<=2;i++){let a=p.add((0,n.uint)(2+r)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+i))),o=u.element(a);e.addAssign(o),t.addAssign(o.mul(o))}let m=e.div(25),h=(0,n.sqrt)((0,n.max)(t.div(25).sub(m.mul(m)),(0,n.float)(0))).mul(o).toVar(),g=(0,n.float)(0).toVar();for(let e=-2;e<=2;e++)for(let t=-2;t<=2;t++){let r=p.add((0,n.uint)(2+e)).mul((0,n.uint)(12)).add(f.add((0,n.uint)(2+t))),i=u.element(r),o=d.element(r),s=(0,n.max)((0,n.max)((0,n.abs)(i.sub(o)).sub(h),(0,n.float)(0)).div((0,n.max)((0,n.max)(i,o),(0,n.float)(.001))).sub(a),(0,n.float)(0)).div((0,n.max)((0,n.float)(1).sub(a),(0,n.float)(1e-4)));g.addAssign(s.mul(s))}let _=g.div(25).clamp(0,1).toVar(),v=(0,n.textureLoad)(r,(0,n.ivec2)(b,x)),y=(0,n.int)((0,n.float)(b).sub(v.x.mul(c)).add(.5)).clamp((0,n.int)(0),(0,n.int)(c).sub(1)),S=(0,n.int)((0,n.float)(x).sub(v.y.mul(l)).add(.5)).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),C=v.w.greaterThan(.5).select((0,n.textureLoad)(i,(0,n.ivec2)(y,S)).w,(0,n.float)(0)).div(4).clamp(0,1),w=_.mul(C);(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(b),(0,n.uint)(x)),(0,n.vec4)(w,_,h,1)).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildTemporalCompute(){this._temporalNodeA=this._buildTemporalForDirection(this._temporalTexA),this._temporalNodeB=this._buildTemporalForDirection(this._temporalTexB)}_buildTemporalForDirection(e){let t=this._colorTexNode,r=this._albedoTexNode,i=this._motionTexNode,a=this._normalDepthTexNode,o=this._prevNormalDepthTexNode,s=this._readTemporalTexNode,c=this._gradientReadTexNode,l=this._outputModulatedTex,u=this.maxAccumFrames,d=this.temporalAlpha,f=this.gradientStrength,p=this.temporalEnabledU,m=this.forceResetU,h=this.resW,g=this.resH;return(0,n.Fn)(()=>{let _=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),v=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(_.lessThan((0,n.int)(h)).and(v.lessThan((0,n.int)(g))),()=>{let y=(0,n.ivec2)(_,v),b=(0,n.textureLoad)(t,y),x=b.xyz,S=b.w,C=(0,n.textureLoad)(r,y).xyz,w=(0,n.max)(C,(0,n.vec3)(Ve)),T=oh(x.div(w)),E=(0,n.vec4)(T,1).toVar(),D=(0,n.vec4)(x,S).toVar();(0,n.If)(p.greaterThan(.5).and(m.lessThan(.5)),()=>{let e=(0,n.textureLoad)(i,y),t=e.w.greaterThan(.5),r=(0,n.float)(_).sub(e.x.mul(h)),l=(0,n.float)(v).sub(e.y.mul(g)),p=r.greaterThanEqual(0).and(r.lessThan((0,n.float)(h))).and(l.greaterThanEqual(0)).and(l.lessThan((0,n.float)(g)));(0,n.If)(t.and(p),()=>{let e=(0,n.textureLoad)(a,y),t=e.xyz.mul(2).sub(1),i=e.w,p=(0,n.int)(r),m=(0,n.int)(l),_=p.add((0,n.int)(1)),v=m.add((0,n.int)(1)),b=r.sub((0,n.float)(p)),x=l.sub((0,n.float)(m)),C=p.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),O=_.clamp((0,n.int)(0),(0,n.int)(h).sub(1)),k=m.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),A=v.clamp((0,n.int)(0),(0,n.int)(g).sub(1)),j=(0,n.float)(1).sub(b).mul((0,n.float)(1).sub(x)),M=b.mul((0,n.float)(1).sub(x)),N=(0,n.float)(1).sub(b).mul(x),P=b.mul(x),F=(e,r,a)=>{let s=(0,n.textureLoad)(o,(0,n.ivec2)(e,r)),c=s.xyz.mul(2).sub(1),l=s.w,u=(0,n.pow)((0,n.dot)(t,c).clamp(0,1),(0,n.float)(16)),d=(0,n.exp)((0,n.abs)(i.sub(l)).div((0,n.max)(i,(0,n.float)(.001))).div((0,n.float)(.05)).negate());return a.mul(u).mul(d)},I=F(C,k,j),L=F(O,k,M),R=F(C,A,N),ee=F(O,A,P),te=I.add(L).add(R).add(ee);(0,n.If)(te.greaterThan((0,n.float)(.01)),()=>{let e=(0,n.textureLoad)(s,(0,n.ivec2)(C,k)),t=(0,n.textureLoad)(s,(0,n.ivec2)(O,k)),r=(0,n.textureLoad)(s,(0,n.ivec2)(C,A)),i=(0,n.textureLoad)(s,(0,n.ivec2)(O,A)),a=(0,n.float)(1).div(te),o=e.xyz.mul(I).add(t.xyz.mul(L)).add(r.xyz.mul(R)).add(i.xyz.mul(ee)).mul(a),l=e.w.mul(I).add(t.w.mul(L)).add(r.w.mul(R)).add(i.w.mul(ee)).mul(a),p=(0,n.textureLoad)(c,y).x.mul(f).clamp(0,1),m=oh((0,n.mix)(o,T,(0,n.mix)((0,n.max)((0,n.float)(1).div(l.add(1)),d),(0,n.float)(1),p))),h=(0,n.min)(l.add(1),u);E.assign((0,n.vec4)(m,h)),D.assign((0,n.vec4)(m.mul(w),S))})})}),(0,n.textureStore)(e,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),E).toWriteOnly(),(0,n.textureStore)(l,(0,n.uvec2)((0,n.uint)(_),(0,n.uint)(v)),D).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}_buildHeatmapCompute(){let e=this._heatmapRawColorTexNode,t=this._heatmapColorTexNode,r=this._heatmapTemporalTexNode,i=this._heatmapNDTexNode,a=this._heatmapMotionTexNode,o=this._heatmapGradientTexNode,s=this._heatmapStorageTex,c=this.debugMode,l=this.resW,u=this.resH;this._heatmapComputeNode=(0,n.Fn)(()=>{let d=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),f=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(l)).and(f.lessThan((0,n.int)(u))),()=>{let p=(0,n.ivec2)(d,f),m=(0,n.vec4)(0,0,0,1).toVar();(0,n.If)(c.equal((0,n.int)(0)),()=>{let e=(0,n.textureLoad)(t,p).xyz;m.assign((0,n.vec4)(e,1))}).ElseIf(c.equal((0,n.int)(1)),()=>{let t=(0,n.float)(0).toVar(),r=(0,n.float)(0).toVar();for(let i=-1;i<=1;i++)for(let a=-1;a<=1;a++){let o=(0,n.textureLoad)(e,(0,n.ivec2)(d.add(a).clamp((0,n.int)(0),(0,n.int)(l).sub(1)),f.add(i).clamp((0,n.int)(0),(0,n.int)(u).sub(1)))).xyz,s=Xo(o);t.addAssign(s),r.addAssign(s.mul(s))}t.divAssign(9),r.divAssign(9);let i=(0,n.max)(r.sub(t.mul(t)),(0,n.float)(0)).div((0,n.max)(t.mul(t),(0,n.float)(1e-4))).mul(10).clamp(0,1),a=i.sub(.5).mul(4).clamp(0,1),o=i.mul(4).clamp(0,1).sub(i.sub(.75).mul(4).clamp(0,1)),s=(0,n.float)(1).sub(i.sub(.25).mul(4).clamp(0,1));m.assign((0,n.vec4)(a,o,s,1))}).ElseIf(c.equal((0,n.int)(2)),()=>{let e=(0,n.textureLoad)(r,p).w.div(32).clamp(0,1);m.assign((0,n.vec4)((0,n.float)(1).sub(e),e,(0,n.float)(.2),1))}).ElseIf(c.equal((0,n.int)(3)),()=>{let e=(0,n.textureLoad)(a,p),t=(0,n.abs)(e.x).mul(100).clamp(0,1),r=(0,n.abs)(e.y).mul(100).clamp(0,1),i=t.add(r).clamp(0,1);m.assign((0,n.vec4)(t,r,i.mul(.3),1))}).ElseIf(c.equal((0,n.int)(4)),()=>{let e=(0,n.textureLoad)(i,p);m.assign((0,n.vec4)(e.xyz,1))}).Else(()=>{let e=(0,n.textureLoad)(o,p).x.mul(5).clamp(0,1);m.assign((0,n.vec4)(e,e.mul(.5),(0,n.float)(1).sub(e),1))}),(0,n.textureStore)(s,(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(f)),m).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[8,8,1])}setupEventListeners(){this.on(`asvgf:reset`,()=>this.resetTemporalData()),this.on(`asvgf:updateParameters`,e=>this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:prevNormalDepth`)||r,a=e.getTexture(`motionVector:screenSpace`);if(!t)return;let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this._outputRT.width||o.height!==this._outputRT.height)&&this.setSize(o.width,o.height),this._colorTexNode.value=t,n&&(this._albedoTexNode.value=n),a&&(this._motionTexNode.value=a),r&&(this._normalDepthTexNode.value=r),i&&(this._prevNormalDepthTexNode.value=i);let s=this.currentMoments===0?this._temporalTexB:this._temporalTexA,c=this.currentMoments===0?this._temporalNodeA:this._temporalNodeB,l=this.currentMoments===0?this._temporalTexA:this._temporalTexB;this._compiled||=(this.renderer.compute(this._gradientNode),this.renderer.compute(this._temporalNodeA),this.renderer.compute(this._temporalNodeB),!0),this._readTemporalTexNode.value=s,this._gradientReadTexNode.value=this._gradientStorageTex;let u=this.gradientStrength.value>0||this.showHeatmap;u&&this.renderer.compute(this._gradientNode),this.forceResetU.value=+!!this._needsWarmReset,this.renderer.compute(c),this._needsWarmReset=!1,this._srcRegion.max.set(this.resW.value,this.resH.value),this.renderer.copyTextureToTexture(l,this._demodulatedRT.texture,this._srcRegion),this.renderer.copyTextureToTexture(this._outputModulatedTex,this._outputRT.texture,this._srcRegion),u&&this.renderer.copyTextureToTexture(this._gradientStorageTex,this._gradientRT.texture,this._srcRegion),e.setTexture(`asvgf:demodulated`,this._demodulatedRT.texture),e.setTexture(`asvgf:output`,this._outputRT.texture),e.setTexture(`asvgf:gradient`,this._gradientRT.texture),this.currentMoments=1-this.currentMoments,this.showHeatmap&&(this._heatmapRawColorTexNode.value=t,this._heatmapColorTexNode.value=this._outputModulatedTex,this._heatmapTemporalTexNode.value=l,r&&(this._heatmapNDTexNode.value=r),a&&(this._heatmapMotionTexNode.value=a),this._heatmapGradientTexNode.value=this._gradientStorageTex,this.renderer.compute(this._heatmapComputeNode),this._srcRegion.max.set(this.heatmapTarget.width,this.heatmapTarget.height),this.renderer.copyTextureToTexture(this._heatmapStorageTex,this.heatmapTarget.texture,this._srcRegion))}setHeatmapEnabled(e){this.showHeatmap=e}setTemporalEnabled(e){this.temporalEnabledU.value=+!!e}updateParameters(e){e&&(e.temporalAlpha!==void 0&&(this.temporalAlpha.value=e.temporalAlpha),e.gradientStrength!==void 0&&(this.gradientStrength.value=e.gradientStrength),e.gradientSigmaScale!==void 0&&(this.gradientSigmaScale.value=e.gradientSigmaScale),e.gradientNoiseFloor!==void 0&&(this.gradientNoiseFloor.value=e.gradientNoiseFloor),e.maxAccumFrames!==void 0&&(this.maxAccumFrames.value=e.maxAccumFrames),e.debugMode!==void 0&&(this.debugMode.value=e.debugMode))}resetTemporalData(){this.currentMoments=0,this._needsWarmReset=!0}reallocateReservedStorage(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._heatmapComputeNode?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose();let e=(e,n)=>{let i=new t.StorageTexture(G,G);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i};this._temporalTexA=e(r.FloatType,r.LinearFilter),this._temporalTexB=e(r.FloatType,r.LinearFilter),this._outputModulatedTex=e(r.FloatType,r.LinearFilter),this._gradientStorageTex=e(r.HalfFloatType,r.LinearFilter),this._heatmapStorageTex=e(r.FloatType,r.NearestFilter),this._buildGradientCompute(),this._buildTemporalCompute(),this._buildHeatmapCompute(),this._compiled=!1,this.currentMoments=0,this._needsWarmReset=!0}setSize(e,t){this._demodulatedRT.setSize(e,t),this._demodulatedRT.texture.needsUpdate=!0,this._outputRT.setSize(e,t),this._outputRT.texture.needsUpdate=!0,this._gradientRT.setSize(e,t),this._gradientRT.texture.needsUpdate=!0,this.heatmapTarget.setSize(e,t),this.heatmapTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/8),this._dispatchY=Math.ceil(t/8),this._gradientNode.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeA.dispatchSize=[this._dispatchX,this._dispatchY,1],this._temporalNodeB.dispatchSize=[this._dispatchX,this._dispatchY,1],this._heatmapComputeNode.dispatchSize=[this._dispatchX,this._dispatchY,1]}reset(){}releaseGPUMemory(){this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._heatmapStorageTex?.dispose(),this.context?.removeTexture(`asvgf:demodulated`),this.context?.removeTexture(`asvgf:output`),this.context?.removeTexture(`asvgf:gradient`),this._demodulatedRT?.texture?.dispose(),this._outputRT?.texture?.dispose(),this._gradientRT?.texture?.dispose(),this.heatmapTarget?.texture?.dispose(),this.resetTemporalData()}dispose(){this._gradientNode?.dispose(),this._temporalNodeA?.dispose(),this._temporalNodeB?.dispose(),this._temporalTexA?.dispose(),this._temporalTexB?.dispose(),this._outputModulatedTex?.dispose(),this._gradientStorageTex?.dispose(),this._demodulatedRT?.dispose(),this._outputRT?.dispose(),this._gradientRT?.dispose(),this._heatmapComputeNode?.dispose(),this._heatmapStorageTex?.dispose(),this.heatmapTarget?.dispose(),this._colorTexNode?.dispose(),this._albedoTexNode?.dispose(),this._motionTexNode?.dispose(),this._normalDepthTexNode?.dispose(),this._prevNormalDepthTexNode?.dispose(),this._readTemporalTexNode?.dispose(),this._gradientReadTexNode?.dispose(),this._heatmapRawColorTexNode?.dispose(),this._heatmapColorTexNode?.dispose(),this._heatmapTemporalTexNode?.dispose(),this._heatmapNDTexNode?.dispose(),this._heatmapMotionTexNode?.dispose(),this._heatmapGradientTexNode?.dispose()}},ch=1e-6,lh=1.5/255,uh=.01,dh=3,fh=2,ph=2,mh=3,hh=2,gh=38,_h=.1,vh=4,yh=Math.cos(89*Math.PI/180),bh=.5,xh=16,Sh={pre:{radiusScale:1,fractionScale:2},blur:{radiusScale:1,fractionScale:1},post:{radiusScale:2,fractionScale:.5}},Ch=.25*Math.SQRT2,wh=[[-1,0,1],[0,1,1],[1,0,1],[0,-1,1],[-Ch,Ch,.5],[Ch,Ch,.5],[Ch,-Ch,.5],[-Ch,-Ch,.5]],Th=(e,t,r)=>(0,n.smoothstep)(0,1,(0,n.float)(1).sub(e.mul(t).add(r).abs())),Eh=(e,t,r)=>{let i=e.mul(t).add(r).abs().mul(-dh);return(0,n.float)(1).div(i.mul(i).sub(i).add(1))},Dh=e=>(0,n.mix)((0,n.float)(1.570796),(0,n.float)(1.395402),(0,n.saturate)(e)).mul((0,n.sqrt)((0,n.saturate)((0,n.float)(1).sub(e)))),Oh=(e,t)=>(0,n.float)(1).sub((0,n.exp2)(e.mul(e).mul(-200))).mul((0,n.pow)((0,n.saturate)(e),t)),kh=(e,t)=>(0,n.saturate)(e).mul((0,n.sqrt)(t.div((0,n.float)(1).sub(t).add(ch)))),Ah=(e,t,r,i)=>{let a=(0,n.max)((0,n.atan)(kh(r,i.mul((0,n.mix)((0,n.saturate)(t),(0,n.float)(1),e)))),(0,n.float)(lh));return(0,n.float)(1).div(a)},jh=(e,t)=>{let r=(0,n.float)(1).div((0,n.mix)((0,n.float)(uh),(0,n.float)(1),(0,n.saturate)(e.mul(t))));return(0,n.vec2)(r,e.mul(r).negate())},Mh=(e,t,r)=>{let i=(0,n.float)(1).div((0,n.mix)((0,n.float)(r),(0,n.float)(1),(0,n.mix)(e.mul(e),e,(0,n.saturate)(t))));return(0,n.vec2)(i,e.mul(i).negate())},Nh=(e,t)=>{let r=(0,n.float)(1).div(t);return(0,n.vec2)(r,e.mul(r).negate())},Ph=(e,t,r,i)=>{let a=(0,n.float)(1).div(e.mul(t));return(0,n.vec2)(a,(0,n.dot)(i,r).mul(a).negate())},Fh=e=>(0,n.vec2)(1).sub((0,n.vec2)(1).sub((0,n.fract)(e.mul(.5)).mul(2)).abs()).min(.99999),Ih=e=>(0,n.vec3)((0,n.dot)(e,(0,n.vec3)(.25,.5,.25)),(0,n.dot)(e,(0,n.vec3)(.5,0,-.5)),(0,n.dot)(e,(0,n.vec3)(-.25,.5,-.25))),Lh=e=>{let t=e.x.sub(e.z);return(0,n.max)((0,n.vec3)(t.add(e.y),e.x.add(e.z),t.sub(e.y)),(0,n.vec3)(0))},Rh=(e,t)=>t.add(ch).div(e.add(ch)),zh=(e,t)=>(0,n.vec4)(e.xyz.mul(Rh(e.x,t)),e.w),Bh=e=>(0,n.vec4)(Ih(Lh(e.xyz)),(0,n.saturate)(e.w)),Vh=(e,t)=>(0,n.sqrt)(t.sub(e.mul(e)).abs()),Hh=(e,t)=>(0,n.vec2)(e.x.mul(t.x).add(e.y.mul(t.y)),e.z.mul(t.x).add(e.w.mul(t.y))),Uh=(e,t)=>(0,n.select)(e.equal(0),(0,n.vec4)(0),t);function Wh(e){let t=Math.imul(e|0,2654435761)>>>0;return t^=t>>>15,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t/4294967296}var Gh=class extends V{constructor(e,i={}){super(`NRD`,{...i,executionMode:ye.PER_CYCLE}),this.renderer=e,this.pathTracer=i.pathTracer||null,this.settings={...Ge,...i.settings||{}};let a=i.width||1,o=i.height||1;this.resW=(0,n.uniform)(a),this.resH=(0,n.uniform)(o),this.minRectDimMulUnproject=(0,n.uniform)(1),this.inputFrames=(0,n.uniform)(0),this.resetU=(0,n.uniform)(0),this.debugMode=(0,n.uniform)(0,`int`),this.rotPre=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotBlur=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.rotPost=(0,n.uniform)(new r.Vector4(1,0,0,1),`vec4`),this.camWorld=(0,n.uniform)(new r.Matrix4,`mat4`),this.camProjInv=(0,n.uniform)(new r.Matrix4,`mat4`),this.camView=(0,n.uniform)(new r.Matrix4,`mat4`),this.prevCamView=(0,n.uniform)(new r.Matrix4,`mat4`),this.camPos=(0,n.uniform)(new r.Vector3,`vec3`),this.prevCamPos=(0,n.uniform)(new r.Vector3,`vec3`),this.cameraProjection=(0,n.uniform)(0,`int`),this.panoLonRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLatRange=(0,n.uniform)(new r.Vector2,`vec2`),this.panoLevelHorizon=(0,n.uniform)(1,`int`),this.u={};for(let e of[`maxAccum`,`maxFast`,`stabilizationStrength`,`historyFixFrameNum`,`historyFixStride`,`prepassBlurRadius`,`minBlurRadius`,`maxBlurRadius`,`lobeAngleFraction`,`roughnessFraction`,`planeDistSensitivity`,`minHitDistanceWeight`,`fastClampSigmaScale`,`fireflyMinRelativeScale`,`antiFirefly`,`disocclusionThreshold`,`lobeVolumePercent`,`handoverFrames`])this.u[e]=(0,n.uniform)(0);this.u.antilag=(0,n.uniform)(new r.Vector2,`vec2`),this.u.convergence=(0,n.uniform)(new r.Vector3,`vec3`),this._syncUniforms(),this._colorTexNode=new t.TextureNode,this._albedoTexNode=new t.TextureNode,this._ndTexNode=new t.TextureNode,this._snTexNode=new t.TextureNode,this._motionTexNode=new t.TextureNode,this._placeholders=new Map;let s=()=>{let e=new r.DataTexture(new Float32Array(4),1,1,r.RGBAFormat,r.FloatType);e.needsUpdate=!0;let n=new t.TextureNode(e);return this._placeholders.set(n,e),n};this._nTmpA=s(),this._nTmpB=s(),this._nHist=s(),this._nFast=s(),this._nInternal=s(),this._nGeom=s(),this._nData=s(),this._nStabRead=s(),this._allocStorage(),this._srcRegion=new r.Box2(new r.Vector2(0,0),new r.Vector2(0,0)),this.outputTarget=new t.RenderTarget(a,o,{type:r.HalfFloatType,format:r.RGBAFormat,minFilter:r.LinearFilter,magFilter:r.LinearFilter,depthBuffer:!1,stencilBuffer:!1}),this._compiled=!1,this._needsReset=!0,this._stabPing=0,this._camInitialized=!1,this._dispatchX=Math.ceil(a/xh),this._dispatchY=Math.ceil(o/xh),this._buildKernels()}_allocStorage(){let e=()=>Yt(r.HalfFloatType);this._tmpA=e(),this._tmpB=e(),this._hist=e(),this._fastHist=e(),this._internal=e(),this._geomPrev=e(),this._stabA=e(),this._stabB=e(),this._dataT=e()}_disposeStorage(){for(let e of[this._tmpA,this._tmpB,this._hist,this._fastHist,this._internal,this._geomPrev,this._stabA,this._stabB,this._dataT])e?.dispose()}_disposeKernels(){for(let e of this._kernels??[])e?.dispose()}updateParameters(e){if(e){for(let t of Object.keys(e))t===`debugMode`?this.debugMode.value=e.debugMode|0:t in Ge&&(this.settings[t]=e[t]);this._syncUniforms()}}_syncUniforms(){let e=this.settings,t=this.u,n=Math.min(e.maxAccumulatedFrameNum,63),r=Math.min(e.maxStabilizedFrameNum,n),i=Math.max(e.maxBlurRadius,e.minBlurRadius);t.maxAccum.value=n,t.maxFast.value=e.maxFastAccumulatedFrameNum,t.stabilizationStrength.value=r/(1+r),t.historyFixFrameNum.value=e.historyFixFrameNum,t.historyFixStride.value=e.historyFixBasePixelStride,t.prepassBlurRadius.value=e.prepassBlurRadius,t.minBlurRadius.value=e.minBlurRadius,t.maxBlurRadius.value=i,t.lobeAngleFraction.value=e.lobeAngleFraction*e.lobeAngleFraction,t.roughnessFraction.value=e.roughnessFraction,t.planeDistSensitivity.value=e.planeDistanceSensitivity,t.minHitDistanceWeight.value=e.minHitDistanceWeight;let a=Math.min(1,Math.max(0,i/2));t.fastClampSigmaScale.value=3+(e.fastHistoryClampingSigmaScale-3)*a,t.fireflyMinRelativeScale.value=e.fireflySuppressorMinRelativeScale,t.antiFirefly.value=+!!e.enableAntiFirefly,t.antilag.value.set(e.antilagLuminanceSigmaScale,e.antilagLuminanceSensitivity),t.disocclusionThreshold.value=e.disocclusionThreshold,t.convergence.value.set(e.convergenceS,e.convergenceB,e.convergenceP),t.lobeVolumePercent.value=e.lobeVolumePercent,t.handoverFrames.value=e.handoverFrames>0?e.handoverFrames:2*n}_worldPosAt(e,t,r,i){let a=ip(e,r,i,this.cameraProjection,this.panoLonRange,this.panoLatRange,this.panoLevelHorizon);return(0,n.vec3)(r[3]).add(a.mul(t))}_pixelUv(e,t){return(0,n.vec2)((0,n.float)(e).add(.5).div(this.resW),(0,n.float)(t).add(.5).div(this.resH))}_clampCoord(e,t){return(0,n.ivec2)(e.clamp((0,n.int)(0),(0,n.int)(this.resW).sub(1)),t.clamp((0,n.int)(0),(0,n.int)(this.resH).sub(1)))}_uvToCoord(e){return this._clampCoord((0,n.int)(e.x.mul(this.resW)),(0,n.int)(e.y.mul(this.resH)))}_advancedNonLinear(e){let t=this.u.convergence,r=(0,n.saturate)(e.div((0,n.float)(1).add(this.u.maxAccum.mul(t.z)))),i=t.x.mul((0,n.mix)(t.y,(0,n.float)(1),r));return(0,n.float)(1).div((0,n.float)(1).add(i.mul(e)))}_handover(e){return(0,n.saturate)(e.div((0,n.max)(this.u.handoverFrames,1)))}_bilinear(e){let t=e.mul((0,n.vec2)(this.resW,this.resH)).sub(.5),r=(0,n.floor)(t),i=(0,n.saturate)(t.sub(r)),a=(0,n.int)(r.x),o=(0,n.int)(r.y),s=(e,t)=>(0,n.select)(e.greaterThanEqual((0,n.int)(0)).and(t.greaterThanEqual((0,n.int)(0))).and(e.lessThan((0,n.int)(this.resW))).and(t.lessThan((0,n.int)(this.resH))),(0,n.float)(1),(0,n.float)(0));return{f:i,taps:[this._clampCoord(a,o),this._clampCoord(a.add(1),o),this._clampCoord(a,o.add(1)),this._clampCoord(a.add(1),o.add(1))],inScreen:[s(a,o),s(a.add(1),o),s(a,o.add(1)),s(a.add(1),o.add(1))],customWeights:e=>[e[0].mul((0,n.float)(1).sub(i.x)).mul((0,n.float)(1).sub(i.y)),e[1].mul(i.x).mul((0,n.float)(1).sub(i.y)),e[2].mul((0,n.float)(1).sub(i.x)).mul(i.y),e[3].mul(i.x).mul(i.y)],filter:e=>(0,n.mix)((0,n.mix)(e[0],e[1],i.x),(0,n.mix)(e[2],e[3],i.x),i.y)}}_applyCustomWeights(e,t,r){let i=e[0].mul(t[0]).add(e[1].mul(t[1])).add(e[2].mul(t[2])).add(e[3].mul(t[3])),a=t[0].add(t[1]).add(t[2]).add(t[3]);return(0,n.select)(a.lessThan(1e-4),r,i.div((0,n.max)(a,1e-4)))}_sampleHistory(e,t,r,i,a){let o=(0,n.vec4)(0).toVar();return(0,n.If)(a,()=>{let r=(0,n.saturate)(t).mul((0,n.vec2)(this.resW,this.resH)),i=(0,n.floor)(r.sub(.5)).add(.5),a=(0,n.saturate)(r.sub(i)),s=bh,c=a.mul(a.mul(a.mul(-s).add(2*s)).sub(s)),l=a.mul(a.mul(a.mul(2-s).sub(3-s))).add(1),u=a.mul(a.mul(a.mul(-(2-s)).add(3-2*s)).add(s)),d=a.mul(a.mul(a.mul(s).sub(s))),f=[c.x,l.x,u.x,d.x],p=[c.y,l.y,u.y,d.y],m=(0,n.int)(i.x).sub(1),h=(0,n.int)(i.y).sub(1),g=(0,n.vec4)(0).toVar(),_=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let n=0;n<4;n++){if((n===0||n===3)&&(t===0||t===3))continue;let r=f[n].mul(p[t]);g.addAssign(e(this._clampCoord(m.add(n),h.add(t))).mul(r)),_.addAssign(r)}o.assign((0,n.select)(_.lessThan(1e-4),(0,n.vec4)(0),g.div((0,n.max)(_,1e-4))))}).Else(()=>{o.assign(this._applyCustomWeights(r.taps.map(t=>e(t)),i,(0,n.vec4)(0)))}),o}_buildKernels(){this._kPre=this._buildSpatial(`pre`),this._kTa=this._buildTemporalAccumulation(),this._kHf=this._buildHistoryFix(),this._kBlur=this._buildSpatial(`blur`),this._kPost=this._buildSpatial(`post`),this._kTsA=this._buildTemporalStabilization(this._stabA),this._kTsB=this._buildTemporalStabilization(this._stabB),this._kernels=[this._kPre,this._kTa,this._kHf,this._kBlur,this._kPost,this._kTsA,this._kTsB]}_dispatchOf(e){return e(this.camWorld,this.camProjInv).compute([this._dispatchX,this._dispatchY,1],[xh,xh,1])}_buildSpatial(e){let t=e===`pre`,{radiusScale:r,fractionScale:i}=Sh[e],a=this.u,o=this._colorTexNode,s=this._albedoTexNode,c=this._ndTexNode,l=this._snTexNode,u=this._nData,d=e===`blur`?this._nTmpA:this._nTmpB,f=e===`blur`?this._tmpB:t?this._tmpA:this._hist,p=this._geomPrev,m=t?this.rotPre:e===`blur`?this.rotBlur:this.rotPost,h=t?a.prepassBlurRadius:a.maxBlurRadius,g=this.camView,_=this.camPos,v=this.resW,y=this.resH,b=this.inputFrames,x=t?e=>{let t=(0,n.textureLoad)(o,e),r=(0,n.textureLoad)(s,e);return(0,n.vec4)(Ih(Ko(t.xyz.div((0,n.max)(r.xyz,(0,n.vec3)(Ve))))),Go(r.w,Wo).min(1))}:e=>(0,n.textureLoad)(d,e),S=(0,n.Fn)(([o,s])=>{let d=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),S=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(d.lessThan((0,n.int)(v)).and(S.lessThan((0,n.int)(y))),()=>{let C=(0,n.ivec2)(d,S),w=(0,n.uvec2)((0,n.uint)(d),(0,n.uint)(S)),T=(0,n.textureLoad)(c,C).w.toVar(),E=T.greaterThanEqual(Re),D=(0,n.textureLoad)(l,C).toVar(),O=(0,n.normalize)(D.xyz.mul(2).sub(1)).toVar(),k=D.w.clamp(.05,1).toVar(),A=(0,n.float)(Re).toVar(),j=x(C).toVar();(0,n.If)(E.not(),()=>{let e=this._pixelUv(d,S),f=this._worldPosAt(e,T,o,s).toVar();A.assign(g.mul((0,n.vec4)(f,1)).z.abs()),(0,n.If)(h.greaterThan(0),()=>{let d=(0,n.dot)(O,(0,n.normalize)(_.sub(f))).abs().toVar(),p=this.minRectDimMulUnproject.mul(A).toVar(),S=b.add(1),w=t?(0,n.max)(b,(0,n.float)(10)):(0,n.textureLoad)(u,C).y.add(b),T=(t?(0,n.float)(1).div(w.add(1)):this._advancedNonLinear(w)).toVar(),E=Oh(k,.5).toVar(),D=A.mul(Be).add(3),M=j.w.toVar(),N=(0,n.saturate)(M.mul(D).div(p)),P=(0,n.float)(1).sub(this._handover(S)),F=(t?N.div(S):N.mul(T)).mul(P),I=a.minBlurRadius.mul((0,n.saturate)((0,n.float)(2).sub(w.div((0,n.max)(a.maxAccum,1))))),L=(0,n.max)((0,n.saturate)((0,n.sqrt)((0,n.saturate)(F)).mul(r)).mul(h).mul(E),I.mul(E)).toVar(),R=Ph(a.planeDistSensitivity,p,f,O).toVar(),ee=Ah(T,a.lobeAngleFraction,k,a.lobeVolumePercent).div(i).toVar(),te=jh(k,a.roughnessFraction.mul(i)).toVar(),z=Nh(M,T).toVar(),ne=a.minHitDistanceWeight.mul(i).mul(E);t||(ne=ne.mul(T)),ne=ne.toVar();let B=(0,n.vec2)(1);if(!t){let e=g.mul((0,n.vec4)(O,0)).xy;B=(0,n.mix)((0,n.vec2)(1).sub(e.abs()),(0,n.vec2)(1),d),B=B.div((0,n.max)(B.x,B.y))}let re=B.mul((0,n.vec2)((0,n.float)(1).div(v),(0,n.float)(1).div(y))).mul(L).toVar(),ie=(0,n.float)(1).toVar();for(let t=0;t<wh.length;t++){let r=wh[t],i=e.add(Hh(m,(0,n.vec2)(r[0],r[1])).mul(re)),a=Fh(i),u=(0,n.select)(a.x.notEqual(i.x).or(a.y.notEqual(i.y)),(0,n.float)(1),(0,n.float)(Math.exp(-.66*r[2]*r[2]))).toVar(),d=this._uvToCoord(a),f=(0,n.textureLoad)(c,d).w,p=this._worldPosAt(a,f,o,s),h=(0,n.textureLoad)(l,d),g=Dh((0,n.dot)(O,(0,n.normalize)(h.xyz.mul(2).sub(1))));u.mulAssign(Th(g,ee,(0,n.float)(0))),u.mulAssign(Th(h.w,te.x,te.y)),u.mulAssign(Th((0,n.dot)(O,p),R.x,R.y)),u.assign((0,n.select)(f.greaterThanEqual(Re),(0,n.float)(0),u));let _=Uh(u,x(d));u.mulAssign(ne.add(Eh(_.w,z.x,z.y))),ie.addAssign(u),j.addAssign(_.mul(u))}j.divAssign((0,n.max)(ie,1e-6)),t||j.assign((0,n.vec4)(j.xyz,M))})}),(0,n.textureStore)(f,w,j).toWriteOnly(),e===`post`&&(0,n.textureStore)(p,w,(0,n.vec4)(O,A)).toWriteOnly()})});return this._dispatchOf(S)}_buildTemporalAccumulation(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._motionTexNode,a=this._nTmpA,o=this._nHist,s=this._nFast,c=this._nInternal,l=this._nGeom,u=this._tmpB,d=this._dataT,f=this.camView,p=this.prevCamView,m=this.camPos,h=this.prevCamPos,g=this.resW,_=this.resH,v=this.inputFrames,y=this.resetU,b=(0,n.Fn)(([b,x])=>{let S=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),C=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(S.lessThan((0,n.int)(g)).and(C.lessThan((0,n.int)(_))),()=>{let g=(0,n.ivec2)(S,C),_=(0,n.uvec2)((0,n.uint)(S),(0,n.uint)(C)),w=(0,n.textureLoad)(t,g).w,T=(0,n.textureLoad)(a,g).toVar();(0,n.If)(w.greaterThanEqual(Re),()=>{(0,n.textureStore)(u,_,T).toWriteOnly(),(0,n.textureStore)(d,_,(0,n.vec4)(0)).toWriteOnly(),(0,n.Return)()});let E=e.maxAccum.mul((0,n.float)(1).sub(y)).toVar(),D=e.maxFast.mul((0,n.float)(1).sub(y)).toVar(),O=(0,n.textureLoad)(r,g),k=(0,n.normalize)(O.xyz.mul(2).sub(1)).toVar(),A=O.w.clamp(.05,1).toVar(),j=this._pixelUv(S,C),M=this._worldPosAt(j,w,b,x).toVar(),N=f.mul((0,n.vec4)(M,1)).z.abs().toVar(),P=(0,n.dot)(k,(0,n.normalize)(m.sub(M))).abs().toVar(),F=this.minRectDimMulUnproject.mul(N).toVar(),I=(0,n.vec3)(0).toVar();I.addAssign(k.mul(.25));for(let e=-1;e<=0;e++)for(let i=-1;i<=0;i++){if(i===0&&e===0)continue;let a=this._clampCoord(S.add(i),C.add(e)),o=(0,n.normalize)((0,n.textureLoad)(r,a).xyz.mul(2).sub(1)),s=(0,n.textureLoad)(t,a).w.lessThan(Re);I.addAssign((0,n.select)(s,o,k).mul(.25))}let L=(0,n.textureLoad)(i,g),R=j.sub(L.xy).toVar(),ee=p.mul((0,n.vec4)(M,1)).z.abs().toVar(),te=this._bilinear(R),z=F.mul((0,n.saturate)(e.disocclusionThreshold.div((0,n.max)(P,.05)))).sub(ch).toVar(),ne=(0,n.float)(1).sub(y),B=[],re=[];for(let e=0;e<4;e++){let t=(0,n.textureLoad)(l,te.taps[e]),r=(0,n.select)((0,n.dot)(t.xyz,I).greaterThan(yh),(0,n.float)(1),(0,n.float)(0)),i=(0,n.select)(t.w.sub(ee).abs().lessThanEqual(z),(0,n.float)(1),(0,n.float)(0)),a=(0,n.select)(t.w.lessThan(Re),(0,n.float)(1),(0,n.float)(0));B.push(r.mul(i).mul(a).mul(te.inScreen[e]).mul(ne).toVar()),re.push((0,n.textureLoad)(c,te.taps[e]).x)}let ie=te.customWeights(B).map(e=>e.toVar()),ae=B[0].add(B[1]).add(B[2]).add(B[3]).greaterThan(3.5).toVar(),oe=B[0].add(B[1].mul(2)).add(B[2].mul(4)).add(B[3].mul(8)),se=this._applyCustomWeights(re,ie,(0,n.float)(0)).toVar(),ce=(0,n.dot)(k,(0,n.normalize)(h.sub(M))).abs().add(.001).div(P.add(.001)).toVar();ce.assign((0,n.mix)((0,n.float)(.1),(0,n.float)(1),(0,n.saturate)(ce.mul(ce))));let le=(0,n.sqrt)((0,n.saturate)(te.filter(B))).mul(ce).toVar();se.assign(se.mul((0,n.mix)(le,(0,n.float)(1),(0,n.float)(1).div(se.add(1))))),se.assign((0,n.min)(se,E));let ue=Bh(this._sampleHistory(e=>(0,n.textureLoad)(o,e),R,te,ie,ae)).toVar(),de=(0,n.max)(this._applyCustomWeights(te.taps.map(e=>(0,n.textureLoad)(s,e).x),ie,(0,n.float)(0)),0).toVar(),fe=v.add(1),pe=this._handover(fe).toVar(),me=se.mul((0,n.float)(1).sub(pe)),he=fe.div(fe.add(me)).toVar(),ge=(0,n.float)(1).div((0,n.float)(1).add(Oh(A,.25).mul(.5).mul(E))),_e=(0,n.vec4)((0,n.mix)(ue.xyz,T.xyz,he),(0,n.mix)(ue.w,T.w,(0,n.max)(he,ge))).toVar(),ve=e.fireflyMinRelativeScale.add((0,n.float)(gh).div(se.add(1))).toVar(),ye=se.mul(e.maxBlurRadius).mul(_h).toVar();ye.assign(ye.div(ye.add(1)).mul((0,n.float)(1).sub(pe)));let V=(0,n.mix)(_e.x,(0,n.min)(_e.x,ue.x.mul(ve)),ye);_e.assign(zh(_e,V));let be=(0,n.float)(1.2).add((0,n.float)(1).div(se.add(1)));_e.assign((0,n.vec4)(_e.xyz,(0,n.mix)(_e.w,(0,n.min)(_e.w,ue.w.mul(be)),ye))),(0,n.textureStore)(u,_,_e).toWriteOnly();let H=(0,n.min)(se,D).mul((0,n.float)(1).sub(pe)),xe=fe.div(fe.add(H)),Se=(0,n.mix)(de,T.x,xe).toVar(),Ce=(0,n.min)(Se,ue.x.mul(ve).mul(vh));Se.assign((0,n.mix)(Se,Ce,ye)),(0,n.textureStore)(d,_,(0,n.vec4)(Se,se,oe,(0,n.select)(ae,(0,n.float)(1),(0,n.float)(0)))).toWriteOnly()})});return this._dispatchOf(b)}_buildHistoryFix(){let e=this.u,t=this._ndTexNode,r=this._snTexNode,i=this._nTmpB,a=this._nData,o=this._tmpA,s=this._fastHist,c=this.camView,l=this.resW,u=this.resH,d=this.inputFrames,f=(0,n.Fn)(([f,p])=>{let m=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),h=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(m.lessThan((0,n.int)(l)).and(h.lessThan((0,n.int)(u))),()=>{let g=(0,n.ivec2)(m,h),_=(0,n.uvec2)((0,n.uint)(m),(0,n.uint)(h)),v=(0,n.textureLoad)(t,g).w;(0,n.If)(v.greaterThanEqual(Re),()=>{let e=(0,n.textureLoad)(i,g);(0,n.textureStore)(o,_,e).toWriteOnly(),(0,n.textureStore)(s,_,(0,n.vec4)(e.x,0,0,0)).toWriteOnly(),(0,n.Return)()});let y=(0,n.textureLoad)(a,g).toVar(),b=y.y.toVar(),x=b.add(d),S=this._handover(d.add(1)).toVar(),C=(0,n.textureLoad)(r,g),w=(0,n.normalize)(C.xyz.mul(2).sub(1)).toVar(),T=C.w.clamp(.05,1).toVar(),E=this._pixelUv(m,h),D=this._worldPosAt(E,v,f,p).toVar(),O=c.mul((0,n.vec4)(D,1)).z.abs(),k=this.minRectDimMulUnproject.mul(O).toVar(),A=(0,n.textureLoad)(i,g).toVar(),j=(0,n.float)(1).div(x.add(1)).toVar(),M=O.mul(Be).add(3),N=(0,n.saturate)(A.w.mul(M).div(k)),P=A.w.toVar(),F=(0,n.round)((0,n.select)(x.lessThan(e.historyFixFrameNum),(0,n.float)(1),(0,n.float)(0)).mul(.5).mul(2/fh).mul(e.historyFixStride).mul((0,n.mix)((0,n.float)(.25).add((0,n.sqrt)(N).mul(.75)),(0,n.float)(1),j))).toVar();(0,n.If)(F.notEqual(0),()=>{let o=Ah(j,e.lobeAngleFraction,T,e.lobeVolumePercent).toVar(),s=Ph(e.planeDistSensitivity,k,D,w).toVar(),c=Nh(P,j).toVar(),d=Mh(T.mul(T),(0,n.sqrt)(e.roughnessFraction),uh).toVar(),m=(0,n.float)(1).add(b).toVar();A.mulAssign(m);for(let e=-fh;e<=fh;e++)for(let h=-fh;h<=fh;h++){if(h===0&&e===0||Math.abs(h)+Math.abs(e)===fh*2)continue;let g=Fh(E.add((0,n.vec2)(h,e).mul(F).mul((0,n.vec2)((0,n.float)(1).div(l),(0,n.float)(1).div(u))))),_=this._uvToCoord(g),v=(0,n.textureLoad)(t,_).w,y=this._worldPosAt(g,v,f,p),b=(0,n.textureLoad)(r,_),x=Eh(Dh((0,n.dot)((0,n.normalize)(b.xyz.mul(2).sub(1)),w)),o,(0,n.float)(0)).toVar();x.mulAssign(Eh(b.w.mul(b.w),d.x,d.y)),x.mulAssign((0,n.float)(1).add((0,n.textureLoad)(a,_).y)),x.mulAssign(Th((0,n.dot)(w,y),s.x,s.y)),x.assign((0,n.select)(v.greaterThanEqual(Re),(0,n.float)(0),x));let S=Uh(x,(0,n.textureLoad)(i,_));x.mulAssign(Eh(S.w,c.x,c.y)),m.addAssign(x),A.addAssign(S.mul(x))}A.divAssign((0,n.max)(m,1e-6))});let I=A.x.toVar(),L=(0,n.saturate)(b.div((0,n.max)(e.historyFixFrameNum,ch))),R=(0,n.mix)(I,y.x,L).toVar();(0,n.textureStore)(s,_,(0,n.vec4)(R,0,0,0)).toWriteOnly();let ee=R.toVar(),te=R.mul(R).toVar(),z=(0,n.float)(0).toVar(),ne=(0,n.float)(0).toVar(),B=(e,r,i)=>{let o=this._clampCoord(m.add(e),h.add(r)),s=(0,n.textureLoad)(t,o).w,c=(0,n.select)(s.greaterThanEqual(Re),R,(0,n.textureLoad)(a,o).x);Math.abs(e)<=ph&&Math.abs(r)<=ph&&(ee.addAssign(c),te.addAssign(c.mul(c))),i&&(z.addAssign(c),ne.addAssign(c.mul(c)))},re=e.antiFirefly.greaterThan(.5);for(let e=-ph;e<=ph;e++)for(let t=-ph;t<=ph;t++)t===0&&e===0||B(t,e,Math.abs(t)>1||Math.abs(e)>1);(0,n.If)(re,()=>{for(let e=-mh;e<=mh;e++)for(let t=-mh;t<=mh;t++)Math.abs(t)<=ph&&Math.abs(e)<=ph||B(t,e,!0)}),(0,n.If)(re,()=>{let e=1/((mh*2+1)**2-9),t=z.mul(e),r=Vh(t,ne.mul(e)).mul(hh);I.assign((0,n.mix)(I.clamp(t.sub(r),t.add(r)),I,S))});{let t=1/(ph*2+1)**2,r=ee.mul(t),i=Vh(r,te.mul(t)).mul(e.fastClampSigmaScale),a=I.clamp(r.sub(i),r.add(i)),o=(0,n.select)(e.maxFast.lessThan(e.maxAccum),(0,n.float)(1),(0,n.float)(0)),s=(0,n.mix)((0,n.float)(1).div((0,n.float)(1).add(o.mul(b).mul(2))),(0,n.float)(1),S);I.assign((0,n.mix)(a,I,s))}(0,n.textureStore)(o,_,zh(A,I)).toWriteOnly()})});return this._dispatchOf(f)}_buildTemporalStabilization(e){let t=this.u,r=this._colorTexNode,i=this._albedoTexNode,a=this._ndTexNode,o=this._snTexNode,s=this._motionTexNode,c=this._nHist,l=this._nData,u=this._nStabRead,d=this._internal,f=this._tmpA,p=this.resW,m=this.resH,h=this.inputFrames,g=this.resetU,_=this.debugMode;return(0,n.Fn)(()=>{let v=(0,n.int)(n.workgroupId.x).mul(xh).add((0,n.int)(n.localId.x)),y=(0,n.int)(n.workgroupId.y).mul(xh).add((0,n.int)(n.localId.y));(0,n.If)(v.lessThan((0,n.int)(p)).and(y.lessThan((0,n.int)(m))),()=>{let p=(0,n.ivec2)(v,y),m=(0,n.uvec2)((0,n.uint)(v),(0,n.uint)(y)),b=(0,n.textureLoad)(a,p).w,x=(0,n.textureLoad)(r,p).toVar();(0,n.If)(b.greaterThanEqual(Re),()=>{(0,n.textureStore)(f,m,x).toWriteOnly(),(0,n.textureStore)(e,m,(0,n.vec4)((0,n.textureLoad)(c,p).x,0,0,0)).toWriteOnly(),(0,n.textureStore)(d,m,(0,n.vec4)(0,1,0,0)).toWriteOnly(),(0,n.Return)()});let S=(0,n.textureLoad)(o,p).w.clamp(.05,1),C=this._pixelUv(v,y),w=(0,n.textureLoad)(s,p),T=C.sub(w.xy).toVar(),E=(0,n.textureLoad)(l,p).toVar(),D=E.y.toVar(),O=(0,n.uint)(E.z.add(.5)).toVar(),k=E.w.greaterThan(.5),A=this._bilinear(T),j=[1,2,4,8].map(e=>(0,n.select)(O.bitAnd((0,n.uint)(e)).notEqual((0,n.uint)(0)),(0,n.float)(1),(0,n.float)(0))),M=A.customWeights(j).map(e=>e.toVar()),N=(0,n.sqrt)((0,n.saturate)(A.filter(j))).toVar(),P=(0,n.textureLoad)(c,p).toVar(),F=P.x.toVar(),I=F.toVar(),L=F.mul(F).toVar();for(let e=-1;e<=1;e++)for(let t=-1;t<=1;t++){if(t===0&&e===0)continue;let r=this._clampCoord(v.add(t),y.add(e)),i=(0,n.textureLoad)(a,r).w,o=(0,n.select)(i.greaterThanEqual(Re),F,(0,n.textureLoad)(c,r).x);I.addAssign(o),L.addAssign(o.mul(o))}I.divAssign(9),L.divAssign(9);let R=Vh(I,L).toVar();(0,n.If)(D.lessThan(t.historyFixFrameNum),()=>{F.assign((0,n.min)(F,I.mul((0,n.float)(1.2).add((0,n.float)(1).div(D.add(1))))))});let ee=(0,n.max)(this._sampleHistory(e=>(0,n.textureLoad)(u,e),T,A,M,k).x,0).toVar(),te=R.mul(t.antilag.x),z=t.antilag.y.mul(4),ne=ee.clamp(I.sub(te),I.add(te)),B=ee.sub(ne).abs().div((0,n.max)(ee,ne).add(ch)),re=(0,n.float)(1).div((0,n.float)(1).add(B.mul(D.mul(N)).div(z))).toVar(),ie=(0,n.min)(D,t.historyFixFrameNum);D.assign((0,n.mix)(ie,D,re));let ae=h.add(1),oe=this._handover(ae),se=N.mul((0,n.float)(1).sub(this._advancedNonLinear(D.mul((0,n.float)(1).sub(oe)).div(ae)))).mul(re).toVar(),ce=(0,n.float)(1).add(se.mul(6)),le=t.stabilizationStrength.mul((0,n.float)(1).sub(g)),ue=(0,n.mix)(F,ee.clamp(I.sub(R.mul(ce)),I.add(R.mul(ce))),(0,n.min)(se,le)).toVar();P.assign(zh(P,ue)),(0,n.textureStore)(e,m,(0,n.vec4)(ue,0,0,0)).toWriteOnly();let de=t.maxAccum.mul((0,n.float)(1).sub(g));(0,n.textureStore)(d,m,(0,n.vec4)((0,n.min)(D.add(1),de),S,0,0)).toWriteOnly();let fe=(0,n.textureLoad)(i,p),pe=(0,n.vec4)(Lh(P.xyz).mul((0,n.max)(fe.xyz,(0,n.vec3)(Ve))),x.w).toVar();(0,n.If)(_.equal((0,n.int)(1)),()=>{let e=(0,n.saturate)(D.div((0,n.max)(t.maxAccum,1)));pe.assign((0,n.vec4)((0,n.float)(1).sub(e),e,.2,1))}).ElseIf(_.equal((0,n.int)(2)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(P.w),1))}).ElseIf(_.equal((0,n.int)(3)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(S),1))}).ElseIf(_.equal((0,n.int)(4)),()=>{let e=E.x.div(E.x.add(1));pe.assign((0,n.vec4)((0,n.vec3)(e),1))}).ElseIf(_.equal((0,n.int)(5)),()=>{pe.assign((0,n.vec4)((0,n.vec3)(E.z.div(15)),1))}),(0,n.textureStore)(f,m,pe).toWriteOnly()})})().compute([this._dispatchX,this._dispatchY,1],[xh,xh,1])}setupEventListeners(){this.on(`denoiser:reset`,()=>this.resetHistory())}resetHistory(){this._needsReset=!0}_updateCamera(){let e=this.pathTracer;if(!e?.uniforms)return;let t=e.uniforms.get(`cameraWorldMatrix`).value,n=e.uniforms.get(`cameraViewMatrix`).value,r=e.uniforms.get(`cameraProjectionMatrixInverse`).value,i=e.uniforms.get(`cameraProjectionMatrix`).value;this._camInitialized&&(this.prevCamView.value.copy(this.camView.value),this.prevCamPos.value.copy(this.camPos.value)),this.camWorld.value.copy(t),this.camProjInv.value.copy(r),this.camView.value.copy(n),this.camPos.value.setFromMatrixPosition(t),this.cameraProjection.value=e.uniforms.get(`cameraProjection`).value,this.panoLonRange.value.copy(e.uniforms.get(`panoLonRange`).value),this.panoLatRange.value.copy(e.uniforms.get(`panoLatRange`).value),this.panoLevelHorizon.value=e.uniforms.get(`panoLevelHorizon`).value,this._camInitialized||=(this.prevCamView.value.copy(n),this.prevCamPos.value.copy(this.camPos.value),!0);let a=i.elements[5]||1,o=1/(.5*this.resH.value*a);this.minRectDimMulUnproject.value=Math.min(this.resW.value,this.resH.value)*o}_updateRotators(e){let t=(t,n)=>{let r=Wh(e*3+n)*Math.PI*2;t.value.set(Math.cos(r),Math.sin(r),-Math.sin(r),Math.cos(r))};t(this.rotPre,0),t(this.rotBlur,1),t(this.rotPost,2)}render(e){if(!this.enabled)return;let t=e.getTexture(`pathtracer:color`),n=e.getTexture(`pathtracer:albedo`),r=e.getTexture(`pathtracer:normalDepth`),i=e.getTexture(`pathtracer:shadingNormal`),a=e.getTexture(`motionVector:screenSpace`);if(!t)return;if(!n||!r||!i||!a){e.setTexture(`nrd:output`,t);return}let o=t.image;o&&o.width>0&&o.height>0&&(o.width!==this.outputTarget.width||o.height!==this.outputTarget.height)&&this.setSize(o.width,o.height);let s=e.getState(`pathtracer:samples`)??this.pathTracer?.frameCount??0;if(s+1>=this.u.handoverFrames.value){e.setTexture(`nrd:output`,t),this._needsReset=!0;return}if(this._colorTexNode.value=t,this._albedoTexNode.value=n,this._ndTexNode.value=r,this._snTexNode.value=i,this._motionTexNode.value=a,this._updateCamera(),this.inputFrames.value=s,this._updateRotators(this.pathTracer?.uniforms?.get(`seedFrame`)?.value??e.getState(`frame`)??0),this.resetU.value=+!!this._needsReset,!this._compiled){for(let e of this._kernels)this.renderer.compute(e);this._compiled=!0}this._nTmpA.value=this._tmpA,this._nTmpB.value=this._tmpB,this._nHist.value=this._hist,this._nFast.value=this._fastHist,this._nInternal.value=this._internal,this._nGeom.value=this._geomPrev,this._nData.value=this._dataT,this._nStabRead.value=this._stabPing===0?this._stabB:this._stabA,this.renderer.compute(this._kPre),this.renderer.compute(this._kTa),this.renderer.compute(this._kHf),this.renderer.compute(this._kBlur),this.renderer.compute(this._kPost),this.renderer.compute(this._stabPing===0?this._kTsA:this._kTsB),this._srcRegion.max.set(this.outputTarget.width,this.outputTarget.height),this.renderer.copyTextureToTexture(this._tmpA,this.outputTarget.texture,this._srcRegion),e.setTexture(`nrd:output`,this.outputTarget.texture),this._stabPing=1-this._stabPing,this._needsReset=!1,this._needsReset=!1}setSize(e,t){this.outputTarget.setSize(e,t),this.outputTarget.texture.needsUpdate=!0,this.resW.value=e,this.resH.value=t,this._dispatchX=Math.ceil(e/xh),this._dispatchY=Math.ceil(t/xh);let n=[this._dispatchX,this._dispatchY,1];for(let e of this._kernels)e&&(e.dispatchSize=n);this._needsReset=!0}releaseGPUMemory(){this._disposeStorage(),this.context?.removeTexture(`nrd:output`),this.outputTarget?.texture?.dispose(),this._needsReset=!0}reallocateReservedStorage(){this._disposeKernels(),this._disposeStorage();for(let[e,t]of this._placeholders)e.value=t;this._allocStorage(),this._buildKernels(),this._compiled=!1,this._needsReset=!0,this._stabPing=0}dispose(){this._disposeKernels(),this._disposeStorage(),this.outputTarget?.dispose();for(let e of[this._colorTexNode,this._albedoTexNode,this._ndTexNode,this._snTexNode,this._motionTexNode])e?.dispose();for(let[e,t]of this._placeholders)e.dispose(),t.dispose();this._placeholders.clear()}},Kh=e=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,1e7),qh=(0,n.wgslFn)(`
896
896
  fn temporalAccumulate(
897
897
  lum: f32,
898
898
  prevMean: f32,
@@ -968,10 +968,10 @@ fn ${e}( c: vec3<f32> ) -> vec3<f32> {
968
968
  return vec4f( newExposure, geoMean, targetExp, 1.0 );
969
969
 
970
970
  }
971
- `),lg=class extends V{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:ye.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,n.uniform)(r.keyValue??.18),this.minExposureU=(0,n.uniform)(r.minExposure??.1),this.maxExposureU=(0,n.uniform)(r.maxExposure??20),this.adaptSpeedBrightU=(0,n.uniform)(r.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,n.uniform)(r.adaptSpeedDark??.5),this.epsilonU=(0,n.uniform)(r.epsilon??1e-4),this.deltaTimeU=(0,n.uniform)(1/60),this.isFirstFrameU=(0,n.uniform)(1),this.previousExposureU=(0,n.uniform)(r.initialExposure??1),this.lowPercentileU=(0,n.uniform)(r.lowPercentile??.1),this.highPercentileU=(0,n.uniform)(r.highPercentile??.9),this.centerWeightU=(0,n.uniform)(r.centerWeight??8),this.inputResW=(0,n.uniform)(1),this.inputResH=(0,n.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=r.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=r.FloatType,this._downsampleStorageTex.format=r.RGBAFormat,this._downsampleStorageTex.minFilter=r.NearestFilter,this._downsampleStorageTex.magFilter=r.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=r.FloatType,this._reductionStorageTex.format=r.RGBAFormat,this._reductionStorageTex.minFilter=r.NearestFilter,this._reductionStorageTex.magFilter=r.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationResult=(0,n.attributeArray)(1,`vec4`),this._readbackBuffer=new t.ReadbackBuffer(16),this._readbackBuffer.name=`AutoExposureAdaptation`,this._histogramBuffer=(0,n.attributeArray)(rg,`uint`).toAtomic()}_buildCompute(){this._buildDownsampleCompute(),this._buildHistogramCompute(),this._buildHistogramAnalyzeCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,r=this.epsilonU,i=this.inputResW,a=this.inputResH;this._downsampleComputeNode=(0,n.Fn)(()=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y)),c=i.div((0,n.float)(64)),l=a.div((0,n.float)(64)),u=(0,n.float)(o).mul(c),d=(0,n.float)(s).mul(l),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let i=0;i<4;i++){let a=Xo((0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(u.add((0,n.float)((i+.5)/4).mul(c))),(0,n.int)(d.add((0,n.float)((t+.5)/4).mul(l))))).xyz);(0,n.If)(a.greaterThan(r),()=>{f.addAssign(a.add(r).log()),p.addAssign(1)})}(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(s)),(0,n.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildHistogramCompute(){let e=this._downsampleTarget.texture,t=this._histogramBuffer,r=this.centerWeightU;this._histogramComputeNode=(0,n.Fn)(()=>{let i=n.localId.x;(0,n.atomicStore)(t.element(i),(0,n.uint)(0)),(0,n.workgroupBarrier)();for(let a=0;a<16;a++){let o=i.mul(16).add(a),s=o.mod(64),c=o.div(64),l=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(s),(0,n.int)(c))),u=l.x,d=l.y;(0,n.If)(d.greaterThan(0),()=>{let e=(0,n.uint)(u.div(d).sub((0,n.float)(ig)).div((0,n.float)(ag)).mul((0,n.float)(rg)).floor().clamp(0,(0,n.float)(rg-1))),i=(0,n.float)(s).add(.5).div((0,n.float)(64)),a=(0,n.float)(c).add(.5).div((0,n.float)(64)),o=i.sub(.5),l=a.sub(.5),f=(0,n.uint)(o.mul(o).add(l.mul(l)).mul(r).negate().exp().mul((0,n.float)(sg)));(0,n.atomicAdd)(t.element(e),f)})}})().compute([1,1,1],[256,1,1])}_buildHistogramAnalyzeCompute(){let e=this._histogramBuffer,t=this._reductionStorageTex,r=this.lowPercentileU,i=this.highPercentileU;this._histogramAnalyzeNode=(0,n.Fn)(()=>{let a=(0,n.float)(0).toVar();(0,n.Loop)(rg,({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(t))))});let o=a.mul(r),s=a.mul(i),c=(0,n.float)(0).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)(rg,({i:t})=>{let r=(0,n.float)((0,n.atomicLoad)(e.element(t)));d.assign(c),c.addAssign(r),(0,n.If)(d.lessThan(s).and(c.greaterThan(o)),()=>{let e=(0,n.float)(ig).add((0,n.float)(t).add(.5).mul((0,n.float)(og)));l.addAssign(e.mul(r)),u.addAssign(r)})});let f=(0,n.max)(u,(0,n.float)(1)),p=l.div(f),m=p.exp();(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(0),(0,n.uint)(0)),(0,n.vec4)(m,a,p,1)).toWriteOnly()})().compute(1,[1,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationResult,r=this.keyValueU,i=this.minExposureU,a=this.maxExposureU,o=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,n.Fn)(()=>{let d=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(0),(0,n.int)(0))).x,f=cg(d,u,r,i,a,o,s,c,l);t.element((0,n.uint)(0)).assign(f)})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>e&&this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=+!!this.isFirstFrame,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._histogramComputeNode),this.renderer.compute(this._histogramAnalyzeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.getArrayBufferAsync(this._adaptationResult.value,this._readbackBuffer).then(t=>{let n=t&&t.buffer?new Float32Array(t.buffer.slice(0)):null;this._readbackBuffer.release(),this._pendingReadback=!1,n&&e===this._readbackGeneration&&this._applyReadback(n)}).catch(()=>{try{this._readbackBuffer.release()}catch{}this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark),e.lowPercentile!==void 0&&(this.lowPercentileU.value=e.lowPercentile),e.highPercentile!==void 0&&(this.highPercentileU.value=e.highPercentile),e.centerWeight!==void 0&&(this.centerWeightU.value=e.centerWeight)}dispose(){this._downsampleComputeNode?.dispose(),this._histogramComputeNode?.dispose(),this._histogramAnalyzeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._readbackBuffer?.dispose(),this._inputTexNode?.dispose(),this._reductionReadTexNode?.dispose()}},ug=class extends V{constructor(e,i={}){super(`Compositor`,{...i,executionMode:ye.ALWAYS}),this.renderer=e,this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode;let a=this._sourceTexNode.sample((0,n.uv)()),o=(0,n.mix)((0,n.vec3)((0,n.dot)(a.xyz,Uo)),a.xyz,this.saturation),s=(0,n.select)(this._transparentBackground,a.w,1);this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.colorNode=(0,n.vec4)(o,s),this.compositorMaterial.blending=r.NoBlending,this.compositorQuad=new t.QuadMesh(this.compositorMaterial)}_resolveSourceTexture(e){return e.getTexture(`bloom:output`)||this.resolveLightTexture(e)}resolveLightTexture(e){return e.getTexture(`oidn:output`)||e.getTexture(`edgeFiltering:output`)||e.getTexture(`bilateralFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`nrd:output`)||e.getTexture(`pathtracer:color`)}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Uo).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let t=this._resolveSourceTexture(e);t&&(this._sourceTexNode.value=t,this.renderer.setRenderTarget(null),this.compositorQuad.render(this.renderer))}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},dg=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},fg=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},pg=!1,mg=[],hg=new WeakMap;function gg(e){pg=!!e}function _g(){return mg.slice()}function vg(){mg.length=0}function yg(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var bg=e=>!e||!e.image||!(e.image.width>0);function xg(e,t,n){if(!pg){n();return}let r=hg.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},hg.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&Sg(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=yg(e).filter(t=>bg(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function Sg(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(bg(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&mg.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}var Cg=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(ln.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new dg,this.eventBus=new fg,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(xg(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};qt();var wg=Pt(`engine`),Tg=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return t!==`time`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,wg.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},Eg=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i);try{return await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,t,r)}finally{this.target.dispose(),this.target=null}}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};xe();var Dg=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:H.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=e.distance;this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:t/this.assetLoader.getSceneScale(),worldDistance:t})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:H.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:`focusChanged`,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:H.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}};xe();var Og={maxBounces:{uniform:`maxBounces`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},maxSubsurfaceSteps:{uniform:`maxSubsurfaceSteps`,reset:!0},maxTransparentBounces:{uniform:`maxTransparentBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},backgroundBlurriness:{uniform:`backgroundBlurriness`,reset:!0},backgroundBlurSamples:{uniform:`backgroundBlurSamples`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},groundProjectionEnabled:{uniform:`groundProjectionEnabled`,reset:!0},groundProjectionRadius:{uniform:`groundProjectionRadius`,reset:!0},groundProjectionHeight:{uniform:`groundProjectionHeight`,reset:!0},groundProjectionLevel:{uniform:`groundProjectionLevel`,reset:!0},enableGroundCatcher:{uniform:`enableGroundCatcher`,reset:!0},groundCatcherHeight:{uniform:`groundCatcherHeight`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},panoramaLevelHorizon:{uniform:`panoLevelHorizon`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},shadowTerminatorOffset:{uniform:`shadowTerminatorOffset`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},noiseThreshold:{uniform:`noiseThreshold`,reset:!0},adaptiveMinSamples:{uniform:`adaptiveMinSamples`,reset:!0},adaptiveStopFraction:{uniform:`adaptiveStopFraction`,reset:!0},usePixelFreeze:{uniform:`usePixelFreeze`,reset:!0},pixelFreezeThreshold:{uniform:`pixelFreezeThreshold`,reset:!0},pixelFreezeStability:{uniform:`pixelFreezeStability`,reset:!0},convergenceOverlay:{handler:`handleConvergenceOverlay`,reset:!1},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},cameraProjection:{handler:`handleCameraProjection`,reset:!0},panoramaLonRange:{handler:`handlePanoramaLonRange`,reset:!0},panoramaLatRange:{handler:`handlePanoramaLatRange`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},interactionRenderScale:{handler:`handleInteractionRenderScale`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},backgroundColor:{handler:`handleBackgroundColor`,reset:!0},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},kg=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),Ag={bounces:`maxBounces`,debugMode:`visMode`},jg=class extends r.EventDispatcher{constructor(e=W,{issues:t=null}={}){super(),this._issues=t,this._values=new Map,this._sources=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind(e){this._pathTracer=e.stages.pathTracer,this._resetCallback=e.resetCallback,this._delegates={},this._handlers=this._buildHandlers(e)}_buildHandlers({stages:e,renderer:t,resetCallback:n,reconcileCompletion:i,denoisingManager:a,cameraManager:o,onInteractionRenderScale:s}){let c=new r.Vector2,l=(t,n)=>{c.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,c)};return{handleCameraProjection:t=>{let n=t===`equirectangular`;e.pathTracer?.setUniform(`cameraProjection`,+!!n),n&&(a?.requiresMotionVectors&&a.setDenoiserStrategy(`edgeaware`),o?.setAutoFocusMode(`manual`))},handlePanoramaLonRange:e=>l(`panoLonRange`,e),handlePanoramaLatRange:e=>l(`panoLatRange`,e),handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.compositor?.setTransparentBackground(t)},handleBackgroundColor:t=>{let n=t?.isColor?t:new r.Color(t);e.pathTracer?.setUniform(`backgroundColor`,n)},handleExposure:n=>{!e.autoExposure?.enabled&&t&&(t.toneMappingExposure=n)},handleSaturation:t=>{e.compositor?.setSaturation(t)},handleConvergenceOverlay:t=>{e.pathTracer?.setUniform(`convergenceOverlay`,t),e.compositor?.setConvergenceOverlay(t),t&&!this.get(`useAdaptiveSampling`)&&n?.()},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t),i?.()},handleMaxSamples:t=>{e.pathTracer?.setUniform(`maxSamples`,t),e.pathTracer?.updateCompletionThreshold(),i?.()},handleRenderTimeLimit:()=>{i?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)},handleInteractionRenderScale:e=>{s?.(e)}}}set(e,t,{reset:n,silent:r,source:i=kg.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:H.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=kg.HOST}={}){let i=!1;for(let[n,a]of Object.entries(e)){let e=this._applyOne(n,a,r);e?.route&&((e.route.reset??!0)&&(i=!0),t||this.dispatchEvent({type:H.SETTING_CHANGED,key:n,value:a,prev:e.prev}))}(n===void 0?i:n)&&this._resetCallback?.()}_applyOne(e,t,n){let r=this._values.get(e);if(r===t)return null;this._values.set(e,t),this._sources.set(e,n);let i=Og[e];return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(ln.SETTING_UNKNOWN_KEY,`unknown setting "${e}" — stored but never applied to any stage`,{key:e})}get(e){return this._values.get(e)}getEffective(){let e={};for(let[t,n]of this._values)e[t]={value:n,source:this._sources.get(t)??kg.DEFAULT,routed:Og[t]!==void 0};return e}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=Og[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(Og))t in e&&(this._values.set(t,e[t]),this._sources.set(t,kg.DEFAULT));for(let[t,n]of Object.entries(Ag))t in e&&(this._values.set(n,e[t]),this._sources.set(n,kg.DEFAULT))}},Mg=512,Ng=4<<20,Pg=15e8,Fg=new TextDecoder;function Ig(e){return e.length>=2&&e[0]===31&&e[1]===139}function Lg(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Rg(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function zg(e){return Ig(e)?`gzip`:Lg(e)?`zip`:Rg(e)?`tar`:null}function Bg(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return Fg.decode(e.subarray(t,r))}function Vg(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=Bg(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function Hg(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function Ug(e){let t=Fg.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var Wg=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Pg,onEntry:r=null}={}){this.filter=e,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(Mg),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(Mg-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===Mg&&(this._headerLen=0,this._readHeader(),this._bodyStart=t+n)}else{let t=Math.min(this._remaining,e.length-n);if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<Mg;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let n=String.fromCharCode(e[156]||48),r=Vg(e,124,12),i=Bg(e,345,155),a=Bg(e,0,100),o=this._pendingName??(i?`${i}/${a}`:a);if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=r+(Mg-r%Mg)%Mg,this._dst=null,this._special=null,this._state=this._remaining>0?`body`:`header`,n===`L`||n===`x`||n===`X`){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}if(n===`5`||n===`g`||n===`K`||o.endsWith(`/`)||n!==`0`&&n!==` `)return;let s=Hg(o);if(s&&(this.listing.push({path:s,size:r}),(!this.filter||this.filter(s,r))&&(this._indexed=!0,!(this.retain&&!this.retain(s,r))))){if(this.retainedBytes+r>this.byteBudget){this.truncated=!0;return}this._dst=new Uint8Array(r),this.retainedBytes+=r}}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=Bg(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=Ug(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}};async function Gg(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await Kg(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function Kg(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=Ng){let r=Math.min(n+Ng,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=Ng){let i=Math.min(r+Ng,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function qg(e,t={}){let{onProgress:n,...r}=t,i=new Wg(r),a=0,o=0;return await Gg(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}async function Jg(e,t={}){let n=new Wg({...t});await Kg(e,e=>n.push(e)),n.end();let{entries:r,listing:i,retainedBytes:a,truncated:o}=n.result(),s=new Map;for(let e of i)e.offset!==void 0&&s.set(e.path,e);return{entries:r,listing:i,read:async t=>{if(r[t])return r[t];let n=s.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},retainedBytes:a,truncated:o,indexed:s.size}}async function Yg(e,t={}){let{onProgress:n,...r}=t,i=new Wg(r);return await Kg(e,e=>i.push(e)),i.end(),i.result()}function Xg(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=Hg(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function Zg(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var Qg={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},$g=9,e_=10,t_=12,n_=13,r_=32,i_=34,a_=35,o_=43,s_=45,c_=46,l_=48,u_=57,d_=91,f_=93,p_=69,m_=101,h_=e=>e===r_||e===$g||e===e_||e===n_||e===t_,g_=e=>e>=l_&&e<=u_,__=15,v_=22,y_=(()=>{let e=new Float64Array(v_+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),b_=new TextDecoder;function x_(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return b_.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var S_=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&h_(e[t]);)t++;if(t<n&&e[t]===a_){for(;t<n&&e[t]!==e_;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===d_)return this.i=t+1,{type:Qg.LBRACKET};if(r===f_)return this.i=t+1,{type:Qg.RBRACKET};if(r===i_){let r=++t;for(;t<n&&e[t]!==i_;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:Qg.STRING,value:x_(e,r,t)}}if(g_(r)||r===c_&&g_(e[t+1])||(r===s_||r===o_)&&(g_(e[t+1])||e[t+1]===c_&&g_(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(h_(n)||n===i_||n===d_||n===f_||n===a_)break;t++}return this.i=t,{type:Qg.WORD,value:x_(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===s_?(i=!0,r++):t[r]===o_&&r++;let a=0,o=0,s=0;for(;r<n&&g_(t[r]);)a=a*10+(t[r]-l_),o++,r++;if(r<n&&t[r]===c_)for(r++;r<n&&g_(t[r]);)a=a*10+(t[r]-l_),o++,s++,r++;let c=0;if(r<n&&(t[r]===m_||t[r]===p_)){let e=r+1,i=!1;if(e<n&&(t[e]===s_||t[e]===o_)&&(i=t[e]===s_,e++),e<n&&g_(t[e])){let a=0;for(;e<n&&g_(t[e]);)a=a*10+(t[e]-l_),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${x_(t,e,r)}"`);let l=c-s;if(!(o<=__&&l>=-v_&&l<=v_)){let n=Number(x_(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${x_(t,e,r)}"`);return{type:Qg.NUMBER,value:n}}let u=l===0?a:l>0?a*y_[l]:a/y_[-l];return i&&(u=-u),{type:Qg.NUMBER,value:u}}};function C_(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function w_(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function T_(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function E_(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function D_(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function O_(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function k_(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function A_(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function j_(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function M_(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function N_(e,t,n){let r=M_(A_(t,e)),i=M_(j_(M_(n),r)),a=j_(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function P_(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return C_();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var F_=8,I_={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array},L_=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,warnings:[]},this.ctm=C_(),this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.objectBeginCTM=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){return this.dirStack=[t],await this._run(new S_(e)),this.ir}_addInstance(e){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let t=this.ir.instances.get(e);t||this.ir.instances.set(e,t={name:e,count:0,matrices:new Float32Array(512)});let n=(t.count+1)*16;if(n>t.matrices.length){let e=new Float32Array(Math.max(n,t.matrices.length*2));e.set(t.matrices),t.matrices=e}let r=t.count*16,i=this.ctm;for(let e=0;e<16;e++)t.matrices[r+e]=i[e];t.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==Qg.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==Qg.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===Qg.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==Qg.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===Qg.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===Qg.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==Qg.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===Qg.NUMBER){let t=[];for(;n()&&t.length<F_;){let e=this._next();if(e.type!==Qg.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=I_[e]||Float64Array,i=new r(F_*4);i.set(t);let a=t.length;for(;n();){let e=this._next();if(e.type!==Qg.NUMBER)return this._finishMixedValue(i,a,e);if(a===i.length){let e=new r(i.length*2);e.set(i),i=e}i[a++]=e.value}return this._next(),a===i.length?i:i.slice(0,a)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==Qg.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===Qg.NUMBER||e.type===Qg.STRING)return e.value;if(e.type===Qg.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==Qg.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this.ctm=C_();break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this.ctm=E_(this.ctm,D_(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this.ctm=E_(this.ctm,O_(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this.ctm=E_(this.ctm,k_(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=N_([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this.ctm=E_(this.ctm,P_(t));break}case`Transform`:this.ctm=this._readBracketedOrBareNumbers(16);break;case`ConcatTransform`:{let e=this._readBracketedOrBareNumbers(16);this.ctm=E_(this.ctm,e);break}case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),this.ctm.slice());break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.slice());break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:P_(this.ctm)};break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),filename:this._str(e.filename,null)};break}case`Integrator`:case`Sampler`:case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=C_(),this.state={material:null,areaLight:null,reverseOrientation:!1};break;case`WorldEnd`:break;case`AttributeBegin`:this.attributeStack.push({ctm:this.ctm.slice(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation});break;case`AttributeEnd`:{let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation});break}case`TransformBegin`:this.transformStack.push(this.ctm.slice());break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:this._next();break;case`TransformTimes`:this._readNumbers(2);break;case`MediumInterface`:this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._peek()&&this._peek().type===Qg.STRING&&this._next();break;case`MakeNamedMedium`:this._skipNamedAndParams();break;case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation};this._emitShape(e);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this.attributeStack.push({ctm:this.ctm.slice(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation}),this.currentObject=e,this.objectBeginCTM=this.ctm.slice(),this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:{this.currentObject=null,this.objectBeginCTM=null;let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation});break}case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=E_(P_(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=await this.resolveInclude(e,t);if(n==null){this._warn(`Include target not found: ${e}`);return}let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(r);try{await this._run(new S_(n))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t)}}_skipTypeAndParams(){this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}},R_={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},z_=[.92,.92,.92];function B_(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function V_(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function H_(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function U_(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:B_(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=W_(i.value[0]);return e&&R_[e]?{rgb:R_[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function W_(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(R_))if(e.toLowerCase().includes(t))return t;return null}function G_(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=V_(e,`uroughness`,null),r=V_(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function K_(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await U_(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await U_(i,`reflectance`,t,null),n=i.eta,r=i.k,c=n&&n.type===`spectrum`&&typeof n.value[0]==`string`;if(e.rgb||e.texture)s(e);else if(n&&r&&!c){let e=(await U_(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await U_(i,`k`,t,[3.9,2.45,2.14])).rgb,r=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);o([r(e[0],n[0]),r(e[1],n[1]),r(e[2],n[2])])}else o(n?(await U_(i,`eta`,t,z_)).rgb||z_:R_.cu);a.metalness=1,a.roughness=G_(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=V_(i,`eta`,1.5),a.roughness=G_(i,0),a.thickness=n===`thindielectric`?0:V_(i,`thickness`,0);break;case`coateddiffuse`:s(await U_(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=G_(i,0);break;case`diffusetransmission`:{let e=await U_(i,`transmittance`,t,[.25,.25,.25]);s(await U_(i,`reflectance`,t,[.25,.25,.25])),a.transmission=e.rgb?(e.rgb[0]+e.rgb[1]+e.rgb[2])/3:.5,a.roughness=1,a.ior=1;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,V_(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,r]=await Promise.all([K_(o,t),K_(s,t)]),i=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,r.color,n),a.roughness=i(e.roughness,r.roughness),a.metalness=i(e.metalness,r.metalness),a.ior=i(e.ior??1.5,r.ior??1.5),a.transmission=i(e.transmission??0,r.transmission??0),a.thickness=i(e.thickness??0,r.thickness??0),a.clearcoat=i(e.clearcoat??0,r.clearcoat??0),a.clearcoatRoughness=i(e.clearcoatRoughness??0,r.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,r.emissive,n),a.emissiveIntensity=i(e.emissiveIntensity??0,r.emissiveIntensity??0),a.map=(n<.5?e.map:r.map)||null;break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await U_(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}return a.roughness=Math.max(0,Math.min(1,a.roughness)),a}function q_(e){return e===3?3/16:3/(8*e)}function J_(e){return 1/(e+3/(8*q_(e)))}function Y_(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function X_(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function Z_(e,t){let n=e.length/3,r=Y_(n,t),i=r.edgeV0.length,a=X_(e,r,n,q_,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function Q_(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=Z_(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=X_(i,Y_(s,a),s,J_,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function $_(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}var ev=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})();function tv(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function nv(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?P_(t):null,c=e.srgb?ev:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=$_(f,p,m);tv(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var rv=2;function iv(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function av(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function ov(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function sv(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function cv(e,t,n){let r=e.length/3,i=t===`bspline`?r-3:Math.max(1,(r-1)/3);if(i<1)return null;let a=Math.max(1,Math.round(n*i)),o=new Float64Array((a+1)*3),s=[0,0,0,0];for(let n=0;n<=a;n++){let r=n/a*i,c=Math.floor(r);c>=i&&(c=i-1);let l=r-c;t===`bspline`?iv(l,s):av(l,s);let u=t===`bspline`?c:c*3,d=0,f=0,p=0;for(let t=0;t<4;t++){let n=(u+t)*3;d+=s[t]*e[n],f+=s[t]*e[n+1],p+=s[t]*e[n+2]}o[n*3]=d,o[n*3+1]=f,o[n*3+2]=p}return{points:o,count:a+1}}function lv(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??rv)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=cv(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=s>=3?s:s*2,f=new Float32Array(u*d*3),p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=!1;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(p[0]=l[n*3]-l[t*3],p[1]=l[n*3+1]-l[t*3+1],p[2]=l[n*3+2]-l[t*3+2],ov(p),_){let e=m[0]*p[0]+m[1]*p[1]+m[2]*p[2];m[0]-=e*p[0],m[1]-=e*p[1],m[2]-=e*p[2],Math.hypot(m[0],m[1],m[2])<1e-9&&sv(p,[0,1,0],m),ov(m)}else{if(a&&a.length>=3)m[0]=a[0],m[1]=a[1],m[2]=a[2],sv(p,m,g),m[0]=g[0],m[1]=g[1],m[2]=g[2];else{let e=Math.abs(p[0]),t=Math.abs(p[1]),n=Math.abs(p[2]);sv(p,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],m)}Math.hypot(m[0],m[1],m[2])<1e-9&&sv(p,[0,1,0],m),ov(m),_=!0}sv(p,m,h),ov(h);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,v=l[e*3],y=l[e*3+1],b=l[e*3+2];for(let t=0;t<d;t++){let n,r,i;if(s>=3){let e=t/s*Math.PI*2,a=Math.cos(e),o=Math.sin(e);n=m[0]*a+h[0]*o,r=m[1]*a+h[1]*o,i=m[2]*a+h[2]*o}else{let e=t<2?m:h,a=t%2==0?-1:1;n=e[0]*a,r=e[1]*a,i=e[2]*a}let a=(e*d+t)*3;f[a]=v+n*c,f[a+1]=y+r*c,f[a+2]=b+i*c}}let v=s,y=new Uint32Array((u-1)*v*6),b=0;for(let e=0;e<u-1;e++)for(let t=0;t<v;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*d+n,a=e*d+r,o=(e+1)*d+r,c=(e+1)*d+n;y[b++]=i,y[b++]=a,y[b++]=o,y[b++]=i,y[b++]=o,y[b++]=c}return{positions:f,indices:b===y.length?y:y.slice(0,b)}}var uv=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],dv=4096;function fv(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function pv(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;let r=new e.constructor(n);return r.set(e),r}function mv(e){return e instanceof Float32Array?e:Float32Array.from(e)}var hv=1e3,gv=45e6,_v=6e6,vv=256,yv=4096,bv=5e5,xv=2,Sv={flat:1,ribbon:1,cylinder:2};function Cv(e,t){let n=Math.min(e.width,dv),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function wv(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var Tv=class{constructor(e={}){this.maxTriangles=e.maxTriangles??gv,this.maxPlacements=e.maxPlacements??_v,this.mergeShapesAbove=e.mergeShapesAbove??vv,this.curveSteps=e.curveSteps??xv,this.curveSides=e.curveSides??null,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0;for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;if(this._batches&&i.getAttribute(`position`).count<=yv){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}let o=this._meshFromGeometry(r,i,a,r.ctm,`shape_${n}`);o&&t.add(o)}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=await this._buildEnvironment(e.lights);return this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:i,report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4;for(let[o,s]of e.instances){let c=e.objects.get(o);if(!c){this.droppedNoTemplate+=s.count,this.warn(`ObjectInstance "${o}" has no template — ${s.count.toLocaleString()} placement(s) dropped`);continue}for(let e of c){if(this._overBudget()){this.skippedForBudget+=s.count;continue}let[c,l]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!c)continue;let u=this._accountGeometry(c),d=Math.max(0,this.maxPlacements-this.placementCount),f=Math.min(s.count,d);if(f<s.count&&(this.skippedForBudget+=s.count-f),f===0)continue;let p=this._materialForGeometry(e,c,l,`instances_${o}`),m=new r.InstancedMesh(c,p,f);m.name=`instance_${n++}`,m.frustumCulled=!1;let h=e.relativeCTM||e.ctm;for(let e=0;e<f;e++)T_(i,s.matrices,e*16,h),m.setMatrixAt(e,a.fromArray(this.convertHandedness?E_(uv,i):i));m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=f,this.reportedMeshes+=f,this.report.length<hv&&this.report.push({mesh:`${m.name} ×${f}`,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+p.color.getHexString(),map:p.map?`yes`:`-`,uv:c.getAttribute(`uv`)?`yes`:`NO`,normals:c.getAttribute(`normal`)?`yes`:`NO`,emissive:p.emissiveIntensity>0?`#${p.emissive.getHexString()}×${p.emissiveIntensity}`:`-`,size:`instanced`,tris:u})}}}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a){let o=!!t.getAttribute(`uv`),s=this._materialForGeometry(e,t,n,a),c=new r.Mesh(t,s);c.name=a;let l=this.convertHandedness?E_(uv,i):i;new r.Matrix4().fromArray(l).decompose(c.position,c.quaternion,c.scale),c.updateMatrix(),t.boundingBox||t.computeBoundingBox();let u=t.boundingBox?t.boundingBox.clone().applyMatrix4(c.matrix).getSize(new r.Vector3):new r.Vector3,d=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<hv&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:s.emissiveIntensity>0?`#${s.emissive.getHexString()}×${s.emissiveIntensity}`:`-`,size:`${u.x.toFixed(2)}×${u.y.toFixed(2)}×${u.z.toFixed(2)}`,tris:d}),c}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=n.clone(),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){let i=this._materialForGeometry(e,t,n,`merged shape`),a=t.getAttribute(`position`),o=t.getAttribute(`normal`),s=t.getAttribute(`uv`),c=t.index,l=a.count;this.triangleCount+=(c?c.count:l)/3,this.reportedMeshes++,this.mergedShapes++;let u=this._batches.get(i);u||this._batches.set(i,u=[null,null]);let d=+!!s,f=u[d];f||(u[d]=f={material:i,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:s?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let p=this.convertHandedness?E_(uv,e.ctm):e.ctm,m=P_(p),h=f.vertexCount;f.positions=pv(f.positions,(h+l)*3),f.normals=pv(f.normals,(h+l)*3),s&&(f.uvs=pv(f.uvs,(h+l)*2));let g=a.array,_=f.positions,v=o?o.array:null,y=f.normals;for(let e=0;e<l;e++){let t=e*3,n=(h+e)*3,r=g[t],i=g[t+1],a=g[t+2];if(_[n]=p[0]*r+p[4]*i+p[8]*a+p[12],_[n+1]=p[1]*r+p[5]*i+p[9]*a+p[13],_[n+2]=p[2]*r+p[6]*i+p[10]*a+p[14],!v)continue;let o=v[t],s=v[t+1],c=v[t+2],l=m[0]*o+m[1]*s+m[2]*c,u=m[4]*o+m[5]*s+m[6]*c,d=m[8]*o+m[9]*s+m[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),y[n]=l,y[n+1]=u,y[n+2]=d}s&&f.uvs.set(s.array.subarray(0,l*2),h*2);let b=c?c.count:l;f.indices=pv(f.indices,f.indexCount+b);let x=f.indices,S=c?c.array:null;for(let e=0;e<b;e++)x[f.indexCount+e]=h+(S?S[e]:e);f.vertexCount+=l,f.indexCount+=b,f.triangles+=b/3,f.triangles>=bv&&(this._flushBatch(f,r),u[d]=null)}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(e.positions.slice(0,e.vertexCount*3),3)),n.setAttribute(`normal`,new r.Float32BufferAttribute(e.normals.slice(0,e.vertexCount*3),3)),e.uvs&&n.setAttribute(`uv`,new r.Float32BufferAttribute(e.uvs.slice(0,e.vertexCount*2),2)),n.setIndex(new r.Uint32BufferAttribute(e.indices.slice(0,e.indexCount),1));let i=new r.Mesh(n,e.material);i.name=`merged_${this._mergedBatches++}`,i.frustumCulled=!1,t.add(i),this.placementCount++,this.report.length<hv&&this.report.push({mesh:i.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles}),e.positions=e.normals=e.uvs=e.indices=null}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(mv(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(mv(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(mv(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(fv(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(V_(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=H_(e,`type`,`flat`),a=V_(e,`width`,1),o=lv({P:t,basis:H_(e,`basis`,`bezier`),width0:V_(e,`width0`,a),width1:V_(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??Sv[i]??1});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(V_(e,`levels`,3)))),{positions:a,indices:o,levels:s}=Q_(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value;if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=[];for(let e=0;e+3<n.length;e+=4){let[t,r,a,o]=[n[e],n[e+1],n[e+2],n[e+3]];i.push(t,r,a,t,a,o)}let a=new r.BufferGeometry;return a.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),a.setIndex(i),a.computeVertexNormals(),a}_plyMesh(e){let t=H_(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)||t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){return new r.SphereGeometry(V_(e,`radius`,1),48,32)}_disk(e){let t=V_(e,`radius`,1),n=V_(e,`innerradius`,0),i=V_(e,`height`,0),a=[],o=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2,s=(e+1)/48*Math.PI*2,c=a.length/3;a.push(Math.cos(r)*n,Math.sin(r)*n,i),a.push(Math.cos(r)*t,Math.sin(r)*t,i),a.push(Math.cos(s)*t,Math.sin(s)*t,i),a.push(Math.cos(s)*n,Math.sin(s)*n,i),o.push(c,c+1,c+2,c,c+2,c+3)}let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(a),3)),s.setIndex(o),s.computeVertexNormals(),s}async _getMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e)},r=await K_(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.opacity}|${e.side}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}async _applyAreaLight(e,t,n){let r=await U_(t.params,`L`,n,[1,1,1]),i=V_(t.params,`scale`,1),a=r.rgb||[1,1,1];e.emissive.setRGB(a[0],a[1],a[2]),e.emissiveIntensity=i}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`){let r=H_(t.params,`filename`,null);if(r)try{let t=await this.resolveImage(r);t?n={texture:t}:this.warn(`image not found for texture "${e}": ${r}`)}catch(t){this.warn(`failed to load texture "${e}" (${r}): ${t.message}`)}}else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}_colorFromLikeNamedMaterial(e){for(let t of wv(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=new r.Matrix4().fromArray(e.cameraToWorld).elements,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1);let s=i.clone().add(a),c=t&&t.yresolution?t.xresolution/t.yresolution:16/9,l=new r.PerspectiveCamera(this._verticalFov(e.params,c),c,.01,1e4);return l.name=`PBRT Camera`,l.up.copy(o.normalize()),l.position.copy(i),l.lookAt(s),w_(e.cameraToWorld)>0!==this.convertHandedness&&(l.scale.x=-1),l.updateMatrixWorld(!0),l}_verticalFov(e,t){let n=V_(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=Cv(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=nv(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=V_(t.params,`scale`,1),i=H_(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=((await U_(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)},[1,1,1])).rgb||[1,1,1]).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&this.warn(`light "${t.type}" not supported (only infinite lights and emissive area lights are mapped)`)}},Ev=new TextDecoder;function Dv(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function Ov(e,t){return!e||t.startsWith(`/`)?Dv(t):Dv(`${e}/${t}`)}var kv=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=Dv(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(Ov(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null){let n=t!==null&&this.findRecord(Ov(t,e))||this.findRecord(e);n?.lazy&&this.release(n)}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=Dv(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}};function Av(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}var jv=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),Mv=jv(`WorldBegin`),Nv=[jv(`Include`),jv(`Import`)];function Pv(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function Fv(e){for(let t=Av(e,Mv);t>=0;t=Av(e,Mv,t+1))if(Pv(e,t))return!0;return!1}function Iv(e,t){for(let n of Nv)for(let r=Av(e,n);r>=0;r=Av(e,n,r+1)){if(!Pv(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=Ev.decode(e.subarray(a,i));t.add(Dv(o).toLowerCase().split(`/`).pop())}}function Lv(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,Fv(t)),Iv(t,n)}return Rv(t,r,n)}function Rv(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function zv(e){return Lv(e)[0]||null}async function Bv(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=new Set,r=new Map;for(let i of t){let t=await e.read(i);t&&(r.set(i.key,Fv(t)),Iv(t,n),i.lazy&&e.release(i))}return Rv(t.map(e=>e.key),r,n)}async function Vv(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new kv(t,n),c=[],l=await Bv(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=await s.readPath(d);if(!f)throw Error(`PBRT loader: entry "${d}" not readable`);let p=d.includes(`/`)?d.slice(0,d.lastIndexOf(`/`)):``,m=new L_({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t)=>s.releasePath(e,t),maxPlacements:e.maxPlacements}),h=performance.now(),g=await m.parse(f,p),_=performance.now()-h;s.releaseScenes();let v=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),y=new Map,b=async e=>{let t=await s.read(e);return t?(s.release(e),r(v(t))):null},x=new Tv({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,resolvePLY:async e=>{let t=s.findRecord(e);return t?(y.has(t.norm)||y.set(t.norm,await b(t)),y.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),S=performance.now(),C=await x.build(g);return{...C,entryPath:d,candidates:l,warnings:[...c,...C.warnings??[]],parseMs:_,buildMs:performance.now()-S}}var Hv=[`sourceFile`,`url`,`file`];function Uv(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function Wv(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Gv(e){let t=Uv(e);if(!t)return null;let n=Uv(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function Kv(e){let t=Uv(e);if(!t)return null;let n=Hv.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=Wv(t.rotation),i=Wv(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function qv(e){let t=Gv(e);if(!t)return null;let n=Kv(t.environment);return n?{environment:n}:null}function Jv(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=qv(e);if(t)return t}return null}Ar();var Yv={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usd:{type:`model`,name:`USD (Universal Scene Description)`},usda:{type:`model`,name:`USDA (USD ASCII)`},usdc:{type:`model`,name:`USDC (USD Crate)`},usdz:{type:`model`,name:`USDZ (USD Archive)`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`},gz:{type:`archive`,name:`Gzipped TAR Archive`},tgz:{type:`archive`,name:`Gzipped TAR Archive`},tar:{type:`archive`,name:`TAR Archive`}},Xv=/\.(usd|usda|usdc)$/i,Zv=/\.(png|jpg|jpeg|avif)$/i,Qv=3e4,$v=4e9;function ey(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var ty=683;function ny(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var ry=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,profile:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._issues=i,this._profile=a??Le(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(ln.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort()}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;U({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){U({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,f.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return Yv[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);U({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await this.loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usd`:case`usda`:case`usdc`:case`usdz`:return await this.loadUSDFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let e=await this.loadEnvironment(n);return this.dispatchEvent({type:`load`,texture:e,filename:t}),e}finally{URL.revokeObjectURL(n)}}async loadEnvironment(e){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:e});let t;if(e.startsWith(`blob:`))t=await this.loadEnvironmentFromBlob(e);else{let n=e.split(/[?#]/)[0].split(`.`).pop().toLowerCase();t=await this.loadEnvironmentByExtension(e,n)}return t.generateMipmaps=!0,this.applyEnvironmentToScene(t),this.dispatchEvent({type:`load`,texture:t,url:e,filename:e.split(/[?#]/)[0].split(`/`).pop()}),t}catch(t){throw this._isCancellation(t)?this._cancellationError():(console.error(`Error loading environment:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n){let i=e._isNetworkUrl(t),a=this._downloadProgress(`Downloading Environment...`,i),o;return n===`hdr`||n===`exr`?o=await(n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader(this._loadingManager).setDataType(r.FloatType))).loadAsync(t,a):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),o=await this.loaderCache.texture.loadAsync(t,a),o.colorSpace=r.SRGBColorSpace),this._downloadComplete(`Processing Environment...`,62),o.mapping=r.EquirectangularReflectionMapping,o.minFilter=r.LinearFilter,o.magFilter=r.LinearFilter,o}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=zg(await this._readHead(e));if(t===`gzip`||t===`tar`){let{listing:n}=await(t===`gzip`?qg:Yg)(e,{filter:()=>!1,onProgress:e=>U({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),{root:r,elements:i}=Zg(n);return{kind:t,root:r,elements:i,entryCount:n.length,totalBytes:n.reduce((e,t)=>e+t.size,0)}}let n=(0,m.unzipSync)(new Uint8Array(await this.readFileAsArrayBuffer(e))),r=Object.keys(n).map(e=>({path:e,size:n[e].length})),{root:i,elements:a}=Zg(r);return{kind:`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=zg(await this._readHead(e));if(s===`tar`){let i=await this._openSeekableArchive(e,t,r,a);if(i.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,n,o,i);for(let e of i.listing)i.entries[e.path]??=await i.read(e.path);return await this._loadNonPBRTArchive(i.entries,t)}let c=s===`gzip`?await this._readStreamedArchive(e,t,s,r,i):(0,m.unzipSync)(new Uint8Array(await this.readFileAsArrayBuffer(e)));return zv(c)?await this.loadPBRTFromZip(c,t,n,o):await this._loadNonPBRTArchive(c,t)}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _openSeekableArchive(e,t,n,r){let i=Array.isArray(n)?n.filter(Boolean):n?[n]:[],a=await Jg(e,{filter:i.length?Xg(i):null,retain:()=>!1}),o=a.listing.reduce((e,t)=>e+t.size,0);return i.length===0&&this._requireElementChoice(t,a.listing,o,r),console.info(`Archive "${t}": indexed ${a.indexed} entries, ${(o/1e9).toFixed(1)} GB, none resident`+(i.length?`, ${i.length} part${i.length>1?`s`:``} selected.`:`.`)),a}_requireElementChoice(e,t,n,r=$v){if(n<r)return;let{root:i,elements:a}=Zg(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this._issues?.record(ln.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},un.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await(n===`gzip`?qg:Yg)(e,{filter:a.length?Xg(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>U({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=Zg(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this._issues?.record(ln.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},un.WARNING),i}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,r={},i=null){if(U({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let a=e=>this.loaderCache.ply.parse(e),o=(e,t)=>this._pbrtTextureFromBytes(e,t),s=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),r=URL.createObjectURL(new Blob([e]));try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}},c=performance.now(),{group:l,environment:u,report:d,warnings:f,meshCount:p,entryPath:m,candidates:h,parseMs:g,buildMs:_,triangleCount:v,placementCount:y,mergedShapes:b,skippedForBudget:x,droppedNoTemplate:S}=await Vv({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides});if(this.lastPBRTStats={parseMs:g,buildMs:_,loaderMs:performance.now()-c,triangleCount:v,placementCount:y,mergedShapes:b,skippedForBudget:x,droppedNoTemplate:S,meshCount:p},h.length>1){let e=h.filter(e=>e!==m);console.warn(`PBRT archive holds ${h.length} scenes; loaded "${m}". Others: ${e.join(`, `)}`),this._issues?.record(ln.ASSET_AMBIGUOUS_ENTRY,`archive holds ${h.length} pbrt scenes; loaded "${m}"`,{loaded:m,alternatives:e},un.WARNING)}if(d&&d.length&&typeof console.table==`function`){let e=d.length<p?` (first ${d.length} of ${p})`:``;console.groupCollapsed(`PBRT loader: ${p} mesh(es) from "${m}"${e}`),console.table(d),console.groupEnd()}return f&&f.length&&(console.warn(`PBRT loader: ${f.length} warning(s) parsing "${m}"`),f.forEach(e=>console.warn(` •`,e))),u?.texture&&(u.texture.generateMipmaps=!0,this.applyEnvironmentToScene(u.texture)),l.name=m||t,this.releaseTargetModel(),this.targetModel=l,u?.texture&&(this.sceneMetadata={environment:{rotation:0,intensity:1}}),U({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:l,filename:`${m} (from ZIP)`}),l}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader().setDataType(r.FloatType));i=await this._loadViaObjectURL(t,e)}else if(n===`tga`){if(!this.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(Yv[n]&&Yv[n].type===`model`)return Xv.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>Xv.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(Xv.test(e)||Zv.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,m.zipSync)(i),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(Xv,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{U({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usd`:case`usda`:case`usdc`:case`usdz`:o=await this.loadUSDFromArrayBuffer(e,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{this.releaseTargetModel(),this.targetModel=e.scene,this.sceneMetadata=Jv(e),this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}finally{this._disposeGLTFLoader(s)}}else return await this.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.releaseTargetModel(),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),Qv))]);return clearTimeout(r),i||this._issues?.record(ln.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${Qv}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.releaseTargetModel(),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){let{dracoDecoderPath:e,ktx2TranscoderPath:t}=Or(),n=new c.DRACOLoader;n.setDecoderConfig({type:`js`}),n.setDecoderPath(e);let r=new l.KTX2Loader;r.setTranscoderPath(t),this.renderer&&(r.detectSupport(this.renderer),r.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1});let i=new o.GLTFLoader(this._loadingManager);return i.setDRACOLoader(n),i.setKTX2Loader(r),i.setMeshoptDecoder(p.MeshoptDecoder),i}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t){this._loadCancelled=!1;let n=await this.createGLTFLoader(),r=e._isNetworkUrl(t);try{U({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:r,loadedBytes:0,totalBytes:0});let e=await n.loadAsync(t,this._downloadProgress(`Downloading Model...`,r));return this._downloadComplete(),this.releaseTargetModel(),this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=Jv(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{this._disposeGLTFLoader(n)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t){this._loadCancelled=!1;let n=await this.createGLTFLoader(),r=e._isNetworkUrl(t);try{U({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:r,loadedBytes:0,totalBytes:0});let e=await n.loadAsync(t,this._downloadProgress(`Downloading Model...`,r));return this._downloadComplete(),this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._disposeGLTFLoader(n)}}appendObject3D(e,t=`object3d`){let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(Me(e),e.parent?.remove(e)):je(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{U({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=Jv(r),U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(U({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(U({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(U({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(U({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let n=this.loaderCache.ply.parse(e),i;if(n.index!==null)i=new r.Mesh(n,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=n.hasAttribute(`color`),i=new r.Points(n,e)}return i.name=t,this.releaseTargetModel(),this.targetModel=i,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(U({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(U({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(U({isLoading:!0,status:`Processing USD Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usd){let{USDLoader:e}=await import(`three/examples/jsm/loaders/USDLoader.js`);this.loaderCache.usd=new e}let n=await new Promise((t,n)=>{this.loaderCache.usd.parse(e,``,t,n)});return n.name=t,this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new jd(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[];e.traverse(e=>{let n=e.userData;if(e.isRectAreaLight&&!n.__radianceConverted&&(e.intensity*=ny(e,e.width,e.height,n),n.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI/ty,n.__candelaConverted=!0),e.isDirectionalLight&&!n.__luxConverted&&(e.intensity/=ty,n.__luxConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let t=n.normalize??!0,i=n.shape??`rectangle`,a=n.intensity*ny(e,n.width,n.height,n),o=new r.RectAreaLight(new r.Color(...n.color),a*this._profile.areaLightIntensityScale,n.width,n.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(n.spread)?n.spread:Math.PI,o.userData.shape=i,o.userData.__radianceConverted=!0,o.name=n.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)});let n=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),n&&(e.geometry=ey(e.geometry));let t=(0,d.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(Yv))r.type===e&&(t[n]=r);return t}return Yv}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}};xe();var iy=Object.freeze(new r.Vector3(1,1,1)),ay=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new r.PerspectiveCamera(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Qe.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Qe.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0}addCameraFromView(e){let t=this.camera,n=new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint}}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}_getSceneScale(){return this._afContext?.assetLoader?.getSceneScale?.()||1}switchCamera(e,t,n,i){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,i??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let a=this.cameras[this.currentCameraIndex];if(a&&(a.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??iy),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let n=this.cameras[e];if(this.camera.position.copy(n.position),this.camera.quaternion.copy(n.quaternion),this.camera.scale.copy(n.scale),this.camera.fov=n.fov,this.camera.near=n.near,this.camera.far=n.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=n.userData?.__rayzeeOrbitTarget;if(e)this.controls.target.copy(e);else{let e=new r.Vector3(0,0,-1).applyQuaternion(n.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i)}this.controls.update()}}this._applyEffects(this.cameras[e]?.userData?.__rayzeeEffects),n?.(),i?.();let o=this._captureEffects();o&&(o.focusDistance/=this._getSceneScale()),this.dispatchEvent({type:`CameraSwitched`,cameraIndex:e,effects:o,fov:this.camera.fov})}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let{meshScene:t,assetLoader:n,floorPlane:r,currentFocusDistance:i,pathTracer:a,setFocusDistance:o,softReset:s,hardReset:c}=e||this._afContext||{};if(!t||this.autoFocusMode===`manual`)return;if(!a?.enableDOF?.value){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let l=a;if(l?.isReady&&l.renderMode?.value===1&&l.frameCount>0&&!l.isComplete)return;let u=this.afScreenPoint.x*2-1,d=-(this.afScreenPoint.y*2-1),f=this.interactionManager?.raycaster;if(!f)return;f.setFromCamera({x:u,y:d},this.camera);let p=f.intersectObjects(t.children,!0).find(e=>e.object!==this.interactionManager?.focusPointIndicator&&e.object!==r&&!e.object.name.includes(`Helper`)&&e.object.type===`Mesh`),m;if(p)m=p.distance,this._lastValidFocusDistance=m;else if(this._lastValidFocusDistance!==null)m=this._lastValidFocusDistance;else{let e=n?.getSceneScale()||1;m=Qe.FALLBACK_DISTANCE*e,this._lastValidFocusDistance=m}let h=this._afPointDirty;this._afPointDirty=!1,h||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(m-this._smoothedFocusDistance)/this._smoothedFocusDistance>Qe.SNAP_THRESHOLD?this._smoothedFocusDistance=m:this._smoothedFocusDistance+=this.afSmoothingFactor*(m-this._smoothedFocusDistance);let g=i,_=this._smoothedFocusDistance;if(h||g===0||Math.abs(_-g)/Math.max(g,.001)>.001){o(_);let e=n?.getSceneScale()||1;this.dispatchEvent({type:H.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Qe.RESET_THRESHOLD&&s?.()}}setInteractionManager(e){this.interactionManager=e}initAutoFocus({meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,settings:i,softReset:a,hardReset:o}){this._afContext={meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,setFocusDistance:e=>i.set(`focusDistance`,e,{silent:!0}),softReset:a,hardReset:o},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>i.get(`focusDistance`)})}dispose(){this.controls?.dispose()}},oy=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e){this._removeAllLights();let t=e.getObjectsByProperty(`isLight`,!0);if(!t||t.length===0){this.updateLights();return}for(let e of t){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(){this.scene.getObjectsByProperty(`isLight`,!0).forEach(e=>{e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}},sy=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>cy(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0});for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4)}let u=new r.DataArrayTexture(s,i,a,o);u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.format=r.RGBAFormat,u.type=r.UnsignedByteType,u.generateMipmaps=!1,u.needsUpdate=!0;let d=this.texture;return this.texture=u,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=u,this.pathTracer.shaderBuilder?.updateGoboMaps?.(u),d?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return console.warn(`GoboManager: unknown gobo "${t}"`),!1;o.userData.gobo={name:e.name,index:e.index,intensity:ly(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function cy(e){return new Promise((t,n)=>{let r=new Image;r.crossOrigin=`anonymous`,r.onload=()=>t(r),r.onerror=()=>n(Error(`Failed to load gobo image: ${e}`)),r.src=e})}function ly(e){return Math.max(0,Math.min(1,e))}function uy(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
972
- `,n);if(r<0)throw Error(`IES (${t}): truncated TILT line`);let i=e.slice(n,r).match(/TILT\s*=\s*(\w+)/i),a=i?i[1].toUpperCase():`NONE`,o=e.slice(r);if(a===`INCLUDE`){let e=my(o),t=2+2*Number(e[1]);o=hy(o,t)}let s=my(o),c=0,l=()=>Number(s[c++]),u=l(),d=l(),f=l(),p=l(),m=l(),h=l();l(),l(),l(),l();let g=l();if(l(),l(),!Number.isFinite(p)||p<=0)throw Error(`IES (${t}): invalid vertical angle count ${p}`);if(!Number.isFinite(m)||m<=0)throw Error(`IES (${t}): invalid horizontal angle count ${m}`);let _=Array(p);for(let e=0;e<p;e++)_[e]=l();let v=Array(m);for(let e=0;e<m;e++)v[e]=l();let y=Array(p);for(let e=0;e<p;e++)y[e]=new Float32Array(m);let b=f*g,x=0;for(let e=0;e<m;e++)for(let t=0;t<p;t++){let n=l()*b;y[t][e]=n,n>x&&(x=n)}return{verticalAngles:_,horizontalAngles:v,candela:y,maxCandela:x,lumens:d*u,photometricType:h,name:t}}function dy(e,t,n){let r=new Uint8Array(t*n),{verticalAngles:i,horizontalAngles:a,candela:o,maxCandela:s}=e;if(s<=0)return r;let c=i[i.length-1],l=a[a.length-1],u=a[0],d=a.length===1||l===u;for(let e=0;e<n;e++){let f=(e+.5)/n*c,p=gy(i,f),m=Math.min(p+1,i.length-1),h=i[m]-i[p],g=h>0?(f-i[p])/h:0;for(let n=0;n<t;n++){let i;if(d)i=_y(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=gy(a,e),s=Math.min(r+1,a.length-1),c=a[s]-a[r],d=c>0?(e-a[r])/c:0,f=o[p][r],h=o[p][s],_=o[m][r],v=o[m][s];i=_y(_y(f,h,d),_y(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function fy(e,t=.1){let{verticalAngles:n,horizontalAngles:r,candela:i,maxCandela:a}=e,o=Math.PI/4;if(a<=0||!n?.length)return o;let s=a*t,c=r.length,l=n[n.length-1],u=!1;for(let e=0;e<n.length;e++){let t=0;for(let n=0;n<c;n++)t+=i[e][n];if(t/=c,t>=s&&(u=!0),u&&t<s){l=n[e];break}}let d=l*Math.PI/180;return Math.min(Math.max(d,5*Math.PI/180),89*Math.PI/180)}function py(e,t,n=.7){let{verticalAngles:r,horizontalAngles:i,candela:a,maxCandela:o}=e;if(o<=0||!r?.length||t<=0)return 0;let s=o*n,c=i.length,l=0;for(let e=0;e<r.length;e++){let t=0;for(let n=0;n<c;n++)t+=a[e][n];if(t/=c,t>=s)l=r[e];else break}let u=t*180/Math.PI,d=u>0?1-l/u:0;return Math.min(Math.max(d,0),1)}function my(e){return e.split(/\s+/).filter(e=>e.length>0)}function hy(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function gy(e,t){if(t<=e[0])return 0;if(t>=e[e.length-1])return e.length-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function _y(e,t,n){return e+(t-e)*n}var vy=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this.texture=null,this.entries=[],this._gridWidth=128,this._gridHeight=128}async loadLibrary(e,{gridWidth:t=128,gridHeight:n=128}={}){if(!Array.isArray(e)||e.length===0)return[];this._gridWidth=t,this._gridHeight=n;let i=(await Promise.all(e.map(async e=>{try{let r=await fetch(e.url);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=uy(await r.text(),e.name);return{it:e,profile:i,grid:dy(i,t,n)}}catch(t){return console.warn(`IESManager: failed to load "${e.name}": ${t.message}`),null}}))).filter(e=>e!==null);if(i.length===0)return[];let a=i.length,o=t*n,s=new Uint8Array(o*4*a),c=[];for(let e=0;e<a;e++){let t=i[e].grid,n=e*o*4;for(let e=0;e<o;e++){let r=t[e];s[n+e*4+0]=r,s[n+e*4+1]=r,s[n+e*4+2]=r,s[n+e*4+3]=255}let r=i[e].profile,a=fy(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:py(r,a),lumens:r.lumens})}let l=new r.DataArrayTexture(s,t,n,a);l.format=r.RGBAFormat,l.type=r.UnsignedByteType,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l.generateMipmaps=!1,l.needsUpdate=!0;let u=this.texture;return this.texture=l,this.entries=c,this.pathTracer.iesProfiles=l,this.pathTracer.shaderBuilder?.updateIESProfiles?.(l),u?.dispose?.(),this.entries.map(({name:e,index:t})=>({name:e,index:t}))}getEntries(){return this.entries.slice()}setSpotLightProfile(e,t,n=1,{applyAutoCone:r=!0}={}){let i=this._findSpotLight(e),a={applied:!1,suggestedAngle:null,suggestedPenumbra:null,suggestedDecay:null,fixtureLumens:null};if(!i)return a;i.userData=i.userData||{};let o=null,s=null,c=null,l=null;if(t==null)delete i.userData.ies;else{let e=this.entries.find(e=>e.name===t);if(!e)return console.warn(`IESManager: unknown profile "${t}"`),a;l=Number.isFinite(e.lumens)?e.lumens:null,i.userData.ies={name:e.name,index:e.index,intensity:yy(n),fixtureLumens:l},r&&(Number.isFinite(e.suggestedAngle)&&(i.angle=e.suggestedAngle,o=e.suggestedAngle),Number.isFinite(e.suggestedPenumbra)&&(i.penumbra=e.suggestedPenumbra,s=e.suggestedPenumbra),i.decay=2,c=2)}return this.pathTracer.updateLights(),this._onReset?.(),{applied:!0,suggestedAngle:o,suggestedPenumbra:s,suggestedDecay:c,fixtureLumens:l}}getSpotLightProfile(e){return this._findSpotLight(e)?.userData?.ies||null}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function yy(e){return Math.max(0,Math.min(1,e))}qt(),Ar();var by=Pt(`oidn`),xy=16,Sy=null;async function Cy(){return Sy||=(await import(`oidn-web`)).initUNetFromURL,Sy}var wy={QUALITY_MODELS:{fast:{model:`rt_hdr_alb_nrm_small`,cleanAux:!1},"fast-clean":{model:`rt_hdr_calb_cnrm_small`,cleanAux:!0},balance:{model:`rt_hdr_calb_cnrm`,cleanAux:!0},high:{model:`rt_hdr_calb_cnrm_large`,cleanAux:!0}},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,tileSize:1024}},Ty=.18,Ey=256,Dy=256,Oy=`
973
- const WG: u32 = ${Ey}u;
974
- const GROUPS: u32 = ${Dy}u;
971
+ `),lg=class extends V{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:ye.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,n.uniform)(r.keyValue??.18),this.minExposureU=(0,n.uniform)(r.minExposure??.1),this.maxExposureU=(0,n.uniform)(r.maxExposure??20),this.adaptSpeedBrightU=(0,n.uniform)(r.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,n.uniform)(r.adaptSpeedDark??.5),this.epsilonU=(0,n.uniform)(r.epsilon??1e-4),this.deltaTimeU=(0,n.uniform)(1/60),this.isFirstFrameU=(0,n.uniform)(1),this.previousExposureU=(0,n.uniform)(r.initialExposure??1),this.lowPercentileU=(0,n.uniform)(r.lowPercentile??.1),this.highPercentileU=(0,n.uniform)(r.highPercentile??.9),this.centerWeightU=(0,n.uniform)(r.centerWeight??8),this.inputResW=(0,n.uniform)(1),this.inputResH=(0,n.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=r.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=r.FloatType,this._downsampleStorageTex.format=r.RGBAFormat,this._downsampleStorageTex.minFilter=r.NearestFilter,this._downsampleStorageTex.magFilter=r.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=r.FloatType,this._reductionStorageTex.format=r.RGBAFormat,this._reductionStorageTex.minFilter=r.NearestFilter,this._reductionStorageTex.magFilter=r.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationResult=(0,n.attributeArray)(1,`vec4`),this._readbackBuffer=new t.ReadbackBuffer(16),this._readbackBuffer.name=`AutoExposureAdaptation`,this._histogramBuffer=(0,n.attributeArray)(rg,`uint`).toAtomic()}_buildCompute(){this._buildDownsampleCompute(),this._buildHistogramCompute(),this._buildHistogramAnalyzeCompute(),this._buildAdaptationCompute()}_buildDownsampleCompute(){let e=this._inputTexNode,t=this._downsampleStorageTex,r=this.epsilonU,i=this.inputResW,a=this.inputResH;this._downsampleComputeNode=(0,n.Fn)(()=>{let o=(0,n.int)(n.workgroupId.x).mul(8).add((0,n.int)(n.localId.x)),s=(0,n.int)(n.workgroupId.y).mul(8).add((0,n.int)(n.localId.y)),c=i.div((0,n.float)(64)),l=a.div((0,n.float)(64)),u=(0,n.float)(o).mul(c),d=(0,n.float)(s).mul(l),f=(0,n.float)(0).toVar(),p=(0,n.float)(0).toVar();for(let t=0;t<4;t++)for(let i=0;i<4;i++){let a=Xo((0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(u.add((0,n.float)((i+.5)/4).mul(c))),(0,n.int)(d.add((0,n.float)((t+.5)/4).mul(l))))).xyz);(0,n.If)(a.greaterThan(r),()=>{f.addAssign(a.add(r).log()),p.addAssign(1)})}(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(o),(0,n.uint)(s)),(0,n.vec4)(f,p,0,1)).toWriteOnly()})().compute([64/8,64/8,1],[8,8,1])}_buildHistogramCompute(){let e=this._downsampleTarget.texture,t=this._histogramBuffer,r=this.centerWeightU;this._histogramComputeNode=(0,n.Fn)(()=>{let i=n.localId.x;(0,n.atomicStore)(t.element(i),(0,n.uint)(0)),(0,n.workgroupBarrier)();for(let a=0;a<16;a++){let o=i.mul(16).add(a),s=o.mod(64),c=o.div(64),l=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(s),(0,n.int)(c))),u=l.x,d=l.y;(0,n.If)(d.greaterThan(0),()=>{let e=(0,n.uint)(u.div(d).sub((0,n.float)(ig)).div((0,n.float)(ag)).mul((0,n.float)(rg)).floor().clamp(0,(0,n.float)(rg-1))),i=(0,n.float)(s).add(.5).div((0,n.float)(64)),a=(0,n.float)(c).add(.5).div((0,n.float)(64)),o=i.sub(.5),l=a.sub(.5),f=(0,n.uint)(o.mul(o).add(l.mul(l)).mul(r).negate().exp().mul((0,n.float)(sg)));(0,n.atomicAdd)(t.element(e),f)})}})().compute([1,1,1],[256,1,1])}_buildHistogramAnalyzeCompute(){let e=this._histogramBuffer,t=this._reductionStorageTex,r=this.lowPercentileU,i=this.highPercentileU;this._histogramAnalyzeNode=(0,n.Fn)(()=>{let a=(0,n.float)(0).toVar();(0,n.Loop)(rg,({i:t})=>{a.addAssign((0,n.float)((0,n.atomicLoad)(e.element(t))))});let o=a.mul(r),s=a.mul(i),c=(0,n.float)(0).toVar(),l=(0,n.float)(0).toVar(),u=(0,n.float)(0).toVar(),d=(0,n.float)(0).toVar();(0,n.Loop)(rg,({i:t})=>{let r=(0,n.float)((0,n.atomicLoad)(e.element(t)));d.assign(c),c.addAssign(r),(0,n.If)(d.lessThan(s).and(c.greaterThan(o)),()=>{let e=(0,n.float)(ig).add((0,n.float)(t).add(.5).mul((0,n.float)(og)));l.addAssign(e.mul(r)),u.addAssign(r)})});let f=(0,n.max)(u,(0,n.float)(1)),p=l.div(f),m=p.exp();(0,n.textureStore)(t,(0,n.uvec2)((0,n.uint)(0),(0,n.uint)(0)),(0,n.vec4)(m,a,p,1)).toWriteOnly()})().compute(1,[1,1,1])}_buildAdaptationCompute(){let e=this._reductionReadTexNode,t=this._adaptationResult,r=this.keyValueU,i=this.minExposureU,a=this.maxExposureU,o=this.adaptSpeedBrightU,s=this.adaptSpeedDarkU,c=this.deltaTimeU,l=this.isFirstFrameU,u=this.previousExposureU;this._adaptationComputeNode=(0,n.Fn)(()=>{let d=(0,n.textureLoad)(e,(0,n.ivec2)((0,n.int)(0),(0,n.int)(0))).x,f=cg(d,u,r,i,a,o,s,c,l);t.element((0,n.uint)(0)).assign(f)})().compute(1,[1,1,1])}setupEventListeners(){this.on(`pipeline:reset`,()=>this.reset()),this.on(`autoexposure:resetHistory`,()=>this.resetHistory()),this.on(`autoexposure:toggle`,e=>{this.enabled=e}),this.on(`autoexposure:updateParameters`,e=>e&&this.updateParameters(e))}render(e){if(!this.enabled)return;let t=e.getTexture(`edgeFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`pathtracer:color`);if(!t)return;let n=performance.now(),r=Math.min((n-this.lastTime)/1e3,.1);if(this.lastTime=n,this.deltaTimeU.value=this.isFirstFrame?1:r,this.isFirstFrameU.value=+!!this.isFirstFrame,this.previousExposureU.value=this.currentExposure,this.inputResW.value=t.image?.width||1,this.inputResH.value=t.image?.height||1,this._inputTexNode.value=t,this.renderer.compute(this._downsampleComputeNode),this.renderer.copyTextureToTexture(this._downsampleStorageTex,this._downsampleTarget.texture),this.renderer.compute(this._histogramComputeNode),this.renderer.compute(this._histogramAnalyzeNode),this.renderer.copyTextureToTexture(this._reductionStorageTex,this._reductionReadTarget.texture),this._reductionReadTexNode.value=this._reductionReadTarget.texture,this.renderer.compute(this._adaptationComputeNode),!this._pendingReadback){this._pendingReadback=!0;let e=this._readbackGeneration;this.renderer.getArrayBufferAsync(this._adaptationResult.value,this._readbackBuffer).then(t=>{let n=t&&t.buffer?new Float32Array(t.buffer.slice(0)):null;this._readbackBuffer.release(),this._pendingReadback=!1,n&&e===this._readbackGeneration&&this._applyReadback(n)}).catch(()=>{try{this._readbackBuffer.release()}catch{}this._pendingReadback=!1})}e.setState(`autoexposure:value`,this.currentExposure),e.setState(`autoexposure:avgLuminance`,this.currentLuminance),this.emit(`autoexposure:updated`,{exposure:this.currentExposure,luminance:this.currentLuminance,targetExposure:this.targetExposure}),this.isFirstFrame=!1}_applyReadback(e){if(!this.enabled||!e||e.length<3)return;let t=e[0],n=e[1],r=e[2];(!isFinite(t)||t<=0)&&(t=1),(!isFinite(n)||n<=0)&&(n=.18),(!isFinite(r)||r<=0)&&(r=t),this.currentExposure=t,this.currentLuminance=n,this.targetExposure=r,this.renderer.toneMappingExposure=t}reset(){this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}resetHistory(){this.isFirstFrame=!0,this.currentExposure=1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this._readbackGeneration++,this._pendingReadback=!1}setSize(){}setExposure(e){this.currentExposure=e,this.previousExposureU.value=e,this.renderer.toneMappingExposure=e}getExposure(){return this.currentExposure}getLuminance(){return this.currentLuminance}updateParameters(e){e.keyValue!==void 0&&(this.keyValueU.value=e.keyValue),e.minExposure!==void 0&&(this.minExposureU.value=e.minExposure),e.maxExposure!==void 0&&(this.maxExposureU.value=e.maxExposure),e.adaptSpeedBright!==void 0&&(this.adaptSpeedBrightU.value=e.adaptSpeedBright),e.adaptSpeedDark!==void 0&&(this.adaptSpeedDarkU.value=e.adaptSpeedDark),e.lowPercentile!==void 0&&(this.lowPercentileU.value=e.lowPercentile),e.highPercentile!==void 0&&(this.highPercentileU.value=e.highPercentile),e.centerWeight!==void 0&&(this.centerWeightU.value=e.centerWeight)}dispose(){this._downsampleComputeNode?.dispose(),this._histogramComputeNode?.dispose(),this._histogramAnalyzeNode?.dispose(),this._adaptationComputeNode?.dispose(),this._downsampleTarget?.dispose(),this._downsampleStorageTex?.dispose(),this._reductionStorageTex?.dispose(),this._reductionReadTarget?.dispose(),this._readbackBuffer?.dispose(),this._inputTexNode?.dispose(),this._reductionReadTexNode?.dispose()}},ug=class extends V{constructor(e,i={}){super(`Compositor`,{...i,executionMode:ye.ALWAYS}),this.renderer=e,this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode;let a=this._sourceTexNode.sample((0,n.uv)()),o=(0,n.mix)((0,n.vec3)((0,n.dot)(a.xyz,Uo)),a.xyz,this.saturation),s=(0,n.select)(this._transparentBackground,a.w,1);this.compositorMaterial=new t.MeshBasicNodeMaterial,this.compositorMaterial.colorNode=(0,n.vec4)(o,s),this.compositorMaterial.blending=r.NoBlending,this.compositorQuad=new t.QuadMesh(this.compositorMaterial)}_resolveSourceTexture(e){return e.getTexture(`bloom:output`)||this.resolveLightTexture(e)}resolveLightTexture(e){return e.getTexture(`oidn:output`)||e.getTexture(`edgeFiltering:output`)||e.getTexture(`bilateralFiltering:output`)||e.getTexture(`asvgf:output`)||e.getTexture(`nrd:output`)||e.getTexture(`pathtracer:color`)}_ensureDebugMaterial(){let e=this._pathTracer?.getConvergenceDebugSource?.();if(!e)return!1;if(this._debugMaterial&&this._debugM2Attr===e.m2&&this._debugMaskAttr===e.frozenMask)return!0;this._debugMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugM2Attr=e.m2,this._debugMaskAttr=e.frozenMask,this._debugTexNode=new t.TextureNode;let i=(0,n.Fn)(()=>{let t=(0,n.dot)(this._debugTexNode.sample((0,n.uv)()).toVar().xyz,Uo).toVar(),r=e.renderWidth,i=e.renderHeight,a=(0,n.int)((0,n.uv)().x.mul((0,n.float)(r))).min(r.sub((0,n.int)(1))).max((0,n.int)(0)),o=(0,n.uint)((0,n.int)((0,n.uv)().y.mul((0,n.float)(i))).min(i.sub((0,n.int)(1))).max((0,n.int)(0)).mul(r).add(a)).toVar(),s=(0,n.storage)(e.m2,`float`).toReadOnly().element(o).toVar(),c=(0,n.storage)(e.frozenMask,`uint`).toReadOnly().element(o).toVar(),l=s.sub(t.mul(t)).max((0,n.float)(0)).div((0,n.float)(e.frame).add(1)).sqrt().toVar(),u=e.usePixelFreeze.greaterThan((0,n.int)(0)),d=(0,n.select)(t.lessThan((0,n.float)(1)),t.sqrt(),t).toVar(),f=(0,n.select)(u,l.div(t.add((0,n.float)(1e-4))),l.div(d.add((0,n.float)(1e-4)))).toVar(),p=(0,n.select)(u,e.pixelFreezeThreshold,e.noiseThreshold).toVar(),m=f.div(p.max((0,n.float)(1e-6))).toVar(),h=(0,n.vec3)(t.div(t.add((0,n.float)(1))).sqrt().mul(.55)).toVar(),g=h.toVar(),_=(0,n.float)(e.frame).greaterThanEqual((0,n.float)(e.adaptiveMinSamples));return(0,n.If)(m.greaterThanEqual((0,n.float)(1)).or(_.not()),()=>{let e=(0,n.mix)((0,n.vec3)(1,.8,.1),(0,n.vec3)(1,.1,.05),m.sub(1).div(3).clamp(0,1));g.assign((0,n.mix)(h,e,.85))}),(0,n.If)(c.equal((0,n.uint)(1)).and(u),()=>{g.assign((0,n.mix)(h,(0,n.vec3)(.1,.45,1),.55))}),g});return this._debugMaterial=new t.MeshBasicNodeMaterial,this._debugMaterial.colorNode=(0,n.vec4)(i().pow(2.2).mul(this._debugExposureComp),1),this._debugMaterial.blending=r.NoBlending,this._debugQuad=new t.QuadMesh(this._debugMaterial),!0}render(e){if(!this.enabled)return;if(this._convergenceOverlay&&this._ensureDebugMaterial()){let t=e.getTexture(`pathtracer:color`);if(t){this._debugTexNode.value=t;let e=this.renderer.toneMapping!==r.NoToneMapping;this._debugExposureComp.value=e?1/Math.max(this.renderer.toneMappingExposure,1e-4):1,this.renderer.setRenderTarget(null),this._debugQuad.render(this.renderer);return}}let t=this._resolveSourceTexture(e);t&&(this._sourceTexNode.value=t,this.renderer.setRenderTarget(null),this.compositorQuad.render(this.renderer))}setConvergenceOverlay(e){this._convergenceOverlay=!!e}setSaturation(e){this.saturation.value=e}setTransparentBackground(e){this._transparentBackground.value=+!!e}dispose(){this._sourceTexNode?.dispose(),this.compositorMaterial?.dispose(),this._debugTexNode?.dispose(),this._debugMaterial?.dispose(),this.compositorQuad=null,this._debugQuad=null,this._debugMaterial=null,this._debugTexNode=null,this._pathTracer=null}},dg=class{constructor(){this.textures=new Map,this.renderTargets=new Map,this.uniforms=new Map,this.state={frame:0,accumulatedFrames:0,renderMode:0,interactionMode:!1,isComplete:!1,tileInfo:null,currentTile:0,totalTiles:0,cameraChanged:!1,cameraMoving:!1,width:0,height:0,time:0,deltaTime:0,enableASVGF:!1,enableEdgeFiltering:!1},this._stateChangeCallbacks=new Map}setTexture(e,t){this.textures.set(e,t)}getTexture(e){return this.textures.get(e)}hasTexture(e){return this.textures.has(e)}removeTexture(e){this.textures.delete(e)}getTextureNames(){return Array.from(this.textures.keys())}clearTextures(){this.textures.clear()}setRenderTarget(e,t){this.renderTargets.set(e,t)}getRenderTarget(e){return this.renderTargets.get(e)}hasRenderTarget(e){return this.renderTargets.has(e)}removeRenderTarget(e){this.renderTargets.delete(e)}getRenderTargetNames(){return Array.from(this.renderTargets.keys())}clearRenderTargets(){this.renderTargets.clear()}setUniform(e,t){this.uniforms.has(e)?this.uniforms.get(e).value=t:this.uniforms.set(e,{value:t})}getUniform(e){return this.uniforms.get(e)}getUniformValue(e){return this.uniforms.get(e)?.value}hasUniform(e){return this.uniforms.has(e)}removeUniform(e){this.uniforms.delete(e)}getUniformNames(){return Array.from(this.uniforms.keys())}clearUniforms(){this.uniforms.clear()}setState(e,t){let n=this.state[e],r=n!==t;return r&&(this.state[e]=t,this._notifyStateChange(e,t,n)),r}getState(e){return this.state[e]}getAllState(){return this.state}setStates(e){let t=[];for(let[n,r]of Object.entries(e))this.setState(n,r)&&t.push(n);return t}hasState(e){return e in this.state}watchState(e,t){this._stateChangeCallbacks.has(e)||this._stateChangeCallbacks.set(e,[]),this._stateChangeCallbacks.get(e).push(t)}unwatchState(e,t){if(!this._stateChangeCallbacks.has(e))return;let n=this._stateChangeCallbacks.get(e),r=n.indexOf(t);r>-1&&n.splice(r,1)}_notifyStateChange(e,t,n){if(!this._stateChangeCallbacks.has(e))return;let r=this._stateChangeCallbacks.get(e);for(let i of r)try{i(t,n)}catch(t){console.error(`Error in state change callback for '${e}':`,t)}}reset(){this.state.frame=0,this.state.accumulatedFrames=0,this.state.isComplete=!1,this.state.cameraChanged=!0,this.state.currentTile=0}incrementFrame(){return this.state.frame++,this.state.accumulatedFrames++,this.state.frame}dispose(){this.textures.clear(),this.renderTargets.clear(),this.uniforms.clear(),this._stateChangeCallbacks.clear(),this.state={}}},fg=class extends r.EventDispatcher{constructor(){super(),this._onceCallbacks=new Map}on(e,t){this.addEventListener(e,t)}once(e,t){let n=r=>{t(r),this.off(e,n),this._onceCallbacks.delete(t)};this._onceCallbacks.set(t,n),this.on(e,n)}off(e,t){let n=this._onceCallbacks.get(t);n?(this.removeEventListener(e,n),this._onceCallbacks.delete(t)):this.removeEventListener(e,t)}emit(e,t){t&&typeof t==`object`&&t.type?this.dispatchEvent(t):this.dispatchEvent({type:e,...t})}removeAllListeners(e){if(e){for(let[t,n]of this._onceCallbacks.entries())this.hasEventListener(e,n)&&(this.removeEventListener(e,n),this._onceCallbacks.delete(t));this._listeners&&this._listeners[e]&&delete this._listeners[e]}else this._onceCallbacks.clear(),this._listeners&&={}}listenerCount(e){return!this._listeners||!this._listeners[e]?0:this._listeners[e].length}clear(){this.removeAllListeners()}eventNames(){return this._listeners?Object.keys(this._listeners):[]}},pg=!1,mg=[],hg=new WeakMap;function gg(e){pg=!!e}function _g(){return mg.slice()}function vg(){mg.length=0}function yg(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var bg=e=>!e||!e.image||!(e.image.width>0);function xg(e,t,n){if(!pg){n();return}let r=hg.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},hg.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&Sg(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=yg(e).filter(t=>bg(e[t].value)),r.phase=r.unboundAtCompile.length<2?`done`:`watch`),a.apply(this,t)};try{n()}finally{i?t.compute=a:delete t.compute}}function Sg(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(bg(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&mg.push({stage:e.name,nodes:n,unboundAtCompile:t.unboundAtCompile.slice(),message:`${e.name}: ${n.join(`, `)} ${n.length===1?`was`:`were`} still holding EmptyTexture when the stage first dispatched, alongside ${t.unboundAtCompile.length-n.length} other unbound node(s), and later received a non-storage texture. Two nodes unbound at compile time can share one GPU binding and then both resolve to whichever is assigned last. Assign these before the first dispatch.`})}var Cg=class{_reportStageFailure(e,t,n){console.error(`[Pipeline] Error in stage '${e}' (${t}):`,n);let r=`${e}:${t}`;this._reportedStageFailures.has(r)||(this._reportedStageFailures.add(r),this._issues?.record(ln.STAGE_RENDER_FAILED,`stage "${e}" threw during ${t} — the frame is incomplete`,{stage:e,phase:t,cause:String(n?.message??n)}))}constructor(e,t,n,{issues:r=null}={}){this.renderer=e,this._issues=r,this._reportedStageFailures=new Set,this.width=t,this.height=n,this.stages=[],this.context=new dg,this.eventBus=new fg,this.context.setState(`width`,t),this.context.setState(`height`,n),this.stats={enabled:!1,logSkipped:!1,timings:new Map,frameCount:0}}addStage(e){this.stages.push(e),e.initialize(this.context,this.eventBus),this.stats.enabled&&console.log(`[Pipeline] Added stage: ${e.name}`)}getStage(e){return this.stages.find(t=>t.name===e)}removeStage(e){let t=this.stages.findIndex(t=>t.name===e);if(t>-1){let e=this.stages[t];return this.stages.splice(t,1),e.dispose&&e.dispose(),this.stats.timings.delete(e.name),!0}return!1}setStageEnabled(e,t){let n=this.getStage(e);n&&(t?n.enable():n.disable())}render(e=null){let t=this.stats.enabled?performance.now():0;for(let t of this.stages){if(!t.shouldExecuteThisFrame(this.context)){this.stats.enabled&&this.stats.logSkipped&&console.log(`[Pipeline] Skipped stage '${t.name}' (executionMode: ${t.executionMode})`);continue}try{let n=this.stats.enabled?performance.now():0;if(xg(t,this.renderer,()=>t.render(this.context,e)),this.stats.enabled){let e=performance.now()-n;this.stats.timings.has(t.name)||this.stats.timings.set(t.name,[]);let r=this.stats.timings.get(t.name);r.push(e),r.length>60&&r.shift()}}catch(e){this._reportStageFailure(t.name,`render`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){this._reportStageFailure(e.name,`reset`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),e.totalMin===void 0?console.log(`Total: no frames recorded yet (pipeline.render() has not run since stats were enabled — the path tracer may have converged and stopped its animation loop)`):console.log(`Total: ${e.total.toFixed(2)}ms (min: ${e.totalMin.toFixed(2)}ms, max: ${e.totalMax.toFixed(2)}ms)`);for(let[t,n]of Object.entries(e.stages))console.log(` ${t}: ${n.avg.toFixed(2)}ms (min: ${n.min.toFixed(2)}ms, max: ${n.max.toFixed(2)}ms)`);console.groupEnd()}getInfo(){return{stageCount:this.stages.length,enabledStages:this.stages.filter(e=>e.enabled).length,stages:this.stages.map(e=>({name:e.name,enabled:e.enabled})),contextState:this.context.getAllState(),textures:this.context.getTextureNames(),renderTargets:this.context.getRenderTargetNames(),uniforms:this.context.getUniformNames(),events:this.eventBus.eventNames()}}logInfo(){let e=this.getInfo();console.group(`[Pipeline] Info`),console.log(`Stages:`,e.stages),console.log(`Context Textures:`,e.textures),console.log(`Context Render Targets:`,e.renderTargets),console.log(`Context Uniforms:`,e.uniforms),console.log(`Event Types:`,e.events),console.log(`State:`,e.contextState),console.groupEnd()}};qt();var wg=Pt(`engine`),Tg=class{constructor(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}updateTime(){this.timeElapsed=(performance.now()-this.lastResetTime)/1e3}isTimeLimitReached(e,t,n){return t!==`time`||!(n>0)||this.timeElapsed<n?!1:e?.frameCount>0?(this.budgetOverrun=!0,!0):(this._budgetHeldWarned||(this._budgetHeldWarned=!0,wg.warn(`render time limit (${n}s) expired before the first sample landed — holding the deadline open to avoid capturing an empty frame`)),!1)}isLimitReached(e,t,n){return e?this.isTimeLimitReached(e,t,n)?!0:this.stopCondition(e)!==null:!1}stopCondition(e){return this.budgetOverrun?`timeLimit`:e?e.frameCount>=e.completionThreshold?`samples`:e._isConvergedComplete?.()?`converged`:null:null}markComplete(){return this.renderCompleteDispatched?!1:(this.renderCompleteDispatched=!0,!0)}reset(){this.timeElapsed=0,this.lastResetTime=performance.now(),this.renderCompleteDispatched=!1,this.budgetOverrun=!1,this._budgetHeldWarned=!1}resumeFromPause(){this.renderCompleteDispatched=!1,this.lastResetTime=performance.now()-this.timeElapsed*1e3}},Eg=class{constructor(e){this.renderer=e,this.target=null,this.material=new t.NodeMaterial,this.material.name=`rayzee:texture-readback`,this.quad=new t.QuadMesh(this.material),this._node=null,this._source=null}_ensureTarget(e,t){this.target&&this.target.width===e&&this.target.height===t||(this.target?.dispose(),this.target=new r.RenderTarget(e,t,{type:r.FloatType,format:r.RGBAFormat,depthBuffer:!1,minFilter:r.NearestFilter,magFilter:r.NearestFilter}))}async read(e,t,r){this._ensureTarget(t,r),this._source!==e&&(this._node=(0,n.texture)(e).load((0,n.ivec2)(n.screenCoordinate.xy)),this.material.outputNode=this._node,this.material.needsUpdate=!0,this._source=e);let i=this.renderer.getRenderTarget();this.renderer.setRenderTarget(this.target),this.quad.render(this.renderer),this.renderer.setRenderTarget(i);try{return await this.renderer.readRenderTargetPixelsAsync(this.target,0,0,t,r)}finally{this.target.dispose(),this.target=null}}dispose(){this.target?.dispose(),this.material.dispose(),this.target=null,this._source=null,this._node=null}};xe();var Dg=class extends r.EventDispatcher{constructor({scene:e,camera:t,canvas:n,assetLoader:i,pathTracer:a,floorPlane:o}){super(),this.scene=e,this.camera=t,this.canvas=n,this.assetLoader=i,this.pathTracer=a,this.floorPlane=o,this.raycaster=new r.Raycaster,this.focusMode=!1,this.focusPointIndicator=null,this.afPointPlacementMode=!1,this.handleAFPointClick=this.handleAFPointClick.bind(this),this.selectedObject=null,this.selectMode=!1,this.clickTimeout=null,this.mouseDownPosition=null,this.dragThreshold=5,this.handleFocusClick=this.handleFocusClick.bind(this),this.handleSelectClick=this.handleSelectClick.bind(this),this.handleSelectDoubleClick=this.handleSelectDoubleClick.bind(this),this.handleMouseDown=this.handleMouseDown.bind(this),this.handleMouseUp=this.handleMouseUp.bind(this),this.handleContextMenu=this.handleContextMenu.bind(this),this.handleContextPointerDown=this.handleContextPointerDown.bind(this),this.handleContextPointerUp=this.handleContextPointerUp.bind(this),this.contextPointerDownPosition=null,this.canvas.addEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.addEventListener(`pointerup`,this.handleContextPointerUp),this.canvas.addEventListener(`contextmenu`,this.handleContextMenu),this._overlayManager=null,this._transformManager=null,this._appDispatch=null,this._orbitControls=null,this._helperScene=null}setDependencies({overlayManager:e,transformManager:t,appDispatch:n,orbitControls:r,helperScene:i}){this._overlayManager=e||null,this._transformManager=t||null,this._appDispatch=n||null,this._orbitControls=r||null,this._helperScene=i||null}select(e){let t=this._overlayManager?.getHelper(`outline`);t&&t.setSelectedObjects(e?[e]:[]),this.selectedObject=e||null,e?this._transformManager?.attach(e):this._transformManager?.detach(),this._appDispatch?.({type:H.OBJECT_SELECTED,object:e||null})}deselect(){this.select(null)}disableMode(){this.disableSelectMode(),this._transformManager?.detach()}on(e,t){return this.addEventListener(e,t),()=>this.removeEventListener(e,t)}toggleFocusMode(){return this.focusMode=!this.focusMode,this.canvas.style.cursor=this.focusMode?`crosshair`:`auto`,this.focusMode?this.canvas.addEventListener(`click`,this.handleFocusClick):this.canvas.removeEventListener(`click`,this.handleFocusClick),this._orbitControls&&(this._orbitControls.enabled=!this.focusMode),this.dispatchEvent({type:`focusModeChanged`,enabled:this.focusMode}),this.focusMode}handleFocusClick(e){let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0);if(n.length>0){let e=n[0],t=e.distance;this.showFocusPoint(e.point),this.toggleFocusMode(),this.dispatchEvent({type:`focusChanged`,distance:t/this.assetLoader.getSceneScale(),worldDistance:t})}}showFocusPoint(e){this.focusPointIndicator&&this.scene.remove(this.focusPointIndicator),this.focusPointIndicator=new r.Mesh(new r.SphereGeometry(this.assetLoader.getSceneScale()*.02,16,16),new r.MeshBasicMaterial({color:65280,transparent:!0,opacity:.8,depthTest:!1})),this.focusPointIndicator.position.copy(e),this.scene.add(this.focusPointIndicator),setTimeout(()=>{this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null)},2e3)}enterAFPointPlacementMode(){this.afPointPlacementMode=!0,this.canvas.style.cursor=`crosshair`,this.canvas.addEventListener(`click`,this.handleAFPointClick)}exitAFPointPlacementMode(){this.afPointPlacementMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`click`,this.handleAFPointClick)}handleAFPointClick(e){let t=this.canvas.getBoundingClientRect(),n=(e.clientX-t.left)/t.width,r=(e.clientY-t.top)/t.height;this.exitAFPointPlacementMode(),this.dispatchEvent({type:`afPointPlaced`,point:{x:n,y:r}})}toggleSelectMode(){return this.selectMode=!this.selectMode,this.canvas.style.cursor=this.selectMode?`pointer`:`auto`,this.selectMode?(this.canvas.addEventListener(`mousedown`,this.handleMouseDown),this.canvas.addEventListener(`mouseup`,this.handleMouseUp),this.canvas.addEventListener(`click`,this.handleSelectClick),this.canvas.addEventListener(`dblclick`,this.handleSelectDoubleClick)):(this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null),this.dispatchEvent({type:`selectModeChanged`,enabled:this.selectMode}),this.selectMode}disableSelectMode(){this.selectMode&&(this.selectMode=!1,this.canvas.style.cursor=`auto`,this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.dispatchEvent({type:`selectModeChanged`,enabled:!1}))}handleMouseDown(e){this.mouseDownPosition={x:e.clientX,y:e.clientY,button:e.button}}wasMouseDragged(e){if(!this.mouseDownPosition)return!1;let t=Math.abs(e.clientX-this.mouseDownPosition.x),n=Math.abs(e.clientY-this.mouseDownPosition.y);return Math.sqrt(t*t+n*n)>this.dragThreshold}handleSelectClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}if(this.mouseDownPosition=null,this.clickTimeout){clearTimeout(this.clickTimeout),this.clickTimeout=null;return}this.clickTimeout=setTimeout(()=>{this.clickTimeout=null;let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n),i=this._pickLightHelper(),a=null;if(r.length>0&&i?a=r[0].distance<=i.distance?r[0].object:i.light:r.length>0?a=r[0].object:i&&(a=i.light),a){let e=this.selectedObject;e&&e.uuid===a.uuid?this.dispatchEvent({type:`objectDeselected`,object:a,uuid:a.uuid}):this.dispatchEvent({type:`objectSelected`,object:a,uuid:a.uuid})}else this.dispatchEvent({type:`objectDeselected`})},250)}handleSelectDoubleClick(e){if(this.wasMouseDragged(e)){this.mouseDownPosition=null;return}this.mouseDownPosition=null,this.clickTimeout&&=(clearTimeout(this.clickTimeout),null);let t=this.getMouseCoordinates(e);this.raycaster.setFromCamera(t,this.camera);let n=this.raycaster.intersectObjects(this.scene.children,!0),r=this.filterValidIntersects(n);if(r.length>0){let e=r[0].object;this.dispatchEvent({type:`objectDoubleClicked`,object:e,uuid:e.uuid})}}handleMouseUp(){}handleContextPointerDown(e){e.button===2&&(this.contextPointerDownPosition={x:e.clientX,y:e.clientY})}handleContextPointerUp(e){if(e.button!==2)return;if(this.contextPointerDownPosition){let t=Math.abs(e.clientX-this.contextPointerDownPosition.x),n=Math.abs(e.clientY-this.contextPointerDownPosition.y);if(Math.sqrt(t*t+n*n)>this.dragThreshold){this.contextPointerDownPosition=null;return}}else return;this.contextPointerDownPosition=null;let t=this.selectedObject;t&&this.dispatchEvent({type:`contextMenuRequested`,x:e.clientX,y:e.clientY,selectedObject:t})}handleContextMenu(e){e.preventDefault()}getMouseCoordinates(e){let t=this.canvas.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height)*2+1}}filterValidIntersects(e){return e.filter(e=>{let t=e.object;return t!==this.focusPointIndicator&&t!==this.floorPlane&&!t.name.includes(`Helper`)&&t.type===`Mesh`})}_pickLightHelper(){if(!this._helperScene||this._helperScene.children.length===0)return null;let e=this.raycaster.intersectObjects(this._helperScene.children,!0);for(let t of e){let e=t.object;for(;e;){if(e.light)return{distance:t.distance,light:e.light};e=e.parent}}return null}updateDependencies({scene:e,camera:t,floorPlane:n}){e&&(this.scene=e),t&&(this.camera=t),n&&(this.floorPlane=n)}wireAppEvents(e){this.addEventListener(`objectSelected`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:H.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:H.OBJECT_DOUBLE_CLICKED,object:t.object,uuid:t.uuid})}),this.addEventListener(`focusChanged`,t=>{e.settings.set(`focusDistance`,t.worldDistance),e.dispatchEvent({type:`focusChanged`,distance:t.distance})}),this.addEventListener(`afPointPlaced`,t=>{e.dispatchEvent({type:H.AF_POINT_PLACED,point:t.point})})}dispose(){this.canvas.removeEventListener(`click`,this.handleAFPointClick),this.canvas.removeEventListener(`click`,this.handleFocusClick),this.canvas.removeEventListener(`mousedown`,this.handleMouseDown),this.canvas.removeEventListener(`mouseup`,this.handleMouseUp),this.canvas.removeEventListener(`click`,this.handleSelectClick),this.canvas.removeEventListener(`dblclick`,this.handleSelectDoubleClick),this.canvas.removeEventListener(`contextmenu`,this.handleContextMenu),this.canvas.removeEventListener(`pointerdown`,this.handleContextPointerDown),this.canvas.removeEventListener(`pointerup`,this.handleContextPointerUp),this.clickTimeout&&=(clearTimeout(this.clickTimeout),null),this.mouseDownPosition=null,this.contextPointerDownPosition=null,this.focusPointIndicator&&=(this.scene.remove(this.focusPointIndicator),null),this.canvas.style.cursor=`auto`,this.scene=null,this.camera=null,this.canvas=null,this.assetLoader=null,this.pathTracer=null,this.floorPlane=null,this.raycaster=null}};xe();var Og={maxBounces:{uniform:`maxBounces`,reset:!0},transmissiveBounces:{uniform:`transmissiveBounces`,reset:!0},maxSubsurfaceSteps:{uniform:`maxSubsurfaceSteps`,reset:!0},maxTransparentBounces:{uniform:`maxTransparentBounces`,reset:!0},environmentIntensity:{uniform:`environmentIntensity`,reset:!0},backgroundIntensity:{uniform:`backgroundIntensity`,reset:!0},backgroundBlurriness:{uniform:`backgroundBlurriness`,reset:!0},backgroundBlurSamples:{uniform:`backgroundBlurSamples`,reset:!0},showBackground:{uniform:`showBackground`,reset:!0},enableEnvironment:{uniform:`enableEnvironment`,reset:!0},groundProjectionEnabled:{uniform:`groundProjectionEnabled`,reset:!0},groundProjectionRadius:{uniform:`groundProjectionRadius`,reset:!0},groundProjectionHeight:{uniform:`groundProjectionHeight`,reset:!0},groundProjectionLevel:{uniform:`groundProjectionLevel`,reset:!0},enableGroundCatcher:{uniform:`enableGroundCatcher`,reset:!0},groundCatcherHeight:{uniform:`groundCatcherHeight`,reset:!0},globalIlluminationIntensity:{uniform:`globalIlluminationIntensity`,reset:!0},panoramaLevelHorizon:{uniform:`panoLevelHorizon`,reset:!0},enableDOF:{uniform:`enableDOF`,reset:!0},focusDistance:{uniform:`focusDistance`,reset:!1},focalLength:{uniform:`focalLength`,reset:!0},aperture:{uniform:`aperture`,reset:!0},apertureScale:{uniform:`apertureScale`,reset:!0},anamorphicRatio:{uniform:`anamorphicRatio`,reset:!0},samplingTechnique:{uniform:`samplingTechnique`,reset:!0},fireflyThreshold:{uniform:`fireflyThreshold`,reset:!0},shadowTerminatorOffset:{uniform:`shadowTerminatorOffset`,reset:!0},enableAlphaShadows:{uniform:`enableAlphaShadows`,reset:!0},useAdaptiveSampling:{uniform:`useAdaptiveSampling`,reset:!0},noiseThreshold:{uniform:`noiseThreshold`,reset:!0},adaptiveMinSamples:{uniform:`adaptiveMinSamples`,reset:!0},adaptiveStopFraction:{uniform:`adaptiveStopFraction`,reset:!0},usePixelFreeze:{uniform:`usePixelFreeze`,reset:!0},pixelFreezeThreshold:{uniform:`pixelFreezeThreshold`,reset:!0},pixelFreezeStability:{uniform:`pixelFreezeStability`,reset:!0},convergenceOverlay:{handler:`handleConvergenceOverlay`,reset:!1},enableEmissiveTriangleSampling:{uniform:`enableEmissiveTriangleSampling`,reset:!0},emissiveBoost:{uniform:`emissiveBoost`,reset:!0},visMode:{uniform:`visMode`,reset:!0},debugVisScale:{uniform:`debugVisScale`,reset:!0},cameraProjection:{handler:`handleCameraProjection`,reset:!0},panoramaLonRange:{handler:`handlePanoramaLonRange`,reset:!0},panoramaLatRange:{handler:`handlePanoramaLatRange`,reset:!0},interactionModeEnabled:{handler:`handleInteractionModeEnabled`,reset:!1},interactionRenderScale:{handler:`handleInteractionRenderScale`,reset:!1},maxSamples:{handler:`handleMaxSamples`,reset:!1},transparentBackground:{handler:`handleTransparentBackground`},backgroundColor:{handler:`handleBackgroundColor`,reset:!0},exposure:{handler:`handleExposure`},saturation:{handler:`handleSaturation`},renderLimitMode:{handler:`handleRenderLimitMode`},renderTimeLimit:{handler:`handleRenderTimeLimit`,reset:!1},renderMode:{handler:`handleRenderMode`},environmentRotation:{handler:`handleEnvironmentRotation`}},kg=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),Ag={bounces:`maxBounces`,debugMode:`visMode`},jg=class extends r.EventDispatcher{constructor(e=W,{issues:t=null}={}){super(),this._issues=t,this._values=new Map,this._sources=new Map,this._pathTracer=null,this._resetCallback=null,this._handlers={},this._delegates={},this._initDefaults(e)}bind(e){this._pathTracer=e.stages.pathTracer,this._resetCallback=e.resetCallback,this._delegates={},this._handlers=this._buildHandlers(e)}_buildHandlers({stages:e,renderer:t,resetCallback:n,reconcileCompletion:i,denoisingManager:a,cameraManager:o,onInteractionRenderScale:s}){let c=new r.Vector2,l=(t,n)=>{c.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,c)};return{handleCameraProjection:t=>{let n=t===`equirectangular`;e.pathTracer?.setUniform(`cameraProjection`,+!!n),n&&(a?.requiresMotionVectors&&a.setDenoiserStrategy(`edgeaware`),o?.setAutoFocusMode(`manual`))},handlePanoramaLonRange:e=>l(`panoLonRange`,e),handlePanoramaLatRange:e=>l(`panoLatRange`,e),handleTransparentBackground:t=>{e.pathTracer?.setUniform(`transparentBackground`,t),e.compositor?.setTransparentBackground(t)},handleBackgroundColor:t=>{let n=t?.isColor?t:new r.Color(t);e.pathTracer?.setUniform(`backgroundColor`,n)},handleExposure:n=>{!e.autoExposure?.enabled&&t&&(t.toneMappingExposure=n)},handleSaturation:t=>{e.compositor?.setSaturation(t)},handleConvergenceOverlay:t=>{e.pathTracer?.setUniform(`convergenceOverlay`,t),e.compositor?.setConvergenceOverlay(t),t&&!this.get(`useAdaptiveSampling`)&&n?.()},handleRenderLimitMode:t=>{e.pathTracer?.setRenderLimitMode?.(t),i?.()},handleMaxSamples:t=>{e.pathTracer?.setUniform(`maxSamples`,t),e.pathTracer?.updateCompletionThreshold(),i?.()},handleRenderTimeLimit:()=>{i?.()},handleRenderMode:t=>{e.pathTracer?.setUniform(`renderMode`,parseInt(t))},handleEnvironmentRotation:t=>{e.pathTracer?.environment.setEnvironmentRotation(t)},handleInteractionModeEnabled:t=>{e.pathTracer?.setInteractionModeEnabled(t)},handleInteractionRenderScale:e=>{s?.(e)}}}set(e,t,{reset:n,silent:r,source:i=kg.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:H.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=kg.HOST}={}){let i=!1;for(let[n,a]of Object.entries(e)){let e=this._applyOne(n,a,r);e?.route&&((e.route.reset??!0)&&(i=!0),t||this.dispatchEvent({type:H.SETTING_CHANGED,key:n,value:a,prev:e.prev}))}(n===void 0?i:n)&&this._resetCallback?.()}_applyOne(e,t,n){let r=this._values.get(e);if(r===t)return null;this._values.set(e,t),this._sources.set(e,n);let i=Og[e];return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(ln.SETTING_UNKNOWN_KEY,`unknown setting "${e}" — stored but never applied to any stage`,{key:e})}get(e){return this._values.get(e)}getEffective(){let e={};for(let[t,n]of this._values)e[t]={value:n,source:this._sources.get(t)??kg.DEFAULT,routed:Og[t]!==void 0};return e}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=Og[e];n&&this._applyRoute(n,t,void 0)}}_applyRoute(e,t,n){e.uniform?(this._pathTracer?.setUniform(e.uniform,t),e.after&&this._pathTracer?.[e.after]?.()):e.handler?this._handlers[e.handler]?.(t,n):e.delegate&&this._delegates[e.delegate]?.updateParam?.(e.param,t)}_initDefaults(e){for(let t of Object.keys(Og))t in e&&(this._values.set(t,e[t]),this._sources.set(t,kg.DEFAULT));for(let[t,n]of Object.entries(Ag))t in e&&(this._values.set(n,e[t]),this._sources.set(n,kg.DEFAULT))}},Mg=512,Ng=4<<20,Pg=15e8,Fg=new TextDecoder;function Ig(e){return e.length>=2&&e[0]===31&&e[1]===139}function Lg(e){return e.length>=4&&e[0]===80&&e[1]===75&&(e[2]===3||e[2]===5||e[2]===7)}function Rg(e){return e.length>=263&&String.fromCharCode(...e.subarray(257,262))===`ustar`}function zg(e){return Ig(e)?`gzip`:Lg(e)?`zip`:Rg(e)?`tar`:null}function Bg(e,t,n){let r=t,i=t+n;for(;r<i&&e[r]!==0;)r++;return Fg.decode(e.subarray(t,r))}function Vg(e,t,n){if(e[t]&128){let r=e[t]&127;for(let i=t+1;i<t+n;i++)r=r*256+e[i];return r}let r=Bg(e,t,n).trim();if(!r)return 0;let i=parseInt(r,8);return Number.isFinite(i)?i:0}function Hg(e){let t=[];for(let n of e.replace(/\\/g,`/`).split(`/`))n===``||n===`.`||(n===`..`?t.pop():t.push(n));return t.join(`/`)}function Ug(e){let t=Fg.decode(e).match(/^\d+ path=(.*)$/m);return t?t[1]:null}var Wg=class{constructor({filter:e=null,retain:t=null,byteBudget:n=Pg,onEntry:r=null}={}){this.filter=e,this.retain=t,this.byteBudget=n,this.onEntry=r,this.entries=Object.create(null),this.listing=[],this.retainedBytes=0,this.truncated=!1,this.finished=!1,this._header=new Uint8Array(Mg),this._headerLen=0,this._state=`header`,this._remaining=0,this._size=0,this._copied=0,this._dst=null,this._special=null,this._pendingName=null,this._abs=0}push(e){let t=this._abs;this._abs+=e.length;let n=0;for(;n<e.length&&!this.finished;)if(this._state===`header`){let r=Math.min(Mg-this._headerLen,e.length-n);this._header.set(e.subarray(n,n+r),this._headerLen),this._headerLen+=r,n+=r,this._headerLen===Mg&&(this._headerLen=0,this._readHeader(),this._bodyStart=t+n)}else{let t=Math.min(this._remaining,e.length-n);if(this._dst&&this._copied<this._size){let r=Math.min(t,this._size-this._copied);this._dst.set(e.subarray(n,n+r),this._copied),this._copied+=r}this._remaining-=t,n+=t,this._remaining===0&&this._endBody()}}end(){this.finished=!0}result(){return{entries:this.entries,listing:this.listing,retainedBytes:this.retainedBytes,truncated:this.truncated}}_readHeader(){let e=this._header,t=!0;for(let n=0;n<Mg;n++)if(e[n]!==0){t=!1;break}if(t){this.finished=!0;return}let n=String.fromCharCode(e[156]||48),r=Vg(e,124,12),i=Bg(e,345,155),a=Bg(e,0,100),o=this._pendingName??(i?`${i}/${a}`:a);if(this._pendingName=null,this._size=r,this._copied=0,this._remaining=r+(Mg-r%Mg)%Mg,this._dst=null,this._special=null,this._state=this._remaining>0?`body`:`header`,n===`L`||n===`x`||n===`X`){this._special=n===`L`?`longname`:`pax`,this._dst=new Uint8Array(r);return}if(n===`5`||n===`g`||n===`K`||o.endsWith(`/`)||n!==`0`&&n!==` `)return;let s=Hg(o);if(s&&(this.listing.push({path:s,size:r}),(!this.filter||this.filter(s,r))&&(this._indexed=!0,!(this.retain&&!this.retain(s,r))))){if(this.retainedBytes+r>this.byteBudget){this.truncated=!0;return}this._dst=new Uint8Array(r),this.retainedBytes+=r}}_endBody(){if(this._state=`header`,this._special===`longname`){this._pendingName=Bg(this._dst,0,this._dst.length),this._dst=null;return}if(this._special===`pax`){let e=Ug(this._dst);e&&(this._pendingName=e),this._dst=null;return}let e=this.listing[this.listing.length-1];this._indexed&&e&&(e.offset=this._bodyStart,this._indexed=!1),this._dst&&=(this.entries[e.path]=this._dst,this.onEntry?.(e.path,this._dst),null)}};async function Gg(e,t){if(typeof DecompressionStream<`u`&&typeof e?.stream==`function`){let n=e.stream().pipeThrough(new DecompressionStream(`gzip`)).getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;t(r)}return}let n=null,r=new m.Gunzip((e,r)=>{e instanceof Error?n=e:e&&e.length&&t(e)});await Kg(e,(e,t)=>{if(r.push(e,t),n)throw n})}async function Kg(e,t){if(e instanceof Uint8Array){for(let n=0;n<e.length;n+=Ng){let r=Math.min(n+Ng,e.length);t(e.subarray(n,r),r===e.length)}e.length===0&&t(e,!0);return}let n=e.size;for(let r=0;r<n;r+=Ng){let i=Math.min(r+Ng,n);t(new Uint8Array(await e.slice(r,i).arrayBuffer()),i===n)}n===0&&t(new Uint8Array,!0)}async function qg(e,t={}){let{onProgress:n,...r}=t,i=new Wg(r),a=0,o=0;return await Gg(e,e=>{i.push(e),a+=e.length,n&&a>=o&&(o=a+(64<<20),n({entries:i.listing.length,bytes:a}))}),i.end(),i.result()}async function Jg(e,t={}){let n=new Wg({...t});await Kg(e,e=>n.push(e)),n.end();let{entries:r,listing:i,retainedBytes:a,truncated:o}=n.result(),s=new Map;for(let e of i)e.offset!==void 0&&s.set(e.path,e);return{entries:r,listing:i,read:async t=>{if(r[t])return r[t];let n=s.get(t);return n?new Uint8Array(await e.slice(n.offset,n.offset+n.size).arrayBuffer()):null},retainedBytes:a,truncated:o,indexed:s.size}}async function Yg(e,t={}){let{onProgress:n,...r}=t,i=new Wg(r);return await Kg(e,e=>i.push(e)),i.end(),i.result()}function Xg(e){let t=(Array.isArray(e)?e:[e]).filter(Boolean).map(e=>{let t=Hg(e);return{p:t,inside:t+`/`}});return t.length===0?()=>!0:e=>{let n=e.lastIndexOf(`/`),r=n<0?``:e.slice(0,n);if(r===``)return!0;let i=r.lastIndexOf(`/textures`),a=i>=0&&i===r.length-9?r.slice(0,i)+`/`:null;for(let{p:n,inside:i}of t)if(e===n||e.startsWith(i)||i.startsWith(r+`/`)||a!==null&&i.startsWith(a))return!0;return!1}}function Zg(e){let t=e.filter(e=>e.path.toLowerCase().endsWith(`.pbrt`)).sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.length-t.path.length||(e.path<t.path?-1:1));if(!t.length)return{root:null,elements:[]};let n=t[0].path,r=n.lastIndexOf(`/`),i=r<0?``:n.slice(0,r),a=i?i+`/`:``,o=new Map;for(let t of e){if(!t.path.startsWith(a))continue;let e=t.path.slice(a.length),n=e.indexOf(`/`);if(n<0)continue;let r=e.slice(0,n),i=o.get(r);i||o.set(r,i={name:r,prefix:a+r,files:0,bytes:0,scenes:0}),i.files++,i.bytes+=t.size,t.path.toLowerCase().endsWith(`.pbrt`)&&i.scenes++}return{root:i,elements:[...o.values()].filter(e=>e.scenes>0).sort((e,t)=>e.bytes-t.bytes)}}var Qg={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},$g=9,e_=10,t_=12,n_=13,r_=32,i_=34,a_=35,o_=43,s_=45,c_=46,l_=48,u_=57,d_=91,f_=93,p_=69,m_=101,h_=e=>e===r_||e===$g||e===e_||e===n_||e===t_,g_=e=>e>=l_&&e<=u_,__=15,v_=22,y_=(()=>{let e=new Float64Array(v_+1);for(let t=0;t<e.length;t++)e[t]=10**t;return e})(),b_=new TextDecoder;function x_(e,t,n){if(n-t===0)return``;let r=!0;for(let i=t;i<n;i++)if(e[i]>127){r=!1;break}if(!r)return b_.decode(e.subarray(t,n));let i=``;for(let r=t;r<n;r++)i+=String.fromCharCode(e[r]);return i}var S_=class{constructor(e){this.bytes=typeof e==`string`?new TextEncoder().encode(e):e,this.i=0,this.n=this.bytes.length,this._ahead=null}peek(){return this._ahead===null&&(this._ahead=this._scan()),this._ahead}next(){let e=this.peek();return this._ahead=null,e}_scan(){let e=this.bytes,t=this.i,n=this.n;for(;;){for(;t<n&&h_(e[t]);)t++;if(t<n&&e[t]===a_){for(;t<n&&e[t]!==e_;)t++;continue}break}if(t>=n)return this.i=t,null;let r=e[t];if(r===d_)return this.i=t+1,{type:Qg.LBRACKET};if(r===f_)return this.i=t+1,{type:Qg.RBRACKET};if(r===i_){let r=++t;for(;t<n&&e[t]!==i_;)t++;if(t>=n)throw Error(`PBRT tokenizer: unterminated string literal`);return this.i=t+1,{type:Qg.STRING,value:x_(e,r,t)}}if(g_(r)||r===c_&&g_(e[t+1])||(r===s_||r===o_)&&(g_(e[t+1])||e[t+1]===c_&&g_(e[t+2])))return this._scanNumber(t);let i=t;for(;t<n;){let n=e[t];if(h_(n)||n===i_||n===d_||n===f_||n===a_)break;t++}return this.i=t,{type:Qg.WORD,value:x_(e,i,t)}}_scanNumber(e){let t=this.bytes,n=this.n,r=e,i=!1;t[r]===s_?(i=!0,r++):t[r]===o_&&r++;let a=0,o=0,s=0;for(;r<n&&g_(t[r]);)a=a*10+(t[r]-l_),o++,r++;if(r<n&&t[r]===c_)for(r++;r<n&&g_(t[r]);)a=a*10+(t[r]-l_),o++,s++,r++;let c=0;if(r<n&&(t[r]===m_||t[r]===p_)){let e=r+1,i=!1;if(e<n&&(t[e]===s_||t[e]===o_)&&(i=t[e]===s_,e++),e<n&&g_(t[e])){let a=0;for(;e<n&&g_(t[e]);)a=a*10+(t[e]-l_),e++;c=i?-a:a,r=e}}if(this.i=r,o===0)throw Error(`PBRT tokenizer: invalid number "${x_(t,e,r)}"`);let l=c-s;if(!(o<=__&&l>=-v_&&l<=v_)){let n=Number(x_(t,e,r));if(Number.isNaN(n))throw Error(`PBRT tokenizer: invalid number "${x_(t,e,r)}"`);return{type:Qg.NUMBER,value:n}}let u=l===0?a:l>0?a*y_[l]:a/y_[-l];return i&&(u=-u),{type:Qg.NUMBER,value:u}}};function C_(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function w_(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function T_(e,t,n,r){for(let i=0;i<4;i++){let a=r[i*4],o=r[i*4+1],s=r[i*4+2],c=r[i*4+3];for(let r=0;r<4;r++)e[i*4+r]=t[n+r]*a+t[n+4+r]*o+t[n+8+r]*s+t[n+12+r]*c}return e}function E_(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7],u=e[8],d=e[9],f=e[10],p=e[11],m=e[12],h=e[13],g=e[14],_=e[15],v=t[0],y=t[1],b=t[2],x=t[3],S=t[4],C=t[5],w=t[6],T=t[7],E=t[8],D=t[9],O=t[10],k=t[11],A=t[12],j=t[13],M=t[14],N=t[15];return[n*v+o*y+u*b+m*x,r*v+s*y+d*b+h*x,i*v+c*y+f*b+g*x,a*v+l*y+p*b+_*x,n*S+o*C+u*w+m*T,r*S+s*C+d*w+h*T,i*S+c*C+f*w+g*T,a*S+l*C+p*w+_*T,n*E+o*D+u*O+m*k,r*E+s*D+d*O+h*k,i*E+c*D+f*O+g*k,a*E+l*D+p*O+_*k,n*A+o*j+u*M+m*N,r*A+s*j+d*M+h*N,i*A+c*j+f*M+g*N,a*A+l*j+p*M+_*N]}function D_(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function O_(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function k_(e,t,n,r){let i=Math.hypot(t,n,r)||1;t/=i,n/=i,r/=i;let a=e*Math.PI/180,o=Math.cos(a),s=Math.sin(a),c=1-o,l=c*t*t+o,u=c*t*n-s*r,d=c*t*r+s*n,f=c*t*n+s*r,p=c*n*n+o,m=c*n*r-s*t;return[l,f,c*t*r-s*n,0,u,p,c*n*r+s*t,0,d,m,c*r*r+o,0,0,0,0,1]}function A_(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function j_(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function M_(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function N_(e,t,n){let r=M_(A_(t,e)),i=M_(j_(M_(n),r)),a=j_(r,i);return[i[0],i[1],i[2],0,a[0],a[1],a[2],0,r[0],r[1],r[2],0,e[0],e[1],e[2],1]}function P_(e){let t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=e[9],d=e[10],f=e[11],p=e[12],m=e[13],h=e[14],g=e[15],_=u*h*c-m*d*c+m*s*f-o*h*f-u*s*g+o*d*g,v=p*d*c-l*h*c-p*s*f+a*h*f+l*s*g-a*d*g,y=l*m*c-p*u*c+p*o*f-a*m*f-l*o*g+a*u*g,b=p*u*s-l*m*s-p*o*d+a*m*d+l*o*h-a*u*h,x=t*_+n*v+r*y+i*b;if(x===0)return C_();let S=1/x;return[_*S,(m*d*i-u*h*i-m*r*f+n*h*f+u*r*g-n*d*g)*S,(o*h*i-m*s*i+m*r*c-n*h*c-o*r*g+n*s*g)*S,(u*s*i-o*d*i-u*r*c+n*d*c+o*r*f-n*s*f)*S,v*S,(l*h*i-p*d*i+p*r*f-t*h*f-l*r*g+t*d*g)*S,(p*s*i-a*h*i-p*r*c+t*h*c+a*r*g-t*s*g)*S,(a*d*i-l*s*i+l*r*c-t*d*c-a*r*f+t*s*f)*S,y*S,(p*u*i-l*m*i-p*n*f+t*m*f+l*n*g-t*u*g)*S,(a*m*i-p*o*i+p*n*c-t*m*c-a*n*g+t*o*g)*S,(l*o*i-a*u*i-l*n*c+t*u*c+a*n*f-t*o*f)*S,b*S,(l*m*r-p*u*r+p*n*d-t*m*d-l*n*h+t*u*h)*S,(p*o*r-a*m*r-p*n*s+t*m*s+a*n*h-t*o*h)*S,(a*u*r-l*o*r+l*n*s-t*u*s-a*n*d+t*o*d)*S]}var F_=8,I_=1,L_=2,R_=3;function z_(e,t){if(e===t)return!0;for(let n=0;n<16;n++)if(e[n]!==t[n])return!1;return!0}var B_={integer:Int32Array,point3:Float32Array,point2:Float32Array,vector3:Float32Array,vector2:Float32Array,vector:Float32Array,normal:Float32Array,rgb:Float32Array};function V_(e,t){let n=new Float32Array(t);return n.set(e),n}var H_=class{constructor(e={}){this.releaseInclude=e.releaseInclude||null,this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.maxPlacements=e.maxPlacements??1/0,this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:new Map,instanceCount:0,skippedInstances:0,objects:new Map,transformTimes:{start:0,end:1},hasMotion:!1,warnings:[]},this.ctm=C_(),this.ctmEnd=null,this.activeTransform=R_,this._ctmSource=null,this._ctmValue=null,this.state={material:null,areaLight:null,reverseOrientation:!1},this.attributeStack=[],this.transformStack=[],this.coordSystems=new Map,this.currentObject=null,this.objectBeginCTM=null,this.dirStack=[``],this.stream=null,this._warnedUnknown=new Set}async parse(e,t=``){return this.dirStack=[t],await this._run(new S_(e)),this.ir}_addInstance(e){if(this.ir.instanceCount>=this.maxPlacements){this.ir.skippedInstances++;return}let t=this.ir.instances.get(e);t||this.ir.instances.set(e,t={name:e,count:0,matrices:new Float32Array(512),matricesEnd:null});let n=(t.count+1)*16;if(n>t.matrices.length){let e=Math.max(n,t.matrices.length*2);t.matrices=V_(t.matrices,e),t.matricesEnd&&=V_(t.matricesEnd,e)}let r=t.count*16,i=this.ctm;for(let e=0;e<16;e++)t.matrices[r+e]=i[e];let a=this._ctmEndSnapshot();if(a&&!t.matricesEnd&&(t.matricesEnd=t.matrices.slice()),t.matricesEnd){let e=a||i;for(let n=0;n<16;n++)t.matricesEnd[r+n]=e[n]}t.count++,this.ir.instanceCount++}_ctmSnapshot(){return this._ctmSource!==this.ctm&&(this._ctmSource=this.ctm,this._ctmValue=this.ctm.slice()),this._ctmValue}_ctmEndSnapshot(){return this.ctmEnd===null||z_(this.ctmEnd,this.ctm)?null:(this.ir.hasMotion=!0,this.ctmEnd.slice())}_concat(e){if(this.activeTransform===R_&&this.ctmEnd===null){this.ctm=E_(this.ctm,e);return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&L_?E_(t,e):t,this.activeTransform&I_&&(this.ctm=E_(this.ctm,e))}_setCTM(e){if(this.activeTransform===R_){this.ctm=e,this.ctmEnd=null;return}let t=this.ctmEnd??this.ctm;this.ctmEnd=this.activeTransform&L_?e:t,this.activeTransform&I_&&(this.ctm=e)}_pushGraphicsState(){this.attributeStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform,material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation})}_popGraphicsState(){let e=this.attributeStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform,this.state={material:e.material,areaLight:e.areaLight,reverseOrientation:e.reverseOrientation})}_peek(){return this.stream.peek()}_next(){return this.stream.next()}_expectNumber(e){let t=this._next();if(!t||t.type!==Qg.NUMBER)throw Error(`PBRT parser: expected number for ${e}, got ${t?t.value:`EOF`}`);return t.value}_expectString(e){let t=this._next();if(!t||t.type!==Qg.STRING)throw Error(`PBRT parser: expected string for ${e}, got ${t?t.value:`EOF`}`);return t.value}_readNumbers(e){let t=[];for(let n=0;n<e;n++)t.push(this._expectNumber(`matrix/transform`));return t}_readBracketedOrBareNumbers(e){if(this._peek()&&this._peek().type===Qg.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==Qg.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===Qg.STRING;){let t=this._next().value.trim().split(/\s+/),n=t[0],r=t[1]===void 0?t[0]:t[1];e[r]={type:n,value:this._parseParamValue(n)}}return e}_parseParamValue(e){let t=this._peek()&&this._peek().type===Qg.LBRACKET;t&&this._next();let n=()=>{let e=this._peek();return t?e&&e.type!==Qg.RBRACKET:!1};if(!t)return[this._coerceValueToken(this._next())];if(this._peek()&&this._peek().type===Qg.NUMBER){let t=[];for(;n()&&t.length<F_;){let e=this._next();if(e.type!==Qg.NUMBER)return this._finishMixedValue(t,t.length,e);t.push(e.value)}if(!n())return this._next(),t;let r=B_[e]||Float64Array,i=new r(F_*4);i.set(t);let a=t.length;for(;n();){let e=this._next();if(e.type!==Qg.NUMBER)return this._finishMixedValue(i,a,e);if(a===i.length){let e=new r(i.length*2);e.set(i),i=e}i[a++]=e.value}return this._next(),a===i.length?i:i.slice(0,a)}let r=[];for(;n();)r.push(this._coerceValueToken(this._next()));return this._next(),r}_finishMixedValue(e,t,n){let r=[];for(let n=0;n<t;n++)r.push(e[n]);for(r.push(this._coerceValueToken(n));this._peek()&&this._peek().type!==Qg.RBRACKET;)r.push(this._coerceValueToken(this._next()));return this._next(),r}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===Qg.NUMBER||e.type===Qg.STRING)return e.value;if(e.type===Qg.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}async _run(e){let t=this.stream;this.stream=e;for(let e=this._next();e!==null;e=this._next()){if(e.type!==Qg.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);let t=this._directive(e.value);t!==void 0&&await t}this.stream=t}_directive(e){switch(e){case`Identity`:this._setCTM(C_());break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this._concat(D_(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this._concat(O_(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this._concat(k_(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=N_([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this._concat(P_(t));break}case`Transform`:this._setCTM(this._readBracketedOrBareNumbers(16));break;case`ConcatTransform`:this._concat(this._readBracketedOrBareNumbers(16));break;case`CoordinateSystem`:this.coordSystems.set(this._expectString(`CoordinateSystem`),{ctm:this.ctm,ctmEnd:this.ctmEnd});break;case`CoordSysTransform`:{let e=this.coordSystems.get(this._expectString(`CoordSysTransform`));e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd);break}case`Camera`:{let e=this._expectString(`Camera type`),t=this._parseParams();this.ir.camera={type:e,params:t,cameraToWorld:P_(this.ctm)};let n=this._ctmEndSnapshot();n&&(this.ir.camera.cameraToWorldEnd=P_(n));break}case`Film`:{this._expectString(`Film type`);let e=this._parseParams();this.ir.film={xresolution:this._num(e.xresolution,1280),yresolution:this._num(e.yresolution,720),filename:this._str(e.filename,null)};break}case`Integrator`:case`Sampler`:case`PixelFilter`:case`Filter`:case`Accelerator`:case`ColorSpace`:case`Option`:this._skipTypeAndParams();break;case`WorldBegin`:this.ctm=C_(),this.ctmEnd=null,this.activeTransform=R_,this.state={material:null,areaLight:null,reverseOrientation:!1};break;case`WorldEnd`:break;case`AttributeBegin`:this._pushGraphicsState();break;case`AttributeEnd`:this._popGraphicsState();break;case`TransformBegin`:this.transformStack.push({ctm:this.ctm,ctmEnd:this.ctmEnd,activeTransform:this.activeTransform});break;case`TransformEnd`:{let e=this.transformStack.pop();e&&(this.ctm=e.ctm,this.ctmEnd=e.ctmEnd,this.activeTransform=e.activeTransform);break}case`ReverseOrientation`:this.state.reverseOrientation=!this.state.reverseOrientation;break;case`Attribute`:this._expectString(`Attribute target`),this._parseParams();break;case`ActiveTransform`:{let e=this._next()?.value;e===`StartTime`?this.activeTransform=I_:e===`EndTime`?this.activeTransform=L_:e===`All`?this.activeTransform=R_:this._warn(`ActiveTransform "${e}" not recognised`);break}case`TransformTimes`:{let[e,t]=this._readNumbers(2);this.ir.transformTimes={start:e,end:t};break}case`MediumInterface`:this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._peek()&&this._peek().type===Qg.STRING&&this._next();break;case`MakeNamedMedium`:this._skipNamedAndParams();break;case`Material`:{let e=this._expectString(`Material type`),t=this._parseParams();this.state.material={type:e,params:t};break}case`MakeNamedMaterial`:{let e=this._expectString(`MakeNamedMaterial name`),t=this._parseParams(),n=this._str(t.type,`diffuse`);this.ir.namedMaterials.set(e,{type:n,params:t});break}case`NamedMaterial`:{let e=this._expectString(`NamedMaterial name`),t=this.ir.namedMaterials.get(e);this.state.material=t||{type:`diffuse`,params:{},_missingRef:e},t||this._warn(`NamedMaterial "${e}" referenced before definition`);break}case`Texture`:{let e=this._expectString(`Texture name`),t=this._expectString(`Texture data type`),n=this._expectString(`Texture class`),r=this._parseParams();this.ir.namedTextures.set(e,{dataType:t,class:n,params:r});break}case`AreaLightSource`:{let e=this._expectString(`AreaLightSource type`),t=this._parseParams();this.state.areaLight={type:e,params:t};break}case`LightSource`:{let e=this._expectString(`LightSource type`),t=this._parseParams();this.ctmEnd!==null&&!z_(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-light`,`animated LightSource transforms are not supported — using the start transform`),this.ir.lights.push({type:e,params:t,ctm:this._ctmSnapshot()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this._ctmSnapshot(),material:this.state.material,areaLight:this.state.areaLight,reverseOrientation:this.state.reverseOrientation},t=this.currentObject===null?this._ctmEndSnapshot():null;t?e.ctmEnd=t:this.currentObject!==null&&this.ctmEnd!==null&&!z_(this.ctmEnd,this.ctm)&&this._warnOnce(`animated-template`,`animated transforms inside ObjectBegin are not supported — using the start transform`),this._emitShape(e);break}case`ObjectBegin`:{let e=this._expectString(`ObjectBegin name`);this._pushGraphicsState(),this.currentObject=e,this.objectBeginCTM=this.ctm.slice(),this.ir.objects.has(e)||this.ir.objects.set(e,[]);break}case`ObjectEnd`:this.currentObject=null,this.objectBeginCTM=null,this._popGraphicsState();break;case`ObjectInstance`:{let e=this._expectString(`ObjectInstance name`);this._addInstance(e);break}case`Include`:case`Import`:{let t=this._expectString(e);return this._include(t)}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=E_(P_(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}async _include(e){let t=this.dirStack[this.dirStack.length-1],n=await this.resolveInclude(e,t);if(n==null){this._warn(`Include target not found: ${e}`);return}let r=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(r);try{await this._run(new S_(n))}finally{this.dirStack.pop(),this.releaseInclude?.(e,t)}}_skipTypeAndParams(){this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===Qg.STRING&&this._next(),this._parseParams()}_num(e,t){return e&&e.value.length?e.value[0]:t}_str(e,t){return e&&e.value.length?e.value[0]:t}_warn(e){this.ir.warnings.push(e)}_warnOnce(e,t){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(t))}_warnUnknown(e){this._warnedUnknown.has(e)||(this._warnedUnknown.add(e),this._warn(`Unsupported directive ignored: ${e}`))}},U_={au:[1,.78,.34],gold:[1,.78,.34],cu:[.95,.64,.54],copper:[.95,.64,.54],ag:[.97,.96,.91],silver:[.97,.96,.91],al:[.91,.92,.92],aluminium:[.91,.92,.92],aluminum:[.91,.92,.92],mgo:[.9,.9,.9],tio2:[.9,.9,.9]},W_=[.92,.92,.92];function G_(e){let t=Math.max(1e3,Math.min(4e4,e))/100,n,r,i;t<=66?(n=255,r=99.47*Math.log(t)-161.12):(n=329.7*(t-60)**-.1332,r=288.12*(t-60)**-.0755),i=t>=66?255:t<=19?0:138.52*Math.log(t-10)-305.04;let a=e=>Math.max(0,Math.min(255,e))/255;return[a(n)**2.2,a(r)**2.2,a(i)**2.2]}function K_(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function q_(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function J_(e,t,n,r=null){let i=e[t];if(!i)return{rgb:r,texture:null};if(i.type===`texture`){let e=i.value[0],t=await n.resolveNamedTexture(e);return t&&t.texture?{rgb:t.constant??null,texture:t.texture}:t&&t.constant?{rgb:t.constant,texture:null}:(n.warn(`texture "${e}" could not be resolved`),{rgb:r,texture:null})}if(i.type===`rgb`||i.type===`color`)return{rgb:[i.value[0],i.value[1],i.value[2]],texture:null};if(i.type===`float`){let e=i.value[0];return{rgb:[e,e,e],texture:null}}if(i.type===`blackbody`)return{rgb:G_(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=Y_(i.value[0]);return e&&U_[e]?{rgb:U_[e].slice(),texture:null}:(n.warn(`named spectrum "${i.value[0]}" approximated to gray`),{rgb:[.5,.5,.5],texture:null})}let e=0,t=0;for(let n=1;n<i.value.length;n+=2)e+=i.value[n],t++;let r=t?e/t:.5;return{rgb:[r,r,r],texture:null}}return{rgb:r,texture:null}}function Y_(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(U_))if(e.toLowerCase().includes(t))return t;return null}function X_(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=K_(e,`uroughness`,null),r=K_(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function Z_(e,t){let n=e?.type||`diffuse`,i=e?.params||{},a=new r.MeshPhysicalMaterial({side:r.DoubleSide,roughness:1,metalness:0}),o=e=>{e&&a.color.setRGB(e[0],e[1],e[2])},s=e=>{o(e.rgb),e.texture&&(a.map=e.texture,e.rgb||a.color.setRGB(1,1,1))};switch(n){case`diffuse`:s(await J_(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await J_(i,`reflectance`,t,null),n=i.eta,r=i.k,c=n&&n.type===`spectrum`&&typeof n.value[0]==`string`;if(e.rgb||e.texture)s(e);else if(n&&r&&!c){let e=(await J_(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await J_(i,`k`,t,[3.9,2.45,2.14])).rgb,r=(e,t)=>((e-1)**2+t**2)/((e+1)**2+t**2);o([r(e[0],n[0]),r(e[1],n[1]),r(e[2],n[2])])}else o(n?(await J_(i,`eta`,t,W_)).rgb||W_:U_.cu);a.metalness=1,a.roughness=X_(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=K_(i,`eta`,1.5),a.roughness=X_(i,0),a.thickness=n===`thindielectric`?0:K_(i,`thickness`,0);break;case`coateddiffuse`:s(await J_(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=X_(i,0);break;case`diffusetransmission`:{let e=await J_(i,`transmittance`,t,[.25,.25,.25]);s(await J_(i,`reflectance`,t,[.25,.25,.25])),a.transmission=e.rgb?(e.rgb[0]+e.rgb[1]+e.rgb[2])/3:.5,a.roughness=1,a.ior=1;break}case`interface`:case`none`:case``:a.transmission=1,a.ior=1,a.roughness=0,a.color.setRGB(1,1,1);break;case`mix`:{let e=i.materials?.value||[],n=Math.max(0,Math.min(1,K_(i,`amount`,.5))),o=e[0]?t.namedMaterials?.get(e[0]):null,s=e[1]?t.namedMaterials?.get(e[1]):null;if(o&&s){let[e,r]=await Promise.all([Z_(o,t),Z_(s,t)]),i=(e,t)=>e*(1-n)+t*n;a.color.lerpColors(e.color,r.color,n),a.roughness=i(e.roughness,r.roughness),a.metalness=i(e.metalness,r.metalness),a.ior=i(e.ior??1.5,r.ior??1.5),a.transmission=i(e.transmission??0,r.transmission??0),a.thickness=i(e.thickness??0,r.thickness??0),a.clearcoat=i(e.clearcoat??0,r.clearcoat??0),a.clearcoatRoughness=i(e.clearcoatRoughness??0,r.clearcoatRoughness??0),a.emissive.lerpColors(e.emissive,r.emissive,n),a.emissiveIntensity=i(e.emissiveIntensity??0,r.emissiveIntensity??0),a.map=(n<.5?e.map:r.map)||null;break}t.warn(`material "mix" — could not resolve inner materials [${e.join(`, `)}], falling back to diffuse`),a.color.set(new r.Color(.6,.6,.6));break}case`subsurface`:case`hair`:case`measured`:t.warn(`material "${n}" not supported — using diffuse approximation`),o((await J_(i,`reflectance`,t,[.5,.5,.5])).rgb),a.roughness=1;break;default:t.warn(`unknown material "${n}" — using neutral diffuse`),a.color.set(new r.Color(.6,.6,.6));break}return a.roughness=Math.max(0,Math.min(1,a.roughness)),a}function Q_(e){return e===3?3/16:3/(8*e)}function $_(e){return 1/(e+3/(8*Q_(e)))}function ev(e,t){let n=new Map,r=[],i=[],a=[],o=[],s=[],c=t.length/3;for(let l=0;l<c;l++)for(let c=0;c<3;c++){let u=t[l*3+c],d=t[l*3+(c+1)%3],f=t[l*3+(c+2)%3],p=u<d?u:d,m=u<d?d:u,h=p*e+m,g=n.get(h);g===void 0?(n.set(h,r.length),r.push(p),i.push(m),a.push(f),o.push(-1),s.push(1)):(o[g]<0&&(o[g]=f),s[g]++)}let l=Array.from({length:e},()=>[]),u=Array.from({length:e},()=>[]);for(let e=0;e<r.length;e++){let t=r[e],n=i[e];l[t].push(n),l[n].push(t),s[e]===1&&(u[t].push(n),u[n].push(t))}return{edgeIndex:n,edgeV0:r,edgeV1:i,edgeOpp0:a,edgeOpp1:o,edgeFaces:s,ring:l,boundaryRing:u}}function tv(e,t,n,r,i){let a=new Float64Array(e.length);for(let o=0;o<n;o++){let n=o*3,s=t.boundaryRing[o];if(s.length===2){let t=s[0]*3,r=s[1]*3,o=1-2*i;for(let s=0;s<3;s++)a[n+s]=o*e[n+s]+i*(e[t+s]+e[r+s]);continue}let c=t.ring[o],l=c.length;if(l===0||s.length>0){for(let t=0;t<3;t++)a[n+t]=e[n+t];continue}let u=r(l),d=0,f=0,p=0;for(let t=0;t<l;t++){let n=c[t]*3;d+=e[n],f+=e[n+1],p+=e[n+2]}let m=1-l*u;a[n]=m*e[n]+u*d,a[n+1]=m*e[n+1]+u*f,a[n+2]=m*e[n+2]+u*p}return a}function nv(e,t){let n=e.length/3,r=ev(n,t),i=r.edgeV0.length,a=tv(e,r,n,Q_,1/8),o=new Float64Array((n+i)*3);o.set(a);for(let t=0;t<i;t++){let i=r.edgeV0[t]*3,a=r.edgeV1[t]*3,s=(n+t)*3,c=r.edgeOpp1[t];if(c<0)for(let t=0;t<3;t++)o[s+t]=.5*(e[i+t]+e[a+t]);else{let n=r.edgeOpp0[t]*3,l=c*3;for(let t=0;t<3;t++)o[s+t]=.375*(e[i+t]+e[a+t])+.125*(e[n+t]+e[l+t])}}let s=t.length/3,c=new Int32Array(s*12),l=(e,t)=>n+r.edgeIndex.get((e<t?e:t)*n+(e<t?t:e));for(let e=0;e<s;e++){let n=t[e*3],r=t[e*3+1],i=t[e*3+2],a=l(n,r),o=l(r,i),s=l(i,n),u=e*12;c[u]=n,c[u+1]=a,c[u+2]=s,c[u+3]=a,c[u+4]=r,c[u+5]=o,c[u+6]=s,c[u+7]=o,c[u+8]=i,c[u+9]=a,c[u+10]=o,c[u+11]=s}return{positions:o,indices:c}}function rv(e,t,n,r=2e6){let i=Float64Array.from(e),a=Int32Array.from(t),o=0;for(let e=0;e<n&&!(a.length/3*4>r);e++){let e=nv(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=tv(i,ev(s,a),s,$_,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function iv(e,t,n){let r=Math.abs(e),i=Math.abs(t),a=Math.sqrt(Math.max(0,1-Math.abs(n))),o=Math.max(r,i),s=o===0?0:Math.min(r,i)/o,c=2/Math.PI*Math.atan(s);r<i&&(c=1-c);let l=c*a,u=a-l;if(n<0){let e=u;u=1-l,l=1-e}return e<0&&(u=-u),t<0&&(l=-l),[.5*(u+1),.5*(l+1)]}var av=(()=>{let e=new Float32Array(256);for(let t=0;t<256;t++){let n=t/255;e[t]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return e})();function ov(e,t,n,r,i,a,o,s){let c=Math.min(Math.max(i*t-.5,0),t-1),l=Math.min(Math.max(a*n-.5,0),n-1),u=Math.floor(c),d=Math.floor(l),f=Math.min(u+1,t-1),p=Math.min(d+1,n-1),m=c-u,h=l-d,g=(d*t+u)*r,_=(d*t+f)*r,v=(p*t+u)*r,y=(p*t+f)*r;for(let t=0;t<3;t++){let n=s?s[e[g+t]]:e[g+t],r=s?s[e[_+t]]:e[_+t],i=s?s[e[v+t]]:e[v+t],a=s?s[e[y+t]]:e[y+t],c=n*(1-m)+r*m,l=i*(1-m)+a*m;o[t]=c*(1-h)+l*h}}function sv(e,t,n=1,r=0){let i=r||Math.min(e.width,4096),a=Math.max(1,i>>1),o=new Float32Array(i*a*4),s=t?P_(t):null,c=e.srgb?av:null,l=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,u=Math.sin(r),d=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,f=u*Math.cos(a),p=d,m=u*Math.sin(a);if(s){let e=s,t=e[0]*f+e[4]*p+e[8]*m,n=e[1]*f+e[5]*p+e[9]*m,r=e[2]*f+e[6]*p+e[10]*m,i=Math.hypot(t,n,r)||1;f=t/i,p=n/i,m=r/i}let[h,g]=iv(f,p,m);ov(e.data,e.width,e.height,e.channels,h,e.bottomUp?1-g:g,l,c);let _=(t*i+r)*4;o[_]=l[0]*n,o[_+1]=l[1]*n,o[_+2]=l[2]*n,o[_+3]=1}}return{data:o,width:i,height:a}}var cv=2;function lv(e,t){let n=e*e,r=n*e;t[0]=(1-3*e+3*n-r)/6,t[1]=(4-6*n+3*r)/6,t[2]=(1+3*e+3*n-3*r)/6,t[3]=r/6}function uv(e,t){let n=1-e;t[0]=n*n*n,t[1]=3*n*n*e,t[2]=3*n*e*e,t[3]=e*e*e}function dv(e){let t=Math.hypot(e[0],e[1],e[2]);return t>0&&(e[0]/=t,e[1]/=t,e[2]/=t),e}function fv(e,t,n){return n[0]=e[1]*t[2]-e[2]*t[1],n[1]=e[2]*t[0]-e[0]*t[2],n[2]=e[0]*t[1]-e[1]*t[0],n}function pv(e,t,n){let r=e.length/3,i=t===`bspline`?r-3:Math.max(1,(r-1)/3);if(i<1)return null;let a=Math.max(1,Math.round(n*i)),o=new Float64Array((a+1)*3),s=[0,0,0,0];for(let n=0;n<=a;n++){let r=n/a*i,c=Math.floor(r);c>=i&&(c=i-1);let l=r-c;t===`bspline`?lv(l,s):uv(l,s);let u=t===`bspline`?c:c*3,d=0,f=0,p=0;for(let t=0;t<4;t++){let n=(u+t)*3;d+=s[t]*e[n],f+=s[t]*e[n+1],p+=s[t]*e[n+2]}o[n*3]=d,o[n*3+1]=f,o[n*3+2]=p}return{points:o,count:a+1}}function mv(e){let{P:t,basis:n=`bezier`,width0:r=1,width1:i=1,N:a=null}=e,o=Math.max(1,Math.round(e.steps??cv)),s=Math.max(1,Math.round(e.sides??1));if(!t||t.length<12)return null;let c=pv(t,n,o);if(!c)return null;let{points:l,count:u}=c,d=s>=3?s:s*2,f=new Float32Array(u*d*3),p=[0,0,0],m=[0,0,0],h=[0,0,0],g=[0,0,0],_=!1;for(let e=0;e<u;e++){let t=Math.max(0,e-1),n=Math.min(u-1,e+1);if(p[0]=l[n*3]-l[t*3],p[1]=l[n*3+1]-l[t*3+1],p[2]=l[n*3+2]-l[t*3+2],dv(p),_){let e=m[0]*p[0]+m[1]*p[1]+m[2]*p[2];m[0]-=e*p[0],m[1]-=e*p[1],m[2]-=e*p[2],Math.hypot(m[0],m[1],m[2])<1e-9&&fv(p,[0,1,0],m),dv(m)}else{if(a&&a.length>=3)m[0]=a[0],m[1]=a[1],m[2]=a[2],fv(p,m,g),m[0]=g[0],m[1]=g[1],m[2]=g[2];else{let e=Math.abs(p[0]),t=Math.abs(p[1]),n=Math.abs(p[2]);fv(p,e<t&&e<n?[1,0,0]:t<n?[0,1,0]:[0,0,1],m)}Math.hypot(m[0],m[1],m[2])<1e-9&&fv(p,[0,1,0],m),dv(m),_=!0}fv(p,m,h),dv(h);let o=e/(u-1||1),c=(r+(i-r)*o)*.5,v=l[e*3],y=l[e*3+1],b=l[e*3+2];for(let t=0;t<d;t++){let n,r,i;if(s>=3){let e=t/s*Math.PI*2,a=Math.cos(e),o=Math.sin(e);n=m[0]*a+h[0]*o,r=m[1]*a+h[1]*o,i=m[2]*a+h[2]*o}else{let e=t<2?m:h,a=t%2==0?-1:1;n=e[0]*a,r=e[1]*a,i=e[2]*a}let a=(e*d+t)*3;f[a]=v+n*c,f[a+1]=y+r*c,f[a+2]=b+i*c}}let v=s,y=new Uint32Array((u-1)*v*6),b=0;for(let e=0;e<u-1;e++)for(let t=0;t<v;t++){let n=s>=3?t:t*2,r=s>=3?(t+1)%s:t*2+1,i=e*d+n,a=e*d+r,o=(e+1)*d+r,c=(e+1)*d+n;y[b++]=i,y[b++]=a,y[b++]=o,y[b++]=i,y[b++]=o,y[b++]=c}return{positions:f,indices:b===y.length?y:y.slice(0,b)}}var hv=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],gv=4096;function _v(e){return e instanceof Uint32Array?new r.Uint32BufferAttribute(e,1):ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===4?new r.Uint32BufferAttribute(new Uint32Array(e.buffer,e.byteOffset,e.length),1):new r.Uint32BufferAttribute(Uint32Array.from(e),1)}function vv(e,t){if(t<=e.length)return e;let n=e.length||1;for(;n<t;)n*=2;let r=new e.constructor(n);return r.set(e),r}function yv(e){return e instanceof Float32Array?e:Float32Array.from(e)}var bv=1e3,xv=45e6,Sv=6e6,Cv=256,wv=4096,Tv=5e5,Ev=2,Dv={flat:1,ribbon:1,cylinder:2};function Ov(e,t){let n=Math.min(e.width,gv),r=null;if(typeof OffscreenCanvas<`u`)r=new OffscreenCanvas(n,n);else if(typeof document<`u`)r=document.createElement(`canvas`),r.width=r.height=n;else return null;try{let i=r.getContext(`2d`,{willReadFrequently:!0});if(!i)return null;i.drawImage(e,0,0,n,n);let{data:a}=i.getImageData(0,0,n,n);return{data:a,width:n,height:n,channels:4,bottomUp:!1,srgb:t}}catch{return null}}function kv(e){let t=[e],n=e,r=[e=>e.replace(/-renamed-\d+$/,``),e=>e.replace(/\d+$/,``),e=>e.replace(/_Color$/i,``),e=>e.replace(/\d+$/,``)];for(let e of r){let r=e(n);r!==n&&r&&t.push(n=r)}return t}var Av=class{constructor(e={}){this.maxTriangles=e.maxTriangles??xv,this.maxPlacements=e.maxPlacements??Sv,this.mergeShapesAbove=e.mergeShapesAbove??Cv,this.curveSteps=e.curveSteps??Ev,this.curveSides=e.curveSides??null,this.resolvePLY=e.resolvePLY||(async()=>null),this.resolveImage=e.resolveImage||(async()=>null),this.resolveEnvironment=e.resolveEnvironment||e.resolveImage||(async()=>null),this.convertHandedness=e.convertHandedness===!0,this.warnings=[],this.report=[],this._materialCache=new Map,this._textureCache=new Map,this._geometryCache=new Map,this._materialBySignature=new Map,this._noUVMaterials=new Map,this._plyCache=new Map}warn(e){this.warnings.push(e)}async build(e){this.ir=e,this._recoveredColors=0,this.reportedMeshes=0,this.triangleCount=0,this.placementCount=0,this.skippedForBudget=0,this._countedGeometries=new WeakSet;let t=new r.Group;t.name=`PBRTScene`,this._batches=e.shapes.length>=this.mergeShapesAbove?new Map:null,this._mergedBatches=0,this.mergedShapes=0,this.droppedNoTemplate=0,this._animated=[];for(let n=0;n<e.shapes.length;n++){if(this._overBudget()){this.skippedForBudget+=e.shapes.length-n;break}let r=e.shapes[n],[i,a]=await Promise.all([this._batches?this._createGeometry(r):this._buildGeometry(r),this._getMaterial(r)]);if(!i)continue;if(this._batches&&!r.motion&&i.getAttribute(`position`).count<=wv){this._mergeShape(r,i,a,t),e.shapes[n]=null;continue}let o=this._meshFromGeometry(r,i,a,r.ctm,`shape_${n}`);o&&(t.add(o),r.motion&&this._animate(o,r.motion))}if(this._batches){for(let e of this._batches.values())this._flushBatch(e[0],t),this._flushBatch(e[1],t);this._batches=null}await this._buildInstances(e,t),await this._buildAnimatedPlacements(e,t),this.skippedForBudget>0&&this.warn(`stopped at ${this.triangleCount.toLocaleString()} stored triangles (budget ${this.maxTriangles.toLocaleString()}) and ${this.placementCount.toLocaleString()} placements (budget ${this.maxPlacements.toLocaleString()}); ${this.skippedForBudget.toLocaleString()} placement(s) skipped`);let n=null;e.camera&&(n=this._buildCamera(e.camera,e.film),n&&t.add(n));let i=e.animation?this._buildClip(e,n):[],a=await this._buildEnvironment(e.lights);return this._reportUnsupportedLights(e.lights),this._recoveredColors>0&&this.warn(`${this._recoveredColors} unreadable texture(s) fell back to the like-named material's colour`),{group:t,camera:n,environment:a,animations:i,report:this.report,meshCount:this.reportedMeshes,triangleCount:this.triangleCount,placementCount:this.placementCount,mergedShapes:this.mergedShapes,droppedNoTemplate:this.droppedNoTemplate,skippedForBudget:this.skippedForBudget,warnings:this.warnings.concat(e.warnings||[])}}_overBudget(){return this.triangleCount>=this.maxTriangles||this.placementCount>=this.maxPlacements}_accountGeometry(e){let t=e.index?e.index.count/3:e.getAttribute(`position`).count/3;return this._countedGeometries.has(e)||(this._countedGeometries.add(e),this.triangleCount+=t),t}async _buildInstances(e,t){let n=0;e.skippedInstances>0&&(this.skippedForBudget+=e.skippedInstances);let i=new Float64Array(16),a=new r.Matrix4;for(let[o,s]of e.instances){let c=e.objects.get(o);if(!c){this.droppedNoTemplate+=s.count,this.warn(`ObjectInstance "${o}" has no template — ${s.count.toLocaleString()} placement(s) dropped`);continue}for(let e of c){if(this._overBudget()){this.skippedForBudget+=s.count;continue}let[c,l]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!c)continue;let u=this._accountGeometry(c),d=Math.max(0,this.maxPlacements-this.placementCount),f=Math.min(s.count,d);if(f<s.count&&(this.skippedForBudget+=s.count-f),f===0)continue;let p=this._materialForGeometry(e,c,l,`instances_${o}`),m=new r.InstancedMesh(c,p,f);m.name=`instance_${n++}`,m.frustumCulled=!1;let h=e.relativeCTM||e.ctm;for(let e=0;e<f;e++)T_(i,s.matrices,e*16,h),m.setMatrixAt(e,a.fromArray(this.convertHandedness?E_(hv,i):i));m.instanceMatrix.needsUpdate=!0,t.add(m),this.placementCount+=f,this.reportedMeshes+=f,this.report.length<bv&&this.report.push({mesh:`${m.name} ×${f}`,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+p.color.getHexString(),map:p.map?`yes`:`-`,uv:c.getAttribute(`uv`)?`yes`:`NO`,normals:c.getAttribute(`normal`)?`yes`:`NO`,emissive:p.emissiveIntensity>0?`#${p.emissive.getHexString()}×${p.emissiveIntensity}`:`-`,size:`instanced`,tris:u})}}}async _buildAnimatedPlacements(e,t){let n=e.animatedInstances??[];for(let i=0;i<n.length;i++){let{name:a,motion:o}=n[i],s=e.objects.get(a);if(!s){this.droppedNoTemplate++;continue}if(this._overBudget()){this.skippedForBudget+=n.length-i;break}let c=new r.Group;c.name=`placement_${i}`;let l=Array.from(o.matrices.subarray(0,16));new r.Matrix4().fromArray(this.convertHandedness?E_(hv,l):l).decompose(c.position,c.quaternion,c.scale);for(let e=0;e<s.length;e++){let t=s[e],[n,r]=await Promise.all([this._buildGeometry(t),this._getMaterial(t)]);if(!n)continue;let i=this._meshFromGeometry(t,n,r,t.relativeCTM||t.ctm,`${c.name}_${e}`,!0);i&&c.add(i)}c.children.length!==0&&(t.add(c),this._animate(c,o))}}_animate(e,t){t.visible&&(e.visible=t.visible[0]===1),this._animated.push({node:e,motion:t})}_buildClip(e,t){let n=[];for(let{node:e,motion:t}of this._animated)if(this._transformTracks(n,e.name,t,(e,t)=>{let n=Array.from(e.subarray(t,t+16));return this.convertHandedness?E_(hv,n):n}),t.visible){let i=t.times,a=i.map((e,t)=>t===0?0:(i[t-1]+e)/2);n.push(new r.BooleanKeyframeTrack(`${e.name}.visible`,a,Array.from(t.visible,e=>e===1)))}let i=e.camera?.motion;if(t&&i){let e=new r.PerspectiveCamera;if(this._transformTracks(n,t.name,i,(t,n)=>(this._poseCamera(e,t.subarray(n,n+16)),e.updateMatrix(),e.matrix.elements)),i.fov){let e=Array.from(i.fov,e=>this._verticalFov({fov:{type:`float`,value:[e]}},t.aspect));n.push(new r.NumberKeyframeTrack(`${t.name}.fov`,i.times.slice(),e))}}for(let e of n)e.optimize();return n.length===0?[]:[new r.AnimationClip(e.animation.name,e.animation.duration,n)]}_transformTracks(e,t,n,i){let a=n.times.length,o=new Float32Array(a*3),s=new Float32Array(a*4),c=new Float32Array(a*3),l=new r.Matrix4,u=new r.Vector3,d=new r.Quaternion,f=new r.Vector3;for(let e=0;e<a;e++)l.fromArray(i(n.matrices,e*16)).decompose(u,d,f),e>0&&d.x*s[e*4-4]+d.y*s[e*4-3]+d.z*s[e*4-2]+d.w*s[e*4-1]<0&&d.set(-d.x,-d.y,-d.z,-d.w),u.toArray(o,e*3),d.toArray(s,e*4),f.toArray(c,e*3);let p=(e,t)=>{for(let n=t;n<e.length;n++)if(e[n]!==e[n%t])return!0;return!1};p(o,3)&&e.push(new r.VectorKeyframeTrack(`${t}.position`,n.times.slice(),o)),p(s,4)&&e.push(new r.QuaternionKeyframeTrack(`${t}.quaternion`,n.times.slice(),s)),p(c,3)&&e.push(new r.VectorKeyframeTrack(`${t}.scale`,n.times.slice(),c))}async _buildShapeMesh(e,t,n){let[r,i]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);return r?this._meshFromGeometry(e,r,i,t,n):null}_meshFromGeometry(e,t,n,i,a,o=!1){let s=!!t.getAttribute(`uv`),c=this._materialForGeometry(e,t,n,a),l=new r.Mesh(t,c);l.name=a;let u=this.convertHandedness&&!o?E_(hv,i):i;new r.Matrix4().fromArray(u).decompose(l.position,l.quaternion,l.scale),l.updateMatrix(),t.boundingBox||t.computeBoundingBox();let d=t.boundingBox?t.boundingBox.clone().applyMatrix4(l.matrix).getSize(new r.Vector3):new r.Vector3,f=this._accountGeometry(t);return this.placementCount++,this.reportedMeshes++,this.report.length<bv&&this.report.push({mesh:a,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+c.color.getHexString(),map:c.map?`yes`:`-`,uv:s?`yes`:`NO`,normals:t.getAttribute(`normal`)?`yes`:`NO`,emissive:c.emissiveIntensity>0?`#${c.emissive.getHexString()}×${c.emissiveIntensity}`:`-`,size:`${d.x.toFixed(2)}×${d.y.toFixed(2)}×${d.z.toFixed(2)}`,tris:f}),l}_materialForGeometry(e,t,n,r){if(!n.map||t.getAttribute(`uv`))return n;let i=this._noUVMaterials.get(n);return i||(this.warn(`${r} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),i=n.clone(),i.map=null,this._noUVMaterials.set(n,i)),i}_mergeShape(e,t,n,r){let i=this._materialForGeometry(e,t,n,`merged shape`),a=t.getAttribute(`position`),o=t.getAttribute(`normal`),s=t.getAttribute(`uv`),c=t.index,l=a.count;this.triangleCount+=(c?c.count:l)/3,this.reportedMeshes++,this.mergedShapes++;let u=this._batches.get(i);u||this._batches.set(i,u=[null,null]);let d=+!!s,f=u[d];f||(u[d]=f={material:i,positions:new Float32Array(3072),normals:new Float32Array(3072),uvs:s?new Float32Array(2048):null,indices:new Uint32Array(3072),vertexCount:0,indexCount:0,triangles:0});let p=this.convertHandedness?E_(hv,e.ctm):e.ctm,m=P_(p),h=f.vertexCount;f.positions=vv(f.positions,(h+l)*3),f.normals=vv(f.normals,(h+l)*3),s&&(f.uvs=vv(f.uvs,(h+l)*2));let g=a.array,_=f.positions,v=o?o.array:null,y=f.normals;for(let e=0;e<l;e++){let t=e*3,n=(h+e)*3,r=g[t],i=g[t+1],a=g[t+2];if(_[n]=p[0]*r+p[4]*i+p[8]*a+p[12],_[n+1]=p[1]*r+p[5]*i+p[9]*a+p[13],_[n+2]=p[2]*r+p[6]*i+p[10]*a+p[14],!v)continue;let o=v[t],s=v[t+1],c=v[t+2],l=m[0]*o+m[1]*s+m[2]*c,u=m[4]*o+m[5]*s+m[6]*c,d=m[8]*o+m[9]*s+m[10]*c,f=Math.hypot(l,u,d);f>0&&(l/=f,u/=f,d/=f),y[n]=l,y[n+1]=u,y[n+2]=d}s&&f.uvs.set(s.array.subarray(0,l*2),h*2);let b=c?c.count:l;f.indices=vv(f.indices,f.indexCount+b);let x=f.indices,S=c?c.array:null;for(let e=0;e<b;e++)x[f.indexCount+e]=h+(S?S[e]:e);f.vertexCount+=l,f.indexCount+=b,f.triangles+=b/3,f.triangles>=Tv&&(this._flushBatch(f,r),u[d]=null)}_flushBatch(e,t){if(!e||e.triangles===0)return;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(e.positions.slice(0,e.vertexCount*3),3)),n.setAttribute(`normal`,new r.Float32BufferAttribute(e.normals.slice(0,e.vertexCount*3),3)),e.uvs&&n.setAttribute(`uv`,new r.Float32BufferAttribute(e.uvs.slice(0,e.vertexCount*2),2)),n.setIndex(new r.Uint32BufferAttribute(e.indices.slice(0,e.indexCount),1));let i=new r.Mesh(n,e.material);i.name=`merged_${this._mergedBatches++}`,i.frustumCulled=!1,t.add(i),this.placementCount++,this.report.length<bv&&this.report.push({mesh:i.name,shape:`merged`,material:`-`,color:`#`+e.material.color.getHexString(),map:e.material.map?`yes`:`-`,uv:e.uvs?`yes`:`NO`,normals:`yes`,emissive:e.material.emissiveIntensity>0?`#${e.material.emissive.getHexString()}×${e.material.emissiveIntensity}`:`-`,size:`merged`,tris:e.triangles}),e.positions=e.normals=e.uvs=e.indices=null}_buildGeometry(e){let t=this._geometryCache.get(e);return t||this._geometryCache.set(e,t=this._createGeometry(e)),t}async _createGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(e.params);case`loopsubdiv`:return this._loopSubdiv(e.params);case`curve`:return this._curve(e.params);case`plymesh`:return this._plyMesh(e.params);case`sphere`:return this._sphere(e.params);case`disk`:return this._disk(e.params);default:return this.warn(`shape "${e.type}" not supported — skipped`),null}}_triangleMesh(e){let t=e.P?.value;if(!t||t.length<9)return this.warn(`trianglemesh missing P`),null;let n=new r.BufferGeometry;n.setAttribute(`position`,new r.Float32BufferAttribute(yv(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(yv(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(yv(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(_v(o)),i||n.computeVertexNormals(),n}_curve(e){let t=e.P?.value;if(!t||t.length<12)return this.warn(`curve needs at least 4 control points`),null;let n=Math.round(K_(e,`degree`,3));if(n!==3)return this.warn(`curve degree ${n} not supported — only cubic`),null;let i=q_(e,`type`,`flat`),a=K_(e,`width`,1),o=mv({P:t,basis:q_(e,`basis`,`bezier`),width0:K_(e,`width0`,a),width1:K_(e,`width1`,a),N:e.N?.value||null,steps:this.curveSteps,sides:this.curveSides??Dv[i]??1});if(!o)return this.warn(`curve could not be tessellated`),null;let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(o.positions,3)),s.setIndex(new r.Uint32BufferAttribute(o.indices,1)),s.computeVertexNormals(),s}_loopSubdiv(e){let t=e.P?.value,n=e.indices?.value;if(!t||t.length<9||!n||n.length<3)return this.warn(`loopsubdiv missing P/indices`),null;let i=Math.max(0,Math.min(6,Math.round(K_(e,`levels`,3)))),{positions:a,indices:o,levels:s}=rv(t,n,i);s<i&&this.warn(`loopsubdiv refined ${s}/${i} levels — the control mesh is too dense for the triangle budget`);let c=new r.BufferGeometry;return c.setAttribute(`position`,new r.Float32BufferAttribute(a,3)),c.setIndex(new r.Uint32BufferAttribute(o,1)),c.computeVertexNormals(),c}_bilinearMesh(e){let t=e.P?.value,n=e.indices?.value;if(!t||!n)return this.warn(`bilinearmesh missing P/indices`),null;let i=[];for(let e=0;e+3<n.length;e+=4){let[t,r,a,o]=[n[e],n[e+1],n[e+2],n[e+3]];i.push(t,r,a,t,a,o)}let a=new r.BufferGeometry;return a.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(t),3)),a.setIndex(i),a.computeVertexNormals(),a}_plyMesh(e){let t=q_(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;let n=this._plyCache.get(t);return n||this._plyCache.set(t,n=this._decodePly(t)),n}async _decodePly(e){try{let t=await this.resolvePLY(e);return t?(t.getAttribute(`normal`)||t.computeVertexNormals(),t):(this.warn(`plymesh file not found: ${e}`),null)}catch(t){return this.warn(`failed to load plymesh ${e}: ${t.message}`),null}}_sphere(e){return new r.SphereGeometry(K_(e,`radius`,1),48,32)}_disk(e){let t=K_(e,`radius`,1),n=K_(e,`innerradius`,0),i=K_(e,`height`,0),a=[],o=[];for(let e=0;e<48;e++){let r=e/48*Math.PI*2,s=(e+1)/48*Math.PI*2,c=a.length/3;a.push(Math.cos(r)*n,Math.sin(r)*n,i),a.push(Math.cos(r)*t,Math.sin(r)*t,i),a.push(Math.cos(s)*t,Math.sin(s)*t,i),a.push(Math.cos(s)*n,Math.sin(s)*n,i),o.push(c,c+1,c+2,c,c+2,c+3)}let s=new r.BufferGeometry;return s.setAttribute(`position`,new r.Float32BufferAttribute(Float32Array.from(a),3)),s.setIndex(o),s.computeVertexNormals(),s}async _getMaterial(e){let t=this._materialCache.get(e.material);if(t||(t=new Map,this._materialCache.set(e.material,t)),t.has(e.areaLight))return t.get(e.areaLight);let n={resolveNamedTexture:e=>this._resolveNamedTexture(e),namedMaterials:this.ir.namedMaterials,warn:e=>this.warn(e)},r=await Z_(e.material,n);e.areaLight&&await this._applyAreaLight(r,e.areaLight,n);let i=this._dedupeMaterial(r);return t.set(e.areaLight,i),i}_dedupeMaterial(e){let t=e.color,n=e.emissive,r=`${t.r},${t.g},${t.b}|${n.r},${n.g},${n.b}|${e.emissiveIntensity}|${e.map?e.map.uuid:`-`}|${e.roughness}|${e.metalness}|${e.transmission}|${e.ior}|${e.thickness}|${e.clearcoat}|${e.clearcoatRoughness}|${e.opacity}|${e.side}`;return this._materialBySignature.get(r)||(this._materialBySignature.set(r,e),e)}async _applyAreaLight(e,t,n){let r=await J_(t.params,`L`,n,[1,1,1]),i=K_(t.params,`scale`,1),a=r.rgb||[1,1,1];e.emissive.setRGB(a[0],a[1],a[2]),e.emissiveIntensity=i}async _resolveNamedTexture(e){if(this._textureCache.has(e))return this._textureCache.get(e);let t=this.ir.namedTextures.get(e),n=null;if(!t)this.warn(`named texture "${e}" not defined`);else if(t.class===`imagemap`){let r=q_(t.params,`filename`,null);if(r)try{let t=await this.resolveImage(r);t?n={texture:t}:this.warn(`image not found for texture "${e}": ${r}`)}catch(t){this.warn(`failed to load texture "${e}" (${r}): ${t.message}`)}}else if(t.class===`constant`){let e=t.params.value;e&&e.type===`rgb`?n={constant:[e.value[0],e.value[1],e.value[2]]}:e&&(n={constant:[e.value[0],e.value[0],e.value[0]]})}else if(t.class===`scale`)n=await this._resolveScaleTexture(e,t);else{let r=this._colorFromLikeNamedMaterial(e);r?(n={constant:r.rgb},this._recoveredColors++):this.warn(`texture class "${t.class}" not supported (texture "${e}")`)}return this._textureCache.set(e,n),n}_colorFromLikeNamedMaterial(e){for(let t of kv(e)){let e=(this.ir?.namedMaterials?.get(t))?.params?.reflectance;if(e&&(e.type===`rgb`||e.type===`color`))return{name:t,rgb:[e.value[0],e.value[1],e.value[2]]}}return null}async _resolveScaleTexture(e,t){let n=t.params.tex,r=null;if(n?.type===`texture`&&typeof n.value[0]==`string`)r=await this._resolveNamedTexture(n.value[0]);else if(n?.type===`rgb`||n?.type===`color`)r={constant:[n.value[0],n.value[1],n.value[2]]};else if(n?.type===`float`){let e=n.value[0];r={constant:[e,e,e]}}let i=t.params.scale,a=[1,1,1];if(i?.type===`rgb`||i?.type===`color`)a=[i.value[0],i.value[1],i.value[2]];else if(i?.type===`float`){let e=i.value[0];a=[e,e,e]}if(r?.texture){let e=r.constant||[1,1,1];return{texture:r.texture,constant:[e[0]*a[0],e[1]*a[1],e[2]*a[2]]}}let o=r?.constant||[1,1,1];return{constant:[o[0]*a[0],o[1]*a[1],o[2]*a[2]]}}_buildCamera(e,t){let n=t&&t.yresolution?t.xresolution/t.yresolution:16/9,i=new r.PerspectiveCamera(this._verticalFov(e.params,n),n,.01,1e4);return i.name=`PBRT Camera`,this._poseCamera(i,e.cameraToWorld),i.updateMatrixWorld(!0),i}_poseCamera(e,t){let n=t,i=new r.Vector3(n[12],n[13],n[14]),a=new r.Vector3(n[8],n[9],n[10]),o=new r.Vector3(n[4],n[5],n[6]);this.convertHandedness&&(i.z*=-1,a.z*=-1,o.z*=-1),e.up.copy(o.normalize()),e.position.copy(i),e.scale.set(1,1,1),e.lookAt(i.clone().add(a)),w_(t)>0!==this.convertHandedness&&(e.scale.x=-1)}_verticalFov(e,t){let n=K_(e,`fov`,90);if(t>=1)return n;let r=n*Math.PI/180;return 2*Math.atan(Math.tan(r/2)/t)*180/Math.PI}_equirectFromInfiniteLight(e,t,n,i){let a=e.image;if(!a?.width||a.width!==a.height)return a?.width!==a?.height&&this.warn(`infinite-light image "${i}" is ${a?.width}x${a?.height}, not square — read as equirectangular, but pbrt would read it as equal-area octahedral`),null;let o=null;if(a.data){let e=a.data.length/(a.width*a.height);if(!Number.isInteger(e)||e<3)return null;o={data:a.data,width:a.width,height:a.height,channels:e,bottomUp:!0}}else if(o=Ov(a,e.colorSpace===r.SRGBColorSpace),!o)return this.warn(`infinite-light image "${i}" could not be read back for octahedral conversion`),null;let{data:s,width:c,height:l}=sv(o,t.ctm,n),u=new r.DataTexture(s,c,l,r.RGBAFormat,r.FloatType);return u.mapping=r.EquirectangularReflectionMapping,u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.needsUpdate=!0,u}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=K_(t.params,`scale`,1),i=q_(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e){let a=this._equirectFromInfiniteLight(e,t,n,i);return a?{texture:a}:(e.mapping=r.EquirectangularReflectionMapping,{texture:e})}this.warn(`infinite-light image not found: ${i}`)}catch(e){this.warn(`failed to load infinite-light image ${i}: ${e.message}`)}let a=((await J_(t.params,`L`,{resolveNamedTexture:async()=>null,warn:e=>this.warn(e)},[1,1,1])).rgb||[1,1,1]).map(e=>e*n),o=new Float32Array(8);for(let e=0;e<2;e++)o[e*4+0]=a[0],o[e*4+1]=a[1],o[e*4+2]=a[2],o[e*4+3]=1;let s=new r.DataTexture(o,2,1,r.RGBAFormat,r.FloatType);return s.mapping=r.EquirectangularReflectionMapping,s.minFilter=r.LinearFilter,s.magFilter=r.LinearFilter,s.needsUpdate=!0,{texture:s}}_reportUnsupportedLights(e){for(let t of e)t.type!==`infinite`&&this.warn(`light "${t.type}" not supported (only infinite lights and emissive area lights are mapped)`)}},jv=1e3,Mv=2048,Nv=1e5;function Pv(e){let t=e[0],n=e=>{let t=e.lastIndexOf(`/`),n=/^(.*?)(\d+)\.pbrt$/i.exec(e.slice(t+1));return n?{group:e.slice(0,t+1)+`\0`+n[1].toLowerCase(),number:parseInt(n[2],10)}:null},r=t?n(t):null;if(!r)return null;let i=new Map;for(let t of e){let e=n(t);e&&e.group===r.group&&!i.has(e.number)&&i.set(e.number,t)}return i.size<2?null:[...i].sort((e,t)=>e[0]-t[0]).slice(0,jv).map(([e,t])=>({path:t,number:e}))}function Fv(e){let t=e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint32Array?new Uint32Array(e.buffer,e.byteOffset,e.length):null;t||=new Uint32Array(Float32Array.from(e).buffer);let n=2166136261;for(let e=0;e<t.length;e++)n=Math.imul(n^t[e],16777619),n^=n>>>15;return(n>>>0).toString(36)+`:`+e.length}function Iv(e){let t=``;for(let n of Object.keys(e).sort()){let{type:r,value:i}=e[n],a=ArrayBuffer.isView(i)||i.length>16&&typeof i[0]==`number`;t+=`${r} ${n}=${a?`#`+Fv(i):i.join(`,`)};`}return t}var Lv=class{constructor(e){this.materialNames=new Map;for(let[t,n]of e.namedMaterials)this.materialNames.set(n,t);this.cache=new Map}of(e){return`${e.type}|${+!!e.reverseOrientation}|${Iv(e.params)}|${this._material(e.material)}|${this._light(e.areaLight)}`}_material(e){if(!e)return`-`;let t=this.cache.get(e);if(t===void 0){let n=this.materialNames.get(e)??e._missingRef;t=n===void 0?`I:`+e.type+`:`+Iv(e.params):`N:`+n,this.cache.set(e,t)}return t}_light(e){if(!e)return`-`;let t=this.cache.get(e);return t===void 0&&this.cache.set(e,t=`L:`+e.type+`:`+Iv(e.params)),t}};function Rv(e,t){let n=new Int32Array(t.length).fill(-1),r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)n[r]=r,r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)n[--a]=--i;return r<i&&r<a&&!zv(e,r,i,t,r,a,n)&&Vv(e,r,i,t,r,a,n),n}function zv(e,t,n,r,i,a,o){let s=n-t,c=a-i,l=Math.min(s+c,Mv),u=l+1,d=new Int32Array(2*l+3),f=[];for(let n=0;n<=l;n++){for(let a=-n;a<=n;a+=2){let l=a===-n||a!==n&&d[u+a-1]<d[u+a+1]?d[u+a+1]:d[u+a-1]+1,p=l-a;for(;l<s&&p<c&&e[t+l]===r[i+p];)l++,p++;if(d[u+a]=l,l>=s&&p>=c)return f.push(d.slice(u-n,u+n+1)),Bv(f,s,c,t,i,o),!0}f.push(d.slice(u-n,u+n+1))}return!1}function Bv(e,t,n,r,i,a){let o=t,s=n;for(let t=e.length-1;t>0;t--){let n=e[t-1],c=e=>n[e+t-1],l=o-s,u=l===-t||l!==t&&c(l-1)<c(l+1)?l+1:l-1,d=c(u),f=d-u;for(;o>d&&s>f;)a[i+--s]=r+--o;o=d,s=f}for(;o>0&&s>0;)a[i+--s]=r+--o}function Vv(e,t,n,r,i,a,o){let s=new Map;for(let r=t;r<n;r++){let t=s.get(e[r]);t?t.push(r):s.set(e[r],[r])}let c=new Map;for(let e=i;e<a;e++){let t=s.get(r[e]);if(!t)continue;let n=c.get(r[e])??0;n<t.length&&(o[e]=t[n],c.set(r[e],n+1))}}function Hv(e,t,n,r){for(let i=0;i<16;i++)if(e[t+i]!==n[r+i])return!1;return!0}function Uv(e,t,n){let r=e.length,i=new Float32Array(16*r),a=null,o=-1;for(let e=0;e<r;e++)if(t(e)){if(i.set(n(e),e*16),o<0)for(let t=0;t<e;t++)i.copyWithin(t*16,e*16,e*16+16);o=e}else a??=new Uint8Array(r).fill(1),a[e]=0,o>=0&&i.copyWithin(e*16,o*16,o*16+16);return{times:e,matrices:i,visible:a}}function Wv(e){if(e.visible)return!1;let t=e.matrices;for(let e=16;e<t.length;e+=16)if(!Hv(t,0,t,e))return!1;return!0}var Gv=class{constructor(e,t){this.times=Float32Array.from(e),this.name=t,this.base=null,this.frame=-1,this.keyIds=new Map,this.tracks=[],this.prev=null,this.placements=new Map,this.templates=new Map,this.cameras=[],this.warnings=new Set}addFrame(e){let t=++this.frame;t===0?this.base=e:this._adoptDefinitions(e);for(let t of e.warnings)this.warnings.add(t);let n=new Lv(e),r=new Int32Array(e.shapes.length);for(let t=0;t<r.length;t++){let i=n.of(e.shapes[t]),a=this.keyIds.get(i);a===void 0&&this.keyIds.set(i,a=this.keyIds.size),r[t]=a}let i=this.prev?Rv(this.prev.keys,r):null,a=Array(r.length);for(let o=0;o<r.length;o++){let r=e.shapes[o],s=i&&i[o]>=0?this.prev.tracks[i[o]]:null;s?(s.last=t,s.ctms?s.ctms.push(r.ctm):r.ctm!==s.shape.ctm&&!Hv(r.ctm,0,s.shape.ctm,0)&&(s.ctms=Array(t-s.first).fill(s.shape.ctm),s.ctms.push(r.ctm))):(s={shape:r,first:t,last:t,ctms:null},t>0&&this._adoptMaterial(r,n.materialNames),this.tracks.push(s)),a[o]=s}this.prev={keys:r,tracks:a},this._addPlacements(e,t,this._resolveTemplates(e,t,n)),this.cameras.push(e.camera?{cameraToWorld:e.camera.cameraToWorld,fov:e.camera.params?.fov?.value?.[0]}:null)}_adoptDefinitions(e){for(let[t,n]of e.namedMaterials)this.base.namedMaterials.has(t)||this.base.namedMaterials.set(t,n);for(let[t,n]of e.namedTextures)this.base.namedTextures.has(t)||this.base.namedTextures.set(t,n)}_resolveTemplates(e,t,n){let r=new Map;for(let[i,a]of e.objects){let e=``;for(let t of a)e+=n.of(t)+`@`+Array.prototype.join.call(t.relativeCTM||t.ctm,`,`)+`;`;let o=i+`\0`+e,s=this.templates.get(o);if(s===void 0&&(s=t===0||!this.base.objects.has(i)?i:`${i} @${t}`,this.templates.set(o,s),t>0)){for(let e of a)this._adoptMaterial(e,n.materialNames);this.base.objects.set(s,a)}r.set(i,s)}return r}_adoptMaterial(e,t){let n=e.material&&t.get(e.material);n!==void 0&&(e.material=this.base.namedMaterials.get(n)??e.material)}_addPlacements(e,t,n){for(let[r,i]of e.instances){let e=n.get(r)??r,a=this.placements.get(e);if(a||this.placements.set(e,a={counts:new Int32Array(this.times.length),diffs:new Map}),a.counts[t]=i.count,t===0)continue;let o=this.base.instances.get(e),s=o?.count??0;for(let e=0;e<i.count;e++){let n=e*16;if(e<s&&Hv(i.matrices,n,o.matrices,n))continue;let r=a.diffs.get(e);r||a.diffs.set(e,r=new Map),r.set(t,i.matrices.slice(n,n+16))}}}finish(){let e=this.base,t=this.times,n=this.frame+1;e.shapes=this.tracks.map(e=>{let{shape:r,first:i,last:a,ctms:o}=e;return(i>0||a<n-1||o)&&(r.motion=Uv(t,e=>e>=i&&e<=a,e=>o?o[e-i]:r.ctm)),r}),e.warnings=[...this.warnings],e.animatedInstances=this._finishPlacements(e,t,n);let r=this.cameras;if(r[0]&&r.every(Boolean)){let n=Uv(t,()=>!0,e=>r[e].cameraToWorld),i=r.map(e=>e.fov??r[0].fov),a=i.some(e=>e!==i[0]);(!Wv(n)||a)&&(e.camera.motion={...n,fov:a?Float32Array.from(i):null})}return e.animation={name:this.name,duration:t[n-1],frames:n},e}_finishPlacements(e,t,n){let r=[],i=0;for(let[a,{counts:o,diffs:s}]of this.placements){let c=e.instances.get(a),l=c?.count??0,u=Math.max(...o.subarray(0,n)),d=[];for(let e=0;e<u;e++){let u=s.get(e),f=!!u;for(let t=0;t<n&&!f;t++)f=e>=o[t];if(f&&r.length<Nv){let n=Uv(t,t=>e<o[t],t=>u?.get(t)??c.matrices.subarray(e*16,e*16+16));r.push({name:a,motion:n})}else f&&i++,e<l&&d.push(e)}if(c&&d.length!==l){let t=new Float32Array(d.length*16);d.forEach((e,n)=>t.set(c.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=l-d.length,c.matrices=t,c.matricesEnd=null,c.count=d.length}}return i>0&&e.warnings.push(`${i.toLocaleString()} moving placement(s) past ${Nv.toLocaleString()} left static`),r}};function Kv(e){if(!e.hasMotion)return e;let{start:t,end:n}=e.transformTimes,r=n-t;if(!(r>0))return e;let i=Float32Array.of(0,r),a=(e,t,n,r)=>{let a=new Float32Array(32);for(let i=0;i<16;i++)a[i]=e[t+i],a[16+i]=n[r+i];return{times:i,matrices:a,visible:null}};for(let t of e.shapes)t.ctmEnd&&(t.motion=a(t.ctm,0,t.ctmEnd,0));e.animatedInstances=[];for(let t of e.instances.values()){if(!t.matricesEnd)continue;let n=[];for(let r=0;r<t.count;r++){let i=r*16;Hv(t.matrices,i,t.matricesEnd,i)||e.animatedInstances.length>=Nv?n.push(r):e.animatedInstances.push({name:t.name,motion:a(t.matrices,i,t.matricesEnd,i)})}if(n.length!==t.count){let r=new Float32Array(n.length*16);n.forEach((e,n)=>r.set(t.matrices.subarray(e*16,e*16+16),n*16)),e.instanceCount-=t.count-n.length,t.matrices=r,t.count=n.length}t.matricesEnd=null}return e.camera?.cameraToWorldEnd&&(e.camera.motion={...a(e.camera.cameraToWorld,0,e.camera.cameraToWorldEnd,0),fov:null}),e.animation={name:`Shutter motion`,duration:r,frames:2},e}var qv=2e6,Jv=new TextDecoder;function Yv(e){let t=e.replace(/\\/g,`/`).split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return n.join(`/`)}function Xv(e,t){return!e||t.startsWith(`/`)?Yv(t):Yv(`${e}/${t}`)}var Zv=class{constructor(e,t=null){this.entries=e,this.source=t,this.records=[],this.byPath=new Map,this.byBase=new Map;let n=(e,t,n)=>{let r=Yv(e).toLowerCase();if(this.byPath.has(r))return;let i={key:e,norm:r,bytes:t,lazy:n};this.records.push(i),this.byPath.set(r,i);let a=r.split(`/`).pop(),o=this.byBase.get(a);o?o.push(i):this.byBase.set(a,[i])};for(let t in e)n(t,e[t],!1);for(let e of t?.listing??[])e.offset!==void 0&&n(e.path,null,!0)}async read(e){return e?e.bytes?e.bytes:!e.lazy||!this.source?null:this.source.read(e.key):null}async readPath(e,t=null){let n=t!==null&&this.findRecord(Xv(t,e))||this.findRecord(e);return this.read(n)}release(e){e.bytes=null,delete this.entries[e.key]}releasePath(e,t=null){let n=t!==null&&this.findRecord(Xv(t,e))||this.findRecord(e);n?.lazy&&this.release(n)}releaseScenes(){for(let e of this.records)e.norm.endsWith(`.pbrt`)&&this.release(e)}findRecord(e){let t=Yv(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t);let n=this.byBase.get(t.split(`/`).pop());return n?n.find(e=>e.norm.endsWith(`/`+t))||(n.length===1?n[0]:null):null}find(e){return this.findRecord(e)?.bytes??null}};function Qv(e,t,n=0){let r=t[0],i=e.length-t.length;outer:for(let a=n;a<=i;a++)if(e[a]===r){for(let n=1;n<t.length;n++)if(e[a+n]!==t[n])continue outer;return a}return-1}var $v=e=>Uint8Array.from(e,e=>e.charCodeAt(0)),ey=$v(`WorldBegin`),ty=[$v(`Include`),$v(`Import`)];function ny(e,t){for(let n=t-1;n>=0;n--){let t=e[n];if(t===10)return!0;if(t!==32&&t!==9)return!1}return!0}function ry(e){for(let t=Qv(e,ey);t>=0;t=Qv(e,ey,t+1))if(ny(e,t))return!0;return!1}function iy(e,t){for(let n of ty)for(let r=Qv(e,n);r>=0;r=Qv(e,n,r+1)){if(!ny(e,r))continue;let i=r+n.length;for(;i<e.length&&(e[i]===32||e[i]===9);)i++;if(e[i]!==34)continue;let a=++i;for(;i<e.length&&e[i]!==34&&e[i]!==10;)i++;if(e[i]!==34)continue;let o=Jv.decode(e.subarray(a,i));t.add(Yv(o).toLowerCase().split(`/`).pop())}}function ay(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Set,r=new Map;for(let i of t){let t=e[i];r.set(i,ry(t)),iy(t,n)}return oy(t,r,n)}function oy(e,t,n){let r=(e,t)=>{let n=e.filter(t);return n.length?n:e},i=r(e,e=>t.get(e));return i=r(i,e=>!n.has(e.toLowerCase().split(`/`).pop())),i=r(i,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),i.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length===t.length?e<t?-1:+(e>t):e.length-t.length:n-r})}function sy(e){return ay(e)[0]||null}async function cy(e){let t=e.records.filter(e=>e.norm.endsWith(`.pbrt`));if(t.length===0)return[];if(t.length===1)return[t[0].key];let n=new Set,r=new Map;for(let i of t){let t=await e.read(i);t&&(r.set(i.key,ry(t)),iy(t,n),i.lazy&&e.release(i))}return oy(t.map(e=>e.key),r,n)}async function ly(e){let{vfs:t,source:n,plyParser:r,imageFromBytes:i,envFromBytes:a,convertHandedness:o}=e,s=new Zv(t,n),c=[],l=await cy(s);if(l.length===0)throw Error(`PBRT loader: no .pbrt file found in archive`);let u=e.entryPath&&l.includes(e.entryPath)?e.entryPath:null;e.entryPath&&!u&&c.push(`PBRT entry "${e.entryPath}" is not a scene in this archive — auto-detecting instead`);let d=u||l[0],f=async t=>{let n=await s.readPath(t);if(!n)throw Error(`PBRT loader: entry "${t}" not readable`);return new H_({resolveInclude:(e,t)=>s.readPath(e,t),releaseInclude:(e,t)=>s.releasePath(e,t),maxPlacements:e.maxPlacements}).parse(n,t.includes(`/`)?t.slice(0,t.lastIndexOf(`/`)):``)},p=performance.now(),m=!u&&e.animation!==!1?Pv(l):null,h;if(m){let e=await f(m[0].path);if(e.shapes.length+e.instanceCount>qv)c.push(`${m.length} animation frames found, but the scene is too large to parse once per frame — loaded "${m[0].path}" only`),m=null,h=Kv(e);else{let t=new Gv(m.map(e=>(e.number-m[0].number)/30),uy(m));t.addFrame(e);for(let e=1;e<m.length;e++)t.addFrame(await f(m[e].path));h=t.finish()}}else h=Kv(await f(d));let g=performance.now()-p;s.releaseScenes();let _=e=>e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),v=new Map,y=async e=>{let t=await s.read(e);return t?(s.release(e),r(_(t))):null},b=new Av({convertHandedness:o,maxTriangles:e.maxTriangles,maxPlacements:e.maxPlacements,mergeShapesAbove:e.mergeShapesAbove,curveSteps:e.curveSteps,curveSides:e.curveSides,resolvePLY:async e=>{let t=s.findRecord(e);return t?(v.has(t.norm)||v.set(t.norm,await y(t)),v.get(t.norm)):null},resolveImage:async e=>{let t=await s.readPath(e);return t?i(t,e):null},resolveEnvironment:async e=>{let t=await s.readPath(e);return t?(a||i)(t,e):null}}),x=performance.now(),S=await b.build(h);return{...S,entryPath:m?m[0].path:d,frames:m?m.map(e=>e.path):null,candidates:l,warnings:[...c,...S.warnings??[]],parseMs:g,buildMs:performance.now()-x}}function uy(e){let t=e[0].path.split(`/`);return`${t.length>1?t[t.length-2]:t[0].replace(/\d+\.pbrt$/i,``)||`frames`} · frames ${e[0].number}–${e[e.length-1].number}`}var dy=[`sourceFile`,`url`,`file`];function fy(e){if(typeof e==`string`)try{let t=JSON.parse(e);return t&&typeof t==`object`?t:null}catch{return null}return e&&typeof e==`object`?e:null}function py(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function my(e){let t=fy(e);if(!t)return null;let n=fy(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function hy(e){let t=fy(e);if(!t)return null;let n=dy.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=py(t.rotation),i=py(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function gy(e){let t=my(e);if(!t)return null;let n=hy(t.environment);return n?{environment:n}:null}function _y(e){if(!e)return null;let t=[e.userData,e.asset?.extras,e.scene?.userData];Array.isArray(e.scenes)&&t.push(...e.scenes.map(e=>e?.userData));for(let e of t){let t=gy(e);if(t)return t}return null}Ar();var vy={glb:{type:`model`,name:`GLB (GLTF Binary)`},gltf:{type:`model`,name:`GLTF`},fbx:{type:`model`,name:`FBX`},obj:{type:`model`,name:`OBJ`},stl:{type:`model`,name:`STL`},ply:{type:`model`,name:`PLY (Polygon File Format)`},dae:{type:`model`,name:`Collada`},"3mf":{type:`model`,name:`3D Manufacturing Format`},usd:{type:`model`,name:`USD (Universal Scene Description)`},usda:{type:`model`,name:`USDA (USD ASCII)`},usdc:{type:`model`,name:`USDC (USD Crate)`},usdz:{type:`model`,name:`USDZ (USD Archive)`},hdr:{type:`environment`,name:`HDR (High Dynamic Range)`},exr:{type:`environment`,name:`EXR (OpenEXR)`},png:{type:`image`,name:`PNG`},jpg:{type:`image`,name:`JPEG`},jpeg:{type:`image`,name:`JPEG`},webp:{type:`image`,name:`WebP`},zip:{type:`archive`,name:`ZIP Archive`},gz:{type:`archive`,name:`Gzipped TAR Archive`},tgz:{type:`archive`,name:`Gzipped TAR Archive`},tar:{type:`archive`,name:`TAR Archive`}},yy=/\.(usd|usda|usdc)$/i,by=/\.(png|jpg|jpeg|avif)$/i,xy=3e4,Sy=4e9;function Cy(e){let t=new r.BufferGeometry;for(let n in e.attributes)t.setAttribute(n,e.attributes[n]);e.index&&t.setIndex(e.index);for(let n of e.groups)t.addGroup(n.start,n.count,n.materialIndex);return t}var wy=683;function Ty(e,t,n,i){if(!(i.normalize??!0))return Math.PI;let a=i.shape===`ellipse`||i.shape===`disk`?Math.PI/4:1,o=e.getWorldScale(new r.Vector3),s=Math.PI*a*Math.abs(t*o.x*n*o.y);return Number.isFinite(s)?s:Math.PI}var Ey=class e extends r.EventDispatcher{constructor(e,t,n,{issues:i=null,profile:a=null}={}){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this.floorPlane=null,this.sceneScale=1,this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this.sceneMetadata=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1,this._issues=i,this._profile=a??Le(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(ln.ASSET_UNREACHABLE,`asset "${e}" could not be fetched — anything depending on it renders without it`,{url:e})}}cancelActiveLoad(){this._loadCancelled=!0,this._loadingManager.abort()}_isCancellation(e){return this._loadCancelled||e?.name===`AbortError`||e?.code===`LOAD_CANCELLED`}_cancellationError(){let e=Error(`Load cancelled`);return e.code=`LOAD_CANCELLED`,e}_downloadProgress(e,t){return n=>{let r=n?.loaded||0,i=n?.lengthComputable&&n.total||0;U({isLoading:!0,status:e,loadedBytes:r,totalBytes:i,canCancel:!!t,progress:i?Math.min(60,2+Math.round(r/i*58)):2})}}_downloadComplete(e=`Processing Data...`,t=62){U({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}_adoptExternalObject(e){let t;try{t=(0,f.clone)(e)}catch(t){throw Error(`Cannot render "${e.name||e.type}": its userData must be JSON-serializable.`,{cause:t})}return t.userData.__rayzeeExternal=!0,this.scene?.children.some(t=>t.uuid===e.uuid)||(t.uuid=e.uuid),e.parent&&(e.parent.updateWorldMatrix(!0,!1),t.applyMatrix4(e.parent.matrixWorld)),t}releaseTargetModel(){this.sceneMetadata=null,this.targetModel&&(this.removeModelRoot(this.targetModel),this.targetModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return vy[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e,t={}){let n=e.name,r=this.getFileFormat(n);if(!r)throw Error(`Unsupported file format: ${n}`);U({isLoading:!0,status:`Loading ${r.name}...`,progress:2});try{let i;switch(r.type){case`model`:i=await this.loadModelFromFile(e,n);break;case`environment`:case`image`:i=await this.loadEnvironmentFromFile(e,n);break;case`archive`:i=await this.loadArchiveFromFile(e,n,t);break;default:throw Error(`Unknown asset type: ${r.type}`)}return i}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:n}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`usd`:case`usda`:case`usdc`:case`usdz`:return await this.loadUSDFromArrayBuffer(r,t);default:throw Error(`Support for ${n} files is not yet implemented`)}}async loadEnvironmentFromFile(e,t){let n=URL.createObjectURL(e);this.uploadedFileInfo={name:t,type:e.type,size:e.size};try{let e=await this.loadEnvironment(n);return this.dispatchEvent({type:`load`,texture:e,filename:t}),e}finally{URL.revokeObjectURL(n)}}async loadEnvironment(e){this._loadCancelled=!1;try{this.dispatchEvent({type:`beforeEnvironmentLoad`,url:e});let t;if(e.startsWith(`blob:`))t=await this.loadEnvironmentFromBlob(e);else{let n=e.split(/[?#]/)[0].split(`.`).pop().toLowerCase();t=await this.loadEnvironmentByExtension(e,n)}return t.generateMipmaps=!0,this.applyEnvironmentToScene(t),this.dispatchEvent({type:`load`,texture:t,url:e,filename:e.split(/[?#]/)[0].split(`/`).pop()}),t}catch(t){throw this._isCancellation(t)?this._cancellationError():(console.error(`Error loading environment:`,t),this.dispatchEvent({type:`error`,message:t.message,filename:e}),t)}}async loadEnvironmentFromBlob(e){let t=await(await fetch(e)).blob(),n=this.determineEnvironmentExtension(t,e),r=URL.createObjectURL(t);try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}}determineEnvironmentExtension(e,t){let n;if(e.type===`image/x-exr`||e.type.includes(`exr`))n=`exr`;else if(e.type===`image/vnd.radiance`||e.type.includes(`hdr`))n=`hdr`;else{let e=t.split(`/`).pop();if(e){let t=e.match(/\.([^.]+)$/);t&&(n=t[1].toLowerCase())}}return!n&&this.uploadedFileInfo&&(n=this.uploadedFileInfo.name.split(`.`).pop().toLowerCase()),n}async loadEnvironmentByExtension(t,n){let i=e._isNetworkUrl(t),a=this._downloadProgress(`Downloading Environment...`,i),o;return n===`hdr`||n===`exr`?o=await(n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader(this._loadingManager).setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader(this._loadingManager).setDataType(r.FloatType))).loadAsync(t,a):(this.loaderCache.texture||(this.loaderCache.texture=new r.TextureLoader(this._loadingManager)),o=await this.loaderCache.texture.loadAsync(t,a),o.colorSpace=r.SRGBColorSpace),this._downloadComplete(`Processing Environment...`,62),o.mapping=r.EquirectangularReflectionMapping,o.minFilter=r.LinearFilter,o.magFilter=r.LinearFilter,o}applyEnvironmentToScene(e){this.scene.background=e,this.scene.environment=e}async _readHead(e,t=512){return e instanceof Uint8Array?e.subarray(0,t):typeof e.slice==`function`&&typeof e.arrayBuffer==`function`?new Uint8Array(await e.slice(0,t).arrayBuffer()):new Uint8Array((await this.readFileAsArrayBuffer(e)).slice(0,t))}async inspectArchive(e){let t=zg(await this._readHead(e));if(t===`gzip`||t===`tar`){let{listing:n}=await(t===`gzip`?qg:Yg)(e,{filter:()=>!1,onProgress:e=>U({isLoading:!0,status:`Scanning archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})}),{root:r,elements:i}=Zg(n);return{kind:t,root:r,elements:i,entryCount:n.length,totalBytes:n.reduce((e,t)=>e+t.size,0)}}let n=(0,m.unzipSync)(new Uint8Array(await this.readFileAsArrayBuffer(e))),r=Object.keys(n).map(e=>({path:e,size:n[e].length})),{root:i,elements:a}=Zg(r);return{kind:`zip`,root:i,elements:a,entryCount:r.length,totalBytes:r.reduce((e,t)=>e+t.size,0)}}async loadArchiveFromFile(e,t,{pbrtEntry:n=null,element:r=null,byteBudget:i,promptBytes:a,...o}={}){try{let s=zg(await this._readHead(e));if(s===`tar`){let i=await this._openSeekableArchive(e,t,r,a);if(i.listing.some(e=>e.path.toLowerCase().endsWith(`.pbrt`)))return await this.loadPBRTFromZip({},t,n,o,i);for(let e of i.listing)i.entries[e.path]??=await i.read(e.path);return await this._loadNonPBRTArchive(i.entries,t)}let c=s===`gzip`?await this._readStreamedArchive(e,t,s,r,i):(0,m.unzipSync)(new Uint8Array(await this.readFileAsArrayBuffer(e)));return sy(c)?await this.loadPBRTFromZip(c,t,n,o):await this._loadNonPBRTArchive(c,t)}catch(e){throw e?.code!==`ARCHIVE_NEEDS_ELEMENT`&&console.error(`Error loading archive:`,e),e}}async _loadNonPBRTArchive(e,t){return await this.processObjMtlPairsInZip(e,t)||await this.findAndLoadModelFromZip(e,t)}async _openSeekableArchive(e,t,n,r){let i=Array.isArray(n)?n.filter(Boolean):n?[n]:[],a=await Jg(e,{filter:i.length?Xg(i):null,retain:()=>!1}),o=a.listing.reduce((e,t)=>e+t.size,0);return i.length===0&&this._requireElementChoice(t,a.listing,o,r),console.info(`Archive "${t}": indexed ${a.indexed} entries, ${(o/1e9).toFixed(1)} GB, none resident`+(i.length?`, ${i.length} part${i.length>1?`s`:``} selected.`:`.`)),a}_requireElementChoice(e,t,n,r=Sy){if(n<r)return;let{root:i,elements:a}=Zg(t);if(a.length<2)return;let o=Error(`"${e}" holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts. Choose which to load — loading all of them at once may exhaust memory.`);throw o.code=`ARCHIVE_NEEDS_ELEMENT`,o.root=i,o.elements=a,o.totalBytes=n,this._issues?.record(ln.ASSET_ARCHIVE_TOO_LARGE,`archive holds ${(n/1e9).toFixed(1)} GB across ${a.length} parts; choose which to load`,{root:i,elements:a.map(e=>e.prefix),totalBytes:n},un.WARNING),o}async _readStreamedArchive(e,t,n,r,i){let a=Array.isArray(r)?r.filter(Boolean):r?[r]:[],{entries:o,listing:s,retainedBytes:c,truncated:l}=await(n===`gzip`?qg:Yg)(e,{filter:a.length?Xg(a):null,...i===void 0?{}:{byteBudget:i},onProgress:e=>U({isLoading:!0,status:`Reading archive… ${(e.bytes/1e9).toFixed(1)} GB`,progress:4})});if(l&&a.length===0){let{root:e,elements:n}=Zg(s),r=s.reduce((e,t)=>e+t.size,0),i=Error(`"${t}" unpacks to ${(r/1e9).toFixed(1)} GB, past the load budget. Load one of its ${n.length} parts instead.`);throw i.code=`ARCHIVE_NEEDS_ELEMENT`,i.root=e,i.elements=n,i.totalBytes=r,this._issues?.record(ln.ASSET_ARCHIVE_TOO_LARGE,`archive unpacks to ${(r/1e9).toFixed(1)} GB; choose one of ${n.length} parts`,{root:e,elements:n.map(e=>e.prefix),totalBytes:r},un.WARNING),i}return a.length&&console.info(`Archive "${t}": loaded ${a.map(e=>`"${e}"`).join(`, `)} — ${Object.keys(o).length} of ${s.length} files, ${(c/1048576).toFixed(1)} MB.`),o}async loadPBRTFromZip(e,t,n=null,r={},i=null){if(U({isLoading:!0,status:`Parsing PBRT scene...`,progress:5}),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let a=e=>this.loaderCache.ply.parse(e),o=(e,t)=>this._pbrtTextureFromBytes(e,t),s=async(e,t)=>{let n=t.split(`.`).pop().toLowerCase(),r=URL.createObjectURL(new Blob([e]));try{return await this.loadEnvironmentByExtension(r,n)}finally{URL.revokeObjectURL(r)}},c=performance.now(),{group:l,environment:u,animations:d,report:f,warnings:p,meshCount:m,entryPath:h,candidates:g,frames:_,parseMs:v,buildMs:y,triangleCount:b,placementCount:x,mergedShapes:S,skippedForBudget:C,droppedNoTemplate:w}=await ly({vfs:e,source:i,entryPath:n,plyParser:a,imageFromBytes:o,envFromBytes:s,animation:r.animation,maxTriangles:r.maxTriangles,maxPlacements:r.maxPlacements,mergeShapesAbove:r.mergeShapesAbove,curveSteps:r.curveSteps,curveSides:r.curveSides});this.lastPBRTStats={parseMs:v,buildMs:y,loaderMs:performance.now()-c,triangleCount:b,placementCount:x,mergedShapes:S,skippedForBudget:C,droppedNoTemplate:w,meshCount:m,frames:_?.length??1};let T=new Set(_??[h]),E=g.filter(e=>!T.has(e));if(E.length>0&&(console.warn(`PBRT archive holds ${g.length} scenes; loaded "${h}". Others: ${E.join(`, `)}`),this._issues?.record(ln.ASSET_AMBIGUOUS_ENTRY,`archive holds ${g.length} pbrt scenes; loaded "${h}"`,{loaded:h,alternatives:E},un.WARNING)),f&&f.length&&typeof console.table==`function`){let e=f.length<m?` (first ${f.length} of ${m})`:``;console.groupCollapsed(`PBRT loader: ${m} mesh(es) from "${h}"${e}`),console.table(f),console.groupEnd()}return p&&p.length&&(console.warn(`PBRT loader: ${p.length} warning(s) parsing "${h}"`),p.forEach(e=>console.warn(` •`,e))),u?.texture&&(u.texture.generateMipmaps=!0,this.applyEnvironmentToScene(u.texture)),l.name=h||t,this.releaseTargetModel(),this.targetModel=l,this.animations=d??[],u?.texture&&(this.sceneMetadata={environment:{rotation:0,intensity:1}}),U({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:l,filename:`${h} (from ZIP)`}),l}async _pbrtTextureFromBytes(e,t){let n=t.split(`.`).pop().toLowerCase(),i;if(n===`exr`||n===`hdr`){let t=n===`hdr`?this.loaderCache.hdr||(this.loaderCache.hdr=new s.HDRLoader().setDataType(r.FloatType)):this.loaderCache.exr||(this.loaderCache.exr=new u.EXRLoader().setDataType(r.FloatType));i=await this._loadViaObjectURL(t,e)}else if(n===`tga`){if(!this.loaderCache.tga){let{TGALoader:e}=await import(`three/examples/jsm/loaders/TGALoader.js`);this.loaderCache.tga=new e}i=await this._loadViaObjectURL(this.loaderCache.tga,e),i.colorSpace=r.SRGBColorSpace}else i=new r.Texture(await createImageBitmap(new Blob([e]))),i.colorSpace=r.SRGBColorSpace;return i.wrapS=i.wrapT=r.RepeatWrapping,i.needsUpdate=!0,i}async _loadViaObjectURL(e,t){let n=URL.createObjectURL(new Blob([t]));try{return await e.loadAsync(n)}finally{URL.revokeObjectURL(n)}}async processObjMtlPairsInZip(e,t){let n=[],r=[];for(let t in e){let i=t.toLowerCase();i.endsWith(`.obj`)?n.push({path:t,content:e[t]}):i.endsWith(`.mtl`)&&r.push({path:t,content:e[t]})}if(n.length>0&&r.length>0){console.log(`Found ${n.length} OBJ files and ${r.length} MTL files in ZIP`);let i=this.findMatchingObjMtlPairs(n,r);if(i.length>0)return console.log(`Found ${i.length} matching OBJ+MTL pairs`),await this.loadOBJMTLPairFromZip(i[0].obj,i[0].mtl,e,t);if(i.length===0)return console.log(`No matching pairs by name, using first OBJ and MTL files`),await this.loadOBJMTLPairFromZip(n[0],r[0],e,t)}return null}findMatchingObjMtlPairs(e,t){let n=[];for(let r of e){let e=r.path.split(`/`).pop().replace(/\.obj$/i,``).toLowerCase();for(let i of t){let t=i.path.split(`/`).pop().replace(/\.mtl$/i,``).toLowerCase();if(e===t||e.includes(t)||t.includes(e)){n.push({obj:r,mtl:i});break}}}return n}async findAndLoadModelFromZip(e){for(let t of[`scene.gltf`,`scene.glb`,`model.gltf`,`model.glb`,`main.gltf`,`main.glb`,`asset.gltf`,`asset.glb`])if(e[t]){console.log(`Found main model file: ${t}`);let n=t.split(`.`).pop().toLowerCase();return await this.loadModelFromZipEntry(e[t],t,n,e)}for(let t in e){let n=t.split(`.`).pop().toLowerCase();if(vy[n]&&vy[n].type===`model`)return yy.test(t)?await this.loadUSDHierarchyFromZip(e):(console.log(`Loading model file from ZIP: ${t}`),await this.loadModelFromZipEntry(e[t],t,n,e))}throw Error(`No supported model files found in the ZIP archive`)}async loadUSDHierarchyFromZip(t){let n=Object.keys(t).filter(e=>yy.test(e));if(n.length===0)throw Error(`No USD layers found in the ZIP archive`);let r=e._pickUSDRootLayer(n);console.log(`Loading USD scene from ZIP: ${r} (${n.length} layers)`);let i={[r]:[t[r],{level:0}]};for(let e of Object.keys(t))e!==r&&(yy.test(e)||by.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,m.zipSync)(i),r)}static _pickUSDRootLayer(e){let t=e=>e.split(`/`).length,n=Math.min(...e.map(t)),r=e.filter(e=>t(e)===n);return r.find(e=>{let t=e.split(`/`);return t.length>1&&t[t.length-1].replace(yy,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{U({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,m.strFromU8)(e),r=new File([new Blob([n])],t);o=await this.loadColladaFromFile(r,t)}break;case`3mf`:o=await this.load3MFFromArrayBuffer(e.buffer,t);break;case`usd`:case`usda`:case`usdc`:case`usdz`:o=await this.loadUSDFromArrayBuffer(e,t);break;default:throw Error(`Support for ${n} files is not yet implemented`)}return URL.revokeObjectURL(a),this.dispatchEvent({type:`load`,model:this.targetModel,filename:`${t} (from ZIP)`}),o}catch(e){throw console.error(`Error loading ${n} from ZIP:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async handleGltfFromZip(e,t,n,i){if(e===`gltf`){let e=(0,m.strFromU8)(t),a=new r.LoadingManager,o=n.split(`/`).slice(0,-1).join(`/`);a.setURLModifier(e=>this.resolveZipResource(e,o,i));let s=await this.createGLTFLoader();s.manager=a;try{return await new Promise((t,n)=>{s.parse(e,``,e=>{this.releaseTargetModel(),this.targetModel=e.scene,this.sceneMetadata=_y(e),this.onModelLoad(this.targetModel).then(()=>t(e))},e=>n(e))})}finally{this._disposeGLTFLoader(s)}}else return await this.loadGLBFromArrayBuffer(t.buffer,n)}async handleObjFromZip(e,t,n){let r=(0,m.strFromU8)(e),i=r.match(/mtllib\s+([^\s]+)/),a=null;i&&i[1]&&(a=await this.loadMtlFromZip(i[1],t,n));let{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=new o;a&&s.setMaterials(a);let c=s.parse(r);return c.name=t,this.releaseTargetModel(),this.targetModel=c,await this.onModelLoad(this.targetModel),c}async preloadMtlTextures(e){let t=[],n=e.loadTexture.bind(e);if(e.loadTexture=(e,r,i,a,o)=>{let s;return t.push(new Promise(e=>s=e)),n(e,r,e=>{s(),i?.(e)},a,e=>{s(),o?.(e)})},e.preload(),t.length===0)return e;let r,i=await Promise.race([Promise.all(t).then(()=>!0),new Promise(e=>r=setTimeout(()=>e(!1),xy))]);return clearTimeout(r),i||this._issues?.record(ln.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${xy}ms; affected materials render untextured`,{pending:t.length}),e}async loadMtlFromZip(e,t,n){let i=t.split(`/`).slice(0,-1).join(`/`),a=[e,`${i}/${e}`,e.split(`/`).pop()];for(let e of a)if(n[e]){let{MTLLoader:t}=await import(`three/examples/jsm/loaders/MTLLoader.js`),a=(0,m.strFromU8)(n[e]),o=new r.LoadingManager;o.setURLModifier(e=>this.resolveZipResource(e,i,n));let s=new t(o).parse(a,i);return await this.preloadMtlTextures(s),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,n,i){let{MTLLoader:a}=await import(`three/examples/jsm/loaders/MTLLoader.js`),{OBJLoader:o}=await import(`three/examples/jsm/loaders/OBJLoader.js`),s=[],c=new r.LoadingManager,l=e.path.split(`/`).slice(0,-1).join(`/`),u=t.path.split(`/`).slice(0,-1).join(`/`);c.setURLModifier(e=>this.resolveTextureInZip(e,l,u,t,n,s));let d=this.prepareFixedMtlContent(t),f=new a(c).parse(d,u);await this.preloadMtlTextures(f);let p=new o(c);p.setMaterials(f);let h=(0,m.strFromU8)(e.content),g=p.parse(h);return this.releaseTargetModel(),this.targetModel=g,await this.onModelLoad(this.targetModel),s.forEach(e=>URL.revokeObjectURL(e)),this.dispatchEvent({type:`load`,model:g,filename:`${e.path} (from ${i})`}),g}prepareFixedMtlContent(e){return(0,m.strFromU8)(e.content).replace(RegExp(`${e.path.split(`/`).pop()}\\s+`,`g`),` `).replace(/([a-zA-Z_]+)([\\/])/g,`$1 $2`)}resolveTextureInZip(e,t,n,r,i,a){let o=e.split(`?`)[0].split(`#`)[0].replace(/^\.\/|^\//,``),s=r.path.split(`/`).pop();o.startsWith(s)&&(o=o.substring(s.length).replace(/^\.\/|^\/|^\./,``));let c=[o,`${t}/${o}`,`${n}/${o}`,`textures/${o}`,`texture/${o}`,`materials/${o}`,o.split(`/`).pop()];for(let e of c)if(i[e]){let t=new Blob([i[e].buffer],{type:`application/octet-stream`}),n=URL.createObjectURL(t);return a.push(n),n}return this.findTextureWithFuzzyMatch(o,i,a)||e}findTextureWithFuzzyMatch(e,t,n){let r=e.split(`/`).pop();for(let e in t)if(e.endsWith(r)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}if(r&&r.length>5)for(let e in t){let i=e.split(`/`).pop();if(i.includes(r)||r.includes(i)){let r=new Blob([t[e].buffer],{type:`application/octet-stream`}),i=URL.createObjectURL(r);return n.push(i),i}}return null}async createGLTFLoader(){let{dracoDecoderPath:e,ktx2TranscoderPath:t}=Or(),n=new c.DRACOLoader;n.setDecoderConfig({type:`js`}),n.setDecoderPath(e);let r=new l.KTX2Loader;r.setTranscoderPath(t),this.renderer&&(r.detectSupport(this.renderer),r.workerConfig={astcSupported:!1,etc1Supported:!1,etc2Supported:!1,dxtSupported:!1,bptcSupported:!1,pvrtcSupported:!1});let i=new o.GLTFLoader(this._loadingManager);return i.setDRACOLoader(n),i.setKTX2Loader(r),i.setMeshoptDecoder(p.MeshoptDecoder),i}_disposeGLTFLoader(e){e&&(e.dracoLoader?.dispose(),e.ktx2Loader?.dispose())}async loadExampleModels(e,t){if(!t||!t[e])throw Error(`No model file at index ${e}`);let n=`${t[e].url}`;return await this.loadModel(n)}async loadModel(t){this._loadCancelled=!1;let n=await this.createGLTFLoader(),r=e._isNetworkUrl(t);try{U({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:r,loadedBytes:0,totalBytes:0});let e=await n.loadAsync(t,this._downloadProgress(`Downloading Model...`,r));return this._downloadComplete(),this.releaseTargetModel(),this.targetModel=e.scene,this.animations=e.animations||[],this.sceneMetadata=_y(e),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e.scene,filename:t.split(`/`).pop()}),e}catch(e){throw this._isCancellation(e)?this._cancellationError():(console.error(`Error loading model:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e)}finally{this._disposeGLTFLoader(n)}}_processAndParent(e){this.processModelObjects(e),this.scene.add(e),e.updateMatrixWorld(!0)}async appendModel(t){this._loadCancelled=!1;let n=await this.createGLTFLoader(),r=e._isNetworkUrl(t);try{U({isLoading:!0,status:`Downloading Model...`,progress:2,canCancel:r,loadedBytes:0,totalBytes:0});let e=await n.loadAsync(t,this._downloadProgress(`Downloading Model...`,r));return this._downloadComplete(),this._processAndParent(e.scene),{root:e.scene,animations:e.animations||[]}}catch(e){throw this._isCancellation(e)?this._cancellationError():e}finally{this._disposeGLTFLoader(n)}}appendObject3D(e,t=`object3d`){let n=this._adoptExternalObject(e);return n.name=e.name||t,this._processAndParent(n),{root:n}}removeModelRoot(e){e&&(e.userData.__rayzeeExternal?(Me(e),e.parent?.remove(e)):je(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{U({isLoading:!0,status:`Processing GLB Data...`,progress:5}),await new Promise(e=>setTimeout(e,0));let r=await n.parseAsync(e,``);return this.releaseTargetModel(),this.targetModel=r.scene,this.animations=r.animations||[],this.sceneMetadata=_y(r),U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(U({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(U({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(U({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(U({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let n=this.loaderCache.ply.parse(e),i;if(n.index!==null)i=new r.Mesh(n,new r.MeshStandardMaterial);else{let e=new r.PointsMaterial({size:.01});e.vertexColors=n.hasAttribute(`color`),i=new r.Points(n,e)}return i.name=t,this.releaseTargetModel(),this.targetModel=i,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(U({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(U({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(U({isLoading:!0,status:`Processing USD Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.usd){let{USDLoader:e}=await import(`three/examples/jsm/loaders/USDLoader.js`);this.loaderCache.usd=new e}let n=await new Promise((t,n)=>{this.loaderCache.usd.parse(e,``,t,n)});return n.name=t,this.releaseTargetModel(),this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){this.releaseTargetModel();let n=this._adoptExternalObject(e);return n.name=e.name||t,this.targetModel=n,U({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}async onModelLoad(e){let t=new jd(`onModelLoad`);t.start(`Camera extraction`);let n=this.extractCamerasFromModel(e);t.end(`Camera extraction`),t.start(`Camera setup`);let i=new r.Box3().setFromObject(e),a=i.getCenter(new r.Vector3),o=i.getSize(new r.Vector3);this.controls.target.copy(a);let s=Math.max(o.x,o.y,o.z),c=this.camera.fov*(Math.PI/180),l=Math.abs(s/Math.sin(c/2)/2),u=Math.PI/6,d=new r.Vector3(Math.cos(u)*l,l/Math.sqrt(2),Math.sin(u)*l);if(this.camera.position.copy(d.add(a)),this.camera.lookAt(a),this.camera.near=s/100,this.camera.far=s*100,this.camera.updateProjectionMatrix(),this.controls.maxDistance=l*10,this.controls.saveState(),this.controls.update(),t.end(`Camera setup`),this.floorPlane){let e=i.min.y;this.floorPlane.position.y=e,this.floorPlane.rotation.x=-Math.PI/2,this.floorPlane.scale.setScalar(s*5)}t.start(`Process model objects`),this.processModelObjects(e),t.end(`Process model objects`),t.start(`Scene add`),this.scene.add(e),t.end(`Scene add`);let f=s;return t.start(`setupPathTracing`),await this.setupPathTracing(e,f),t.end(`setupPathTracing`),t.print(),this.dispatchEvent({type:`modelProcessed`,model:e,cameras:n,sceneData:{center:a,size:o,maxDim:s,sceneScale:f}}),this.dispatchEvent({type:`SceneRebuild`}),{center:a,size:o,maxDim:s,sceneScale:f}}extractCamerasFromModel(e){let t=[];return e.updateWorldMatrix(!0,!0),e.traverse(e=>{if(e.isCamera){let n=e.clone();n.userData.__rayzeeSourceUuid=e.uuid,e.getWorldPosition(n.position),e.getWorldQuaternion(n.quaternion),e.getWorldScale(n.scale),n.scale.set(Math.sign(n.scale.x)||1,Math.sign(n.scale.y)||1,Math.sign(n.scale.z)||1),(!n.name||n.name===``)&&(n.name=`Model Camera ${t.length+1}`),n.isPerspectiveCamera&&(n.aspect=this.camera.aspect,n.updateProjectionMatrix()),t.push(n)}}),t}processModelObjects(e){let t=[];e.traverse(e=>{let n=e.userData;if(e.isRectAreaLight&&!n.__radianceConverted&&(e.intensity*=Ty(e,e.width,e.height,n),n.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI/wy,n.__candelaConverted=!0),e.isDirectionalLight&&!n.__luxConverted&&(e.intensity/=wy,n.__luxConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let t=n.normalize??!0,i=n.shape??`rectangle`,a=n.intensity*Ty(e,n.width,n.height,n),o=new r.RectAreaLight(new r.Color(...n.color),a*this._profile.areaLightIntensityScale,n.width,n.height);o.userData.normalize=t,o.userData.spread=Number.isFinite(n.spread)?n.spread:Math.PI,o.userData.shape=i,o.userData.__radianceConverted=!0,o.name=n.name,e.add(o)}e.isMesh&&Array.isArray(e.material)&&t.push(e)});let n=e.userData.__rayzeeExternal===!0;for(let e of t){if(!e.parent)continue;console.log(`Found multi-material mesh:`,e.name),n&&(e.geometry=Cy(e.geometry));let t=(0,d.createMeshesFromMultiMaterialMesh)(e);for(let e of t.children)e.geometry.userData.__rayzeeOwned=!0;e.parent.add(t),e.parent.remove(e)}}async setupPathTracing(e,t){this.sceneScale=t}createFloorPlane(){this.floorPlane=new r.Mesh(new r.CircleGeometry,new r.MeshPhysicalMaterial({transparent:!1,color:3158064,roughness:1,metalness:0,opacity:0,transmission:0})),this.floorPlane.name=`Ground`,this.floorPlane.visible=!1,this.scene.add(this.floorPlane)}setFloorPlane(e){this.floorPlane=e}getSceneScale(){return this.sceneScale}getTargetModel(){return this.targetModel}getSupportedFormats(e=null){if(e){let t={};for(let[n,r]of Object.entries(vy))r.type===e&&(t[n]=r);return t}return vy}dispose(){for(let e in this.loaderCache){let t=this.loaderCache[e];t&&typeof t.dispose==`function`&&t.dispose()}this.loaderCache={},this._listeners=void 0,this._loadingManager.onError=void 0,this._issues=null,this.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}};xe();var Dy=Object.freeze(new r.Vector3(1,1,1)),Oy=class extends r.EventDispatcher{constructor(e){super();let t=e.clientWidth,n=e.clientHeight;this.camera=new r.PerspectiveCamera(60,t/n||1,.01,1e3),this.camera.position.set(0,0,5),this.controls=new h.OrbitControls(this.camera,e),this.controls.screenSpacePanning=!0,this.controls.zoomToCursor=!0,this.controls.saveState(),this.interactionManager=null,this.cameras=[this.camera],this.currentCameraIndex=0,this._userCameraCounter=0,this.autoFocusMode=Qe.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Qe.SMOOTHING_FACTOR,this._lastValidFocusDistance=null,this._smoothedFocusDistance=null,this._afPointDirty=!1,this._afSuspended=!1,this._defaultCameraState=null,this._onResize=null,this._onReset=null,this._getSettings=null,this._applySettings=null}setCameras(e){this.cameras=e,this._userCameraCounter=0}addCameraFromView(e){let t=this.camera,n=new r.PerspectiveCamera(t.fov,t.aspect,t.near,t.far);return n.position.copy(t.position),n.quaternion.copy(t.quaternion),n.scale.copy(t.scale),n.updateMatrixWorld(!0),n.userData.__rayzeeUserCamera=!0,n.userData.__rayzeeEffects=this._captureEffects(),this.controls&&(n.userData.__rayzeeOrbitTarget=this.controls.target.clone()),this._userCameraCounter+=1,n.name=e||`View Camera ${this._userCameraCounter}`,this.cameras.push(n),this.cameras.length-1}removeCamera(e){if(!Number.isInteger(e)||e<=0||e>=this.cameras.length||!this.cameras[e]?.userData?.__rayzeeUserCamera)return!1;let t=this.currentCameraIndex===e;return this.cameras.splice(e,1),t?(this.currentCameraIndex=-1,this.switchCamera(0)):this.currentCameraIndex>e&&--this.currentCameraIndex,!0}getCameraNames(){return!this.cameras||this.cameras.length===0?[`Default Camera`]:this.cameras.map((e,t)=>t===0?`Default Camera`:e.name||`Camera ${t}`)}initCallbacks({onResize:e,onReset:t,getSettings:n,applySettings:r}){this._onResize=e,this._onReset=t,this._getSettings=n,this._applySettings=r}_captureEffects(){let e=this._getSettings;return e?{enableDOF:e(`enableDOF`),focusDistance:e(`focusDistance`),aperture:e(`aperture`),focalLength:e(`focalLength`),apertureScale:e(`apertureScale`),anamorphicRatio:e(`anamorphicRatio`),autoFocusMode:this.autoFocusMode,afScreenPoint:{...this.afScreenPoint}}:null}_applyEffects(e){e&&(this._applySettings?.({enableDOF:e.enableDOF,focusDistance:e.focusDistance,aperture:e.aperture,focalLength:e.focalLength,apertureScale:e.apertureScale,anamorphicRatio:e.anamorphicRatio}),e.autoFocusMode!==void 0&&this.setAutoFocusMode(e.autoFocusMode),e.afScreenPoint&&this.setAFScreenPoint(e.afScreenPoint.x,e.afScreenPoint.y))}_getSceneScale(){return this._afContext?.assetLoader?.getSceneScale?.()||1}switchCamera(e,t,n,i){if(t??=this._getSettings?.(`focusDistance`),n??=this._onResize,i??=this._onReset,!this.cameras||this.cameras.length===0)return;(e<0||e>=this.cameras.length)&&(console.warn(`CameraManager: Invalid camera index ${e}. Using default camera.`),e=0);let a=this.cameras[this.currentCameraIndex];if(a&&(a.userData.__rayzeeEffects=this._captureEffects()),this.currentCameraIndex===0&&e!==0&&(this._defaultCameraState={position:this.camera.position.clone(),quaternion:this.camera.quaternion.clone(),scale:this.camera.scale.clone(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.scale.copy(e.scale??Dy),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let n=this.cameras[e];if(this.camera.position.copy(n.position),this.camera.quaternion.copy(n.quaternion),this.camera.scale.copy(n.scale),this.camera.fov=n.fov,this.camera.near=n.near,this.camera.far=n.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls){let e=n.userData?.__rayzeeOrbitTarget;if(e)this.controls.target.copy(e);else{let e=new r.Vector3(0,0,-1).applyQuaternion(n.quaternion),i=t||5;this.controls.target.copy(this.camera.position).addScaledVector(e,i)}this.controls.update()}}this._applyEffects(this.cameras[e]?.userData?.__rayzeeEffects),n?.(),i?.();let o=this._captureEffects();o&&(o.focusDistance/=this._getSceneScale()),this.dispatchEvent({type:`CameraSwitched`,cameraIndex:e,effects:o,fov:this.camera.fov})}focusOn(e){!e||!this.controls||(this.controls.target.copy(e),this.controls.update(),this._onReset?.())}get active(){return this.camera}getNames(){return this.getCameraNames()}setAutoFocusMode(e){this.autoFocusMode=e,e!==`manual`&&(this._smoothedFocusDistance=null,this._afPointDirty=!0)}setAFScreenPoint(e,t){this.afScreenPoint={x:e,y:t},this._afPointDirty=!0}enterAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.enterAFPointPlacementMode(),this.controls&&(this.controls.enabled=!1))}exitAFPointPlacementMode(){this.interactionManager&&(this.interactionManager.exitAFPointPlacementMode(),this.controls&&(this.controls.enabled=!0))}updateAutoFocus(e){let{meshScene:t,assetLoader:n,floorPlane:r,currentFocusDistance:i,pathTracer:a,setFocusDistance:o,softReset:s,hardReset:c}=e||this._afContext||{};if(!t||this.autoFocusMode===`manual`)return;if(!a?.enableDOF?.value){this._afSuspended=!0;return}this._afSuspended&&(this._afSuspended=!1,this._smoothedFocusDistance=null);let l=a;if(l?.isReady&&l.renderMode?.value===1&&l.frameCount>0&&!l.isComplete)return;let u=this.afScreenPoint.x*2-1,d=-(this.afScreenPoint.y*2-1),f=this.interactionManager?.raycaster;if(!f)return;f.setFromCamera({x:u,y:d},this.camera);let p=f.intersectObjects(t.children,!0).find(e=>e.object!==this.interactionManager?.focusPointIndicator&&e.object!==r&&!e.object.name.includes(`Helper`)&&e.object.type===`Mesh`),m;if(p)m=p.distance,this._lastValidFocusDistance=m;else if(this._lastValidFocusDistance!==null)m=this._lastValidFocusDistance;else{let e=n?.getSceneScale()||1;m=Qe.FALLBACK_DISTANCE*e,this._lastValidFocusDistance=m}let h=this._afPointDirty;this._afPointDirty=!1,h||this._smoothedFocusDistance===null||this._smoothedFocusDistance===0||Math.abs(m-this._smoothedFocusDistance)/this._smoothedFocusDistance>Qe.SNAP_THRESHOLD?this._smoothedFocusDistance=m:this._smoothedFocusDistance+=this.afSmoothingFactor*(m-this._smoothedFocusDistance);let g=i,_=this._smoothedFocusDistance;if(h||g===0||Math.abs(_-g)/Math.max(g,.001)>.001){o(_);let e=n?.getSceneScale()||1;this.dispatchEvent({type:H.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Qe.RESET_THRESHOLD&&s?.()}}setInteractionManager(e){this.interactionManager=e}initAutoFocus({meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,settings:i,softReset:a,hardReset:o}){this._afContext={meshScene:e,assetLoader:t,floorPlane:n,pathTracer:r,setFocusDistance:e=>i.set(`focusDistance`,e,{silent:!0}),softReset:a,hardReset:o},Object.defineProperty(this._afContext,`currentFocusDistance`,{get:()=>i.get(`focusDistance`)})}dispose(){this.controls?.dispose()}},ky=class extends r.EventDispatcher{constructor(e,t,n,r={}){super(),this.scene=e,this.sceneHelpers=t,this.pathTracer=n,this._onReset=r.onReset||null}addLight(e){let t={DirectionalLight:{position:[1,1,1],intensity:1,color:`#ffffff`},PointLight:{position:[0,2,0],intensity:1e3,color:`#ffffff`},SpotLight:{position:[0,1,0],intensity:1e3,color:`#ffffff`,angle:15},RectAreaLight:{position:[0,2,0],intensity:100,color:`#ffffff`,width:2,height:2}}[e];if(!t)return null;let n;if(e===`DirectionalLight`)n=new r.DirectionalLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`PointLight`)n=new r.PointLight(t.color,t.intensity),n.position.fromArray(t.position);else if(e===`SpotLight`){n=new r.SpotLight(t.color,t.intensity),n.position.fromArray(t.position),n.angle=r.MathUtils.degToRad(t.angle);let e=new r.Object3D;this.scene.add(e),n.target=e}else e===`RectAreaLight`&&(n=new r.RectAreaLight(t.color,t.intensity,t.width,t.height),n.position.fromArray(t.position),n.lookAt(0,0,0),n.userData.normalize=!0,n.userData.spread=Math.PI,n.userData.shape=`rectangle`);n.userData.temperature=6500,n.userData.useTemperature=!1,n.userData.exposure=0;let i=this.scene.getObjectsByProperty(`isLight`,!0).length;return n.name=`${e.replace(`Light`,``)} ${i+1}`,this.scene.add(n),this.updateLights(),this._syncHelpers(),this._onReset?.(),this._buildDescriptor(n)}removeLight(e){let t=this.scene.getObjectByProperty(`uuid`,e);return!t||!t.isLight?!1:(this.sceneHelpers.remove(t),t.target&&t.target.removeFromParent(),t.removeFromParent(),this.updateLights(),this._onReset?.(),!0)}clearLights(){this.sceneHelpers.clear(),this._removeAllLights(),this.updateLights(),this._onReset?.()}getLights(){return this.scene.getObjectsByProperty(`isLight`,!0).map(e=>this._buildDescriptor(e))}updateLights(){this.pathTracer?.updateLights(),this.sceneHelpers?.visible&&this.sceneHelpers.update()}transferSceneLights(e){this._removeAllLights();let t=e.getObjectsByProperty(`isLight`,!0);if(!t||t.length===0){this.updateLights();return}for(let e of t){let t=e.clone();if(e.updateWorldMatrix(!0,!1),e.getWorldPosition(t.position),e.getWorldQuaternion(t.quaternion),e.getWorldScale(t.scale),t.isRectAreaLight&&(t.width*=t.scale.x,t.height*=t.scale.y,t.scale.set(1,1,1)),(e.isSpotLight||e.isDirectionalLight)&&e.target){let n=new r.Object3D;e.target.updateWorldMatrix(!0,!1),e.target.getWorldPosition(n.position),this.scene.add(n),t.target=n}this.scene.add(t)}this.updateLights(),this._syncHelpers()}setShowLightHelper(e){this.sceneHelpers.visible=e,e?this._syncHelpers():this.sceneHelpers.clear()}add(e){return this.addLight(e)}remove(e){return this.removeLight(e)}clear(){this.clearLights()}getAll(){return this.getLights()}sync(){this.updateLights()}showHelpers(e){this.setShowLightHelper(e)}dispose(){this._disposed||(this._disposed=!0,this.sceneHelpers?.clear(),this._removeAllLights(),this._onReset=null,this.pathTracer=null,this.sceneHelpers=null,this.scene=null)}_removeAllLights(){this.scene.getObjectsByProperty(`isLight`,!0).forEach(e=>{e.target&&this.scene.remove(e.target),this.scene.remove(e)})}_syncHelpers(){if(!this.sceneHelpers.visible)return;let e=this.scene.getObjectsByProperty(`isLight`,!0);this.sceneHelpers.sync(e)}_buildDescriptor(e){let t=0;e.type===`SpotLight`&&e.angle!==void 0?t=r.MathUtils.radToDeg(e.angle):e.type===`DirectionalLight`&&(t=r.MathUtils.radToDeg(e.userData?.angle??0));let n={uuid:e.uuid,name:e.name,type:e.type,visible:e.visible,intensity:e.intensity,color:`#${e.color.getHexString()}`,position:[e.position.x,e.position.y,e.position.z],angle:t,temperature:e.userData?.temperature??6500,useTemperature:e.userData?.useTemperature??!1,exposure:e.userData?.exposure??0};if(e.type===`RectAreaLight`){n.width=e.width,n.height=e.height,n.normalize=e.userData?.normalize??!0,n.spread=r.MathUtils.radToDeg(e.userData?.spread??Math.PI);let t=e.userData?.shape;n.shape=t===`square`||t===`rectangle`||t===`disk`||t===`ellipse`?t:t===1?`ellipse`:`rectangle`;let i=e.getWorldDirection(e.position.clone());n.target=[e.position.x+i.x,e.position.y+i.y,e.position.z+i.z]}else e.type===`SpotLight`&&e.target?(n.target=[e.target.position.x,e.target.position.y,e.target.position.z],n.distance=e.distance??0,n.penumbra=e.penumbra??0,n.decay=e.decay??2):e.type===`PointLight`&&(n.distance=e.distance??0,n.decay=e.decay??2);return(e.type===`SpotLight`||e.type===`DirectionalLight`)&&e.userData?.gobo&&(n.gobo=e.userData.gobo.name,n.goboIntensity=e.userData.gobo.intensity,n.goboInverted=!!e.userData.gobo.inverted,e.type===`DirectionalLight`&&(n.goboScale=e.userData.gobo.scale??5)),e.type===`SpotLight`&&e.userData?.ies&&(n.ies=e.userData.ies.name,n.iesIntensity=e.userData.ies.intensity??1,n.fixtureLumens=e.userData.ies.fixtureLumens??null),n}},Ay=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this.texture=null,this.entries=[],this._size=256}async loadLibrary(e,{size:t=256}={}){if(!Array.isArray(e)||e.length===0)return[];this._size=t;let n=await Promise.all(e.map(e=>jy(e.url))),i=t,a=t,o=n.length,s=new Uint8Array(i*a*o*4),c=document.createElement(`canvas`);c.width=i,c.height=a;let l=c.getContext(`2d`,{willReadFrequently:!0});for(let e=0;e<o;e++){l.clearRect(0,0,i,a),l.drawImage(n[e],0,0,i,a);let t=l.getImageData(0,0,i,a);s.set(t.data,e*i*a*4)}let u=new r.DataArrayTexture(s,i,a,o);u.minFilter=r.LinearFilter,u.magFilter=r.LinearFilter,u.format=r.RGBAFormat,u.type=r.UnsignedByteType,u.generateMipmaps=!1,u.needsUpdate=!0;let d=this.texture;return this.texture=u,this.entries=e.map((e,t)=>({name:e.name,index:t})),this.pathTracer.goboMaps=u,this.pathTracer.shaderBuilder?.updateGoboMaps?.(u),d?.dispose?.(),this.entries}getEntries(){return this.entries.slice()}setLightGobo(e,t,n={}){let{intensity:r=1,inverted:i=!1,scale:a=5}=n,o=this._findGoboLight(e);if(!o)return!1;if(o.userData=o.userData||{},t==null)delete o.userData.gobo;else{let e=this.entries.find(e=>e.name===t);if(!e)return console.warn(`GoboManager: unknown gobo "${t}"`),!1;o.userData.gobo={name:e.name,index:e.index,intensity:My(r),inverted:!!i,scale:Math.max(1e-4,a)}}return this.pathTracer.updateLights(),this._onReset?.(),!0}setLightGoboInverted(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.inverted=!!t,this.pathTracer.updateLights(),this._onReset?.(),!0):!1}setLightGoboScale(e,t){let n=this._findGoboLight(e);return n?.userData?.gobo?(n.userData.gobo.scale=Math.max(1e-4,t),this.pathTracer.updateLights(),this._onReset?.(),!0):!1}getLightGobo(e){return this._findGoboLight(e)?.userData?.gobo||null}setSpotLightGobo(e,t,n=1,r=!1){return this.setLightGobo(e,t,{intensity:n,inverted:r})}setSpotLightGoboInverted(e,t){return this.setLightGoboInverted(e,t)}getSpotLightGobo(e){return this.getLightGobo(e)}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null}_findGoboLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&(t.isSpotLight||t.isDirectionalLight)?t:null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function jy(e){return new Promise((t,n)=>{let r=new Image;r.crossOrigin=`anonymous`,r.onload=()=>t(r),r.onerror=()=>n(Error(`Failed to load gobo image: ${e}`)),r.src=e})}function My(e){return Math.max(0,Math.min(1,e))}function Ny(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
972
+ `,n);if(r<0)throw Error(`IES (${t}): truncated TILT line`);let i=e.slice(n,r).match(/TILT\s*=\s*(\w+)/i),a=i?i[1].toUpperCase():`NONE`,o=e.slice(r);if(a===`INCLUDE`){let e=Ly(o),t=2+2*Number(e[1]);o=Ry(o,t)}let s=Ly(o),c=0,l=()=>Number(s[c++]),u=l(),d=l(),f=l(),p=l(),m=l(),h=l();l(),l(),l(),l();let g=l();if(l(),l(),!Number.isFinite(p)||p<=0)throw Error(`IES (${t}): invalid vertical angle count ${p}`);if(!Number.isFinite(m)||m<=0)throw Error(`IES (${t}): invalid horizontal angle count ${m}`);let _=Array(p);for(let e=0;e<p;e++)_[e]=l();let v=Array(m);for(let e=0;e<m;e++)v[e]=l();let y=Array(p);for(let e=0;e<p;e++)y[e]=new Float32Array(m);let b=f*g,x=0;for(let e=0;e<m;e++)for(let t=0;t<p;t++){let n=l()*b;y[t][e]=n,n>x&&(x=n)}return{verticalAngles:_,horizontalAngles:v,candela:y,maxCandela:x,lumens:d*u,photometricType:h,name:t}}function Py(e,t,n){let r=new Uint8Array(t*n),{verticalAngles:i,horizontalAngles:a,candela:o,maxCandela:s}=e;if(s<=0)return r;let c=i[i.length-1],l=a[a.length-1],u=a[0],d=a.length===1||l===u;for(let e=0;e<n;e++){let f=(e+.5)/n*c,p=zy(i,f),m=Math.min(p+1,i.length-1),h=i[m]-i[p],g=h>0?(f-i[p])/h:0;for(let n=0;n<t;n++){let i;if(d)i=By(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=zy(a,e),s=Math.min(r+1,a.length-1),c=a[s]-a[r],d=c>0?(e-a[r])/c:0,f=o[p][r],h=o[p][s],_=o[m][r],v=o[m][s];i=By(By(f,h,d),By(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function Fy(e,t=.1){let{verticalAngles:n,horizontalAngles:r,candela:i,maxCandela:a}=e,o=Math.PI/4;if(a<=0||!n?.length)return o;let s=a*t,c=r.length,l=n[n.length-1],u=!1;for(let e=0;e<n.length;e++){let t=0;for(let n=0;n<c;n++)t+=i[e][n];if(t/=c,t>=s&&(u=!0),u&&t<s){l=n[e];break}}let d=l*Math.PI/180;return Math.min(Math.max(d,5*Math.PI/180),89*Math.PI/180)}function Iy(e,t,n=.7){let{verticalAngles:r,horizontalAngles:i,candela:a,maxCandela:o}=e;if(o<=0||!r?.length||t<=0)return 0;let s=o*n,c=i.length,l=0;for(let e=0;e<r.length;e++){let t=0;for(let n=0;n<c;n++)t+=a[e][n];if(t/=c,t>=s)l=r[e];else break}let u=t*180/Math.PI,d=u>0?1-l/u:0;return Math.min(Math.max(d,0),1)}function Ly(e){return e.split(/\s+/).filter(e=>e.length>0)}function Ry(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function zy(e,t){if(t<=e[0])return 0;if(t>=e[e.length-1])return e.length-1;let n=0,r=e.length-1;for(;r-n>1;){let i=n+r>>1;e[i]<=t?n=i:r=i}return n}function By(e,t,n){return e+(t-e)*n}var Vy=class{constructor(e,t={}){this.pathTracer=e,this._onReset=t.onReset||null,this.texture=null,this.entries=[],this._gridWidth=128,this._gridHeight=128}async loadLibrary(e,{gridWidth:t=128,gridHeight:n=128}={}){if(!Array.isArray(e)||e.length===0)return[];this._gridWidth=t,this._gridHeight=n;let i=(await Promise.all(e.map(async e=>{try{let r=await fetch(e.url);if(!r.ok)throw Error(`HTTP ${r.status}`);let i=Ny(await r.text(),e.name);return{it:e,profile:i,grid:Py(i,t,n)}}catch(t){return console.warn(`IESManager: failed to load "${e.name}": ${t.message}`),null}}))).filter(e=>e!==null);if(i.length===0)return[];let a=i.length,o=t*n,s=new Uint8Array(o*4*a),c=[];for(let e=0;e<a;e++){let t=i[e].grid,n=e*o*4;for(let e=0;e<o;e++){let r=t[e];s[n+e*4+0]=r,s[n+e*4+1]=r,s[n+e*4+2]=r,s[n+e*4+3]=255}let r=i[e].profile,a=Fy(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:Iy(r,a),lumens:r.lumens})}let l=new r.DataArrayTexture(s,t,n,a);l.format=r.RGBAFormat,l.type=r.UnsignedByteType,l.minFilter=r.LinearFilter,l.magFilter=r.LinearFilter,l.generateMipmaps=!1,l.needsUpdate=!0;let u=this.texture;return this.texture=l,this.entries=c,this.pathTracer.iesProfiles=l,this.pathTracer.shaderBuilder?.updateIESProfiles?.(l),u?.dispose?.(),this.entries.map(({name:e,index:t})=>({name:e,index:t}))}getEntries(){return this.entries.slice()}setSpotLightProfile(e,t,n=1,{applyAutoCone:r=!0}={}){let i=this._findSpotLight(e),a={applied:!1,suggestedAngle:null,suggestedPenumbra:null,suggestedDecay:null,fixtureLumens:null};if(!i)return a;i.userData=i.userData||{};let o=null,s=null,c=null,l=null;if(t==null)delete i.userData.ies;else{let e=this.entries.find(e=>e.name===t);if(!e)return console.warn(`IESManager: unknown profile "${t}"`),a;l=Number.isFinite(e.lumens)?e.lumens:null,i.userData.ies={name:e.name,index:e.index,intensity:Hy(n),fixtureLumens:l},r&&(Number.isFinite(e.suggestedAngle)&&(i.angle=e.suggestedAngle,o=e.suggestedAngle),Number.isFinite(e.suggestedPenumbra)&&(i.penumbra=e.suggestedPenumbra,s=e.suggestedPenumbra),i.decay=2,c=2)}return this.pathTracer.updateLights(),this._onReset?.(),{applied:!0,suggestedAngle:o,suggestedPenumbra:s,suggestedDecay:c,fixtureLumens:l}}getSpotLightProfile(e){return this._findSpotLight(e)?.userData?.ies||null}dispose(){this.texture?.dispose?.(),this.texture=null,this.entries=[],this.pathTracer=null,this._onReset=null}_findSpotLight(e){let t=this.pathTracer?.scene?.getObjectByProperty?.(`uuid`,e);return t&&t.isSpotLight?t:null}};function Hy(e){return Math.max(0,Math.min(1,e))}qt(),Ar();var Uy=Pt(`oidn`),Wy=16,Gy=null;async function Ky(){return Gy||=(await import(`oidn-web`)).initUNetFromBuffer,Gy}var qy={QUALITY_MODELS:{fast:{model:`rt_hdr_alb_nrm_small`,cleanAux:!1},"fast-clean":{model:`rt_hdr_calb_cnrm_small`,cleanAux:!0},balance:{model:`rt_hdr_calb_cnrm`,cleanAux:!0},high:{model:`rt_hdr_calb_cnrm_large`,cleanAux:!0}},DEFAULT_OPTIONS:{enableOIDN:!0,oidnQuality:`fast`,tileSize:1024}},Jy=.18,Yy=256,Xy=256,Zy=`
973
+ const WG: u32 = ${Yy}u;
974
+ const GROUPS: u32 = ${Xy}u;
975
975
 
976
976
  @group(0) @binding(0) var<storage, read> col: array<vec4<f32>>;
977
977
  @group(0) @binding(1) var<storage, read_write> partials: array<f32>;
@@ -990,7 +990,7 @@ fn treeSum( lid: u32 ) {
990
990
  }
991
991
  }
992
992
 
993
- @compute @workgroup_size(${Ey})
993
+ @compute @workgroup_size(${Yy})
994
994
  fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
995
995
  @builtin(local_invocation_id) lid: vec3<u32>,
996
996
  @builtin(workgroup_id) wid: vec3<u32> ) {
@@ -1013,7 +1013,7 @@ fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
1013
1013
  if ( lid.x == 0u ) { partials[ wid.x ] = sdata[ 0 ]; }
1014
1014
  }
1015
1015
 
1016
- @compute @workgroup_size(${Ey})
1016
+ @compute @workgroup_size(${Yy})
1017
1017
  fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
1018
1018
 
1019
1019
  var v = 0.0;
@@ -1023,12 +1023,12 @@ fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
1023
1023
  treeSum( lid.x );
1024
1024
 
1025
1025
  if ( lid.x == 0u ) {
1026
- let scale = ${Ty} / exp2( sdata[ 0 ] / f32( params.x ) );
1026
+ let scale = ${Jy} / exp2( sdata[ 0 ] / f32( params.x ) );
1027
1027
  // Mirrors the CPU guard: a non-finite or non-positive scale means no scaling at all.
1028
1028
  scaleOut[ 0 ] = select( 1.0, scale, scale > 0.0 && scale < 3.4e38 );
1029
1029
  }
1030
1030
  }
1031
- `,ky=`
1031
+ `,Qy=`
1032
1032
  @group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;
1033
1033
  @group(0) @binding(1) var<storage, read> scaleBuf: array<f32>;
1034
1034
 
@@ -1040,7 +1040,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32>,
1040
1040
  let c = col[ i ];
1041
1041
  col[ i ] = vec4<f32>( c.xyz * scaleBuf[ 0 ], c.w );
1042
1042
  }
1043
- `,Ay=64,jy=32768,My=16,Ny=32,Py=`
1043
+ `,$y=64,eb=32768,tb=16,nb=32,rb=`
1044
1044
  struct UnpackParams {
1045
1045
  srcWidth: u32,
1046
1046
  tileX: u32,
@@ -1058,7 +1058,7 @@ struct UnpackParams {
1058
1058
  @group(0) @binding(3) var<storage, read> inColor: array<vec4<f32>>;
1059
1059
  @group(0) @binding(4) var dst: texture_storage_2d<rgba16float, write>;
1060
1060
 
1061
- @compute @workgroup_size(${My}, ${My})
1061
+ @compute @workgroup_size(${tb}, ${tb})
1062
1062
  fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1063
1063
 
1064
1064
  if ( gid.x >= P.tileW || gid.y >= P.tileH ) { return; }
@@ -1072,7 +1072,245 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1072
1072
  // survives the denoise.
1073
1073
  textureStore( dst, vec2<u32>( px, py ), vec4<f32>( src[ si ].xyz / scaleBuf[ 0 ], inColor[ si ].w ) );
1074
1074
  }
1075
- `,Fy=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...wy.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{by.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=wy;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/xy)*xy;return t<=this.maxTileSize?t:Math.max(xy,Math.floor(this.maxTileSize/xy)*xy)}async _setupUNetDenoiser(){if(this.state.isLoading){this._reloadPending=!0;return}do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){by.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await Cy())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),by.debug(`UNet weights loaded:`,e)}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Or(),{QUALITY_MODELS:t}=wy;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(wy.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(wy.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,by.debug(`denoise complete in ${Y.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?by.debug(`denoise aborted`):by.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return by.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures();if(!r?.color)return by.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return by.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n);let a=i.createCommandEncoder({label:`oidn-tex-to-buf`}),o=t*16,s=this._gpuInputPaddedRowBytes,c=s>o,l=this._gpuInputPadBuffer,u=(e,r)=>{if(!c)a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:r,offset:0,bytesPerRow:o,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});else{a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:l,offset:0,bytesPerRow:s,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});for(let e=0;e<n;e++)a.copyBufferToBuffer(l,e*s,r,e*o,o)}};u(r.color,this._gpuInputBuffers.color),u(r.albedo,this._gpuInputBuffers.albedo),u(r.normal,this._gpuInputBuffers.normal),i.queue.submit([a.finish()]),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n),!e&&!this._hasOutput&&this._unpackToTexture(this._gpuInputBuffers.color,t,{x:0,y:0,width:t,height:n},!1);let d={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(d,e)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};let s=e*16,c=Math.ceil(s/256)*256;c===s?this._gpuInputPaddedRowBytes=s:(this._gpuInputPadBuffer=i.createBuffer({label:`oidn-in-pad`,size:c*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),this._gpuInputPaddedRowBytes=c)}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:Oy}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:ky}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:Py}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:Dy*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(Dy,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/Ay),r=Math.min(n,jy),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n,r=!0){let i=this.gpuDevice;if(!i||!this._ensureScalePipelines(i))return;let{x:a,y:o,width:s,height:c}=n;if(this._ensureOutputTexture(i,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let l=i.createBuffer({label:`oidn-unpack-params`,size:Ny,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{i.queue.writeBuffer(l,0,new Uint32Array([t,a,o,s,c,0,0,0]));let n=i.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),u=i.createCommandEncoder({label:`oidn-output-unpack`}),d=u.beginComputePass({label:`oidn-output-unpack`});d.setPipeline(this._unpackPipeline),d.setBindGroup(0,n),d.dispatchWorkgroups(Math.ceil(s/My),Math.ceil(c/My),1),d.end(),i.queue.submit([u.finish()]),r&&(this._hasOutput=!0)}finally{l.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){by.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,by.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{by.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this.state.abortController=null,this.removeAllListeners?.(),by.debug(`disposed`)}},Iy='let e={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`},t=null;async function n(){return t||(t=await import(e.ortRuntimeUrl),t.env.wasm.wasmPaths=e.ortWasmPaths,t.env.logLevel=`error`,t)}function r(){return`${e.cacheNamespace}:ai-upscaler-models`}const i=`models`;let a=null,o=null;function s(){return new Promise((e,t)=>{let n=indexedDB.open(r(),1);n.onupgradeneeded=()=>n.result.createObjectStore(i),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function c(e){try{let t=await s();return await new Promise((n,r)=>{let a=t.transaction(i,`readonly`).objectStore(i).get(e);a.onsuccess=()=>n(a.result||null),a.onerror=()=>r(a.error)})}catch{return null}}async function l(e,t){try{let n=await s();await new Promise((r,a)=>{let o=n.transaction(i,`readwrite`);o.objectStore(i).put(t,e),o.oncomplete=()=>r(),o.onerror=()=>a(o.error)})}catch{}}async function u(e){let t=await c(e);if(t)return console.log(`AI Upscaler Worker: model loaded from cache (${(t.byteLength/1024/1024).toFixed(1)}MB)`),t;let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model: ${n.status}`);let r=await n.arrayBuffer();return l(e,r.slice(0)),r}async function d(e,t){if(a&&o===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}a&&=(await a.release(),null);let[r,i]=await Promise.all([u(e),n()]);a=await i.InferenceSession.create(r,t),o=e;let s=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);s=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${s}`)}catch{}let c=(r.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${c}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:s})}async function f(e,t,r,i){let o=await n(),s=a.inputNames[0],c=a.outputNames[0],l=new o.Tensor(`float32`,e,[1,3,r,t]),u=(await a.run({[s]:l}))[c].data;self.postMessage({type:`inferred`,outputData:u,id:i},[u.buffer])}self.onmessage=async t=>{let{type:n}=t.data;try{n===`load`?(t.data.ortRuntimeUrl&&(e.ortRuntimeUrl=t.data.ortRuntimeUrl),t.data.ortWasmPaths&&(e.ortWasmPaths=t.data.ortWasmPaths),t.data.cacheNamespace&&(e.cacheNamespace=t.data.cacheNamespace),await d(t.data.url,t.data.sessionOptions)):n===`infer`?await f(t.data.tileData,t.data.width,t.data.height,t.data.id):n===`dispose`&&a&&(await a.release(),a=null,o=null)}catch(e){self.postMessage({type:`error`,message:e.message,id:t.data?.id})}};',Ly=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Iy],{type:`text/javascript;charset=utf-8`});function Ry(e){let t;try{if(t=Ly&&(self.URL||self.webkitURL).createObjectURL(Ly),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(Iy),{type:`module`,name:e?.name})}}Ar();var zy=e=>sd(e)?(e=>e>1?1:e<0?0:e):(e=>e**+cd),By={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function Vy(){let{upscalerModelBaseUrl:e}=Or(),t={};for(let n in By){t[n]={};for(let r in By[n])t[n][r]=e+By[n][r]}return t}var Hy={get QUALITY_PRESETS(){return Vy()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Uy=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||Hy.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0}async _ensureSession(){let e=Hy.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new Ry,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o}=Or();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Hy.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*a,i*a),t.isHDR&&(this._hdrToneMapFn=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),this._hdrEncode=zy(this.getToneMapping()),this._hdrExposure=ud(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Hy.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,md(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut);let s=this._hdrEncode;l[d]=s(this._tmOut[0]),l[c+d]=s(this._tmOut[1]),l[2*c+d]=s(this._tmOut[2])}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:n,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),l=ud(this.getExposure(),this.getToneMapping()),u=zy(this.getToneMapping()),d=this.getSaturation(),f=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,r=n[t]*l,i=n[t+1]*l,a=n[t+2]*l;d!==1&&(f[0]=r,f[1]=i,f[2]=a,md(f,d),r=f[0],i=f[1],a=f[2]),c(r,i,a,1,f),s[t]=u(f[0])*255+.5|0,s[t+1]=u(f[1])*255+.5|0,s[t+2]=u(f[2])*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Hy.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0,console.log(`AIUpscaler disposed`)}};function Wy(){let{wgsl:e,bindings:t}=Qi({group:Gy,firstBinding:Ky});return{wgsl:e,bindings:t,version:Hi()}}var Gy,Ky,qy,Jy,Yy,Xy=y((()=>{ca(),Gy=0,Ky=3,Wy().wgsl,qy=e=>`
1075
+ `,ib=class extends r.EventDispatcher{constructor(e,t={}){if(super(),!e)throw Error(`OIDNDenoiser requires a renderer`);this.renderer=e,this._renderWidth=e.domElement.width,this._renderHeight=e.domElement.height,this.backendParamsGetter=t.backendParams||null,this.getGPUTextures=t.getGPUTextures||null,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._lumBindGroup=null,this._lumPartials=null,this._lumParams=null,this._inputScaleBuffer=null,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._unpackPipeline=null,this._outGPUTexture=null,this._outTexture=null,this._outTexSize={width:0,height:0},this.config={...qy.DEFAULT_OPTIONS,...t},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._tilesWritten=0,this._runId=0,this._hasOutput=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._weights=new Map,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{Uy.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=qy;return(t[e]||t.balance).cleanAux}getRuntimeInfo(){return this.unet?.getRuntimeInfo?.()??null}profileNextDenoise(){return this.unet?.profileNextExecution?.()??!1}async getLastDenoiseProfile(){return await this.unet?.getLastExecutionProfile?.()??null}_resolveTileSize(){let e=Math.max(this._renderWidth,this._renderHeight);if(!e)return this.maxTileSize;let t=Math.ceil(e/Wy)*Wy;return t<=this.maxTileSize?t:Math.max(Wy,Math.floor(this.maxTileSize/Wy)*Wy)}async _setupUNetDenoiser(){if(this.state.isLoading){this._reloadPending=!0;return}do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){Uy.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1}}while(this._reloadPending);if(this._pendingStart&&this.unet&&this.enabled){let e=this._pendingStartContinuous;this._pendingStart=!1,this._pendingStartContinuous=!1,this.start({continuous:e})}}async _loadUNetWeights(){let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet)return;this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.state.isDenoising&&this.state.abortController?.abort(),await new Promise(e=>setTimeout(e,0)),this.unet.dispose(),null);let n;if(this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await Ky())(await this._fetchWeights(e),n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),Uy.debug(`UNet weights loaded:`,e)}_fetchWeights(e){let t=this._weights.get(e);return t||(t=fetch(e).then(t=>{if(!t.ok)throw Error(`HTTP ${t.status} fetching ${e}`);return t.arrayBuffer()}),t.catch(()=>this._weights.delete(e)),this._weights.set(e,t)),t}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=Or(),{QUALITY_MODELS:t}=qy;return`${e}${(t[this.quality]||t.balance).model}.tza`}async updateConfiguration(e){Object.keys(e).some(t=>this.config[t]!==e[t])&&(Object.assign(this.config,e),this.quality=this.config.oidnQuality,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(qy.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(qy.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start({continuous:e=!1}={}){if(!this.enabled||this.state.isDenoising)return!1;if(this.unet&&!this.state.isLoading&&this._activeTileSize!==this._resolveTileSize()&&await this._setupUNetDenoiser(),this.state.isLoading)return this._pendingStartContinuous=this._pendingStart?this._pendingStartContinuous&&e:e,this._pendingStart=!0,!1;this.dispatchEvent({type:`start`,continuous:e});let t=performance.now(),n=await this.execute(e);return n&&(this.renderer?.resetState?.(),this.lastDenoiseMs=performance.now()-t,Uy.debug(`denoise complete in ${Y.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}async execute(e=!1){if(!this.enabled||!this.unet)return!1;let t=++this._runId;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNetGPU(e)!==!1}catch(e){return e.name===`AbortError`?Uy.debug(`denoise aborted`):Uy.error(`denoise error:`,e),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNetGPU(e=!1){let t=this._renderWidth,n=this._renderHeight;if(!this.getGPUTextures)return Uy.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures({continuous:e});if(!r?.color)return Uy.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return Uy.warn(`gpuDevice not available`),!1;this._ensureGPUInputBuffers(t,n);let a=i.createCommandEncoder({label:`oidn-tex-to-buf`}),o=t*16,s=this._gpuInputPaddedRowBytes,c=s>o,l=this._gpuInputPadBuffer,u=(e,r)=>{if(!c)a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:r,offset:0,bytesPerRow:o,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});else{a.copyTextureToBuffer({texture:e,mipLevel:0},{buffer:l,offset:0,bytesPerRow:s,rowsPerImage:n},{width:t,height:n,depthOrArrayLayers:1});for(let e=0;e<n;e++)a.copyBufferToBuffer(l,e*s,r,e*o,o)}};u(r.color,this._gpuInputBuffers.color),u(r.albedo,this._gpuInputBuffers.albedo),u(r.normal,this._gpuInputBuffers.normal),i.queue.submit([a.finish()]),this._computeInputScale(i,t*n),this._applyColorScale(i,t*n),!e&&!this._hasOutput&&this._unpackToTexture(this._gpuInputBuffers.color,t,{x:0,y:0,width:t,height:n},!1);let d={color:{data:this._gpuInputBuffers.color,width:t,height:n},albedo:{data:this._gpuInputBuffers.albedo,width:t,height:n},normal:{data:this._gpuInputBuffers.normal,width:t,height:n}};return this._executeWithAbortGPU(d,e)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};let s=e*16,c=Math.ceil(s/256)*256;c===s?this._gpuInputPaddedRowBytes=s:(this._gpuInputPadBuffer=i.createBuffer({label:`oidn-in-pad`,size:c*t,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC}),this._gpuInputPaddedRowBytes=c)}_destroyGPUInputBuffers(){this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._colorScaleBindGroup=null,this._lumBindGroup=null,this._lumPartials?.destroy(),this._lumPartials=null,this._lumParams?.destroy(),this._lumParams=null,this._inputScaleBuffer?.destroy(),this._inputScaleBuffer=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._gpuInputBufferSize={width:0,height:0}}_ensureScalePipelines(e){let t=this._gpuInputBuffers.color;if(!e||!t)return!1;if(!this._lumLayout){this._lumLayout=e.createBindGroupLayout({label:`oidn-autoexposure`,entries:[{binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:`read-only-storage`}},{binding:1,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}},{binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{type:`uniform`}},{binding:3,visibility:GPUShaderStage.COMPUTE,buffer:{type:`storage`}}]});let t=e.createShaderModule({label:`oidn-autoexposure`,code:Zy}),n=e.createPipelineLayout({bindGroupLayouts:[this._lumLayout]});this._lumReducePipeline=e.createComputePipeline({label:`oidn-autoexposure-reduce`,layout:n,compute:{module:t,entryPoint:`reduce`}}),this._lumFinalizePipeline=e.createComputePipeline({label:`oidn-autoexposure-finalize`,layout:n,compute:{module:t,entryPoint:`finalize`}})}return this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:Qy}),entryPoint:`main`}}),this._unpackPipeline||=e.createComputePipeline({label:`oidn-output-unpack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-unpack`,code:rb}),entryPoint:`main`}}),this._inputScaleBuffer||(this._inputScaleBuffer=e.createBuffer({label:`oidn-input-scale`,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST|GPUBufferUsage.COPY_SRC,size:4}),this._lumPartials=e.createBuffer({label:`oidn-autoexposure-partials`,size:Xy*4,usage:GPUBufferUsage.STORAGE}),this._lumParams=e.createBuffer({label:`oidn-autoexposure-params`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})),this._lumBindGroup||=e.createBindGroup({label:`oidn-autoexposure`,layout:this._lumLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._lumPartials}},{binding:2,resource:{buffer:this._lumParams}},{binding:3,resource:{buffer:this._inputScaleBuffer}}]}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._inputScaleBuffer}}]}),!0}_computeInputScale(e,t){if(!this._ensureScalePipelines(e))return;if(globalThis.__OIDN_NO_INPUT_SCALE){e.queue.writeBuffer(this._inputScaleBuffer,0,new Float32Array([1]));return}e.queue.writeBuffer(this._lumParams,0,new Uint32Array([t,0,0,0]));let n=e.createCommandEncoder({label:`oidn-autoexposure`}),r=n.beginComputePass({label:`oidn-autoexposure-reduce`});r.setPipeline(this._lumReducePipeline),r.setBindGroup(0,this._lumBindGroup),r.dispatchWorkgroups(Xy,1,1),r.end();let i=n.beginComputePass({label:`oidn-autoexposure-finalize`});i.setPipeline(this._lumFinalizePipeline),i.setBindGroup(0,this._lumBindGroup),i.dispatchWorkgroups(1,1,1),i.end(),e.queue.submit([n.finish()])}_applyColorScale(e,t){if(!this._ensureScalePipelines(e))return;let n=Math.ceil(t/$y),r=Math.min(n,eb),i=Math.ceil(n/r),a=e.createCommandEncoder({label:`oidn-color-scale`}),o=a.beginComputePass({label:`oidn-color-scale`});o.setPipeline(this._colorScalePipeline),o.setBindGroup(0,this._colorScaleBindGroup),o.dispatchWorkgroups(r,i,1),o.end(),e.queue.submit([a.finish()])}get outputTexture(){return this._outTexture}_ensureOutputTexture(e,n,i){if(this._outGPUTexture&&this._outTexSize.width===n&&this._outTexSize.height===i)return;this._releaseOutputTexture(),this._outGPUTexture=e.createTexture({label:`oidn-output`,size:{width:n,height:i,depthOrArrayLayers:1},format:`rgba16float`,usage:GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC});let a=new t.ExternalTexture(this._outGPUTexture);a.name=`oidn:output`,a.image={width:n,height:i,depth:1},a.type=r.HalfFloatType,a.format=r.RGBAFormat,a.colorSpace=r.NoColorSpace,a.minFilter=r.NearestFilter,a.magFilter=r.NearestFilter,a.wrapS=r.ClampToEdgeWrapping,a.wrapT=r.ClampToEdgeWrapping,a.generateMipmaps=!1,a.flipY=!1,this._outTexture=a,this._outTexSize={width:n,height:i}}_releaseOutputTexture(){this._outTexture?.dispose(),this._outGPUTexture?.destroy(),this._outTexture=null,this._outGPUTexture=null,this._outTexSize={width:0,height:0}}_unpackToTexture(e,t,n,r=!0){let i=this.gpuDevice;if(!i||!this._ensureScalePipelines(i))return;let{x:a,y:o,width:s,height:c}=n;if(this._ensureOutputTexture(i,this._renderWidth,this._renderHeight),!this._outGPUTexture)return;let l=i.createBuffer({label:`oidn-unpack-params`,size:nb,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});try{i.queue.writeBuffer(l,0,new Uint32Array([t,a,o,s,c,0,0,0]));let n=i.createBindGroup({label:`oidn-output-unpack`,layout:this._unpackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:this._inputScaleBuffer}},{binding:3,resource:{buffer:this._gpuInputBuffers.color}},{binding:4,resource:this._outGPUTexture.createView()}]}),u=i.createCommandEncoder({label:`oidn-output-unpack`}),d=u.beginComputePass({label:`oidn-output-unpack`});d.setPipeline(this._unpackPipeline),d.setBindGroup(0,n),d.dispatchWorkgroups(Math.ceil(s/tb),Math.ceil(c/tb),1),d.end(),i.queue.submit([u.finish()]),r&&(this._hasOutput=!0)}finally{l.destroy()}}_executeWithAbortGPU(e,t=!1){return new Promise((n,r)=>{if(this.state.abortController?.signal.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._tilesWritten=0;let a=()=>{i&&=(i(),null),r(new DOMException(`Aborted`,`AbortError`))};this.state.abortController.signal.addEventListener(`abort`,a,{once:!0}),i=this.unet.tileExecute({...e,done:async e=>{this.state.abortController.signal.removeEventListener(`abort`,a),i=null;try{this._tilesWritten===0&&this._displayGPUOutput(e),n()}catch(e){r(e)}},progress:(e,n,r)=>{if(!e?.data||!r)return;let i=e.width,a=e.height,o=Math.min(r.width,i-r.x),s=Math.min(r.height,a-r.y);if(o<=0||s<=0)return;let c={x:r.x,y:r.y,width:o,height:s};this._unpackToTexture(e.data,i,c),this._tilesWritten++,this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}})})}_displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){Uy.error(`gpuDevice not available for the output picture`);return}this._unpackToTexture(e,t,{x:0,y:0,width:t,height:n})}abort(){this._pendingStart=!1,this._pendingStartContinuous=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this.state.isDenoising=!1,Uy.debug(`denoise aborted`))}get hasOutput(){return this._hasOutput}invalidateOutput(){this._hasOutput=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this._renderWidth=e,this._renderHeight=t,this._hasOutput=!1,this.lastDenoiseMs=0,this._setupUNetDenoiser().catch(e=>{Uy.error(`reinitialize after size change failed:`,e)})}dispose(){this.abort(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._releaseOutputTexture(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._unpackPipeline=null,this.unet=null,this._weights.clear(),this.state.abortController=null,this.removeAllListeners?.(),Uy.debug(`disposed`)}},ab=Object.freeze({maxLength:8,smoothLength:2,roughStart:.45,roughEnd:.7,depthTolerance:.05,normalTolerance:.8,movedLength:2}),ob=8,sb=288,cb=16,lb=1,ub=2,db=1073741824,fb=`
1076
+ struct Params {
1077
+ size: vec2<u32>,
1078
+ reset: u32,
1079
+ flags: u32,
1080
+ maxLength: f32,
1081
+ smoothLength: f32,
1082
+ depthTolerance: f32,
1083
+ normalTolerance: f32,
1084
+ roughStart: f32,
1085
+ roughEnd: f32,
1086
+ samples: f32,
1087
+ historyScale: f32,
1088
+ camWorld: mat4x4<f32>,
1089
+ projInv: mat4x4<f32>,
1090
+ prevViewProj: mat4x4<f32>,
1091
+ prevCamPos: vec4<f32>,
1092
+ moved: vec4<u32>,
1093
+ movedLength: f32,
1094
+ };
1095
+
1096
+ @group(0) @binding(0) var<uniform> P: Params;
1097
+
1098
+ fn finite3( v: vec3<f32> ) -> bool {
1099
+ let e = bitcast<vec3<u32>>( v ) & vec3<u32>( 0x7f800000u );
1100
+ return all( e != vec3<u32>( 0x7f800000u ) );
1101
+ }
1102
+
1103
+ // [0,1]-encoded in and out, renormalised like FinalWrite's clean aux.
1104
+ fn mixNormal( h: vec3<f32>, c: vec3<f32>, t: f32 ) -> vec3<f32> {
1105
+ let m = mix( h * 2.0 - 1.0, c * 2.0 - 1.0, t );
1106
+ let l = length( m );
1107
+ return select( c, m / l * 0.5 + 0.5, l > 1e-4 );
1108
+ }
1109
+ `,pb=fb+`
1110
+ @group(0) @binding(1) var geoCur: texture_2d<f32>;
1111
+ @group(0) @binding(2) var geoPrev: texture_2d<f32>;
1112
+ @group(0) @binding(3) var<storage, read_write> picked: array<i32>;
1113
+ @group(0) @binding(4) var<storage, read_write> copies: array<atomic<u32>>;
1114
+ @group(0) @binding(5) var instanceLeaf: texture_2d<u32>;
1115
+ @group(0) @binding(6) var<storage, read> movedLeaves: array<u32>;
1116
+ @group(0) @binding(7) var<storage, read> movedToPrev: array<mat4x4<f32>>;
1117
+
1118
+ fn movedIndex( leaf: u32 ) -> i32 {
1119
+
1120
+ var lo = 0u;
1121
+ var hi = P.moved.x;
1122
+ loop {
1123
+
1124
+ if ( lo >= hi ) { break; }
1125
+ let mid = ( lo + hi ) / 2u;
1126
+ let v = movedLeaves[ mid ];
1127
+ if ( v == leaf ) { return i32( mid ); }
1128
+ if ( v < leaf ) { lo = mid + 1u; } else { hi = mid; }
1129
+
1130
+ }
1131
+ return -1;
1132
+
1133
+ }
1134
+
1135
+ @compute @workgroup_size(${ob}, ${ob})
1136
+ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1137
+
1138
+ if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
1139
+
1140
+ let g = textureLoad( geoCur, vec2<i32>( gid.xy ), 0 );
1141
+ var best = -1.0;
1142
+ var pick = -1;
1143
+ var movedFlag = 0;
1144
+
1145
+ if ( P.reset == 0u && g.w < ${Re.toFixed(1)} ) {
1146
+
1147
+ let size = vec2<f32>( P.size );
1148
+ let uv = ( vec2<f32>( gid.xy ) + 0.5 ) / size;
1149
+ let rc = P.projInv * vec4<f32>( uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 1.0, 1.0 );
1150
+ let dir = normalize( ( P.camWorld * vec4<f32>( rc.xyz / rc.w, 0.0 ) ).xyz );
1151
+ var wp = P.camWorld[ 3 ].xyz + dir * g.w;
1152
+ var n = g.xyz * 2.0 - 1.0;
1153
+
1154
+ // A moved object's surface is looked for where the object was.
1155
+ let leaf = textureLoad( instanceLeaf, vec2<i32>( gid.xy ), 0 ).x;
1156
+ if ( leaf > 0u && P.moved.x > 0u ) {
1157
+
1158
+ let m = movedIndex( leaf - 1u );
1159
+ if ( m >= 0 ) {
1160
+
1161
+ let toPrev = movedToPrev[ u32( m ) ];
1162
+ wp = ( toPrev * vec4<f32>( wp, 1.0 ) ).xyz;
1163
+ n = normalize( ( toPrev * vec4<f32>( n, 0.0 ) ).xyz );
1164
+ movedFlag = ${db};
1165
+
1166
+ }
1167
+
1168
+ }
1169
+
1170
+ let clip = P.prevViewProj * vec4<f32>( wp, 1.0 );
1171
+
1172
+ if ( clip.w > 0.0 ) {
1173
+
1174
+ let pos = vec2<f32>( clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5 ) * size - 0.5;
1175
+ let base = vec2<i32>( floor( pos ) );
1176
+ let f = fract( pos );
1177
+ let expected = length( wp - P.prevCamPos.xyz );
1178
+
1179
+ for ( var j = 0; j < 2; j++ ) {
1180
+ for ( var i = 0; i < 2; i++ ) {
1181
+
1182
+ let q = base + vec2<i32>( i, j );
1183
+ if ( any( q < vec2<i32>( 0 ) ) || any( q >= vec2<i32>( P.size ) ) ) { continue; }
1184
+ let h = textureLoad( geoPrev, q, 0 );
1185
+ if ( abs( h.w - expected ) >= P.depthTolerance * expected ) { continue; }
1186
+ if ( dot( n, h.xyz * 2.0 - 1.0 ) <= P.normalTolerance ) { continue; }
1187
+ let w = select( 1.0 - f.x, f.x, i == 1 ) * select( 1.0 - f.y, f.y, j == 1 );
1188
+ if ( w > best ) { best = w; pick = q.y * i32( P.size.x ) + q.x; }
1189
+
1190
+ }
1191
+ }
1192
+
1193
+ }
1194
+
1195
+ }
1196
+
1197
+ picked[ gid.y * P.size.x + gid.x ] = select( pick, pick | movedFlag, pick >= 0 );
1198
+ if ( pick >= 0 ) { atomicAdd( &copies[ u32( pick ) ], 1u ); }
1199
+
1200
+ }
1201
+ `,mb=fb+`
1202
+ @group(0) @binding(1) var curColor: texture_2d<f32>;
1203
+ @group(0) @binding(2) var curAlbedo: texture_2d<f32>;
1204
+ @group(0) @binding(3) var curNormal: texture_2d<f32>;
1205
+ @group(0) @binding(4) var shading: texture_2d<f32>;
1206
+ @group(0) @binding(5) var histColor: texture_2d<f32>;
1207
+ @group(0) @binding(6) var histAlbedo: texture_2d<f32>;
1208
+ @group(0) @binding(7) var histNormal: texture_2d<f32>;
1209
+ @group(0) @binding(8) var<storage, read> picked: array<i32>;
1210
+ @group(0) @binding(9) var<storage, read> copies: array<u32>;
1211
+ @group(0) @binding(10) var outColor: texture_storage_2d<rgba32float, write>;
1212
+ @group(0) @binding(11) var outAlbedo: texture_storage_2d<rgba32float, write>;
1213
+ @group(0) @binding(12) var outNormal: texture_storage_2d<rgba32float, write>;
1214
+
1215
+ @compute @workgroup_size(${ob}, ${ob})
1216
+ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1217
+
1218
+ if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
1219
+
1220
+ let p = vec2<i32>( gid.xy );
1221
+ var cur = textureLoad( curColor, p, 0 );
1222
+ if ( ! finite3( cur.xyz ) ) { cur = vec4<f32>( 0.0, 0.0, 0.0, cur.w ); }
1223
+ let ca = textureLoad( curAlbedo, p, 0 );
1224
+ let cn = textureLoad( curNormal, p, 0 );
1225
+
1226
+ var len = 0.0;
1227
+ var hc = cur.xyz;
1228
+ var ha = ca.xyz;
1229
+ var hn = cn.xyz;
1230
+ let raw = picked[ gid.y * P.size.x + gid.x ];
1231
+ let movedPx = raw >= 0 && ( raw & ${db} ) != 0;
1232
+ let pick = select( raw, raw & ~${db}, raw >= 0 );
1233
+
1234
+ if ( pick >= 0 ) {
1235
+
1236
+ let q = vec2<i32>( pick % i32( P.size.x ), pick / i32( P.size.x ) );
1237
+ let c = textureLoad( histColor, q, 0 ).xyz;
1238
+
1239
+ if ( finite3( c ) ) {
1240
+
1241
+ let a = textureLoad( histAlbedo, q, 0 );
1242
+ hc = c;
1243
+ ha = a.xyz;
1244
+ hn = textureLoad( histNormal, q, 0 ).xyz;
1245
+ len = a.w;
1246
+ if ( ( P.flags & ${ub}u ) != 0u ) { len = len / f32( max( copies[ u32( pick ) ], 1u ) ); }
1247
+
1248
+ }
1249
+
1250
+ }
1251
+
1252
+ let rough = textureLoad( shading, p, 0 ).w;
1253
+ var cap = mix( P.smoothLength, P.maxLength, smoothstep( P.roughStart, P.roughEnd, rough ) );
1254
+ if ( movedPx ) { cap = min( cap, P.movedLength ); }
1255
+ let newLen = min( len + 1.0, cap );
1256
+ let t = 1.0 / newLen;
1257
+
1258
+ textureStore( outColor, p, vec4<f32>( mix( hc, cur.xyz, t ), cur.w ) );
1259
+ textureStore( outAlbedo, p, vec4<f32>( mix( ha, ca.xyz, t ), newLen ) );
1260
+ let n = select( cn.xyz, mixNormal( hn, cn.xyz, t ), ( P.flags & ${lb}u ) != 0u );
1261
+ textureStore( outNormal, p, vec4<f32>( n, cn.w ) );
1262
+
1263
+ }
1264
+ `,hb=fb+`
1265
+ @group(0) @binding(1) var accColor: texture_2d<f32>;
1266
+ @group(0) @binding(2) var accAlbedo: texture_2d<f32>;
1267
+ @group(0) @binding(3) var accNormal: texture_2d<f32>;
1268
+ @group(0) @binding(4) var histColor: texture_2d<f32>;
1269
+ @group(0) @binding(5) var histAlbedo: texture_2d<f32>;
1270
+ @group(0) @binding(6) var histNormal: texture_2d<f32>;
1271
+ @group(0) @binding(7) var outColor: texture_storage_2d<rgba32float, write>;
1272
+ @group(0) @binding(8) var outAlbedo: texture_storage_2d<rgba32float, write>;
1273
+ @group(0) @binding(9) var outNormal: texture_storage_2d<rgba32float, write>;
1274
+
1275
+ @compute @workgroup_size(${ob}, ${ob})
1276
+ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1277
+
1278
+ if ( gid.x >= P.size.x || gid.y >= P.size.y ) { return; }
1279
+
1280
+ let p = vec2<i32>( gid.xy );
1281
+ let ac = textureLoad( accColor, p, 0 );
1282
+ let aa = textureLoad( accAlbedo, p, 0 );
1283
+ let an = textureLoad( accNormal, p, 0 );
1284
+
1285
+ var k = 0.0;
1286
+ var hc = ac.xyz;
1287
+ var ha = aa.xyz;
1288
+ var hn = an.xyz;
1289
+
1290
+ if ( P.reset == 0u ) {
1291
+
1292
+ let c = textureLoad( histColor, p, 0 ).xyz;
1293
+
1294
+ if ( finite3( c ) ) {
1295
+
1296
+ let a = textureLoad( histAlbedo, p, 0 );
1297
+ k = a.w * P.historyScale;
1298
+ hc = c;
1299
+ ha = a.xyz;
1300
+ hn = textureLoad( histNormal, p, 0 ).xyz;
1301
+
1302
+ }
1303
+
1304
+ }
1305
+
1306
+ let t = P.samples / max( k + P.samples, 1e-6 );
1307
+ textureStore( outColor, p, vec4<f32>( mix( hc, ac.xyz, t ), ac.w ) );
1308
+ textureStore( outAlbedo, p, vec4<f32>( mix( ha, aa.xyz, t ), min( k + P.samples, P.maxLength ) ) );
1309
+ let n = select( an.xyz, mixNormal( hn, an.xyz, t ), ( P.flags & ${lb}u ) != 0u );
1310
+ textureStore( outNormal, p, vec4<f32>( n, an.w ) );
1311
+
1312
+ }
1313
+ `,gb=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`unfilterable-float`}}),_b=e=>({binding:e,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:`write-only`,format:`rgba32float`}}),vb=(e,t)=>({binding:e,visibility:GPUShaderStage.COMPUTE,buffer:{type:t}}),yb=class{constructor(e){this.device=e,this.settings={...ab,cleanAux:!1,splitCopies:!0},this.valid=!1,this.width=0,this.height=0,this._sets=null,this._current=0,this._picked=null,this._copies=null,this._paramsBuffer=null,this._pipelines=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._movedCount=0,this._paramData=new ArrayBuffer(sb),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._prevViewProj=new Float32Array(16),this._prevCamPos=new Float32Array(4)}get textures(){return this.valid?this._sets[this._current]:null}invalidate(){this.valid=!1}accumulate(e,t,n=null){if(!this._ensure(e.width,e.height))return;this._uploadMoved(n),this._writeParams(t,!this.valid,0,1);let r=this._sets[this._current],i=this._sets[1-this._current],{select:a,blend:o}=this._pipelines,s=this.device.createCommandEncoder({label:`oidn-history`});s.clearBuffer(this._copies),this._dispatch(s,a,[{buffer:this._paramsBuffer},e.geo,e.geoPrev,{buffer:this._picked},{buffer:this._copies},e.leaf,{buffer:this._movedLeaves},{buffer:this._movedToPrev}]),this._dispatch(s,o,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,e.shading,r.color,r.albedo,r.normal,{buffer:this._picked},{buffer:this._copies},i.color,i.albedo,i.normal]),this.device.queue.submit([s.finish()]),this._current=1-this._current,this.valid=!0,this._rememberCamera(t)}merge(e,t,n,{commit:r=!1,keepHistory:i=!0,historyScale:a=1}={}){if(!this._ensure(e.width,e.height))return null;this._writeParams(n,!this.valid||!i,t,a);let o=this._sets[this._current],s=this._sets[1-this._current],c=this.device.createCommandEncoder({label:`oidn-history-merge`});return this._dispatch(c,this._pipelines.merge,[{buffer:this._paramsBuffer},e.color,e.albedo,e.normal,o.color,o.albedo,o.normal,s.color,s.albedo,s.normal]),this.device.queue.submit([c.finish()]),r&&(this._current=1-this._current,this.valid=!0,this._rememberCamera(n)),s}dispose(){this._releaseTextures(),this._paramsBuffer?.destroy(),this._movedLeaves?.destroy(),this._movedToPrev?.destroy(),this._paramsBuffer=null,this._movedLeaves=null,this._movedToPrev=null,this._movedCapacity=0,this._pipelines=null}_ensure(e,t){if(!e||!t)return!1;if(this._ensurePipelines(),this._sets&&this.width===e&&this.height===t)return!0;this._releaseTextures();let n=this.device,r=GPUTextureUsage.STORAGE_BINDING|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC,i=i=>n.createTexture({label:i,size:{width:e,height:t},format:`rgba32float`,usage:r});return this._sets=[0,1].map(e=>({color:i(`oidn-history-color-${e}`),albedo:i(`oidn-history-albedo-${e}`),normal:i(`oidn-history-normal-${e}`)})),this._picked=n.createBuffer({label:`oidn-history-picked`,size:e*t*4,usage:GPUBufferUsage.STORAGE}),this._copies=n.createBuffer({label:`oidn-history-copies`,size:e*t*4,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t,this._current=0,this.valid=!1,!0}_ensurePipelines(){if(this._pipelines)return;let e=this.device,t=(t,n,r)=>{let i=e.createBindGroupLayout({label:t,entries:r});return{pipeline:e.createComputePipeline({label:t,layout:e.createPipelineLayout({bindGroupLayouts:[i]}),compute:{module:e.createShaderModule({label:t,code:n}),entryPoint:`main`}}),layout:i}},n=vb(0,`uniform`);this._pipelines={select:t(`oidn-history-select`,pb,[n,gb(1),gb(2),vb(3,`storage`),vb(4,`storage`),{binding:5,visibility:GPUShaderStage.COMPUTE,texture:{sampleType:`uint`}},vb(6,`read-only-storage`),vb(7,`read-only-storage`)]),blend:t(`oidn-history-blend`,mb,[n,...[1,2,3,4,5,6,7].map(gb),vb(8,`read-only-storage`),vb(9,`read-only-storage`),_b(10),_b(11),_b(12)]),merge:t(`oidn-history-merge`,hb,[n,...[1,2,3,4,5,6].map(gb),_b(7),_b(8),_b(9)])},this._paramsBuffer=e.createBuffer({label:`oidn-history-params`,size:sb,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._growMoved(cb)}_growMoved(e){this._movedLeaves?.destroy(),this._movedToPrev?.destroy();let t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST;this._movedLeaves=this.device.createBuffer({label:`oidn-history-moved-leaves`,size:e*4,usage:t}),this._movedToPrev=this.device.createBuffer({label:`oidn-history-moved-matrices`,size:e*64,usage:t}),this._movedCapacity=e}_uploadMoved(e){this._movedCount=e?.count??0,this._movedCount&&(this._movedCount>this._movedCapacity&&this._growMoved(Math.max(this._movedCount,this._movedCapacity*2)),this.device.queue.writeBuffer(this._movedLeaves,0,e.leaves,0,this._movedCount),this.device.queue.writeBuffer(this._movedToPrev,0,e.toPrev,0,this._movedCount*16))}_dispatch(e,{pipeline:t,layout:n},r){let i=r.map((e,t)=>({binding:t,resource:e.buffer?e:e.createView()})),a=e.beginComputePass();a.setPipeline(t),a.setBindGroup(0,this.device.createBindGroup({layout:n,entries:i})),a.dispatchWorkgroups(Math.ceil(this.width/ob),Math.ceil(this.height/ob)),a.end()}_writeParams(e,t,n,r){let i=this.settings,a=this._paramU32,o=this._paramF32;a[0]=this.width,a[1]=this.height,a[2]=+!!t,a[3]=(i.cleanAux?lb:0)|(i.splitCopies?ub:0),o[4]=i.maxLength,o[5]=i.smoothLength,o[6]=i.depthTolerance,o[7]=i.normalTolerance,o[8]=i.roughStart,o[9]=i.roughEnd,o[10]=n,o[11]=r,o.set(e.world,12),o.set(e.projInv,28),o.set(this._prevViewProj,44),o.set(this._prevCamPos,60),a[64]=this._movedCount,o[68]=i.movedLength,this.device.queue.writeBuffer(this._paramsBuffer,0,this._paramData)}_rememberCamera(e){this._prevViewProj.set(e.viewProj),this._prevCamPos[0]=e.world[12],this._prevCamPos[1]=e.world[13],this._prevCamPos[2]=e.world[14]}_releaseTextures(){this._sets?.forEach(e=>Object.values(e).forEach(e=>e.destroy())),this._picked?.destroy(),this._copies?.destroy(),this._sets=null,this._picked=null,this._copies=null,this.width=0,this.height=0,this.valid=!1}},bb='let e={ortRuntimeUrl:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/ort.webgpu.bundle.min.mjs`,ortWasmPaths:`https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.3/dist/`,cacheNamespace:`rayzee`},t=null;async function n(){return t||(t=await import(e.ortRuntimeUrl),t.env.wasm.wasmPaths=e.ortWasmPaths,t.env.logLevel=`error`,t)}function r(){return`${e.cacheNamespace}:ai-upscaler-models`}const i=`models`;let a=null,o=null;function s(){return new Promise((e,t)=>{let n=indexedDB.open(r(),1);n.onupgradeneeded=()=>n.result.createObjectStore(i),n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function c(e){try{let t=await s();return await new Promise((n,r)=>{let a=t.transaction(i,`readonly`).objectStore(i).get(e);a.onsuccess=()=>n(a.result||null),a.onerror=()=>r(a.error)})}catch{return null}}async function l(e,t){try{let n=await s();await new Promise((r,a)=>{let o=n.transaction(i,`readwrite`);o.objectStore(i).put(t,e),o.oncomplete=()=>r(),o.onerror=()=>a(o.error)})}catch{}}async function u(e){let t=await c(e);if(t)return console.log(`AI Upscaler Worker: model loaded from cache (${(t.byteLength/1024/1024).toFixed(1)}MB)`),t;let n=await fetch(e);if(!n.ok)throw Error(`Failed to fetch model: ${n.status}`);let r=await n.arrayBuffer();return l(e,r.slice(0)),r}async function d(e,t){if(a&&o===e){self.postMessage({type:`loaded`,backend:`webgpu`});return}a&&=(await a.release(),null);let[r,i]=await Promise.all([u(e),n()]);a=await i.InferenceSession.create(r,t),o=e;let s=512;try{let e=await navigator.gpu?.requestAdapter(),t=await e?.requestAdapterInfo?.()||e?.info,n=/apple|swiftshader|llvmpipe/i.test(t?.vendor||``)||/apple|swiftshader/i.test(t?.architecture||``),r=t?.device?.toLowerCase?.()?.includes(`integrated`)||/intel.*iris|intel.*uhd|intel.*hd|amd.*vega|radeon.*graphics/i.test(t?.description||``);s=n?128:r?256:512,console.log(`AI Upscaler Worker: GPU="${t?.description||t?.device||`unknown`}", tileSize=${s}`)}catch{}let c=(r.byteLength/1024/1024).toFixed(1);console.log(`AI Upscaler Worker: model loaded (${c}MB), backend: webgpu`),self.postMessage({type:`loaded`,backend:`webgpu`,tileSize:s})}async function f(e,t,r,i){let o=await n(),s=a.inputNames[0],c=a.outputNames[0],l=new o.Tensor(`float32`,e,[1,3,r,t]),u=(await a.run({[s]:l}))[c].data;self.postMessage({type:`inferred`,outputData:u,id:i},[u.buffer])}self.onmessage=async t=>{let{type:n}=t.data;try{n===`load`?(t.data.ortRuntimeUrl&&(e.ortRuntimeUrl=t.data.ortRuntimeUrl),t.data.ortWasmPaths&&(e.ortWasmPaths=t.data.ortWasmPaths),t.data.cacheNamespace&&(e.cacheNamespace=t.data.cacheNamespace),await d(t.data.url,t.data.sessionOptions)):n===`infer`?await f(t.data.tileData,t.data.width,t.data.height,t.data.id):n===`dispose`&&a&&(await a.release(),a=null,o=null)}catch(e){self.postMessage({type:`error`,message:e.message,id:t.data?.id})}};',xb=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,bb],{type:`text/javascript;charset=utf-8`});function Sb(e){let t;try{if(t=xb&&(self.URL||self.webkitURL).createObjectURL(xb),!t)throw``;let n=new Worker(t,{type:`module`,name:e?.name});return n.addEventListener(`error`,()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),n}catch{return new Worker(`data:text/javascript;charset=utf-8,`+encodeURIComponent(bb),{type:`module`,name:e?.name})}}Ar();var Cb=e=>sd(e)?(e=>e>1?1:e<0?0:e):(e=>e**+cd),wb={fast:{2:`2x-spanx2-ch48.onnx`,4:`4xNomos8k_span_otf_strong_fp32_opset17.onnx`},balanced:{2:`2xNomosUni_compact_otf_medium.onnx`,4:`RealESRGAN_x4plus.onnx`},quality:{2:`2x-realesrgan-x2plus.onnx`,4:`4xNomos2_hq_mosr_fp32.onnx`}};function Tb(){let{upscalerModelBaseUrl:e}=Or(),t={};for(let n in wb){t[n]={};for(let r in wb[n])t[n][r]=e+wb[n][r]}return t}var Eb={get QUALITY_PRESETS(){return Tb()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Db=class extends r.EventDispatcher{constructor(e,t,n={}){if(super(),!e||!t)throw Error(`AIUpscaler requires output canvas and renderer`);this.renderer=t,this.input=t.domElement,this.output=e,this.getSourceCanvas=n.getSourceCanvas||null,this.getGPUTextures=n.getGPUTextures||null,this.getExposure=n.getExposure||(()=>1),this.getToneMapping=n.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=n.getSaturation||(()=>1),this.enabled=!1,this.hdr=!1,this.scaleFactor=n.scaleFactor||2,this.quality=n.quality||`fast`,this.refreshInput=n.refreshInput||null,this.tileSize=n.tileSize||Eb.TILE_SIZE,this._tileSizeOverride=!!n.tileSize,this.state={isUpscaling:!1,isLoading:!1,abortController:null},this._worker=null,this._currentModelUrl=null,this._tileId=0,this._pendingWorkerHandlers=new Set,this._upscaledAlpha=null,this._upscaledAlphaWidth=0,this._backupCanvas=null,this._baseWidth=e.width,this._baseHeight=e.height,this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0}async _ensureSession(){let e=Eb.QUALITY_PRESETS[this.quality];if(!e)throw Error(`Unknown quality preset: ${this.quality}`);let t=e[this.scaleFactor];if(!t)throw Error(`No model for ${this.quality}/${this.scaleFactor}x`);if(!(this._worker&&this._currentModelUrl===t)){this.state.isLoading=!0,this.dispatchEvent({type:`loading`,message:`Loading ${this.scaleFactor}x upscale model...`});try{this._worker||=new Sb,await new Promise((e,n)=>{let r=t=>{t.data.type===`loaded`?(this._worker.removeEventListener(`message`,r),t.data.tileSize&&!this._tileSizeOverride&&(this.tileSize=t.data.tileSize),console.log(`AI Upscaler: ${this.scaleFactor}x model loaded, backend: ${t.data.backend}, tileSize: ${this.tileSize}`),e()):t.data.type===`error`&&(this._worker.removeEventListener(`message`,r),n(Error(t.data.message)))},{ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o}=Or();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Eb.SESSION_OPTIONS,ortRuntimeUrl:i,ortWasmPaths:a,cacheNamespace:o})}),this._currentModelUrl=t,this.dispatchEvent({type:`loaded`})}catch(e){throw console.error(`AI Upscaler: Failed to load model:`,e),this.dispatchEvent({type:`error`,error:e}),e}finally{this.state.isLoading=!1}}}async start(){if(!this.enabled||this.state.isUpscaling||this.state.isLoading)return!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.();let t=performance.now()-e;console.log(`AI Upscaler: ${this.scaleFactor}x upscale completed in ${t.toFixed(1)}ms`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled)return!1;this.state.abortController=new AbortController,this.state.isUpscaling=!0,this.hdr&&this.getGPUTextures?this._capturedSource=await this._captureSourceHDR():this._capturedSource=this._captureSource(),this._createBackup(this._capturedSource);let e=this._capturedSource.width*this.scaleFactor,t=this._capturedSource.height*this.scaleFactor;this.output.width=e,this.output.height=t;let n=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});n.imageSmoothingEnabled=!0,n.imageSmoothingQuality=`high`,n.drawImage(this._backupCanvas,0,0,e,t),this._revealOutput();try{return await this._ensureSession(),await this._runUpscale(),this.dispatchEvent({type:`resolution_changed`,width:this.output.width,height:this.output.height}),!0}catch(e){return e.name===`AbortError`?console.log(`AI Upscaler: Upscaling was aborted`):(console.error(`AI Upscaler: Upscaling error:`,e),this.dispatchEvent({type:`error`,error:e}),this._restoreBackup(),this.input.style.opacity=`1`,this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight})),!1}finally{this._capturedSource=null,this._upscaledAlpha=null,this._backupCanvas=null,this.state.isUpscaling&&(this.state.isUpscaling=!1,this.state.abortController=null,this.dispatchEvent({type:`end`}))}}abort(){this.state.isUpscaling&&(this.state.abortController?.abort(),this._cleanupPendingWorkerHandlers(),this.input.style.opacity=`1`,this._restoreBackup(),this.dispatchEvent({type:`resolution_changed`,width:this._baseWidth,height:this._baseHeight}),this.state.isUpscaling=!1,this.dispatchEvent({type:`end`}),console.log(`AI Upscaler: Aborted`))}async _runUpscale(){let e=this.state.abortController.signal,t=this._capturedSource;this._capturedSource=null;let{width:n,height:i}=t,a=this.scaleFactor,o=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0});this._cacheUpscaledAlpha(t,n*a,i*a),t.isHDR&&(this._hdrToneMapFn=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),this._hdrEncode=Cb(this.getToneMapping()),this._hdrExposure=ud(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Eb.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,md(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut);let s=this._hdrEncode;l[d]=s(this._tmOut[0]),l[c+d]=s(this._tmOut[1]),l[2*c+d]=s(this._tmOut[2])}else l[d]=a[u]/255,l[c+d]=a[u+1]/255,l[2*c+d]=a[u+2]/255}return l}async _inferTile(e,t,n){let r=++this._tileId;return new Promise((i,a)=>{let o=e=>{e.data.id===r&&(this._worker.removeEventListener(`message`,o),this._pendingWorkerHandlers.delete(o),e.data.type===`inferred`?i(e.data.outputData):e.data.type===`error`&&a(Error(e.data.message)))};this._pendingWorkerHandlers.add(o),this._worker.addEventListener(`message`,o),this._worker.postMessage({type:`infer`,tileData:e,width:t,height:n,id:r},[e.buffer])})}_tensorToImageData(e,t,n,r,i){let a=new ImageData(t,n),o=a.data,s=t*n,c=this._upscaledAlpha,l=this._upscaledAlphaWidth;for(let n=0;n<s;n++)if(o[n*4]=Math.min(255,Math.max(0,e[n]*255+.5))|0,o[n*4+1]=Math.min(255,Math.max(0,e[s+n]*255+.5))|0,o[n*4+2]=Math.min(255,Math.max(0,e[2*s+n]*255+.5))|0,c){let e=n/t|0,a=n%t;o[n*4+3]=c[(i+e)*l+(r+a)]}else o[n*4+3]=255;return a}_cacheUpscaledAlpha(e,t,n){let{data:r,width:i,height:a}=e,o=e.isHDR,s=o?1:255,c=!1;for(let e=3;e<r.length;e+=4)if(r[e]<s){c=!0;break}if(!c){this._upscaledAlpha=null,this._upscaledAlphaWidth=0;return}let l=document.createElement(`canvas`);l.width=i,l.height=a;let u=l.getContext(`2d`),d=u.createImageData(i,a);for(let e=0,t=i*a;e<t;e++){let t=o?Math.min(Math.max(r[e*4+3]*255,0),255)|0:r[e*4+3];d.data[e*4]=t,d.data[e*4+1]=t,d.data[e*4+2]=t,d.data[e*4+3]=255}u.putImageData(d,0,0);let f=document.createElement(`canvas`);f.width=t,f.height=n;let p=f.getContext(`2d`);p.imageSmoothingEnabled=!0,p.imageSmoothingQuality=`high`,p.drawImage(l,0,0,t,n);let m=p.getImageData(0,0,t,n).data,h=new Uint8Array(t*n);for(let e=0,r=t*n;e<r;e++)h[e]=m[e*4];this._upscaledAlpha=h,this._upscaledAlphaWidth=t}_createBackup(e){this._backupCanvas=document.createElement(`canvas`),this._backupCanvas.width=e.width,this._backupCanvas.height=e.height;let t=this._backupCanvas.getContext(`2d`);if(e.isHDR){let{data:n,width:i,height:a}=e,o=t.createImageData(i,a),s=o.data,c=ad.get(this.getToneMapping())||ad.get(r.ACESFilmicToneMapping),l=ud(this.getExposure(),this.getToneMapping()),u=Cb(this.getToneMapping()),d=this.getSaturation(),f=new Float32Array(3);for(let e=0,t=i*a;e<t;e++){let t=e*4,r=n[t]*l,i=n[t+1]*l,a=n[t+2]*l;d!==1&&(f[0]=r,f[1]=i,f[2]=a,md(f,d),r=f[0],i=f[1],a=f[2]),c(r,i,a,1,f),s[t]=u(f[0])*255+.5|0,s[t+1]=u(f[1])*255+.5|0,s[t+2]=u(f[2])*255+.5|0,s[t+3]=255}t.putImageData(o,0,0)}else t.putImageData(e,0,0)}_restoreBackup(){this._backupCanvas&&=(this.output.width=this._backupCanvas.width,this.output.height=this._backupCanvas.height,this.output.getContext(`2d`).drawImage(this._backupCanvas,0,0),null)}toggleHDR(e){this.hdr=!!e}setQuality(e){if(!Eb.QUALITY_PRESETS[e]){console.warn(`AIUpscaler: Invalid quality "${e}", must be fast/balanced/quality`);return}this.quality=e}setScaleFactor(e){if(e=Number(e),e!==2&&e!==4){console.warn(`AIUpscaler: Invalid scale factor ${e}, must be 2 or 4`);return}this.scaleFactor=e}setBaseSize(e,t){this._baseWidth=e,this._baseHeight=t}_cleanupPendingWorkerHandlers(){if(this._worker)for(let e of this._pendingWorkerHandlers)this._worker.removeEventListener(`message`,e);this._pendingWorkerHandlers.clear()}async dispose(){this.abort(),this._cleanupPendingWorkerHandlers(),this._worker&&=(this._worker.postMessage({type:`dispose`}),this._worker.terminate(),null),this._currentModelUrl=null,this._backupCanvas=null,this._upscaledAlpha=null,this.state.abortController=null,this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=null,this._hdrStagingWidth=0,this._hdrStagingHeight=0,console.log(`AIUpscaler disposed`)}};function Ob(){let{wgsl:e,bindings:t}=Qi({group:kb,firstBinding:Ab});return{wgsl:e,bindings:t,version:Hi()}}var kb,Ab,jb,Mb,Nb,Pb=y((()=>{ca(),kb=0,Ab=3,Ob().wgsl,jb=e=>`
1076
1314
  struct Params {
1077
1315
  width: u32,
1078
1316
  height: u32,
@@ -1103,7 +1341,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1103
1341
  let b8 = rayzee_to_u8( rayzee_encode( mapped, params.mode ) );
1104
1342
  dst[ gid.y * params.width + gid.x ] = b8.x | ( b8.y << 8u ) | ( b8.z << 16u ) | ( 255u << 24u );
1105
1343
  }
1106
- `,Jy=32,Yy=class{constructor(e,t=`rayzee:tonemap`){this.device=e,this.label=t,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(Jy),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=Wy();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:qy(e)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*4;this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:Jy,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:a,height:o}=this;this._paramU32[0]=a,this._paramU32[1]=o,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this.device.queue.writeBuffer(this._params,0,this._paramData);let s=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),c=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...s,{binding:0,resource:{buffer:e,size:a*o*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),l=this.device.createCommandEncoder({label:this.label}),u=l.beginComputePass();u.setPipeline(this._pipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(o/8)),u.end(),l.copyBufferToBuffer(this._storage,0,this._map,0,a*o*4),this.device.queue.submit([l.finish()]),await this._map.mapAsync(GPUMapMode.READ);let d=new Uint8ClampedArray(this._map.getMappedRange().slice(0));return this._map.unmap(),d}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}})),Zy=b({NeuralSuperRes:()=>fb,SR_MAX_INPUT:()=>cb,SR_SCALE:()=>2,presentRGBA8:()=>ab,readDenoisedHalf:()=>tb,releaseDenoisedReader:()=>eb,renderUpscaled:()=>rb});function Qy(){if(lb)return lb;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,lb=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),lb):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function $y(e,t,n){if(db&&(db.device!==e||db.width!==t||db.height!==n)&&eb(),db)return db;let r=t*n*8;return db={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:ub}),entryPoint:`main`}})},db}function eb(){db?.storage.destroy(),db?.map.destroy(),db=null}async function tb(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=$y(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function nb(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(H.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(H.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function rb(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await fb.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.set(`maxSamples`,r);let u=nb(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await tb(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&ib(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function ib(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function ab(e,t,n,r){return ib(e,t,n,r)}var ob,sb,cb,lb,ub,db,fb,pb=y((()=>{xe(),qt(),Xy(),Ar(),ob=2,sb=Pt(`neural`),cb=2048,lb=null,ub=`
1344
+ `,Mb=32,Nb=class{constructor(e,t=`rayzee:tonemap`){this.device=e,this.label=t,this.width=0,this.height=0,this._pipeline=null,this._storage=null,this._map=null,this._params=null,this._paramData=new ArrayBuffer(Mb),this._paramU32=new Uint32Array(this._paramData),this._paramF32=new Float32Array(this._paramData),this._shaderVersion=-1,this._bindings=[],this._tables=new Map,this.disposed=!1}_ensurePipeline(){let{wgsl:e,bindings:t,version:n}=Ob();this._pipeline&&this._shaderVersion===n||(this._bindings=t,this._shaderVersion=n,this._pipeline=this.device.createComputePipeline({label:this.label,layout:`auto`,compute:{module:this.device.createShaderModule({label:this.label,code:jb(e)}),entryPoint:`main`}}))}_ensureTables(){let e=new Set;for(let{index:t,transform:n}of this._bindings){let{data:r,size:i}=n.table;e.add(t);let a=this._tables.get(t);if(a&&a.data===r)continue;a?.texture.destroy();let o=this.device.createTexture({label:`${this.label}-${n.wgslConst}`,size:[i,i,i],dimension:`3d`,format:`rgba16float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});this.device.queue.writeTexture({texture:o},r,{bytesPerRow:i*8,rowsPerImage:i},[i,i,i]),this._tables.set(t,{texture:o,data:r,view:o.createView()})}for(let[t,n]of this._tables)e.has(t)||(n.texture.destroy(),this._tables.delete(t))}ensureSize(e,t){if(this._ensurePipeline(),this._ensureTables(),this.width===e&&this.height===t&&this._storage)return;this._releaseBuffers();let n=e*t*4;this._storage=this.device.createBuffer({label:`${this.label}-out`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._map=this.device.createBuffer({label:`${this.label}-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._params=this.device.createBuffer({label:`${this.label}-params`,size:Mb,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.width=e,this.height=t}async toRGBA8(e,{exposure:t=1,toneMapping:n=0,saturation:r=1,flipY:i=!1}={}){if(this.disposed)throw Error(`PackedToneMapper: disposed`);if(!this._storage)throw Error(`PackedToneMapper: call ensureSize() first`);this._ensurePipeline(),this._ensureTables();let{width:a,height:o}=this;this._paramU32[0]=a,this._paramU32[1]=o,this._paramU32[2]=n>>>0,this._paramU32[3]=+!!i,this._paramF32[4]=t,this._paramF32[5]=r,this.device.queue.writeBuffer(this._params,0,this._paramData);let s=[...this._tables.entries()].map(([e,t])=>({binding:e,resource:t.view})),c=this.device.createBindGroup({layout:this._pipeline.getBindGroupLayout(0),entries:[...s,{binding:0,resource:{buffer:e,size:a*o*8}},{binding:1,resource:{buffer:this._storage}},{binding:2,resource:{buffer:this._params}}]}),l=this.device.createCommandEncoder({label:this.label}),u=l.beginComputePass();u.setPipeline(this._pipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(Math.ceil(a/8),Math.ceil(o/8)),u.end(),l.copyBufferToBuffer(this._storage,0,this._map,0,a*o*4),this.device.queue.submit([l.finish()]),await this._map.mapAsync(GPUMapMode.READ);let d=new Uint8ClampedArray(this._map.getMappedRange().slice(0));return this._map.unmap(),d}_releaseBuffers(){this._storage?.destroy(),this._map?.destroy(),this._params?.destroy(),this._storage=null,this._map=null,this._params=null}dispose(){if(!this.disposed){this.disposed=!0,this._releaseBuffers();for(let e of this._tables.values())e.texture.destroy();this._tables.clear(),this._pipeline=null}}}})),Fb=b({NeuralSuperRes:()=>Xb,SR_MAX_INPUT:()=>Kb,SR_SCALE:()=>2,presentRGBA8:()=>Ub,readDenoisedHalf:()=>zb,releaseDenoisedReader:()=>Rb,renderUpscaled:()=>Vb});function Ib(){if(qb)return qb;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,qb=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getNativeSR)return t(globalThis.NeuralRuntime.getNativeSR());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getNativeSR;if(!e)return n(Error(`Neural runtime loaded but exposed no super-resolution entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),qb):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}function Lb(e,t,n){if(Yb&&(Yb.device!==e||Yb.width!==t||Yb.height!==n)&&Rb(),Yb)return Yb;let r=t*n*8;return Yb={device:e,width:t,height:n,storage:e.createBuffer({label:`rayzee:neural-sr-pack`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),map:e.createBuffer({label:`rayzee:neural-sr-pack-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),pipeline:e.createComputePipeline({label:`rayzee:neural-sr-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`rayzee:neural-sr-pack`,code:Jb}),entryPoint:`main`}})},Yb}function Rb(){Yb?.storage.destroy(),Yb?.map.destroy(),Yb=null}async function zb(e){let t=e?._outGPUTexture;if(!t)throw Error(`NeuralSuperRes: no denoised frame — enable OIDN and finish a render first`);let n=e.gpuDevice,{width:r,height:i}=e._outTexSize,a=Lb(n,r,i),o=n.createBindGroup({layout:a.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:t.createView()},{binding:1,resource:{buffer:a.storage}}]}),s=n.createCommandEncoder({label:`rayzee:neural-sr-pack`}),c=s.beginComputePass();c.setPipeline(a.pipeline),c.setBindGroup(0,o),c.dispatchWorkgroups(Math.ceil(r/8),Math.ceil(i/8)),c.end(),s.copyBufferToBuffer(a.storage,0,a.map,0,r*i*8),n.queue.submit([s.finish()]),await a.map.mapAsync(GPUMapMode.READ);let l=new Uint16Array(a.map.getMappedRange().slice(0));return a.map.unmap(),{half:l,width:r,height:i}}function Bb(e,t,n){return new Promise((r,i)=>{let a=!1,o=(t,n)=>{a||(a=!0,e.removeEventListener(H.DENOISING_END,c),clearInterval(l),clearTimeout(u),t?r():i(n))},s=!1,c=()=>{(e.stages?.pathTracer?.frameCount??0)>=t&&(s=!0)};e.addEventListener(H.DENOISING_END,c);let l=setInterval(()=>{s&&o(!0)},200),u=setTimeout(()=>o(!1,Error(`NeuralSuperRes: timed out waiting for the render to finish`)),n)})}async function Vb(e,{outputWidth:t,outputHeight:n,samples:r=64,upscaler:i=null,timeoutMs:a=6e5,present:o=!0,onProgress:s=()=>{}}={}){if(t%2||n%2)throw Error(`renderUpscaled: output must be divisible by 2, got ${t}x${n}`);let c=t/2,l=n/2,u=e.stages?.pathTracer,d={width:u?.width,height:u?.height,maxSamples:e.settings?.get?.(`maxSamples`),finalDenoise:e.denoisingManager?.finalDenoise,paused:e.pauseRendering},f=!i,p=i,m={};try{if(!p){let e=performance.now();s(`Loading the super-resolution model`),p=await Xb.create({width:c,height:l,onProgress:s}),m.load=performance.now()-e}else if(p.inputWidth!==c||p.inputHeight!==l)throw Error(`renderUpscaled: upscaler is ${p.inputWidth}x${p.inputHeight}, need ${c}x${l}`);let i=performance.now();s(`Tracing ${c}x${l} at ${r} spp`),e.pauseRendering=!1,e.setCanvasSize(c,l),await new Promise(e=>setTimeout(e,300)),e.denoisingManager.applyOIDNEnabled(!0),e.settings.set(`maxSamples`,r);let u=Bb(e,r,a);e.reset(),await u,e.pauseRendering=!0,m.render=performance.now()-i,s(`Reading the denoised frame`);let d=performance.now(),f=await zb(e.denoisingManager?.denoiser);m.read=performance.now()-d,s(`Upscaling to ${t}x${n}`);let h={exposure:e.renderer.toneMappingExposure,toneMapping:e.renderer.toneMapping,saturation:e.settings.get(`saturation`)??1},{rgba8:g,width:_,height:v,ms:y,toneMs:b}=await p.upscaleToRGBA8(f,h);return m.upscale=y,m.tonemap=b,o&&Hb(e.denoisingManager?.upscalerCanvas,g,_,v),{rgba8:g,width:_,height:v,timings:m,upscaler:p}}catch(e){throw f&&p?.dispose(),e}finally{d.width&&d.height&&e.setCanvasSize(d.width,d.height),d.maxSamples!==void 0&&e.settings?.set?.(`maxSamples`,d.maxSamples),d.finalDenoise!==void 0&&e.denoisingManager?.applyOIDNEnabled(d.finalDenoise),e.pauseRendering=d.paused}}function Hb(e,t,n,r){return e?(e.width=n,e.height=r,e.getContext(`2d`).putImageData(new ImageData(new Uint8ClampedArray(t.buffer??t),n,r),0,0),e.style.display=`block`,!0):!1}function Ub(e,t,n,r){return Hb(e,t,n,r)}var Wb,Gb,Kb,qb,Jb,Yb,Xb,Zb=y((()=>{xe(),qt(),Pb(),Ar(),Wb=2,Gb=Pt(`neural`),Kb=2048,qb=null,Jb=`
1107
1345
  @group(0) @binding(0) var src: texture_2d<f32>;
1108
1346
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1109
1347
 
@@ -1116,7 +1354,7 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
1116
1354
  dst[ a ] = pack2x16float( c.rg );
1117
1355
  dst[ a + 1u ] = pack2x16float( vec2<f32>( c.b, 1.0 ) );
1118
1356
  }
1119
- `,db=null,fb=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralSuperRes.create: width and height must be positive integers`);if(t>2048||n>2048)throw Error(`NeuralSuperRes.create: input capped at ${cb}px per side (${cb*2}px output), got ${t}x${n}. Above that the runtime's history plane exceeds maxTextureDimension2D and it fails later with an unrelated bind-group error.`);let i=await Qy(),a=document.createElement(`canvas`);a.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`,document.body.appendChild(a);let o;try{o=await i.create(a,{width:t,height:n,onProgress:r,timestamps:!0,nrSettings:null})}catch(e){throw a.remove(),e}let s=new e(o,a);return s._allocate(),s}_allocate(){let e=this.inputWidth,t=this.inputHeight;this._color=new Uint16Array(e*t*4),this._depth=new Float32Array(e*t),this._motion=new Uint16Array(e*t*2)}async _run(e){if(this.disposed)throw Error(`NeuralSuperRes: disposed`);let t=this.inputWidth,n=this.inputHeight;if(e.width!==t||e.height!==n)throw Error(`NeuralSuperRes: expected a ${t}x${n} source, got ${e.width}x${e.height}`);let r=this._color;if(!e.half||e.half.length!==r.length)throw Error(`NeuralSuperRes: expected ${r.length} packed halfs from readDenoisedHalf, got ${e.half?.length}`);r.set(e.half),this._depth.fill(.5),this._motion.fill(0);let i=performance.now(),a=await this.sr.render(this.slot,{color:r,depth:this._depth,motion:this._motion,reset:!0,jitter:[0,0]});return await this.sr.device.queue.onSubmittedWorkDone(),{result:a,ms:performance.now()-i}}async upscaleToRGBA8(e,t={}){let{result:n,ms:r}=await this._run(e),{outputWidth:i,outputHeight:a}=this.geometry;this._toneMapper??=new Yy(this.sr.device,`rayzee:neural-sr-tonemap`),this._toneMapper.ensureSize(i,a);let o=performance.now();return{rgba8:await this._toneMapper.toRGBA8(n.hdr.buffer??n.hdr,{exposure:t.exposure??1,toneMapping:t.toneMapping??0,saturation:t.saturation??1,flipY:!0}),width:i,height:a,ms:r,toneMs:performance.now()-o}}dispose(){if(!this.disposed){this.disposed=!0,this._toneMapper?.dispose(),this._toneMapper=null,this.canvas.remove();try{this.sr.destroy()}catch(e){sb.warn(`super resolution teardown:`,e)}}}}})),mb=b({NeuralRetouch:()=>Tb,RETOUCH_COLOR_STRENGTH:()=>0,RETOUCH_DEFAULTS:()=>vb,RETOUCH_MAX_PIXELS:()=>bb,RETOUCH_RANGES:()=>xb,enhanceFrame:()=>_b});function hb(e={}){let{colorStrength:t=0,...n}=e;return{runtime:{...vb,...n},colorStrength:t}}function gb(){if(Sb)return Sb;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,Sb=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getSrNrChain)return t(globalThis.NeuralRuntime.getSrNrChain());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getSrNrChain;if(!e)return n(Error(`Neural runtime loaded but exposed no retouch entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),Sb):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}async function _b({source:e,settings:t={},instance:n=null,exposure:r=1,tone:i=null,onProgress:a=()=>{}}){let o=n;o&&(o.width!==e.width||o.height!==e.height)&&(o.dispose(),o=null),o||=await Tb.create({width:e.width,height:e.height,settings:t,onProgress:a});let{runtime:s,colorStrength:c}=hb(t),l=o.staging;if(!e.half||e.half.length!==l.length)throw Error(`NeuralRetouch: expected ${l.length} packed halfs, got ${e.half?.length}`);l.set(e.half),o.device.queue.writeBuffer(o.source,0,l),o.chain.pipeline.paperWhite=1/Math.min(Math.max(r,1/Eb),Eb),o.chain.pipeline.colorStrength=c;let u=performance.now(),d=o.device.createCommandEncoder({label:`rayzee:retouch`});await o.chain.encode(d,o.slot,{buffer:o.source},s,()=>{},{reset:!0}),o.device.queue.submit([d.finish()]),await o.device.queue.onSubmittedWorkDone();let f=i?await o.readOutputToned(i):await o.readOutputHDR();return{instance:o,...f,ms:performance.now()-u}}var vb,yb,bb,xb,Sb,Cb,wb,Tb,Eb,Db=y((()=>{Xy(),qt(),Ar(),vb=Object.freeze({enabled:!0,intensity:1,localTone:1,localStructure:1,skinStructure:-1,autoMask:!0,style:0,preset:0,uiCorrection:!1}),yb=Pt(`neural`),bb=2048*2048,xb=Object.freeze({intensity:[0,1],localTone:[0,2],localStructure:[0,2],skinStructure:[-1,2],style:[0,2],preset:[0,3]}),Sb=null,Cb=`
1357
+ `,Yb=null,Xb=class e{constructor(e,t){this.sr=e,this.canvas=t,this.slot=0,this._color=null,this._depth=null,this._motion=null,this._toneMapper=null,this.disposed=!1}get geometry(){return this.sr.geometry}get inputWidth(){return this.sr.geometry.width}get inputHeight(){return this.sr.geometry.height}get outputWidth(){return this.sr.geometry.outputWidth}get outputHeight(){return this.sr.geometry.outputHeight}static async create({width:t,height:n,onProgress:r=()=>{}}={}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralSuperRes.create: width and height must be positive integers`);if(t>2048||n>2048)throw Error(`NeuralSuperRes.create: input capped at ${Kb}px per side (${Kb*2}px output), got ${t}x${n}. Above that the runtime's history plane exceeds maxTextureDimension2D and it fails later with an unrelated bind-group error.`);let i=await Ib(),a=document.createElement(`canvas`);a.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`,document.body.appendChild(a);let o;try{o=await i.create(a,{width:t,height:n,onProgress:r,timestamps:!0,nrSettings:null})}catch(e){throw a.remove(),e}let s=new e(o,a);return s._allocate(),s}_allocate(){let e=this.inputWidth,t=this.inputHeight;this._color=new Uint16Array(e*t*4),this._depth=new Float32Array(e*t),this._motion=new Uint16Array(e*t*2)}async _run(e){if(this.disposed)throw Error(`NeuralSuperRes: disposed`);let t=this.inputWidth,n=this.inputHeight;if(e.width!==t||e.height!==n)throw Error(`NeuralSuperRes: expected a ${t}x${n} source, got ${e.width}x${e.height}`);let r=this._color;if(!e.half||e.half.length!==r.length)throw Error(`NeuralSuperRes: expected ${r.length} packed halfs from readDenoisedHalf, got ${e.half?.length}`);r.set(e.half),this._depth.fill(.5),this._motion.fill(0);let i=performance.now(),a=await this.sr.render(this.slot,{color:r,depth:this._depth,motion:this._motion,reset:!0,jitter:[0,0]});return await this.sr.device.queue.onSubmittedWorkDone(),{result:a,ms:performance.now()-i}}async upscaleToRGBA8(e,t={}){let{result:n,ms:r}=await this._run(e),{outputWidth:i,outputHeight:a}=this.geometry;this._toneMapper??=new Nb(this.sr.device,`rayzee:neural-sr-tonemap`),this._toneMapper.ensureSize(i,a);let o=performance.now();return{rgba8:await this._toneMapper.toRGBA8(n.hdr.buffer??n.hdr,{exposure:t.exposure??1,toneMapping:t.toneMapping??0,saturation:t.saturation??1,flipY:!0}),width:i,height:a,ms:r,toneMs:performance.now()-o}}dispose(){if(!this.disposed){this.disposed=!0,this._toneMapper?.dispose(),this._toneMapper=null,this.canvas.remove();try{this.sr.destroy()}catch(e){Gb.warn(`super resolution teardown:`,e)}}}}})),Qb=b({NeuralRetouch:()=>lx,RETOUCH_COLOR_STRENGTH:()=>0,RETOUCH_DEFAULTS:()=>nx,RETOUCH_MAX_PIXELS:()=>ix,RETOUCH_RANGES:()=>ax,enhanceFrame:()=>tx});function $b(e={}){let{colorStrength:t=0,...n}=e;return{runtime:{...nx,...n},colorStrength:t}}function ex(){if(ox)return ox;let{neuralRuntimeUrl:e,neuralAssetBaseUrl:t}=Or();return t?(globalThis.__NEURAL_ASSET_BASE__=t,ox=new Promise((t,n)=>{if(globalThis.NeuralRuntime?.getSrNrChain)return t(globalThis.NeuralRuntime.getSrNrChain());let r=document.createElement(`script`);r.src=e,r.onload=()=>{let e=globalThis.NeuralRuntime?.getSrNrChain;if(!e)return n(Error(`Neural runtime loaded but exposed no retouch entry`));t(e())},r.onerror=()=>n(Error(`Failed to load the neural runtime from ${e}`)),document.head.appendChild(r)}),ox):Promise.reject(Error(`No neural model location: set neuralAssetBaseUrl with configureAssets()`))}async function tx({source:e,settings:t={},instance:n=null,exposure:r=1,tone:i=null,onProgress:a=()=>{}}){let o=n;o&&(o.width!==e.width||o.height!==e.height)&&(o.dispose(),o=null),o||=await lx.create({width:e.width,height:e.height,settings:t,onProgress:a});let{runtime:s,colorStrength:c}=$b(t),l=o.staging;if(!e.half||e.half.length!==l.length)throw Error(`NeuralRetouch: expected ${l.length} packed halfs, got ${e.half?.length}`);l.set(e.half),o.device.queue.writeBuffer(o.source,0,l),o.chain.pipeline.paperWhite=1/Math.min(Math.max(r,1/ux),ux),o.chain.pipeline.colorStrength=c;let u=performance.now(),d=o.device.createCommandEncoder({label:`rayzee:retouch`});await o.chain.encode(d,o.slot,{buffer:o.source},s,()=>{},{reset:!0}),o.device.queue.submit([d.finish()]),await o.device.queue.onSubmittedWorkDone();let f=i?await o.readOutputToned(i):await o.readOutputHDR();return{instance:o,...f,ms:performance.now()-u}}var nx,rx,ix,ax,ox,sx,cx,lx,ux,dx=y((()=>{Pb(),qt(),Ar(),nx=Object.freeze({enabled:!0,intensity:1,localTone:1,localStructure:1,skinStructure:-1,autoMask:!0,style:0,preset:0,uiCorrection:!1}),rx=Pt(`neural`),ix=2048*2048,ax=Object.freeze({intensity:[0,1],localTone:[0,2],localStructure:[0,2],skinStructure:[-1,2],style:[0,2],preset:[0,3]}),ox=null,sx=`
1120
1358
  @group(0) @binding(0) var src: texture_2d<f32>;
1121
1359
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1122
1360
 
@@ -1130,7 +1368,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1130
1368
  let b = u32(clamp(c.b, 0.0, 1.0) * 255.0 + 0.5);
1131
1369
  dst[gid.y * size.x + gid.x] = r | (g << 8u) | (b << 16u) | (255u << 24u);
1132
1370
  }
1133
- `,wb=`
1371
+ `,cx=`
1134
1372
  @group(0) @binding(0) var src: texture_2d<f32>;
1135
1373
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
1136
1374
 
@@ -1143,4 +1381,4 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
1143
1381
  dst[a] = pack2x16float(c.rg);
1144
1382
  dst[a + 1u] = pack2x16float(vec2<f32>(c.b, 1.0));
1145
1383
  }
1146
- `,Tb=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(bb/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await gb()).create(o,t,n,a,hb(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:Cb}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:wb}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Yy(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){yb.warn(`retouch teardown:`,e)}}}},Eb=20}));xe(),qt();var Ob=Pt(`neural`),kb=120,Ab=2,jb=1,Mb=0,Nb=300,Pb=5,Fb=3,Ib=3,Lb=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:r,getExposure:i,getSaturation:a}){super(),this.renderer=e,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=r,this._stages=n,this._getExposure=i,this._getSaturation=a,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._finalQuality=W.oidnQuality,this.finalDenoise=W.enableOIDN,this.continuousDenoise=W.continuousDenoise,this.continuousDenoiseInterval=W.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.denoiser=new Fy(this.renderer,{...W,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:H.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:H.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Uy(this.upscalerCanvas,this.renderer,{scaleFactor:W.upscalerScale||2,quality:W.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=W.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:H.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:H.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:H.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);t&&(i&&!t.enabled&&t.reset(),t.enabled=i),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>Nb*Fb&&(this._movingHopeless=!0);let n=!this._movingHopeless&&(t<2||e<=Nb);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<Ib||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?Mb:this._lastCadenceSamples===0?jb:Ab,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>kb&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>Pb&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:`resolution_changed`,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){Ob.warn(`neural pass skipped: the engine has no overlay canvas to present on`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){Ob.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:H.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(pb(),Zy));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(Db(),mb)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(Ob.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:`resolution_changed`,width:u.width,height:u.height})}catch(e){Ob.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:H.UPSCALING_END})}}}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,r=()=>{if(this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()){if(n&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay()}dispose(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=qe[e];if(!t)return;let n={};for(let e of Ke)n[e]=Ge[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=We[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},Rb=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},zb=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,g.outline)(e,i,{selectedObjects:[],edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let a=(0,n.uniform)(3),o=(0,n.uniform)(new r.Color(16777215)),s=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:c,hiddenEdge:l}=this._outlineNode,u=c.mul(o).add(l.mul(s)).mul(a),d=u.r.max(u.g).max(u.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(u,d),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Bb(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Vb(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var Hb=4096,Ub=class{constructor(){this.canvas=Bb(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Vb(this._sizeSource,Hb);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){Ae(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};qt();var Wb=Pt(`overlay`),Gb=(e,t)=>e.visible&&e.layer===t&&e.render,Kb=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Bb(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new Ub().init({device:e,sizeSource:t})}catch(e){Wb.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new Rb;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new zb(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(Wb.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())Gb(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Gb(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Gb(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Vb(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())Gb(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};xe();var qb=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this.wakeCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles`)}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){return this._mixerRoot.updateMatrixWorld(!0),e=>this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null}};xe();var Jb=new r.Vector3(0,0,-1),Yb=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e}attach(e){if(this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target)){let t=e.target.position.clone().sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Jb,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1,this._lastLightPosition=e.position.clone()}}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:H.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},Xb=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};qt(),xe(),ca();var Zb=new WeakMap,Qb=Pt(`engine`);function $b(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var ex=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function tx(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||ex.test(n)}}var nx=class extends r.EventDispatcher{constructor(e,t={}){super();try{Zb.get(e)?.dispose()}catch(e){Qb.warn(`prior canvas owner dispose failed`,e)}Zb.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Le(t.profile),this._issues=new fn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:H.ISSUE,issue:e})}),this.color=new mo({issues:this._issues}),co(this.color),this.settings=new jg({...W,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._maxTextureSize=W.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new qb,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Tg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Qb.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Qb.debug(`WebGPU path tracer app initialized`),this}animate(){if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:H.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Qb.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME});return}this.pipeline.render(),this.stages.pathTracer.isComplete||(this.completion.updateTime(),this.denoisingManager?.tickContinuousDenoise(this.stages.pathTracer.frameCount)),this._ensureVRAMWiring();let t=this.stages.pathTracer?.vramTracker,n=this.stages.pathTracer?.frameCount??0;if(t&&(n<=1||n%30==0)&&t.measure(),Te({timeElapsed:this.completion.timeElapsed,samples:Ee(this.stages.pathTracer),memoryUsed:t?.current??0,memoryPeak:t?.peak??0}),this.completion.isTimeLimitReached(this.stages.pathTracer,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context});let e={samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:H.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME})}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Qb.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:H.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,this.animationManagerId||this.animate()}reset(e=!1){this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:H.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:H.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])je(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Qb.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Zb.get(this.canvas)===this&&Zb.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Ae(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:`SceneUnloaded`}))}}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:`ModelLoaded`,filename:e.name});return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:`TexturesReprocessed`,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}async _loadWithSceneRebuild(e,t){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:kg.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:H.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._tagPrimarySceneObject();let t=new jd(``,{namespace:`scene`,level:`info`}),n=this.meshScene.environment,r=null;if(e?(t.start(`Environment fetch + CDF (concurrent)`),r=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>t.end(`Environment fetch + CDF (concurrent)`))):n?.image?.data&&(t.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=n,r=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{t.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(n)})),t.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),t.end(`BVH build (SceneProcessor)`),U({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),t.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,this.meshScene.environment))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),t.end(`GPU data transfer`),U({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),t.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),t.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(t.start(`Pipeline precompile`),await this.precompileRaster(),t.end(`Pipeline precompile`)),r&&(U({status:`Finalizing environment map...`,progress:95}),await r,this.stages.pathTracer.environment.applyCDFResults());let i=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,i,{reset:!1}),this.settings.set(`groundCatcherHeight`,i,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return t.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),t.end(`Apply settings`),t.print(this._sceneSummaryParts()),we(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[Y.count(e.triangleCount,`tri`),t?Y.count(t,`mesh`,`meshes`):null,Y.count(e.materialData.materialCount,`material`),n?Y.count(n,`map`):null,Y.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=await this.assetLoader.appendModel(e);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,url:e,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:`SceneObjectRemoved`,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}_dispatchCamerasUpdated(){this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles),this.stages.pathTracer.updateBVHData(this._sdf.bvh),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset()}),r}updateMeshTransforms(e){let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,G);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(He,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=(typeof navigator<`u`&&navigator.deviceMemory||4)>=8&&r>=1024*1024*1024?He:2048,a=Ue(Math.min(n,i));if((this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??a)!==a){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>a||e.height>a)&&this.renderer.setSize(Math.min(e.width,a),Math.min(e.height,a),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:`reserved_render_size_changed`,size:a})}return a}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});t<e.requestedPx&&this._issues.warn(ln.RENDER_RESERVE_CAPPED,`reserved render size ${Y.n(e.requestedPx)}px was capped to ${Y.n(t)}px by this device's limits — renders above ${Y.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return G}_isRenderSizeSupported(e,t){return e>G||t>G?(this._issues.record(ln.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${G}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:G}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?wt:Tt;this.denoisingManager?.setCadenceSuspended(n),this.cameraManager.controls.enabled=!n,this.settings.setMany(Et(r),{silent:!0,source:kg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await a.blueNoiseReady;let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){let r=e!==`linear`&&e!==`srgb`;if(r&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let i=this.stages?.pathTracer,a=i?.storageTextures?.readTarget;if(!a)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:o,height:s}=i,c=n===`display`?await this._readDisplaySource(a,o,s):await this.renderer.readRenderTargetPixelsAsync(a,0,0,o,s,0);if(e===`linear`)return{data:c,width:o,height:s,colorSpace:e,workingSpace:this.color?.workingSpace??null};if(r){let{rgba:t,colorSpace:n}=this.color.exportPixels(c,e);return{data:t,width:o,height:s,colorSpace:n}}return{data:hd(c,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:o,height:s,colorSpace:e}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>Qb.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures());let t=()=>e.measure();this._addTrackedListener(this,`SceneRebuild`,t),this._addTrackedListener(this,`EnvironmentLoaded`,t),this._addTrackedListener(this,`resolution_changed`,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(n);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async _readDisplaySource(e,t,n){let r=this.pipeline?.context,i=r&&this.stages.compositor?.resolveLightTexture(r);return!i||i===e.texture?await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0):(this._textureReadback??=new Eg(this.renderer),await this._textureReadback.read(i,t,n))}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Wi(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Wi(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Qb.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=tx(e),this.adapterInfo.isSoftware&&(this._issues.warn(ln.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Qb.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await this.renderer.init(),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},$b(a,this._deviceLostHolder),a.onuncapturederror=e=>Qb.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new ay(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new Bd({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new ry(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this._addTrackedListener(this.cameraManager.controls,`change`,()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Cg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Dg({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new oy(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new sy(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new vy(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Yb({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new Xb(this.transformManager)),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this.refreshFrame()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this._addTrackedListener(this.cameraManager,`CameraSwitched`,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,H.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[H.DENOISING_START,H.DENOISING_END,H.UPSCALING_START,H.UPSCALING_PROGRESS,H.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[H.ANIMATION_STARTED,H.ANIMATION_PAUSED,H.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,H.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,H.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,cameraManager:this.cameraManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())}}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:H.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new nh(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new rh(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new ih(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new sh(this.renderer,{enabled:!1}),this.stages.nrd=new Gh(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new Jh(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new Xh(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ng(this.renderer,{enabled:!1}),this.stages.autoExposure=new lg(this.renderer,{enabled:W.autoExposure??!1}),this.stages.compositor=new ug(this.renderer,{saturation:this.settings.get(`saturation`)??W.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Lb({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:H.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:H.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Kb(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function rx(e){let t=await ax(e);try{return await ix(t,e)}finally{t.dispose()}}async function ix(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,onProgress:i=void 0}={}){let a=await e.renderFrames(t,{onProgress:i,allowEarlyRetire:r});return{...await e.renderToBuffer({colorSpace:n}),samples:a,retiredBy:a<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo}}async function ax({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null}={}){if(!e)throw Error(`openHeadless: a canvas is required`);let c=new nx(e,{autoResize:!1,strict:i,profile:a});try{return c.setReservedRenderResolution(Math.max(n,r)),await c.init(),c.setCanvasSize(n,r),t&&await c.loadModel(t),s&&c.settings.setMany(s,{silent:!0}),o&&c.setDeterministicMode(!0),c}catch(e){throw c.dispose(),e}}xe();var ox=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=wt.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`production`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.finalDenoise&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:H.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:H.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(Te({samples:Ee(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(H.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(H.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app,t=e.settings.getEffective();return{settings:Object.keys(Et(wt)).map(e=>[e,t[e]]),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.finalDenoise,oidnQuality:e.denoisingManager?.oidnQuality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};xe(),Ar(),qt(),pb(),Db(),ca(),e.AF_DEFAULTS=Qe,e.ASVGF_QUALITY_PRESETS=We,e.AUTO_FOCUS_MODES=Ze,e.AnimationManager=qb,e.BVH_LEAF_MARKERS=ct,e.CAMERA_PRESETS=Xe,e.CAMERA_RANGES=Je,e.CameraManager=ay,e.ColorManagement=mo,e.DEFAULT_LUT_SIZE=Ca,e.DEFAULT_MAX_EV=Sa,e.DEFAULT_MIN_EV=xa,e.DEFAULT_TEXTURE_MATRIX=Ct,e.DEFAULT_WORKING_SPACE=ao,e.DenoisingManager=Lb,e.ENGINE_DEFAULTS=W,e.EngineEvents=H,e.EngineIssueError=dn,e.GoboManager=sy,e.IESManager=vy,e.INTERACTIVE_RENDER_CONFIG=Tt,e.ISSUE_CODES=ln,e.ISSUE_SEVERITY=un,e.InteractionManager=Dg,e.IssueLog=fn,e.LOG_LEVELS=Lt,e.LightManager=oy,e.Logger=Gt,e.MATERIAL_DEFAULTS=J,e.MATERIAL_VALUE_SOURCE=Sn,e.MAX_RESERVABLE_RENDER_SIZE=He,e.MAX_SCENE_BYTES=Yu,e.MAX_TABLE_TRANSFORMS=ta,e.MEMORY_CONSTANTS=Dt,e.MemoryLedger=ed,e.NRD_DEFAULTS=Ge,e.NRD_HIT_DIST_A=ze,e.NRD_HIT_DIST_B=Be,e.NRD_PRESET_KEYS=Ke,e.NRD_QUALITY_PRESETS=qe,e.OCIO_VIEW_BASE=ea,e.OverlayManager=Kb,e.PRODUCTION_RENDER_CONFIG=wt,e.PathTracerApp=nx,e.PipelineContext=dg,e.RENDER_PROFILES=Ie,e.RETOUCH_DEFAULTS=vb,e.RETOUCH_MAX_PIXELS=bb,e.RETOUCH_RANGES=xb,e.RenderPipeline=Cg,e.RenderSettings=jg,e.RenderStage=V,e.SAFE_SCENE_BYTES=Ju,e.SETTING_SOURCE=kg,e.SKY_PRESETS=Ye,e.SR_MAX_INPUT=cb,e.SR_SCALE=ob,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=dt,e.TRIANGLE_DATA_LAYOUT=$e,e.TransformManager=Yb,e.VIEW_TRANSFORMS=oa,e.VRAMTracker=tp,e.VideoRenderManager=ox,e.addAllOcioViews=Pa,e.addOcioView=Na,e.addViewTransform=Ji,e.applyMatrixRGBA8=Si,e.bakeLut=fa,e.bufferBytes=$f,e.buildOcioView=Aa,e.buildToneMapWGSL=Qi,e.canvasColorSpaceFor=lo,e.captureHeadless=ix,e.clearBindingAuditFindings=vg,e.clearInputOverrides=Ya,e.configureAssets=Dr,e.convertColor=li,e.convertEncodedRGBA8=_i,e.convertPixelsF32=ui,e.createLogger=Pt,e.deriveAlphaMode=En,e.describeAdapter=tx,e.displayCanvasFit=Er,e.estimateSceneBytes=Qu,e.extractMatrix=Ci,e.extractSceneMetadata=Jv,e.findNativeLinearSpace=po,e.fmt=Y,e.getActiveColorManagement=so,e.getAssetConfig=Or,e.getBindingAuditFindings=_g,e.getRegistryVersion=Hi,e.getRenderProfile=Le,e.getViewTransform=Wi,e.hasColorSpace=Ti,e.isColorManaged=ho,e.isDataSpace=wi,e.isDataTexture=to,e.linearToSrgb=pi,e.listFileRules=Qa,e.listInputOverrides=Xa,e.listViewTransforms=Gi,e.makeCpuSampler=va,e.measureBakeError=ba,e.onRegistryChange=Ui,e.openHeadless=ax,e.parseSceneMetadata=qv,e.probeAddressSpace=$u,e.removeViewTransform=Yi,e.renderHeadless=rx,e.renderUpscaled=rb,e.resolveInputSpace=eo,e.setActiveColorManagement=co,e.setBindingAudit=gg,e.setInputOverride=Ja,e.srgbToLinear=fi,e.textureBytes=ep,e.textureInputSpace=io});
1384
+ `,lx=class e{constructor(e,t){this.chain=e,this.canvas=t,this.slot=0,this.source=null,this.staging=null,this._readbackPipeline=null,this._readbackStorage=null,this._readbackMap=null,this._hdrPipeline=null,this._hdrStorage=null,this._hdrMap=null,this._toneMapper=null,this.disposed=!1}get device(){return this.chain.device}get width(){return this.chain.pipeline.geometry.validWidth}get height(){return this.chain.pipeline.geometry.validHeight}static async create({width:t,height:n,canvas:r=null,settings:i={},onProgress:a=()=>{}}){if(!Number.isInteger(t)||!Number.isInteger(n)||t<1||n<1)throw Error(`NeuralRetouch.create: width and height must be positive integers`);if(t*n>4194304)throw Error(`NeuralRetouch.create: ${t}x${n} is ${(t*n/1e6).toFixed(1)} MP, above the ${(ix/1e6).toFixed(1)} MP this pass survives. Past it the run takes minutes and then loses every GPU device in the page.`);let o=r??document.createElement(`canvas`);r||(o.style.cssText=`position:fixed;left:-10000px;top:0;pointer-events:none`);let s=new e(await(await ex()).create(o,t,n,a,$b(i).runtime),o);return s._allocate(),s}_allocate(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;this.source=this.device.createBuffer({label:`rayzee:retouch-source`,size:e*t*8,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),this.staging=new Uint16Array(e*t*4);let n=e*t*4;this._readbackStorage=this.device.createBuffer({label:`rayzee:retouch-readback`,size:n,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._readbackMap=this.device.createBuffer({label:`rayzee:retouch-readback-map`,size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._readbackPipeline=this.device.createComputePipeline({label:`rayzee:retouch-readback`,layout:`auto`,compute:{module:this.device.createShaderModule({code:sx}),entryPoint:`main`}});let r=e*t*8;this._hdrStorage=this.device.createBuffer({label:`rayzee:retouch-hdr`,size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),this._hdrMap=this.device.createBuffer({label:`rayzee:retouch-hdr-map`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),this._hdrPipeline=this.device.createComputePipeline({label:`rayzee:retouch-hdr`,layout:`auto`,compute:{module:this.device.createShaderModule({code:cx}),entryPoint:`main`}})}async _packHDR(e,t,n=!1){let r=this.chain.pipeline.slots[this.slot]?.hdrOutput;if(!r)throw Error("NeuralRetouch: the runtime has no scene-referred output. Either no frame has been produced yet, or neural-runtime.js was re-vendored without its `rayzee-patch` edits.");let i=this.device.createBindGroup({layout:this._hdrPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:r.createView()},{binding:1,resource:{buffer:this._hdrStorage}}]}),a=this.device.createCommandEncoder({label:`rayzee:retouch-hdr`}),o=a.beginComputePass();o.setPipeline(this._hdrPipeline),o.setBindGroup(0,i),o.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),o.end(),n&&a.copyBufferToBuffer(this._hdrStorage,0,this._hdrMap,0,e*t*8),this.device.queue.submit([a.finish()])}async readOutputHDR(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry;await this._packHDR(e,t,!0),await this._hdrMap.mapAsync(GPUMapMode.READ);let n=new Uint16Array(this._hdrMap.getMappedRange().slice(0));return this._hdrMap.unmap(),{half:n,width:e,height:t}}async readOutputToned(e){let{validWidth:t,validHeight:n}=this.chain.pipeline.geometry;return await this._packHDR(t,n),this._toneMapper??=new Nb(this.device,`rayzee:retouch-tonemap`),this._toneMapper.ensureSize(t,n),{rgba8:await this._toneMapper.toRGBA8(this._hdrStorage,{exposure:e.exposure??1,toneMapping:e.toneMapping??0,saturation:e.saturation??1}),width:t,height:n}}async readOutput(){let{validWidth:e,validHeight:t}=this.chain.pipeline.geometry,n=this.chain.pipeline.slots[this.slot]?.output;if(!n)throw Error(`NeuralRetouch.readOutput: the pass has not produced a frame yet`);let r=this.device.createBindGroup({layout:this._readbackPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()},{binding:1,resource:{buffer:this._readbackStorage}}]}),i=this.device.createCommandEncoder({label:`rayzee:retouch-readback`}),a=i.beginComputePass();a.setPipeline(this._readbackPipeline),a.setBindGroup(0,r),a.dispatchWorkgroups(Math.ceil(e/8),Math.ceil(t/8)),a.end(),i.copyBufferToBuffer(this._readbackStorage,0,this._readbackMap,0,e*t*4),this.device.queue.submit([i.finish()]),await this._readbackMap.mapAsync(GPUMapMode.READ);let o=new Uint8ClampedArray(this._readbackMap.getMappedRange().slice(0));return this._readbackMap.unmap(),o}dispose(){if(!this.disposed){this.disposed=!0,this.source?.destroy(),this._readbackStorage?.destroy(),this._readbackMap?.destroy(),this._hdrStorage?.destroy(),this._hdrMap?.destroy(),this._toneMapper?.dispose();try{this.chain.destroy()}catch(e){rx.warn(`retouch teardown:`,e)}}}},ux=20}));xe(),qt();var fx=Pt(`neural`),px=120,mx=2,hx=1,gx=0,_x=300,vx=5,yx=3,bx=3,xx=16,Sx=e=>Math.max(0,1-e/xx),Cx=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,stages:n,pipeline:i,getExposure:a,getSaturation:o}){super(),this.renderer=e,this.mainCanvas=t,this.upscalerCanvas=this._createUpscalerCanvas(t),this.pipeline=i,this._stages=n,this._getExposure=a,this._getSaturation=o,this.denoiser=null,this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null,this.neuralRendering=!1,this.neuralRenderingSettings={},this._retouch=null,this._superResModule=null,this._neuralPostBusy=!1,this._finalQuality=W.oidnQuality,this.finalDenoise=W.enableOIDN,this.continuousDenoise=W.continuousDenoise,this.continuousDenoiseInterval=W.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._failedRefreshes=0,this._cadenceSuspended=!1,this._movingDenoiseMs=[],this._movingHopeless=!1,this._holdWhileMoving=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.temporalHistory=W.oidnTemporalHistory,this._history=null,this._historyDirty=!0,this._knownResetCount=0,this._seenTracedFrames=0,this._viewProj=new r.Matrix4,this._historyCamera={world:null,projInv:null,viewProj:null},this._movedPlacements=new Map,this._movedUpload={count:0,leaves:new Uint32Array,toPrev:new Float32Array},this._matA=new r.Matrix4,this._matB=new r.Matrix4,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createUpscalerCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,n.style.display=`none`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this._holdWhileMoving=null,this._movingDenoiseMs.length=0,this._movingHopeless=!1,this._historyDirty=!0,this.denoiser?.abort(),this._unpublishOutput(),this.denoiser?.setSize(e,t),this.upscalerCanvas&&(this.upscalerCanvas.width!==e||this.upscalerCanvas.height!==t)&&(this.upscalerCanvas.width=e,this.upscalerCanvas.height=t),this.upscaler?.setBaseSize(e,t),this._syncGBufferStages()}restoreBaseResolution(){return!this.upscalerCanvas||!this._lastRenderWidth||!this._lastRenderHeight||!(this.upscalerCanvas.width!==this._lastRenderWidth||this.upscalerCanvas.height!==this._lastRenderHeight)?!1:(this.upscalerCanvas.width=this._lastRenderWidth,this.upscalerCanvas.height=this._lastRenderHeight,!0)}setupDenoiser(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.denoiser=new ib(this.renderer,{...W,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),getGPUTextures:({continuous:t=!1}={})=>{if(!e?.storageTextures?.readTarget)return null;let n=t?this._historyTextures():null;if(n)return n;let r=e.storageTextures.getReadTextures(),{backend:i}=this.renderer;return{color:i.get(r.color).texture,normal:i.get(r.normalDepth).texture,albedo:i.get(r.albedo).texture}}}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:H.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>{this.denoiser?.hasOutput&&this._publishOutput(),this.dispatchEvent({type:H.DENOISING_END,continuous:!!e.continuous})},this._denoiserTileHandler=e=>{if(e.continuous)return;this._publishOutput();let t=this.pipeline?.context;this._stages.compositor&&t&&this._stages.compositor.render(t)},this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler),this.denoiser.addEventListener(`tileProgress`,this._denoiserTileHandler)}setupUpscaler(){if(!this.upscalerCanvas)return;let e=this._stages.pathTracer;this.upscaler=new Db(this.upscalerCanvas,this.renderer,{scaleFactor:W.upscalerScale||2,quality:W.upscalerQuality||`fast`,getSourceCanvas:()=>this.renderer.domElement,refreshInput:()=>{let e=this.pipeline?.context;this._stages.compositor&&e&&this._stages.compositor.render(e)},getGPUTextures:()=>{if(!e?.storageTextures?.readTarget)return null;let t=e.storageTextures.getReadTextures();return{color:this.renderer.backend.get(t.color).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation()}),this.upscaler.enabled=W.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:H.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:H.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:H.UPSCALING_END}),this.upscaler.addEventListener(`resolution_changed`,this._upscalerResChangedHandler),this.upscaler.addEventListener(`start`,this._upscalerStartHandler),this.upscaler.addEventListener(`progress`,this._upscalerProgressHandler),this.upscaler.addEventListener(`end`,this._upscalerEndHandler)}get denoiserStrategy(){return this.continuousDenoise?`oidn`:this._stages.asvgf?.enabled?`asvgf`:this._stages.nrd?.enabled?`nrd`:this._stages.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.enabled=!1),n.nrd&&(n.nrd.enabled=!1),n.variance&&(n.variance.enabled=!1),n.bilateralFilter&&(n.bilateralFilter.enabled=!1),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!1),this._clearDenoiserTextures(),this.setContinuousDenoise(e===`oidn`),e){case`asvgf`:n.asvgf.enabled=!0,n.variance&&(n.variance.enabled=!0),n.bilateralFilter&&(n.bilateralFilter.enabled=!0),n.asvgf.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`);break;case`nrd`:n.nrd&&(n.nrd.enabled=!0,n.nrd.resetHistory?.(),this._applyNRDPreset(t||`medium`));break;case`edgeaware`:n.variance&&(n.variance.enabled=!0),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!0);break}this._syncGBufferStages()}setASVGFEnabled(e,t){let n=this._stages;n.asvgf&&(n.asvgf.enabled=e),n.variance&&(n.variance.enabled=e),n.bilateralFilter&&(n.bilateralFilter.enabled=e),e&&(n.nrd&&(n.nrd.enabled=!1),n.asvgf?.setTemporalEnabled?.(!0),this._applyASVGFPreset(t||`medium`)),n.edgeFilter&&n.edgeFilter.setFilteringEnabled(!e),this._syncGBufferStages()}applyASVGFPreset(e){this._applyASVGFPreset(e)}setAutoExposureEnabled(e,t){let n=this._stages;n.autoExposure&&(n.autoExposure.enabled=e,!e&&this.renderer&&(this.renderer.toneMappingExposure=t))}get requiresMotionVectors(){return!!(this._stages.asvgf?.enabled||this._stages.nrd?.enabled)}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=this.requiresMotionVectors,i=r||this.historyWanted||!!(e.edgeFilter?.enabled||e.bilateralFilter?.enabled);this.historyWanted||this._releaseHistory(),t&&(i&&!t.enabled&&t.reset(),t.enabled=i,t.setInstanceLeafOutput?.(this.historyWanted)),n&&(r&&!n.enabled&&(n.matricesInitialized=!1,n.isFirstFrame=!0,n.frameCount=0),n.enabled=r),e.pathTracer?.setAuxGBufferEnabled?.(i||!!this.denoiser?.enabled),e.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(this._finalQuality));for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this.denoiser&&(this._pendingStartUpscaler&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingCloseDenoise&&this.denoiser.removeEventListener(`end`,this._pendingCloseDenoise)),this._pendingStartUpscaler=null,this._pendingCloseDenoise=null}get holdsWhileMoving(){if(!this._stages.pathTracer?.viewIsChanging||!this.continuousDenoise||this._cadenceSuspended||!this.denoiser?.enabled||this._movingHopeless)return!1;let e=this.movingCostMs,t=this._movingDenoiseMs.length;e>_x*yx&&(this._movingHopeless=!0,this._syncGBufferStages());let n=!this._movingHopeless&&(t<2||e<=_x);return this._holdWhileMoving=(this._holdWhileMoving===null||this._holdWhileMoving)&&n,this._holdWhileMoving}skipsTrace(){return this.holdsWhileMoving&&!!this.denoiser?.state.isDenoising}get movingCostMs(){return this._movingDenoiseMs.length?Math.min(...this._movingDenoiseMs):0}_publishOutput(){let e=this.pipeline?.context,t=this.denoiser?.outputTexture;e&&t&&e.setTexture(`oidn:output`,t)}_unpublishOutput(){this.pipeline?.context?.removeTexture(`oidn:output`),this.denoiser?.invalidateOutput()}_checkHeldFrameHealthy(){!this.denoiser?.hasOutput||this._failedRefreshes<bx||this._unpublishOutput()}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||this._cadenceSuspended||!t)return!1;this._checkHeldFrameHealthy();let n=!!this._stages.pathTracer?.viewIsChanging;if(!n)this._holdWhileMoving=null,this._movingDenoiseMs.length=0;else if(!this.holdsWhileMoving)return!1;if(t.state.isDenoising||t.state.isLoading||!n&&e<=this._lastCadenceSamples)return!1;let r=performance.now(),i=n?gx:this._lastCadenceSamples===0?hx:mx,a=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*i);if(r-this._lastCadenceAt<a)return!1;this._lastCadenceAt=r,this._lastCadenceSamples=e,t.lastDenoiseMs>px&&(this._cadenceDowngraded=!0);let o=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==o&&t.updateQuality(o),t.start({continuous:!0}).then(e=>{this._failedRefreshes=e?0:this._failedRefreshes+1,!(!e||!n)&&(this._movingDenoiseMs.push(t.lastDenoiseMs),this._movingDenoiseMs.length>vx&&this._movingDenoiseMs.shift())}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}setCadenceSuspended(e){this._cadenceSuspended=!!e,this._historyDirty=!0,this._cadenceSuspended&&(this.denoiser?.abort(),this._unpublishOutput())}setContinuousDenoise(e){this.continuousDenoise=!!e,this._syncOIDNInUse(),this._lastCadenceAt=-1/0,this._resetCadence()}_useFinalQuality(){let e=this.denoiser;e&&e.quality!==this._finalQuality&&e.updateQuality(this._finalQuality)}_resetCadence(){this._lastCadenceSamples=0}setTemporalHistory(e){this.temporalHistory=!!e,this._syncGBufferStages()}get historyWanted(){return this.temporalHistory&&this.continuousDenoise&&!!this.denoiser?.enabled&&!this._movingHopeless}get historyActive(){let e=this._stages.pathTracer;return this.historyWanted&&!this._cadenceSuspended&&!!this._stages.normalDepth?.enabled&&(e?.uniforms?.get(`cameraProjection`)?.value??0)===0&&!(e?.visMode?.value>0)}beforeReset({keepHistory:e=!1}={}){let t=this._stages.pathTracer;if(!t||!this.historyActive)return;let n=t.resetCount!==this._knownResetCount;if(!e||n&&t.frameCount<2){this._historyDirty=!0;return}if(t.frameCount<2)return;let r=this._historyInputs();r&&(this._ensureHistory().merge(r,t.frameCount,this._historyCameraNow(),{commit:!0,keepHistory:!this._historyDirty&&!n,historyScale:Sx(t.frameCount)}),this._historyDirty=!1)}afterReset(){this._knownResetCount=this._stages.pathTracer?.resetCount??0}afterTrace(){let e=this._stages.pathTracer;if(!e||e.tracedFrames===this._seenTracedFrames)return;if(this._seenTracedFrames=e.tracedFrames,e.resetCount!==this._knownResetCount&&(this._historyDirty=!0,this._knownResetCount=e.resetCount),!this.historyActive||e.frame.value!==0){this._movedPlacements.clear();return}let t=this._historyInputs();if(!t){this._movedPlacements.clear(),this._historyDirty=!0;return}let n=this._ensureHistory();this._historyDirty&&n.invalidate(),n.accumulate(t,this._historyCameraNow(),this._takeMovedPlacements()),this._historyDirty=!1}notePlacementMoving(e,t,n){e<0||!this.historyActive||this._movedPlacements.has(e)||this._movedPlacements.set(e,{world:t,offset:n,prev:t.slice(n,n+16)})}_takeMovedPlacements(){let e=this._movedPlacements,t=this._movedUpload;if(t.count=e.size,!e.size)return t;t.leaves.length<e.size&&(t.leaves=new Uint32Array(e.size*2),t.toPrev=new Float32Array(e.size*32));let n=[...e.keys()].sort((e,t)=>e-t);for(let r=0;r<n.length;r++){let{world:i,offset:a,prev:o}=e.get(n[r]);this._matB.fromArray(i,a).invert(),this._matA.fromArray(o).multiply(this._matB).toArray(t.toPrev,r*16),t.leaves[r]=n[r]}return e.clear(),t}_historyTextures(){let e=this._stages.pathTracer,t=this._history;if(!t?.valid||this._historyDirty||!this.historyActive||e.isComplete||e.resetCount!==this._knownResetCount||t.width!==this._lastRenderWidth||t.height!==this._lastRenderHeight)return null;if(e.frameCount<=1)return t.textures;if(e.frameCount>=xx)return null;let n=this._historyInputs();return n?t.merge(n,e.frameCount,this._historyCameraNow(),{historyScale:Sx(e.frameCount)}):null}_historyInputs(){let e=this._stages.pathTracer,t=this.pipeline?.context,n=this.renderer?.backend;if(!e?.storageTextures?.readTarget||!t||!n)return null;let r=e.storageTextures.getReadTextures(),i=e=>e?n.get(e)?.texture:null,a={color:i(r.color),albedo:i(r.albedo),normal:i(r.normalDepth),geo:i(t.getTexture(`pathtracer:normalDepth`)),geoPrev:i(t.getTexture(`pathtracer:prevNormalDepth`)),shading:i(t.getTexture(`pathtracer:shadingNormal`)),leaf:i(t.getTexture(`pathtracer:instanceLeaf`)),width:e.width,height:e.height};return a.color&&a.albedo&&a.normal&&a.geo&&a.geoPrev&&a.shading&&a.leaf?a:null}_historyCameraNow(){let e=this._stages.pathTracer;this._viewProj.multiplyMatrices(e.cameraProjectionMatrix.value,e.cameraViewMatrix.value);let t=this._historyCamera;return t.world=e.cameraWorldMatrix.value.elements,t.projInv=e.cameraProjectionMatrixInverse.value.elements,t.viewProj=this._viewProj.elements,t}_ensureHistory(){return this._history??=new yb(this.renderer.backend.device),this._history.settings.cleanAux=!!this.denoiser?.expectsCleanAux(this._finalQuality),this._history}_releaseHistory(){this._history?.dispose(),this._history=null,this._historyDirty=!0,this._movedPlacements.clear()}setUpscalerBackend(e){let t=e===`neural`?`neural`:`esrgan`;t!==this.upscalerBackend&&(this.upscalerBackend=t,this._restoreRenderDisplay(),t!==`neural`&&this._releaseNeuralUpscaler())}_restoreRenderDisplay(){let e=this.upscalerCanvas&&this.upscalerCanvas.style.display!==`none`;return this.upscalerCanvas&&(this.upscalerCanvas.style.display=`none`),this.mainCanvas&&(this.mainCanvas.style.opacity=`1`),e&&this._lastRenderWidth&&this._lastRenderHeight&&this.dispatchEvent({type:`resolution_changed`,width:this._lastRenderWidth,height:this._lastRenderHeight}),!!e}_releaseNeuralUpscaler(){this._neuralUpscaler?.dispose(),this._neuralUpscaler=null,this._superResModule?.releaseDenoisedReader()}setNeuralRendering(e,t=null){this.neuralRendering=!!e,t&&(this.neuralRenderingSettings={...this.neuralRenderingSettings,...t}),this.neuralRendering||(this._releaseNeuralRetouch(),this._restoreRenderDisplay())}_releaseNeuralRetouch(){this._retouch?.dispose(),this._retouch=null}async _runNeuralPost(e){let t=this.upscaler?.enabled&&this.upscalerBackend===`neural`,n=this.neuralRendering;if(!(!t&&!n)&&!this._neuralPostBusy){if(!this.upscalerCanvas){fx.warn(`neural pass skipped: the engine has no overlay canvas to present on`);return}if(!this.pipeline?.context?.getTexture(`oidn:output`)){fx.warn(`neural pass skipped: no denoised picture — it needs OIDN`);return}this._neuralPostBusy=!0,this.dispatchEvent({type:H.UPSCALING_START});try{let r=await Promise.resolve().then(()=>(Zb(),Fb));this._superResModule=r;let i=n?await Promise.resolve().then(()=>(dx(),Qb)):null,a=this.denoiser?._outTexSize,o=(a?.width??0)*(a?.height??0),s=n&&o<=i.RETOUCH_MAX_PIXELS;if(n&&!s&&(fx.warn(`Neural rendering skipped: the render is ${(o/1e6).toFixed(1)} MP, above the ${(i.RETOUCH_MAX_PIXELS/1e6).toFixed(1)} MP the pass survives.`+(t?` The upscale still ran.`:``)),this._releaseNeuralRetouch()),!t&&!s)return;let c={exposure:this._getEffectiveExposure(),toneMapping:this._getToneMapping(),saturation:this._getSaturation?.()??1},l=await r.readDenoisedHalf(this.denoiser);t&&(this._neuralUpscaler&&(this._neuralUpscaler.inputWidth!==l.width||this._neuralUpscaler.inputHeight!==l.height)&&this._releaseNeuralUpscaler(),this._neuralUpscaler||=await r.NeuralSuperRes.create({width:l.width,height:l.height}));let u=l;if(s){let e=await i.enhanceFrame({source:u,settings:this.neuralRenderingSettings,instance:this._retouch,exposure:c.exposure,tone:t?null:c});this._retouch=e.instance,u=e}if(t&&(u=await this._neuralUpscaler.upscaleToRGBA8(u,c)),!e()){this.dropDisplay();return}if(r.presentRGBA8(this.upscalerCanvas,u.rgba8,u.width,u.height),!e()){this.dropDisplay();return}this.mainCanvas&&(this.mainCanvas.style.opacity=`0`),this.dispatchEvent({type:`resolution_changed`,width:u.width,height:u.height})}catch(e){fx.warn(`neural pass failed`,e)}finally{this._neuralPostBusy=!1,this.dispatchEvent({type:H.UPSCALING_END})}}}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,r=()=>{if(this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()){if(n&&this._onDisplayRefresh?.(),this.neuralRendering||this.upscaler?.enabled&&this.upscalerBackend===`neural`){this._runNeuralPost(e);return}this.upscaler?.enabled&&this.upscaler.start()}};if(!n){r();return}let i=()=>{e()&&(this._pendingStartUpscaler=r,this.denoiser.addEventListener(`end`,r),n===`final`?(this._useFinalQuality(),this.denoiser.start()):this.denoiser.start({continuous:!0}))};if(this._resetCadence(),this.denoiser.state.isDenoising){let e=()=>{this.denoiser?.removeEventListener(`end`,e),this._pendingCloseDenoise===e&&(this._pendingCloseDenoise=null),i()};this._pendingCloseDenoise=e,this.denoiser.addEventListener(`end`,e)}else i()}abort(e,{keepDisplay:t=!1}={}){this._cleanupCompletionListener(),this._restoreRenderDisplay(),e&&e!==this.mainCanvas&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort();let n=!!this._stages.pathTracer?.viewIsChanging,r=t&&this.continuousDenoise&&!this._cadenceSuspended&&!!this.denoiser?.hasOutput&&(!n||this.holdsWhileMoving);this.denoiser&&!r&&(this.denoiser.enabled&&this.denoiser.abort(),this._unpublishOutput()),this._resetCadence()}dropDisplay(){this._unpublishOutput(),this._restoreRenderDisplay(),this._historyDirty=!0}dispose(){this._cleanupCompletionListener(),this._releaseNeuralUpscaler(),this._releaseNeuralRetouch(),this._unpublishOutput(),this._releaseHistory(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),this._denoiserTileHandler&&this.denoiser.removeEventListener(`tileProgress`,this._denoiserTileHandler),this.denoiser.dispose(),null),this.upscaler&&(this._upscalerResChangedHandler&&this.upscaler.removeEventListener(`resolution_changed`,this._upscalerResChangedHandler),this._upscalerStartHandler&&this.upscaler.removeEventListener(`start`,this._upscalerStartHandler),this._upscalerProgressHandler&&this.upscaler.removeEventListener(`progress`,this._upscalerProgressHandler),this._upscalerEndHandler&&this.upscaler.removeEventListener(`end`,this._upscalerEndHandler),this.upscaler.dispose(),this.upscaler=null,this.upscalerBackend=`esrgan`,this._neuralUpscaler=null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._denoiserTileHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this._onReset=null,this._onPostProcessRefresh=null,this._onDisplayRefresh=null,this.upscalerCanvas?.parentNode&&(this.upscalerCanvas.parentNode.removeChild(this.upscalerCanvas),this.upscalerCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=e}setDisplayRefreshCallback(e){this._onDisplayRefresh=e}setSettings(e){this._settings=e}setASVGFParams(e){this._stages.asvgf?.updateParameters(e)}toggleASVGFHeatmap(e){this._stages.asvgf?.setHeatmapEnabled?.(e)}configureASVGFForMode(e){this._stages.asvgf&&(this._stages.asvgf.enabled=e.enabled,this._stages.variance&&(this._stages.variance.enabled=e.enabled),this._stages.bilateralFilter&&(this._stages.bilateralFilter.enabled=e.enabled),e.enabled&&this._stages.asvgf.updateParameters(e),this._syncGBufferStages())}setEdgeAwareParams(e){this._stages.edgeFilter?.updateUniforms(e)}setAutoExposureParams(e){this._stages.autoExposure?.updateParameters(e)}applyOIDNEnabled(e){this.finalDenoise=!!e,this._syncOIDNInUse()}get oidnQuality(){return this._finalQuality}setOIDNEnabled(e){this.applyOIDNEnabled(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}_syncOIDNInUse(){this.denoiser&&(this.denoiser.enabled=this.finalDenoise||this.continuousDenoise)}applyOIDNQuality(e){this._finalQuality=e,this._cadenceDowngraded=!1,this.denoiser?.updateQuality(e)}setOIDNQuality(e){this.applyOIDNQuality(e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e),e||this._restoreRenderDisplay()}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}setStrategy(e,t){this.setDenoiserStrategy(e,t),this._onReset?.()}setNRDParams(e){this._stages.nrd?.updateParameters(e)}applyNRDPreset(e){this._applyNRDPreset(e)}setNRDDebugMode(e){this._stages.nrd?.updateParameters({debugMode:e})}_setTileHelper(e){let t=this._overlayManager?.getHelper(`tiles`);t&&(t.enabled=e,e||t.hide())}_getEffectiveExposure(){return this._stages.autoExposure?.enabled?this.renderer.toneMappingExposure:this._getExposure()}_getToneMapping(){return this.renderer.toneMapping}_clearDenoiserTextures(){let e=this.pipeline?.context;e&&[`asvgf:output`,`asvgf:demodulated`,`asvgf:gradient`,`variance:output`,`bilateralFiltering:output`,`edgeFiltering:output`,`nrd:output`,`oidn:output`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=qe[e];if(!t)return;let n={};for(let e of Ke)n[e]=Ge[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=We[e];t&&(this._stages.asvgf?.updateParameters(t),this._stages.bilateralFilter?.updateParameters(t),this._stages.variance&&t.varianceBoost!==void 0&&(this._stages.variance.varianceBoost.value=t.varianceBoost))}},wx=class{constructor(){this.layer=`hud`,this.visible=!1,this._tileBounds=null,this._imageWidth=1,this._imageHeight=1,this.enabled=!0,this._borderColor=`rgba(255, 0, 0, 0.6)`,this._borderWidthRatio=1/540,this._borderWidthMin=1.5,this._borderWidthMax=4}setActiveTile(e){this._tileBounds=e}setRenderSize(e,t){this._imageWidth=e,this._imageHeight=t}render(e,t,n){if(!this._tileBounds)return;let r=this._tileBounds,i=t/this._imageWidth,a=n/this._imageHeight,o=r.x*i,s=r.y*a,c=r.width*i,l=r.height*a,u=Math.min(this._borderWidthMax,Math.max(this._borderWidthMin,Math.min(t,n)*this._borderWidthRatio));e.strokeStyle=this._borderColor,e.lineWidth=u,e.strokeRect(o,s,c,l)}show(){this.enabled&&(this.visible=!0)}hide(){this.visible=!1,this._tileBounds=null}dispose(){this.visible=!1}},Tx=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,g.outline)(e,i,{selectedObjects:[],edgeThickness:(0,n.uniform)(1),edgeGlow:(0,n.uniform)(0)});let a=(0,n.uniform)(3),o=(0,n.uniform)(new r.Color(16777215)),s=(0,n.uniform)(new r.Color(1640965)),{visibleEdge:c,hiddenEdge:l}=this._outlineNode,u=c.mul(o).add(l.mul(s)).mul(a),d=u.r.max(u.g).max(u.b).clamp(0,1);this._material=new t.MeshBasicNodeMaterial,this._material.colorNode=(0,n.vec4)(u,d),this._material.transparent=!0,this._material.blending=r.CustomBlending,this._material.blendEquation=r.AddEquation,this._material.blendSrc=r.OneFactor,this._material.blendDst=r.OneFactor,this._material.blendEquationAlpha=r.AddEquation,this._material.blendSrcAlpha=r.OneFactor,this._material.blendDstAlpha=r.OneFactor,this._material.toneMapped=!1,this._material.depthTest=!1,this._material.depthWrite=!1,this._quad=new t.QuadMesh(this._material)}setSelectedObjects(e){this._outlineNode.selectedObjects=e}get visible(){return this._enabled&&this._outlineNode.selectedObjects.length>0}render(e){if(!this.visible)return;let t=e.autoClear;e.autoClear=!1,e.setRenderTarget(null),this._quad.render(e),e.autoClear=t}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1,this._outlineNode?.dispose(),this._material?.dispose(),this._quad=null}};function Ex(e=!1){let t=document.createElement(`canvas`);return t.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;`+(e?`display:none;`:``),t}function Dx(e,t=1/0){let n=e?.getBoundingClientRect();if(!n||n.width===0||n.height===0)return null;let r=Math.min(window.devicePixelRatio||1,2),i=Math.round(n.width*r),a=Math.round(n.height*r),o=t/Math.max(i,a);return o<1&&(i=Math.max(1,Math.round(i*o)),a=Math.max(1,Math.round(a*o))),{width:i,height:a}}var Ox=4096,kx=class{constructor(){this.canvas=Ex(!0),this._visible=!1,this.renderer=null,this._sizeSource=null}async init({device:e,sizeSource:n}){this._sizeSource=n;let i=e.onuncapturederror,a=new t.WebGPURenderer({canvas:this.canvas,device:e,alpha:!0,antialias:(window.devicePixelRatio||1)<2});return await a.init(),e.onuncapturederror=i,a.outputColorSpace=r.SRGBColorSpace,a.setPixelRatio(1),a.setClearColor(0,0),a.autoClear=!1,this.renderer=a,this.syncSize(),this}get isVisible(){return this._visible}syncSize(){if(!this.renderer)return;let e=Dx(this._sizeSource,Ox);!e||e.width===this.canvas.width&&e.height===this.canvas.height||this.renderer.setSize(e.width,e.height,!1)}begin(){this.renderer&&(this.renderer.setRenderTarget(null),this.renderer.clear())}setVisible(e){this._visible!==e&&(this._visible=e,this.canvas.style.display=e?``:`none`)}dispose(){Ae(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}};qt();var Ax=Pt(`overlay`),jx=(e,t)=>e.visible&&e.layer===t&&e.render,Mx=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Ex(),this._hudCtx=this._hudCanvas.getContext(`2d`),this._helperScene=null,this._viewOverlay=null}async initViewRenderer({device:e,sizeSource:t}){if(!(!e||!t))try{this._viewOverlay=await new kx().init({device:e,sizeSource:t})}catch(e){Ax.error(`overlay surface unavailable — light gizmos, transform gizmo and outlines are disabled`,e),this._viewOverlay=null}}setHelperScene(e){this._helperScene=e}getHUDCanvas(){return this._hudCanvas}mount(e){if(!e)return;let t=this._viewOverlay?.canvas;t&&t.parentElement!==e&&e.appendChild(t),this._hudCanvas.parentElement!==e&&e.appendChild(this._hudCanvas)}setupDefaultHelpers({helperScene:e,meshScene:t,pipeline:n,denoisingManager:r,app:i,renderWidth:a,renderHeight:o}){this.setHelperScene(e);let s=new wx;this.register(`tiles`,s),s.setRenderSize(a||1,o||1),i.addEventListener(`resolution_changed`,e=>{s.setRenderSize(e.width,e.height)}),n.eventBus.on(`pipeline:reset`,()=>s.hide()),this._wireDenoiserTileEvents(s,r);let c=new Tx(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.continuous||t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(Ax.warn(`helper "${e}" already registered — replacing.`),this._helpers.get(e).dispose?.()),this._helpers.set(e,t)}unregister(e){let t=this._helpers.get(e);t&&(t.dispose?.(),this._helpers.delete(e))}show(e){this._helpers.get(e)?.show()}hide(e){this._helpers.get(e)?.hide()}toggle(e){let t=this._helpers.get(e);t&&(t.visible?t.hide():t.show())}getHelper(e){return this._helpers.get(e)??null}isVisible(e){return this._helpers.get(e)?.visible??!1}showAll(){for(let e of this._helpers.values())e.show()}hideAll(){for(let e of this._helpers.values())e.hide()}render(){let e=this._viewOverlay;if(e){let t=this._hasVisibleSceneOverlay();(t||e.isVisible)&&(e.syncSize(),e.begin(),t&&this._renderSceneLayer(e.renderer),e.setVisible(t))}this.refreshHUD()}_renderSceneLayer(e){this._helperScene?.render(e,this.camera);for(let t of this._helpers.values())jx(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(jx(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(jx(e,`hud`)){n=!0;break}if(!n){e.style.display!==`none`&&(e.style.display=`none`);return}e.style.display!==``&&(e.style.display=``);let r=e.clientWidth,i=e.clientHeight,a=r>0&&i>0?Dx(e):null;if(a){(e.width!==a.width||e.height!==a.height)&&(e.width=a.width,e.height=a.height),t.clearRect(0,0,a.width,a.height),t.save(),t.scale(a.width/r,a.height/i);for(let e of this._helpers.values())jx(e,`hud`)&&e.render(t,r,i);t.restore(),e.style.display!==``&&(e.style.display=``)}}dispose(){for(let e of this._helpers.values())e.dispose?.();this._helpers.clear(),this._viewOverlay?.dispose(),this._viewOverlay=null,this._hudCanvas.parentElement&&this._hudCanvas.parentElement.removeChild(this._hudCanvas)}};xe();var Nx=class extends r.EventDispatcher{constructor(){super(),this.mixer=null,this.timer=new r.Timer,this.actions=[],this.isPlaying=!1,this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._tempVec=new r.Vector3,this._skinnedCache=null,this._clipsCache=null,this._savedTimeScale=1,this.onFinished=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null,this.wakeCallback=null,this.applyPoseCallback=null}init(e,t,n,i){if(this.dispose(),!i||i.length===0)return;this._scene=e,this._mixerRoot=t,this._meshes=n,this.mixer=new r.AnimationMixer(t);let a=i.map(e=>this.mixer.clipAction(e)),o=(e,t)=>e.name===t||e.getObjectByName(t)!==void 0;!a.some(e=>e.getClip().tracks.some(e=>{let n=e.name.split(`.`)[0];return o(t,n)}))&&t!==e&&(console.log(`[AnimationManager] Tracks did not resolve from model root, retrying with scene root`),this.mixer=new r.AnimationMixer(e),this._mixerRoot=e,a=i.map(e=>this.mixer.clipAction(e))),this.actions=a,this._rigid=!n.some(e=>e?.isSkinnedMesh)&&!i.some(e=>e.tracks.some(e=>e.name.includes(`morphTargetInfluences`))),this._planClips(i),this.mixer.addEventListener(`finished`,()=>{this.isPlaying=!1,this.timer.reset(),this.onFinished&&this.onFinished()}),this._meshTriRanges=[],this._skinnedCache=[];let s=0;for(let e of n){let t=e.geometry,n=t.attributes.position,r=t.index?t.index.array:null,i=r?r.length/3:n.count/3,a=n.count;this._meshTriRanges.push({start:s,count:i,uniqueVerts:a,indices:r}),s+=i}this._skinnedCache=[],this._meshPositions=[];let c=n.filter(e=>e.isSkinnedMesh).length;console.debug(`[AnimationManager] Init: ${i.length} clips, ${n.length} meshes (${c} skinned), ${s} triangles, ${this._rigid?`rigid`:`deforming`}`)}_planClips(e){let t=this._mixerRoot,n=new Map;if(t.traverse?.(e=>{n.has(e.name)||n.set(e.name,e),n.set(e.uuid,e)}),this._plans=e.map(e=>{let t=new Set,i=!1;for(let a of e.tracks){let{nodeName:e,propertyName:o}=r.PropertyBinding.parseTrackName(a.name),s=n.get(e);s&&(t.add(s),o===`visible`&&(i=!0))}let a=[];for(let e=0;e<this._meshes.length;e++)for(let n=this._meshes[e];n;n=n.parent)if(t.has(n)){a.push(e);break}let o=new Set;for(let e of t)e.traverse(e=>e.isCamera&&o.add(e));return{meshes:Int32Array.from(a),visibility:i,cameras:[...o]}}),this._allPlan=null,!this._rigid)return;this._slotOf=new Int32Array(this._meshes.length).fill(-1);let i=0;for(let e of this._plans)for(let t of e.meshes)this._slotOf[t]<0&&(this._slotOf[t]=i++);this._lastWorld=new Float64Array(i*16).fill(NaN),this._lastVisible=new Uint8Array(i).fill(2)}_planFor(e){if(!this._plans)return null;if(e>=0)return this._plans[e]??null;if(!this._allPlan){let e=new Set,t=new Set,n=!1;for(let r of this._plans)r.meshes.forEach(t=>e.add(t)),r.cameras.forEach(e=>t.add(e)),n||=r.visibility;this._allPlan={meshes:Int32Array.from(e),visibility:n,cameras:[...t]}}return this._allPlan}_applyRigidPose(e){let t=this._planFor(e);if(!t)return;let n=[],r=!1,i=this._lastWorld,a=this._lastVisible;for(let e of t.meshes){let o=this._meshes[e],s=this._slotOf[e],c=o.matrixWorld.elements,l=s*16;for(let t=0;t<16;t++)if(i[l+t]!==c[t]){for(let e=0;e<16;e++)i[l+e]=c[e];n.push(e);break}if(t.visibility||a[s]===2){let e=1;for(let t=o;t;t=t.parent)if(!t.visible){e=0;break}a[s]!==e&&(a[s]=e,r=!0)}}(n.length||r||t.cameras.length)&&this.applyPoseCallback?.({meshIndices:n,visibilityChanged:r,cameras:t.cameras})}play(e=0){if(!(!this.mixer||this.actions.length===0)){if(this.mixer.stopAllAction(),e===-1)for(let e of this.actions)e.play();else e>=0&&e<this.actions.length&&this.actions[e].play();this._activeClip=e,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:H.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:H.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this._rigid&&(this._mixerRoot.updateMatrixWorld(!0),this._applyRigidPose(-1)),this.dispatchEvent({type:H.ANIMATION_STOPPED}))}setSpeed(e){this._savedTimeScale=e,this.mixer&&this.isPlaying&&(this.mixer.timeScale=e)}setLoop(e){let t=e?r.LoopRepeat:r.LoopOnce;for(let n of this.actions)n.setLoop(t),n.clampWhenFinished=!e}seekTo(e,t=0){if(!this.mixer||this.actions.length===0)return null;if(this._activeClip=t,this.mixer.stopAllAction(),t===-1)for(let e of this.actions)e.play();else t>=0&&t<this.actions.length&&this.actions[t].play();this.mixer.setTime(e);for(let e of this.actions)e.isRunning()&&(e.paused=!0);return this._poseReader()}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._poseReader()}_scratch(e,t,n){let r=e[t];return r&&r.length===n?r:e[t]=new Float32Array(n)}_poseReader(){if(this._mixerRoot.updateMatrixWorld(!0),this._rigid)return this._applyRigidPose(this._activeClip),null;let e=this._planFor(this._activeClip)?.cameras;return e?.length&&this.applyPoseCallback?.({meshIndices:[],visibilityChanged:!1,cameras:e}),e=>this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._tempVec,n=this._meshes[e],{count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._scratch(this._skinnedCache,e,i*3),s=this._scratch(this._meshPositions,e,r*9),c=n.matrixWorld;for(let e=0;e<i;e++)n.getVertexPosition(e,t),t.applyMatrix4(c),o[e*3]=t.x,o[e*3+1]=t.y,o[e*3+2]=t.z;if(a)for(let e=0;e<r;e++){let t=e*3,n=a[t]*3,r=a[t+1]*3,i=a[t+2]*3,c=e*9;s[c]=o[n],s[c+1]=o[n+1],s[c+2]=o[n+2],s[c+3]=o[r],s[c+4]=o[r+1],s[c+5]=o[r+2],s[c+6]=o[i],s[c+7]=o[i+1],s[c+8]=o[i+2]}else for(let e=0;e<r;e++){let t=e*3*3,n=(e*3+1)*3,r=(e*3+2)*3,i=e*9;s[i]=o[t],s[i+1]=o[t+1],s[i+2]=o[t+2],s[i+3]=o[n],s[i+4]=o[n+1],s[i+5]=o[n+2],s[i+6]=o[r],s[i+7]=o[r+1],s[i+8]=o[r+2]}return s}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._meshPositions=null,this._skinnedCache=null,this._clipsCache=null,this._rigid=!1,this._plans=null,this._allPlan=null,this._activeClip=0,this._slotOf=null,this._lastWorld=null,this._lastVisible=null}};xe();var Px=new r.Vector3(0,0,-1),Fx=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new _.TransformControls(e,t),this._gizmoScene=new r.Scene,this._gizmoScene.add(this._controls.getHelper()),this._attached=null,this._isDragging=!1,this._meshes=null,this._refitInFlight=!1,this._baselineComputed=!1,this._tempForward=new r.Vector3,this._lightTargetDistance=null,this._lastLightPosition=null,this._onDraggingChanged=this._onDraggingChanged.bind(this),this._onObjectChange=this._onObjectChange.bind(this),this._controls.addEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.addEventListener(`objectChange`,this._onObjectChange)}setMeshData(e){this._meshes=e}attach(e){if(this._attached!==e&&(this._controls.attach(e),this._attached=e,this._lightTargetDistance=null,this._lastLightPosition=null,e.isLight&&e.target)){let t=e.target.position.clone().sub(e.position),n=t.length();n>1e-4?(e.quaternion.setFromUnitVectors(Px,t.normalize()),this._lightTargetDistance=n):this._lightTargetDistance=1,this._lastLightPosition=e.position.clone()}}detach(){this._attached&&(this._controls.detach(),this._attached=null,this._lightTargetDistance=null,this._lastLightPosition=null)}setMode(e){this._controls.setMode(e),this._app?.dispatchEvent({type:H.TRANSFORM_MODE_CHANGED,mode:e}),this._app?.refreshFrame()}setSpace(e){this._controls.setSpace(e),this._app?.refreshFrame()}get isDragging(){return this._isDragging}get attachedObject(){return this._attached}get controls(){return this._controls}render(e){if(!this._attached)return;let t=e.autoClear;e.autoClear=!1,e.clearDepth(),e.setRenderTarget(null),e.render(this._gizmoScene,this._camera),e.autoClear=t}_onDraggingChanged(e){this._isDragging=e.value,this._orbitControls&&(this._orbitControls.enabled=!e.value),e.value?this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:H.OBJECT_TRANSFORM_END}))}_onObjectChange(){this._app.needsReset=!0,this._app.wake(),this._attached?.isLight&&this._syncLightDuringDrag()}_syncLightDuringDrag(){let e=this._attached;if(e.target){let t=this._controls.mode;if(t===`translate`&&this._lastLightPosition){let t=this._tempForward.copy(e.position).sub(this._lastLightPosition);e.target.position.add(t),e.target.updateMatrixWorld(!0)}else if(t===`rotate`&&this._lightTargetDistance!=null){let t=this._tempForward.set(0,0,-1).applyQuaternion(e.quaternion);e.target.position.copy(e.position).addScaledVector(t,this._lightTargetDistance),e.target.updateMatrixWorld(!0)}this._lastLightPosition.copy(e.position)}this._app.lightManager?.updateLights()}_finalizeLightTransform(){let e=this._attached;e.isRectAreaLight&&(e.scale.x!==1||e.scale.y!==1)&&(e.width*=e.scale.x,e.height*=e.scale.y,e.scale.set(1,1,1)),this._app.lightManager?.updateLights()}_recomputeAndRefit(){if(!this._meshes||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){this._refitInFlight=!0;try{this._app.updateMeshTransforms(e)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},Ix=class{constructor(e){this.layer=`scene`,this._transformManager=e,this._enabled=!0}get visible(){return this._enabled&&this._transformManager.attachedObject!==null}render(e){this._transformManager.render(e)}show(){this._enabled=!0}hide(){this._enabled=!1}dispose(){this._enabled=!1}};qt(),xe(),ca();var Lx=new WeakMap,Rx=Pt(`engine`);function zx(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Bx=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Vx(e){let t=e.info??{},n=`${t.vendor??``} ${t.architecture??``} ${t.device??``} ${t.description??``}`;return{vendor:t.vendor??``,architecture:t.architecture??``,device:t.device??``,description:t.description??``,isSoftware:t.isFallbackAdapter===!0||e.isFallbackAdapter===!0||Bx.test(n)}}var Hx=class extends r.EventDispatcher{constructor(e,t={}){super();try{Lx.get(e)?.dispose()}catch(e){Rx.warn(`prior canvas owner dispose failed`,e)}Lx.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._maxSceneBytes=t.maxSceneBytes,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Le(t.profile),this._issues=new fn({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:H.ISSUE,issue:e})}),this.color=new mo({issues:this._issues}),co(this.color),this.settings=new jg({...W,environmentRotation:this._profile.environmentRotation,saturation:this._profile.saturation},{issues:this._issues}),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._emittersMoved=!1,this._maxTextureSize=W.maxTextureSize,this.pipeline=null,this._pendingReservedRenderSize=null,this.stages={},this.cameraManager=null,this.lightManager=null,this.goboManager=null,this.iesManager=null,this.denoisingManager=null,this.overlayManager=null,this.interactionManager=null,this.transformManager=null,this.animationManager=new Nx,this.environmentManager=null,this.isInitialized=!1,this.pauseRendering=!1,this._pathTracerEnabled=!0,this._rasterPrecompile=null,this.animationManagerId=null,this.needsReset=!1,this._loadingInProgress=!1,this._needsDisplayRefresh=!1,this._paused=!1,this._emissiveSamplingUserSet=!1,this.completion=new Tg,this._resizeDebounceTimer=null,this._displayWidth=0,this._displayHeight=0,this._renderScale=1,this._pendingRenderScale=null,this._trackedListeners=[],this._disposed=!1,this._deviceLost=!1,this._gpuDevice=null,this._deviceLostHolder=null,this._deterministic=!1,this._dispatchPinned=!1,this._deterministicRestore=null,this.adapterInfo=null}_addTrackedListener(e,t,n){e&&(e.addEventListener(t,n),this._trackedListeners.push({target:e,type:t,handler:n}))}_removeTrackedListeners(){for(let{target:e,type:t,handler:n}of this._trackedListeners)try{e.removeEventListener(t,n)}catch(e){Rx.warn(`failed to remove listener`,t,e)}this._trackedListeners.length=0}async init(){return await this._initRenderer(),this._applyPendingReservedRenderSize(),this._initCameraManager(),this._initScenes(),this._initAssetPipeline(),this._initPipeline(),await this._initManagers(),this._wireEvents(),this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setupMaterial(),this.isInitialized=!0,Rx.debug(`WebGPU path tracer app initialized`),this}animate(){if(this._deviceLost)return;if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:H.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this._applyPendingRenderScale(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Rx.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}let e=this.needsReset;if(this.needsReset&&=(this.stages.pathTracer?.noteViewChanged(),this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}if(this.denoisingManager?.skipsTrace()){e&&this.stages.pathTracer.enterInteractionMode(),this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME});return}this.pipeline.render(),this.denoisingManager?.afterTrace(),this.stages.pathTracer.isComplete||(this.completion.updateTime(),this.denoisingManager?.tickContinuousDenoise(this.stages.pathTracer.frameCount)),this._ensureVRAMWiring();let t=this.stages.pathTracer?.vramTracker,n=this.stages.pathTracer?.frameCount??0;if(t&&(n<=1||n%30==0)&&t.measure(),Te({timeElapsed:this.completion.timeElapsed,samples:Ee(this.stages.pathTracer),memoryUsed:t?.current??0,memoryPeak:t?.peak??0}),this.completion.isTimeLimitReached(this.stages.pathTracer,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`))&&(this.stages.pathTracer.isComplete=!0),this.stages.pathTracer.isComplete&&this.completion.markComplete()){this.denoisingManager.onRenderComplete({isStillComplete:()=>this.completion.renderCompleteDispatched,context:this.pipeline?.context});let e={samples:this.stages.pathTracer.frameCount,timeElapsed:this.completion.timeElapsed,budgetOverrun:this.completion.budgetOverrun,reason:this.completion.stopCondition(this.stages.pathTracer)??`samples`};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:H.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:H.FRAME})}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Rx.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:H.DEVICE_LOST,reason:e?.reason,message:e?.message}))}wake(){this._deviceLost||!this.animationManagerId&&this.isInitialized&&!this._paused&&this.animate()}pause(){this._paused=!0,this.stopAnimation()}resume(){this._paused=!1,this.animationManagerId||this.animate()}reset(e=!1,{motion:t=!1}={}){t&&this.stages.pathTracer?.noteViewChanged(),this.denoisingManager?.beforeReset({keepHistory:e||t}),this.pipeline&&(this.pipeline.reset(),e||(this.pipeline.eventBus.emit(`asvgf:reset`),this.pipeline.eventBus.emit(`denoiser:reset`))),this.denoisingManager?.afterReset(),this._abortPostProcess({keepDisplay:!0}),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:H.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:H.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this._issues.detach(),this.color?.dispose(),this.color=null,this._textureReadback?.dispose(),this._textureReadback=null,this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])je(e);this.meshScene.clear(),this.meshScene=null}this._sceneHelpers?.clear(),this._sceneHelpers=null,this.scene?.clear(),this.scene=null;try{let e=(0,n.texture)().value,t=(0,n.cubeTexture)().value;e?._listeners?.dispose&&(e._listeners.dispose.length=0),t?._listeners?.dispose&&(t._listeners.dispose.length=0)}catch(e){Rx.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Lx.get(this.canvas)===this&&Lx.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Ae(this.renderer),this.renderer=null,this.stages={},this.isInitialized=!1}}unloadScene(){if(this.isInitialized){if(this._loadingInProgress)throw Error(`PathTracerApp.unloadScene: cannot unload while a load is in progress`);this._disposed||(this.animationManager?.dispose(),this._animRefitInFlight=!1,this.interactionManager?.deselect(),this.transformManager?.detach?.(),this.assetLoader?.releaseTargetModel(),this.lightManager?.clearLights?.(),this.stages.pathTracer&&(this.stages.pathTracer.setTriangleData(new Float32Array(32),0),this.stages.pathTracer.setBVHData(new Float32Array(16)),this.stages.pathTracer.materialData.setMaterialData(new Float32Array(16)),this.stages.pathTracer.setEmissiveTriangleData?.(new Float32Array,0,0),this.stages.pathTracer.setupMaterial()),this.denoisingManager?.dropDisplay(),this.reset(),this.dispatchEvent({type:`SceneUnloaded`}))}}async loadModel(e){await this._loadWithSceneRebuild(()=>this.assetLoader.loadModel(e),{type:`ModelLoaded`,url:e})}async loadObject3D(e,t=`object3d`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadObject3D(e,t),{type:`Object3DLoaded`,name:t})}_busyError(e){let t=Error(`${e}: another load is already in progress`);return t.code=`LOAD_IN_PROGRESS`,t}async loadEnvironment(e){if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadEnvironment`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async inspectArchive(e){return await this.assetLoader.inspectArchive(e)}async loadFile(e,t={}){let n=this.assetLoader?.getFileFormat(e?.name||``);if(!n)throw Error(`Unsupported file format: ${e?.name}`);if(n.type!==`environment`&&n.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e,t),{type:`ModelLoaded`,filename:e.name});return}if(this._loadingInProgress)throw this._busyError(`PathTracerApp.loadFile`);this._loadingInProgress=!0;try{await this.assetLoader.loadAssetFromFile(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.applyHDRI(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,filename:e.name})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}cancelLoad(){this._loadingInProgress&&this.assetLoader?.cancelActiveLoad()}async setMaxTextureSize(e,{reprocess:t=!0}={}){let n=this._maxTextureSize;if(this._maxTextureSize=this._sdf?.setMaxTextureSize(e)??e,typeof this.stages?.pathTracer?.sdfs?.setMaxTextureSize==`function`&&this.stages.pathTracer.sdfs.setMaxTextureSize(this._maxTextureSize),t&&this._maxTextureSize!==n&&this._sdf?.triangles&&!this._loadingInProgress){this._loadingInProgress=!0;try{await this.loadSceneData(),this.reset(),this.dispatchEvent({type:`TexturesReprocessed`,maxTextureSize:this._maxTextureSize})}finally{this._loadingInProgress=!1}}}async _loadWithSceneRebuild(e,t){if(this._loadingInProgress)throw this._busyError(`PathTracerApp`);this._loadingInProgress=!0;try{await e(),this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()}),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.denoisingManager?.dropDisplay(),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}catch(e){throw(!e||e.code!==`LOAD_IN_PROGRESS`)&&this._discardFailedLoad(),e}finally{this._loadingInProgress=!1}}_discardFailedLoad(){try{this._clearAppendedModels(),this.assetLoader?.releaseTargetModel(),this.denoisingManager?.dropDisplay(),this.reset()}catch(e){console.warn(`PathTracerApp: could not clear the scene after a failed load`,e)}}get sceneMetadata(){return this.assetLoader?.sceneMetadata??null}_beginSceneMetadataEnvironment(){let e=this.sceneMetadata?.environment;return!this._applySceneMetadataEnabled||!e?.sourceFile||!this.stages.pathTracer?null:(this.stages.pathTracer.environment.beginHDRI(),this._applyingSceneMetadata=!0,this.assetLoader.loadEnvironment(e.sourceFile).catch(t=>(this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment "${e.sourceFile}" failed to load — lighting falls back to the previous environment`,{sourceFile:e.sourceFile,cause:String(t?.message??t)}),null)).finally(()=>{this._applyingSceneMetadata=!1}))}_applySceneMetadataSettings(e){let t=this.sceneMetadata,n=t?.environment;if(!n)return;let r={enableEnvironment:!0,showBackground:!0,transparentBackground:!1};n.intensity!==void 0&&(r.environmentIntensity=n.intensity,r.backgroundIntensity=n.intensity),n.rotation!==void 0&&(r.environmentRotation=n.rotation),this.settings.setMany(r,{reset:!1,source:kg.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:H.SCENE_METADATA_APPLIED,metadata:t,environment:{...n}})}async loadSceneData({pendingEnvironment:e=null}={}){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._emittersMoved=!1,this._tagPrimarySceneObject();let t=new jd(``,{namespace:`scene`,level:`info`}),n=this.meshScene.environment,r=null;if(e?(t.start(`Environment fetch + CDF (concurrent)`),r=e.then(async e=>{e&&(await this.stages.pathTracer.environment.applyHDRI(e),this._applySceneMetadataSettings(e))}).catch(e=>this._issues.record(ln.ENVIRONMENT_LOAD_FAILED,`authored environment failed to install — the scene is lit by whatever was already loaded`,{cause:String(e?.message??e)})).finally(()=>t.end(`Environment fetch + CDF (concurrent)`))):n?.image?.data&&(t.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=n,r=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>{t.end(`Environment CDF build (worker)`),this._applySceneMetadataEnabled&&this._applySceneMetadataSettings(n)})),t.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),t.end(`BVH build (SceneProcessor)`),U({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),t.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,this.meshScene.environment))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),t.end(`GPU data transfer`),U({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),t.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),t.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(t.start(`Pipeline precompile`),await this.precompileRaster(),t.end(`Pipeline precompile`)),r&&(U({status:`Finalizing environment map...`,progress:95}),await r,this.stages.pathTracer.environment.applyCDFResults());let i=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,i,{reset:!1}),this.settings.set(`groundCatcherHeight`,i,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return t.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),t.end(`Apply settings`),t.print(this._sceneSummaryParts()),we(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.setCount??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[Y.count(e.triangleCount,`tri`),t?Y.count(t,`mesh`,`meshes`):null,Y.count(e.materialData.materialCount,`material`),n?Y.count(n,`map`):null,Y.count(e.bvhNodeCount,`BVH node`)]}_tagPrimarySceneObject(){let e=this.sceneModel;e&&(e.userData.__rayzeeSceneObject=!0)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.sceneModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r)}async _finishRebuildNoReframe(e){await this.loadSceneData(),this._recalibrateControlLimits(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),e&&this.dispatchEvent(e)}async addModel(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModel: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=await this.assetLoader.appendModel(e);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,url:e,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async addModelFromObject3D(e,{name:t}={}){if(this._loadingInProgress)throw Error(`PathTracerApp.addModelFromObject3D: another load is already in progress`);this._loadingInProgress=!0,this._preserveSelectionOnRebuild=!0;try{let{root:n}=this.assetLoader.appendObject3D(e,t||`object3d`);return n.userData.__rayzeeSceneObject=!0,t&&(n.userData.__rayzeeName=t),await this._finishRebuildNoReframe({type:`ModelAdded`,id:n.uuid}),n.uuid}finally{this._preserveSelectionOnRebuild=!1,this._loadingInProgress=!1}}async removeSceneObject(e){if(!this.meshScene)return!1;let t=this.assetLoader?.floorPlane;if(t&&t.uuid===e)return!1;let n=this.getSceneObject(e);if(!n)return!1;if(this._loadingInProgress)throw Error(`PathTracerApp.removeSceneObject: another load is already in progress`);this._loadingInProgress=!0;try{return this.interactionManager?.deselect(),this.transformManager?.detach?.(),n===this.sceneModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(n),await this._finishRebuildNoReframe({type:`SceneObjectRemoved`,id:e}),!0}finally{this._loadingInProgress=!1}}setSceneObjectVisibility(e,t){return this.setMeshVisibilityByUuid(e,t)}get currentCameraIndex(){return this.cameraManager?.currentCameraIndex??0}addCamera({name:e}={}){let t=this.cameraManager.addCameraFromView(e);return this.cameraManager.switchCamera(t),this._dispatchCamerasUpdated(),t}removeCamera(e){let t=this.cameraManager.removeCamera(e);return t&&this._dispatchCamerasUpdated(),t}_dispatchCamerasUpdated(){this.dispatchEvent({type:`CamerasUpdated`,cameras:this.cameraManager.cameras,cameraNames:this.cameraManager.getCameraNames()})}get sceneMeshes(){return this._sdf?.meshes??[]}get sceneModel(){return this.assetLoader?.targetModel??null}getSceneObject(e){let t=this.meshScene?.children.find(t=>t.uuid===e);return t?.userData?.__rayzeeSceneObject?t:null}async refitBVH(e,t){let n=await this._sdf.refitBVH(e,t);return this.stages.pathTracer.updateTriangleData(this._sdf.triangles),this.stages.pathTracer.updateBVHData(this._sdf.bvh),this.reset(!1,{motion:!0}),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(!1,{motion:!0}),this._sdf.scheduleBackgroundRebuild(e,e=>{let t=this._sdf.computeBLASDirtyRanges([e]);this.stages.pathTracer.updateBufferRanges(t.triRanges,t.bvhRanges),this.reset(!1,{motion:!0})}),r}_applyAnimationPose({meshIndices:e,visibilityChanged:t,cameras:n}){if(!this._sdf?.instanceTable)return;let r=!1;e.length>0&&(this._notePlacementsMoving(e),this._sdf.updateMeshTransforms(e),this.stages.pathTracer?.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this._sdf.movesEmitters(e)&&(this._emittersMoved=!0,this.animationManager.isPlaying||this._refreshMovedEmitters()),r=!0),t&&(this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),r=!0),n.length>0&&this._followAnimatedCamera(n)&&(r=!0),r&&this.reset(!1,{motion:!0})}_notePlacementsMoving(e){let t=this.denoisingManager,n=this._sdf?.instanceTable;if(!(!t?.historyActive||!n))for(let r of e){let e=n.placementRunOf(r);if(e)for(let r=e.start;r<e.start+e.count;r++)t.notePlacementMoving(n.tlasLeafIndex[r],n.world,r*16)}}_refreshMovedEmitters(){this._emittersMoved&&(this._emittersMoved=!1,this._uploadEmissivePayload(this._sdf?.refreshEmissiveTransforms()??null))}_followAnimatedCamera(e){let t=this.cameraManager,n=t.currentCameraIndex>0?t.cameras[t.currentCameraIndex]:null,i=n?.userData?.__rayzeeSourceUuid,a=i&&e.find(e=>e.uuid===i);if(!a)return!1;a.updateWorldMatrix(!0,!1);let o=new r.Vector3;a.matrixWorld.decompose(n.position,n.quaternion,o),n.scale.set(Math.sign(o.x)||1,Math.sign(o.y)||1,Math.sign(o.z)||1),a.isPerspectiveCamera&&(n.fov=a.fov);let s=t.camera,c=t.controls,l=c?c.target.distanceTo(s.position):0;if(s.position.copy(n.position),s.quaternion.copy(n.quaternion),s.scale.copy(n.scale),s.isPerspectiveCamera&&n.isPerspectiveCamera&&(s.fov=n.fov),s.updateProjectionMatrix(),s.updateMatrixWorld(!0),c){let e=new r.Vector3(0,0,-1).applyQuaternion(s.quaternion);c.target.copy(s.position).addScaledVector(e,l||1)}return!0}updateMeshTransforms(e){this._notePlacementsMoving(e);let t=this._sdf.updateMeshTransforms(e);return this.stages.pathTracer.updateBufferRanges([],[this._sdf.computeTLASDirtyRange()]),this.reset(!1,{motion:!0}),t}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,G);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(He,Math.floor(n)||256));let r=this.renderer.backend?.device?.limits?.maxStorageBufferBindingSize||128*1024*1024,i=(typeof navigator<`u`&&navigator.deviceMemory||4)>=8&&r>=1024*1024*1024?He:2048,a=Ue(Math.min(n,i));if((this.stages?.pathTracer?.storageTextures?.writeColor?.image?.width??a)!==a){let e=this.pauseRendering;this.pauseRendering=!0;try{let e=this.renderer.domElement;(e.width>a||e.height>a)&&this.renderer.setSize(Math.min(e.width,a),Math.min(e.height,a),!1);for(let e of Object.values(this.stages))e?.reallocateReservedStorage?.()}finally{this.pauseRendering=e}this.reset(),this.dispatchEvent({type:`reserved_render_size_changed`,size:a})}return a}_applyPendingReservedRenderSize(){let e=this._pendingReservedRenderSize;if(!e)return;this._pendingReservedRenderSize=null;let t=this.setReservedRenderResolution(e.requestedPx,{allowLower:e.allowLower});t<e.requestedPx&&this._issues.warn(ln.RENDER_RESERVE_CAPPED,`reserved render size ${Y.n(e.requestedPx)}px was capped to ${Y.n(t)}px by this device's limits — renders above ${Y.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return G}_isRenderSizeSupported(e,t){return e>G||t>G?(this._issues.record(ln.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${G}px storage reserve — resize ignored, so output stays at the previous size. Raise it with setReservedRenderResolution( ${Math.max(e,t)} ) before init().`,{width:e,height:t,reserve:G}),!1):!0}onResize(){let e=this.canvas.clientWidth,t=this.canvas.clientHeight;if(e===0||t===0||!this._isRenderSizeSupported(e,t))return;this.renderer.setPixelRatio(1),this._setDisplaySize(e,t);let n=this.denoisingManager?._lastRenderWidth??0,r=this.denoisingManager?._lastRenderHeight??0;e===n&&t===r||(clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=setTimeout(()=>{this._applyRenderResize(e,t)},300))}_applyRenderResize(e,t){this._isRenderSizeSupported(e,t)&&(this.pipeline?.setSize(this._scaled(e),this._scaled(t)),this.denoisingManager?.setRenderSize(e,t),this.needsReset=!0,this.dispatchEvent({type:`resolution_changed`,width:e,height:t}))}setCanvasSize(e,t){return e===0||t===0||!this._isRenderSizeSupported(e,t)?null:(this.renderer.setPixelRatio(1),this._setDisplaySize(e,t),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}_scaled(e){return Math.max(1,Math.round(e*this._renderScale))}_setDisplaySize(e,t){this._displayWidth=e,this._displayHeight=t,this.renderer.setSize(this._scaled(e),this._scaled(t),!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix()}_interactionRenderScale(){if(this.denoisingManager?.continuousDenoise)return 1;let e=Number(this.settings.get(`interactionRenderScale`));return e>0?Math.min(1,Math.max(.125,e)):1}_requestRenderScale(e){this._pendingRenderScale=e}_applyPendingRenderScale(){this._pendingRenderScale!==null&&this._applyRenderScale(this._pendingRenderScale)}_applyRenderScale(e){this._pendingRenderScale=null,!(this._disposed||e===this._renderScale)&&(this._renderScale=e,!(!this._displayWidth||!this._displayHeight)&&(this._setDisplaySize(this._displayWidth,this._displayHeight),this.pipeline?.setSize(this._scaled(this._displayWidth),this._scaled(this._displayHeight)),this.pipeline?.eventBus.emit(`asvgf:reset`),this.pipeline?.eventBus.emit(`denoiser:reset`),this.needsReset=!0))}configureForMode(e,t={}){let n=e===`production`,r=n?wt:Tt;this.denoisingManager?.setCadenceSuspended(n),this.cameraManager.controls.enabled=!n,this.settings.setMany(Et(r),{silent:!0,source:kg.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),this.denoisingManager.applyOIDNEnabled(r.enableOIDN),this.denoisingManager.applyOIDNQuality(r.oidnQuality)),this.denoisingManager?._syncGBufferStages?.(),this.denoisingManager?.upscaler?.abort(),t.canvasWidth&&t.canvasHeight&&(this.setReservedRenderResolution(Math.max(t.canvasWidth,t.canvasHeight)),this.setCanvasSize(t.canvasWidth,t.canvasHeight)),this.needsReset=!1,this.pauseRendering=!1,n){let e=this.stages.pathTracer?.vramTracker;e&&(e.measure(),e.resetPeak())}this.reset()}refreshFrame(){this._needsDisplayRefresh=!0,this.wake()}_abortPostProcess({keepDisplay:e=!1}={}){if(this.denoisingManager?.abort(this.canvas,{keepDisplay:e}),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}requestPostProcessRefresh(){!this.stages.pathTracer?.isReady||this._deviceLost||(this._abortPostProcess(),this.completion.renderCompleteDispatched=!1,this.wake())}setDeterministicMode(e=!0,{pinDispatch:t=!0}={}){let n=this.stages.pathTracer;if(!n)return!1;if(e)this._deterministicRestore||={settings:{useAdaptiveSampling:this.settings.get(`useAdaptiveSampling`),usePixelFreeze:this.settings.get(`usePixelFreeze`),interactionModeEnabled:this.settings.get(`interactionModeEnabled`),renderLimitMode:this.settings.get(`renderLimitMode`),renderTimeLimit:this.settings.get(`renderTimeLimit`)},bounceEarlyExit:n._bounceEarlyExitThreshold,dynamicDispatch:n._useDynamicDispatch,autoFocusMode:this.cameraManager?.autoFocusMode,autoExposure:this.stages.autoExposure?.enabled,continuousDenoise:this.denoisingManager?.continuousDenoise},this.settings.setMany({useAdaptiveSampling:!1,usePixelFreeze:!1,interactionModeEnabled:!1,renderLimitMode:`frames`,renderTimeLimit:0},{silent:!0}),t?(n._bounceEarlyExitThreshold=-1,n._useDynamicDispatch=!1):(n._bounceEarlyExitThreshold=this._deterministicRestore.bounceEarlyExit,n._useDynamicDispatch=this._deterministicRestore.dynamicDispatch),this.cameraManager?.setAutoFocusMode(`manual`),this.stages.autoExposure&&(this.stages.autoExposure.enabled=!1),this.denoisingManager?.setContinuousDenoise(!1),n._pinSeedToFrame=!0,this._deterministic=!0,this._dispatchPinned=t;else if(this._deterministicRestore){let e=this._deterministicRestore;this.settings.setMany(e.settings,{silent:!0}),n._bounceEarlyExitThreshold=e.bounceEarlyExit,n._useDynamicDispatch=e.dynamicDispatch,e.autoFocusMode!==void 0&&this.cameraManager?.setAutoFocusMode(e.autoFocusMode),this.stages.autoExposure&&e.autoExposure!==void 0&&(this.stages.autoExposure.enabled=e.autoExposure),e.continuousDenoise!==void 0&&this.denoisingManager?.setContinuousDenoise(e.continuousDenoise),n._pinSeedToFrame=!1,this._deterministicRestore=null,this._deterministic=!1,this._dispatchPinned=!1}return this.reset(),this.stopAnimation(),this._deterministic}get issues(){return this._issues.list}get issueErrors(){return this._issues.errors}clearIssues(){this._issues.clear()}get isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r,allowEarlyRetire:i=!1}={}){let a=this.stages.pathTracer;if(!a)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await a.blueNoiseReady;let o=(t?0:a.frameCount)+e;this.settings.get(`maxSamples`)<o&&this.settings.set(`maxSamples`,o,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let s=e+64,c=0,l=!1;for(;a.frameCount<o&&c<s;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!a.isReady)throw Error(`renderFrames: path tracer stage is not ready`);if(this.pipeline.render(),c++,a.isComplete&&a.frameCount<o){l=!0;break}r?.(a.frameCount),n>0&&c%n===0&&await new Promise(e=>setTimeout(e,0))}if(a.frameCount<o&&!(l&&i)){let e=l?"adaptive sampling retired the frame at the convergence threshold — pass `allowEarlyRetire: true`, or disable it with setDeterministicMode()":`something retired the render (maxSamples, a stray reset, or a canvas resize)`;throw Error(`renderFrames: stopped at ${a.frameCount}/${o} samples after ${c} passes — ${e}`)}return a.frameCount}async renderToBuffer({colorSpace:e=`srgb`,preserveAlpha:t=!1,source:n=`accumulation`}={}){let r=e!==`linear`&&e!==`srgb`;if(r&&!this.color?.hasConfig)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb' without a colour config loaded, got "${e}"`);let i=this.stages?.pathTracer,a=i?.storageTextures?.readTarget;if(!a)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:o,height:s}=i,c=n===`display`?await this._readDisplaySource(a,o,s):await this.renderer.readRenderTargetPixelsAsync(a,0,0,o,s,0);if(e===`linear`)return{data:c,width:o,height:s,colorSpace:e,workingSpace:this.color?.workingSpace??null};if(r){let{rgba:t,colorSpace:n}=this.color.exportPixels(c,e);return{data:t,width:o,height:s,colorSpace:n}}return{data:hd(c,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:o,height:s,colorSpace:e}}enableGPUTiming(e=!0){let t=this.renderer?.backend;return!t||e&&t.hasFeature?.(`timestamp-query`)!==!0?!1:(t.trackTimestamp=e,t.trackTimestamp===e)}profileNextDenoise(){return this.denoisingManager?.denoiser?.profileNextDenoise()??!1}async getDenoiseProfile(){let e=this.denoisingManager?.denoiser;return e?{profile:await e.getLastDenoiseProfile(),runtime:e.getRuntimeInfo()}:null}async getGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`),await e.resolveTimestampsAsync(`render`);let t=e.info.compute.timestamp||0,n=e.info.render.timestamp||0;return{compute:t,render:n,total:t+n}}async getKernelGPUTimings(){let e=this.renderer;if(!e?.backend?.trackTimestamp)return null;await e.resolveTimestampsAsync(`compute`);let t=e.backend.timestampQueryPool?.compute?.timestamps;if(!t||t.size===0)return null;let n=new Map,r=this.stages?.pathTracer?._kernelManager?.kernels;if(r)for(let[e,t]of r)n.set(t.id,e);let i=[],a=-1;for(let[e,n]of t){let t=e.split(`:`);if(t.length!==4)continue;let r=Number(t[3].slice(1));Number.isFinite(r)&&(i.push({nodeId:Number(t[2]),f:r,ms:n}),r>a&&(a=r))}let o={},s=0,c=0;for(let e of i){if(e.f!==a)continue;s+=e.ms;let t=n.get(e.nodeId);t===void 0?c+=e.ms:o[t]=(o[t]??0)+e.ms}return{kernels:o,total:s,unattributed:c,frame:a}}getCanvas(){if(!this.renderer?.domElement)return null;let e=this.denoisingManager?.upscalerCanvas;return e&&e.style.display!==`none`?e:(this.stages.compositor&&this.pipeline?.context&&this.stages.compositor.render(this.pipeline.context),this.renderer.domElement)}screenshot({type:e=`image/png`,quality:t}={}){let n=this.getCanvas();return n?new Promise(r=>n.toBlob(r,e,t)):Promise.resolve(null)}getStatistics(){try{return this._sdf?.getStatistics?.()??null}catch{return null}}get pathTracerEnabled(){return this._pathTracerEnabled}set pathTracerEnabled(e){this._pathTracerEnabled=e,e||this.precompileRaster()}precompileRaster(){return!this.renderer||!this.meshScene?Promise.resolve():(this._rasterPrecompile??=this.renderer.compileAsync(this.meshScene,this.cameraManager.camera).catch(e=>Rx.warn(`raster fallback precompile failed`,e)),this._rasterPrecompile)}get isLoading(){return this._loadingInProgress}isComplete(){return this.stages.pathTracer?.isComplete??!1}getFrameCount(){return this.stages.pathTracer?.frameCount||0}getConvergenceStats(){return this.stages.pathTracer?.getConvergenceStats?.()??null}get vram(){return this.stages.pathTracer?.vramTracker??null}getMemoryInfo(){return this.stages.pathTracer?.vramTracker?.measure()??{current:0,peak:0,byCategory:{}}}getHostMemoryInfo(){let e=this._sdf;return e?.memory?{preflight:e.memoryPreflight,...e.memory.report}:null}_ensureVRAMWiring(){if(this._vramWired)return;let e=this.stages.pathTracer?.vramTracker;if(!e)return;e.register(`stages`,()=>this._collectStageTextures());let t=()=>e.measure();this._addTrackedListener(this,`SceneRebuild`,t),this._addTrackedListener(this,`EnvironmentLoaded`,t),this._addTrackedListener(this,`resolution_changed`,t),this._vramWired=!0}_collectStageTextures(){let e=[],t=this.stages||{},n=t.pathTracer;for(let r in t){let i=t[r];if(!(!i||i===n||typeof i!=`object`))for(let t in i){let n=i[t];n&&(n.isTexture||n.isRenderTarget)&&e.push(n)}}return e}getSceneMinY(){if(!this.meshScene)return 0;let e=new r.Box3().setFromObject(this.meshScene);return Number.isFinite(e.min.y)?e.min.y:0}getMaterialProperty(e,t){return this.stages.pathTracer?.materialData.getMaterialProperty(e,t)}getMaterialPropertySource(e,t){return this.stages.pathTracer?.materialData.getMaterialPropertySource(e,t)}setMaterialProperty(e,t,n){this.stages.pathTracer?.materialData.updateMaterialProperty(e,t,n),[`emissive`,`emissiveIntensity`].includes(t)&&this._sdf&&this._uploadEmissivePayload(this._sdf.updateMaterialEmissive(e,t,n)),this.reset()}_uploadEmissivePayload(e){!e||!this.stages.pathTracer||(this.stages.pathTracer.setEmissiveTriangleData(e.rawData,e.emissiveCount,e.totalPower,e.bitTrailMap),e.lightBVHNodeData&&this.stages.pathTracer.setLightBVHData(e.lightBVHNodeData,e.lightBVHNodeCount))}_refreshEmissiveForVisibility(){let e=this._sdf?.instanceTable;if(!e)return;let t=new Set;for(let n=0;n<e.count;n++)e.isSet[n]&&!e.visible[n]&&t.add(e.sourceMesh[n]);this._uploadEmissivePayload(this._sdf.rebuildEmissiveForVisibility(t))}setEmissiveTriangleSampling(e){this._emissiveSamplingUserSet=!0,this.settings.set(`enableEmissiveTriangleSampling`,e)}hasEmissiveGeometry(){return(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0}setMeshVisibility(e,t){this.stages.pathTracer?.updateMeshVisibility(e,t),this._refreshEmissiveForVisibility(),this.reset()}updateAllMeshVisibility(){this.stages.pathTracer?.updateAllMeshVisibility(),this._refreshEmissiveForVisibility(),this.reset()}getScene(){return this.meshScene||this.scene}setMeshVisibilityByUuid(e,t){let n=this.getScene()?.getObjectByProperty(`uuid`,e);if(!n)return null;let r=typeof t==`function`?!!t(n.visible):!!t;return n.visible=r,this.updateAllMeshVisibility(),r}setTextureTransform(e,t,n){this.stages.pathTracer?.materialData.updateTextureTransform(e,t,n),this.reset()}async _readDisplaySource(e,t,n){let r=this.pipeline?.context,i=r&&this.stages.compositor?.resolveLightTexture(r);return!i||i===e.texture?await this.renderer.readRenderTargetPixelsAsync(e,0,0,t,n,0):(this._textureReadback??=new Eg(this.renderer),await this._textureReadback.read(i,t,n))}async setTextureColorSpace(e,n){if(!e?.isTexture)throw Error(`setTextureColorSpace wants a three.js texture`);let r=e.userData??={};r.__rayzeeOriginalColorSpace===void 0&&(r.__rayzeeOriginalColorSpace=e.colorSpace);let i=r.__rayzeeOriginalColorSpace;if(delete r.ocioColorSpace,delete r.__rayzeeColorSpaceChoice,n==null)e.colorSpace=i,delete r.__rayzeeOriginalColorSpace;else if(n===`srgb`||n===`linear`)e.colorSpace=n===`srgb`?t.SRGBColorSpace:t.LinearSRGBColorSpace,r.__rayzeeColorSpaceChoice=n;else{if(!this.color?.hasConfig)throw Error(`"${n}" needs a colour config loaded`);r.ocioColorSpace=n,e.colorSpace=t.SRGBColorSpace}e.needsUpdate=!0,this.stages.pathTracer?.sdfs&&await this.rebuildMaterials()}async loadColorConfig(e={}){await this._leaveColorWorkingSpace();let t=Wi(this.renderer?.toneMapping),n=await this.color.loadConfig(e);return this.color.workingSpaceAdopted&&await this.applyColorWorkingSpace(),(!(t?.source===`ocio`&&Wi(this.renderer?.toneMapping)===t)||this.color.workingSpaceAdopted)&&this.reset(),n}async unloadColorConfig(){await this._leaveColorWorkingSpace(),this.color.unloadConfig(),this.reset()}async _leaveColorWorkingSpace(){this.color?.workingSpaceAdopted&&(this.color.setWorkingSpace(null),await this.applyColorWorkingSpace())}async applyColorWorkingSpace(){let e=this.environmentManager?.getEnvironmentTexture?.(),t=!1;if(e&&this.color?.hasConfig)try{t=this.color.convertTexturePixels(e)}catch(e){Rx.warn(`environment colour conversion failed: ${e.message}`)}this.stages.pathTracer?.sdfs&&(await this.rebuildMaterials(),this._uploadEmissivePayload(this._sdf?.rebuildEmissiveColors?.()??null)),t&&await this.environmentManager?.buildEnvironmentCDF?.(),this.reset()}async rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);this.adapterInfo=Vx(e),this.adapterInfo.isSoftware&&(this._issues.warn(ln.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Rx.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits,r={maxColorAttachmentBytesPerSample:128};for(let e of[`maxBufferSize`,`maxStorageBufferBindingSize`,`maxSampledTexturesPerShaderStage`,`maxStorageTexturesPerShaderStage`,`maxTextureArrayLayers`,`maxTextureDimension2D`,`maxComputeInvocationsPerWorkgroup`,`maxComputeWorkgroupStorageSize`,`maxComputeWorkgroupSizeX`,`maxComputeWorkgroupSizeY`,`maxComputeWorkgroupSizeZ`]){let t=n[e];t!==void 0&&(r[e]=t)}if(r.maxStorageBuffersPerShaderStage=Math.min(n.maxStorageBuffersPerShaderStage,10),this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:r}),await this.renderer.init(),!this.renderer.backend?.isWebGPUBackend)throw Error(`WebGPU backend unavailable — three.js fell back to WebGL2, which cannot run the path tracer's compute kernels. Check GPU process flags and driver support.`);let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},zx(a,this._deviceLostHolder),a.onuncapturederror=e=>Rx.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=this._profile.toneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1),this.color.attachRenderer(this.renderer)}_initCameraManager(){this.cameraManager=new Oy(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new M}_initAssetPipeline(){this._sdf=new Bd({issues:this._issues,...this._maxSceneBytes===void 0?{}:{maxSceneBytes:this._maxSceneBytes}}),this.assetLoader=new Ey(this.meshScene,this.cameraManager.camera,this.cameraManager.controls,{issues:this._issues,profile:this._profile}),this.assetLoader.setRenderer(this.renderer),this.assetLoader.createFloorPlane(),this._addTrackedListener(this.cameraManager.controls,`change`,()=>{this.needsReset=!0,this.stages.pathTracer?.enterInteractionMode(),this.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new Cg(this.renderer,e||1,t||1,{issues:this._issues}),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.nrd),this.pipeline.addStage(this.stages.asvgf),this.pipeline.addStage(this.stages.variance),this.pipeline.addStage(this.stages.bilateralFilter),this.pipeline.addStage(this.stages.edgeFilter),this.pipeline.addStage(this.stages.autoExposure),this.pipeline.addStage(this.stages.compositor);let n=this.canvas.clientWidth||1,r=this.canvas.clientHeight||1;this._displayWidth=n,this._displayHeight=r,this.pipeline.setSize(n,r),this.pipeline.eventBus.on(`pathtracer:interactionStart`,()=>this._requestRenderScale(this._interactionRenderScale())),this.pipeline.eventBus.on(`pathtracer:interactionEnd`,()=>this._applyRenderScale(1))}async _initManagers(){this.interactionManager=new Dg({scene:this.meshScene,camera:this.cameraManager.camera,canvas:this.canvas,assetLoader:this.assetLoader,pathTracer:null,floorPlane:this.assetLoader.floorPlane}),this.interactionManager.wireAppEvents(this),this.cameraManager.setInteractionManager(this.interactionManager),this.lightManager=new ky(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new Ay(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new Vy(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Fx({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new Ix(this.transformManager)),this.interactionManager.setDependencies({overlayManager:this.overlayManager,transformManager:this.transformManager,appDispatch:e=>this.dispatchEvent(e),orbitControls:this.cameraManager.controls,helperScene:this._sceneHelpers.scene}),this.denoisingManager.setOverlayManager(this.overlayManager),this.denoisingManager.setResetCallback(()=>this.reset()),this.denoisingManager.setPostProcessRefreshCallback(()=>this.requestPostProcessRefresh()),this.denoisingManager.setDisplayRefreshCallback(()=>this.refreshFrame()),this.denoisingManager.setSettings(this.settings),this.environmentManager=this.stages.pathTracer.environment,this.environmentManager.callbacks.onAutoExposureReset=()=>this.pipeline.eventBus.emit(`autoexposure:resetHistory`)}_wireEvents(){this._addTrackedListener(this.cameraManager,`CameraSwitched`,e=>this.dispatchEvent(e)),this._addTrackedListener(this.cameraManager,H.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[H.DENOISING_START,H.DENOISING_END,H.UPSCALING_START,H.UPSCALING_PROGRESS,H.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this.animationManager.applyPoseCallback=e=>this._applyAnimationPose(e),this._forwardEvents(this.animationManager,[H.ANIMATION_STARTED,H.ANIMATION_PAUSED,H.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,H.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters()}),this._addTrackedListener(this.animationManager,H.ANIMATION_STOPPED,()=>{this._animRefitInFlight=!1}),this.cameraManager.initCallbacks({onResize:()=>this.onResize(),onReset:()=>this.reset(),getSettings:e=>this.settings.get(e),applySettings:e=>this.settings.setMany(e,{silent:!0,reset:!1})}),this.cameraManager.initAutoFocus({meshScene:this.meshScene,assetLoader:this.assetLoader,floorPlane:this.assetLoader.floorPlane,pathTracer:this.stages.pathTracer,settings:this.settings,softReset:()=>this.reset(!0),hardReset:()=>this.reset()}),this.settings.bind({stages:this.stages,renderer:this.renderer,resetCallback:()=>this.reset(),reconcileCompletion:()=>this._reconcileCompletion(),denoisingManager:this.denoisingManager,cameraManager:this.cameraManager,onInteractionRenderScale:()=>{this.stages.pathTracer?.interactionMode&&this._requestRenderScale(this._interactionRenderScale())}}),this.renderer.toneMappingExposure=this.settings.get(`exposure`)??1,this.onResize(),this.resizeHandler=()=>this.onResize(),this._autoResize&&this._addTrackedListener(window,`resize`,this.resizeHandler),this._onAssetLoaded=async e=>{if(!this._loadingInProgress&&!(this._applyingSceneMetadata&&e.texture)){if(e.model)this._clearAppendedModels(),await this.loadSceneData({pendingEnvironment:this._beginSceneMetadataEnvironment()});else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.sceneModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this._refreshMovedEmitters(),this.dispatchEvent({type:H.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new nh(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new rh(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new ih(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new sh(this.renderer,{enabled:!1}),this.stages.nrd=new Gh(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new Jh(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new Xh(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ng(this.renderer,{enabled:!1}),this.stages.autoExposure=new lg(this.renderer,{enabled:W.autoExposure??!1}),this.stages.compositor=new ug(this.renderer,{saturation:this.settings.get(`saturation`)??W.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Cx({renderer:this.renderer,mainCanvas:this.canvas,stages:{pathTracer:this.stages.pathTracer,normalDepth:this.stages.normalDepth,motionVector:this.stages.motionVector,asvgf:this.stages.asvgf,nrd:this.stages.nrd,variance:this.stages.variance,bilateralFilter:this.stages.bilateralFilter,edgeFilter:this.stages.edgeFilter,autoExposure:this.stages.autoExposure,compositor:this.stages.compositor},pipeline:this.pipeline,getExposure:()=>this.settings.get(`exposure`)??1,getSaturation:()=>this.settings.get(`saturation`)??1}),this.denoisingManager.setupDenoiser(),this.denoisingManager.setupUpscaler(),this.denoisingManager._syncGBufferStages();let e=this.canvas.clientWidth||1,t=this.canvas.clientHeight||1;this.denoisingManager.setRenderSize(e,t)}_reconcileCompletion(){let e=this.stages.pathTracer;if(!e)return;let t=this.completion.isLimitReached(e,this.settings.get(`renderLimitMode`),this.settings.get(`renderTimeLimit`));t&&!e.isComplete?e.isComplete=!0:!t&&e.isComplete&&(e.isComplete=!1,this.completion.resumeFromPause(),this.denoisingManager?.abort(this.canvas),this.dispatchEvent({type:H.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:H.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Mx(this.cameraManager.camera),this.overlayManager.setupDefaultHelpers({helperScene:this._sceneHelpers,meshScene:this.meshScene,pipeline:this.pipeline,denoisingManager:this.denoisingManager,app:this,renderWidth:this.denoisingManager?._lastRenderWidth||this.canvas.clientWidth||1,renderHeight:this.denoisingManager?._lastRenderHeight||this.canvas.clientHeight||1}),await this.overlayManager.initViewRenderer({device:this.renderer.backend?.device,sizeSource:this.canvas}),this._container=this._container||this.canvas.parentNode||null,this.overlayManager.mount(this._container)}_syncControlsAfterLoad(){this.cameraManager.controls.saveState(),this.cameraManager.controls.update()}_recalibrateControlLimits(){if(!this.meshScene||!this.cameraManager)return;let e=new r.Box3,t=new r.Box3;for(let n of this.meshScene.children)n.userData?.__rayzeeSceneObject&&(t.setFromObject(n),t.isEmpty()||e.union(t));if(e.isEmpty())return;let n=Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z);if(!Number.isFinite(n)||n<=0)return;let{camera:i,controls:a}=this.cameraManager,o=i.fov*(Math.PI/180),s=Math.abs(n/Math.sin(o/2)/2);this.cameraManager.currentCameraIndex===0&&(i.near=n/100,i.far=n*100,i.updateProjectionMatrix());let c=i.position.distanceTo(a.target);a.minDistance=Math.min(n/1e3,c),a.maxDistance=Math.max(s*10,c*1.1),a.update()}_forwardEvents(e,t){if(e)for(let n of t)this._addTrackedListener(e,n,e=>this.dispatchEvent(e))}};async function Ux(e){let t=await Gx(e);try{return await Wx(t,e)}finally{t.dispose()}}async function Wx(e,{samples:t=64,colorSpace:n=`srgb`,allowEarlyRetire:r=!1,onProgress:i=void 0}={}){let a=await e.renderFrames(t,{onProgress:i,allowEarlyRetire:r});return{...await e.renderToBuffer({colorSpace:n}),samples:a,retiredBy:a<t?`converged`:`count`,issues:e.issues,adapter:e.adapterInfo}}async function Gx({canvas:e,model:t=null,width:n=1920,height:r=1080,strict:i=!0,profile:a=`physical`,deterministic:o=!0,settings:s=null}={}){if(!e)throw Error(`openHeadless: a canvas is required`);let c=new Hx(e,{autoResize:!1,strict:i,profile:a});try{return c.setReservedRenderResolution(Math.max(n,r)),await c.init(),c.setCanvasSize(n,r),t&&await c.loadModel(t),s&&c.settings.setMany(s,{silent:!0}),o&&c.setDeterministicMode(!0),c}catch(e){throw c.dispose(),e}}xe();var Kx=class{constructor(e){this._app=e,this._cancelled=!1,this._rendering=!1}async renderAnimation(e={}){let{clipIndex:t=0,fps:n=30,speed:r=1,samplesPerFrame:i=wt.maxSamples,enableOIDN:a=!0,onFrame:o,onProgress:s,onComplete:c}=e,l=this._app;if(!l.animationManager?.hasAnimations){console.warn(`VideoRenderManager: No animation clips available`),c?.(!1);return}let u=l.animationManager.clips[t];if(!u){console.warn(`VideoRenderManager: Invalid clip index ${t}`),c?.(!1);return}let d=u.duration/(r||1),f=e.totalFrames||Math.ceil(d*n),p=1/n;this._cancelled=!1,this._rendering=!0;let m=this._saveState();l.stopAnimation(),l.configureForMode(`production`),l.settings.setMany({maxSamples:i},{silent:!0}),l.stages.pathTracer?.updateCompletionThreshold?.(),l.cameraManager.controls&&(l.cameraManager.controls.enabled=!1);try{for(let e=0;e<f&&!this._cancelled;e++){let n=e*p*r,i=l.animationManager.seekTo(n,t);if(i?await l.refitBVH(i):l.reset(),l.stopAnimation(),await this._accumulateFrame(l),this._cancelled||(a&&l.denoisingManager?.finalDenoise&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:H.VIDEO_RENDER_PROGRESS,...u})}}catch(e){console.error(`VideoRenderManager: Render error:`,e),this._cancelled=!0}finally{this._restoreState(m),this._rendering=!1;let e=!this._cancelled;c?.(e),l.dispatchEvent({type:H.VIDEO_RENDER_COMPLETE,success:e})}}cancel(){this._cancelled=!0}get isRendering(){return this._rendering}async _accumulateFrame(e){let t=e.stages.pathTracer;if(t?.isReady)for(;!t.isComplete&&!this._cancelled;)e.cameraManager.camera.updateMatrixWorld(),e.pipeline.render(),t.frameCount%4==0&&(Te({samples:Ee(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(H.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(H.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app,t=e.settings.getEffective();return{settings:Object.keys(Et(wt)).map(e=>[e,t[e]]),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.finalDenoise,oidnQuality:e.denoisingManager?.oidnQuality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;for(let[n,r]of e.settings)r&&t.settings.set(n,r.value,{silent:!0,reset:!1,source:r.source});t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.denoisingManager?.setCadenceSuspended(!1),t.animationManager?.stop(),t.reset(),t.wake()}};xe(),Ar(),qt(),Zb(),dx(),ca(),e.AF_DEFAULTS=Qe,e.ASVGF_QUALITY_PRESETS=We,e.AUTO_FOCUS_MODES=Ze,e.AnimationManager=Nx,e.BVH_LEAF_MARKERS=ct,e.CAMERA_PRESETS=Xe,e.CAMERA_RANGES=Je,e.CameraManager=Oy,e.ColorManagement=mo,e.DEFAULT_LUT_SIZE=Ca,e.DEFAULT_MAX_EV=Sa,e.DEFAULT_MIN_EV=xa,e.DEFAULT_TEXTURE_MATRIX=Ct,e.DEFAULT_WORKING_SPACE=ao,e.DenoisingManager=Cx,e.ENGINE_DEFAULTS=W,e.EngineEvents=H,e.EngineIssueError=dn,e.GoboManager=Ay,e.IESManager=Vy,e.INTERACTIVE_RENDER_CONFIG=Tt,e.ISSUE_CODES=ln,e.ISSUE_SEVERITY=un,e.InteractionManager=Dg,e.IssueLog=fn,e.LOG_LEVELS=Lt,e.LightManager=ky,e.Logger=Gt,e.MATERIAL_DEFAULTS=J,e.MATERIAL_VALUE_SOURCE=Sn,e.MAX_RESERVABLE_RENDER_SIZE=He,e.MAX_SCENE_BYTES=Yu,e.MAX_TABLE_TRANSFORMS=ta,e.MEMORY_CONSTANTS=Dt,e.MemoryLedger=ed,e.NRD_DEFAULTS=Ge,e.NRD_HIT_DIST_A=ze,e.NRD_HIT_DIST_B=Be,e.NRD_PRESET_KEYS=Ke,e.NRD_QUALITY_PRESETS=qe,e.OCIO_VIEW_BASE=ea,e.OverlayManager=Mx,e.PRODUCTION_RENDER_CONFIG=wt,e.PathTracerApp=Hx,e.PipelineContext=dg,e.RENDER_PROFILES=Ie,e.RETOUCH_DEFAULTS=nx,e.RETOUCH_MAX_PIXELS=ix,e.RETOUCH_RANGES=ax,e.RenderPipeline=Cg,e.RenderSettings=jg,e.RenderStage=V,e.SAFE_SCENE_BYTES=Ju,e.SETTING_SOURCE=kg,e.SKY_PRESETS=Ye,e.SR_MAX_INPUT=Kb,e.SR_SCALE=Wb,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=dt,e.TRIANGLE_DATA_LAYOUT=$e,e.TransformManager=Fx,e.VIEW_TRANSFORMS=oa,e.VRAMTracker=tp,e.VideoRenderManager=Kx,e.addAllOcioViews=Pa,e.addOcioView=Na,e.addViewTransform=Ji,e.applyMatrixRGBA8=Si,e.bakeLut=fa,e.bufferBytes=$f,e.buildOcioView=Aa,e.buildToneMapWGSL=Qi,e.canvasColorSpaceFor=lo,e.captureHeadless=Wx,e.clearBindingAuditFindings=vg,e.clearInputOverrides=Ya,e.configureAssets=Dr,e.convertColor=li,e.convertEncodedRGBA8=_i,e.convertPixelsF32=ui,e.createLogger=Pt,e.deriveAlphaMode=En,e.describeAdapter=Vx,e.displayCanvasFit=Er,e.estimateSceneBytes=Qu,e.extractMatrix=Ci,e.extractSceneMetadata=_y,e.findNativeLinearSpace=po,e.fmt=Y,e.getActiveColorManagement=so,e.getAssetConfig=Or,e.getBindingAuditFindings=_g,e.getRegistryVersion=Hi,e.getRenderProfile=Le,e.getViewTransform=Wi,e.hasColorSpace=Ti,e.isColorManaged=ho,e.isDataSpace=wi,e.isDataTexture=to,e.linearToSrgb=pi,e.listFileRules=Qa,e.listInputOverrides=Xa,e.listViewTransforms=Gi,e.makeCpuSampler=va,e.measureBakeError=ba,e.onRegistryChange=Ui,e.openHeadless=Gx,e.parseSceneMetadata=gy,e.probeAddressSpace=$u,e.removeViewTransform=Yi,e.renderHeadless=Ux,e.renderUpscaled=Vb,e.resolveInputSpace=eo,e.setActiveColorManagement=co,e.setBindingAudit=gg,e.setInputOverride=Ja,e.srgbToLinear=fi,e.textureBytes=ep,e.textureInputSpace=io});