rayzee 7.30.2 → 7.31.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +113 -2
- package/dist/rayzee.es.js +2733 -2251
- package/dist/rayzee.umd.js +232 -7
- package/package.json +1 -1
- package/src/EngineDefaults.js +9 -1
- package/src/EngineIssues.js +1 -0
- package/src/Passes/OIDNDenoiser.js +497 -347
- package/src/PathTracerApp.js +23 -3
- package/src/Processor/AssetLoader.js +106 -13
- package/src/Processor/PBRT/EqualAreaOctahedral.js +149 -0
- package/src/Processor/PBRT/LoopSubdivision.js +240 -0
- package/src/Processor/PBRT/PBRTMath.js +9 -0
- package/src/Processor/PBRT/PBRTSceneBuilder.js +82 -1
- package/src/Processor/PBRT/index.js +63 -9
- package/src/Processor/SceneProcessor.js +17 -1
- package/src/Processor/ToneMapWGSL.js +162 -0
- package/src/managers/CameraManager.js +11 -0
- package/src/managers/DenoisingManager.js +251 -22
- package/src/managers/OverlayManager.js +4 -0
- package/src/managers/VideoRenderManager.js +5 -5
package/dist/rayzee.umd.js
CHANGED
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
return seed;
|
|
114
114
|
|
|
115
115
|
}
|
|
116
|
-
`,[te,L]),ge={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},_e=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ge.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 ge.ALWAYS:return!0;case ge.PER_CYCLE:return t===0?!0:n===!0;case ge.PER_TILE:return!0;case ge.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},ve=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,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}},V={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`},ye=new t.QuadMesh(null).geometry,be=null;function xe(e){be=e}var Se=()=>be?.({type:V.LOADING_RESET}),H=e=>{be?.({type:V.LOADING_UPDATE,...e})},Ce=e=>{be?.({type:V.STATS_UPDATE,...e})};function we(e){return e.frameCount||0}function Te(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Ee(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Ee(e),e.dispose()}}function Ee(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function De({material:e,geometry:t,children:n}){if(e&&Te(e),t&&t.dispose(),n.length>0)for(let e of n)De(e)}function Oe(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize),e.dispose(),e._canvasTarget=null;let t=ye._listeners?.dispose;t&&(t.length=0)}function ke(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Te(e);return}for(;e.children.length>0;)for(let t of e.children)ke(t);De(e),e.removeFromParent(),e.clear()}}function Ae(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function je(e,t){return t}function Me(e,t=!1){return t?1:1/(e+1)}function Ne(){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 Pe=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:270,toneMapping:4,saturation:1.2}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Fe(e=`viewer`){let t=Pe[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Pe).join(`, `)}`);return t}var U={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Pe.viewer.toneMapping,exposure:1,saturation:Pe.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Pe.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,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`,debugGbufferMaps:!1,enableUpscaler:!1,upscalerScale:2,upscalerQuality:`fast`,upscalerHdr:!0,debugMode:0,debugThreshold:100,debugModel:0,enableBloom:!1,bloomStrength:.2,bloomRadius:.15,bloomThreshold:.85,interactionModeEnabled:!0,debugVisScale:100,denoiserStrategy:`none`,enableASVGF:!1,asvgfTemporalAlpha:.1,asvgfAtrousIterations:8,asvgfPhiColor:10,asvgfPhiNormal:128,asvgfPhiDepth:1,asvgfVarianceBoost:1,asvgfMaxAccumFrames:32,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},Ie=6e4,Le=3,Re=.1,ze=.01,Be=4096,W=2048;function Ve(e){return W=Math.max(256,Math.min(Be,Math.floor(e)||256)),W}var He={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}},Ue={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},We=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],Ge={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}},Ke={fov:{min:10,max:90,default:U.fov},focusDistance:{min:.3,max:100,default:U.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:U.aperture},focalLength:{min:0,max:200,default:U.focalLength}},qe={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}},Je={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}},Ye={MANUAL:`manual`,AUTO:`auto`},Xe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},G={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},K={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}},Ze=e=>Number.isFinite(e)&&e>0?e:0,Qe={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},q={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},$e=64;function et(e,t){let n=Math.ceil(Math.max(1,e)/$e)*$e;return Math.min(t,Math.max(q.MIN_TEXTURE_WIDTH,n))}function tt(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 nt(e,t){return et(e.width,t)*e.height*e.count*4}function rt(e,t){return e.reduce((e,n)=>e+nt(n,t),0)}function it(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=tt(r[t].units.concat(r[i].units)),o=nt(a,n)-nt(r[t],n)-nt(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 at(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(q.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(tt)}function ot(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(tt(t))}else e===a?o.push(tt(n[e].units.concat([r]))):o.push(n[e]);if(rt(o,t)<rt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function st(e,t,n=q.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=>tt([e]));if(a.length>n){let e=at(i,n,t),r=it(a,n,t);a=rt(e,t)<rt(r,t)?e:r,a=ot(a,t)}return a.map(e=>({width:et(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function ct(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 lt(e,t){return e*q.BUCKET_LAYER_STRIDE+t}var ut=[0,0,1,1,0,0,0,1],dt={maxSamples:150,bounces:20,transmissiveBounces:8,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},ft={maxSamples:U.maxSamples,bounces:U.bounces,renderMode:U.renderMode,enableAlphaShadows:U.enableAlphaShadows,transmissiveBounces:U.transmissiveBounces,maxSubsurfaceSteps:U.maxSubsurfaceSteps,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0},pt={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},mt={silent:0,error:1,warn:2,info:3,debug:4},ht=`info`,gt=`rayzeeLogLevel`,_t=`rayzeeLogNamespaces`,vt=`color:#7c8494`,yt=`color:inherit`,bt=null,xt=null;function St(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function Ct(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function wt(){if(bt!==null)return bt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in mt?(bt=mt[e],bt):(bt=mt[St(gt)]??mt[ht],bt)}function Tt(){if(xt!==null)return xt;let e=globalThis.__RAYZEE_LOG_NS__??St(_t);return xt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],xt}function Et(e,t){if(t<mt.debug)return!0;let n=Tt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Dt(e,t,n){if(e>wt()||!Et(t,e))return;let r=e===mt.error?console.error:e===mt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,vt,yt,...n.slice(1)):r(`%c${i}`,vt,...n)}var J={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`)=>`${J.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Ot={levels:mt,setLevel(e){return e in mt?(globalThis.__RAYZEE_LOG_LEVEL__=e,bt=mt[e],Ct(gt,e===ht?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(mt).join(`, `)}`),this.getLevel())},getLevel(){let e=wt();return Object.keys(mt).find(t=>mt[t]===e)},isEnabled(e){return(mt[e]??mt.debug)<=wt()},only(...e){let t=e.flat().filter(Boolean);return xt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),Ct(_t,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return bt=null,xt=null,this.getLevel()}};function kt(e){return{namespace:e,error:(...t)=>Dt(mt.error,e,t),warn:(...t)=>Dt(mt.warn,e,t),info:(...t)=>Dt(mt.info,e,t),debug:(...t)=>Dt(mt.debug,e,t),isEnabled:e=>Ot.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Dt(mt.info,e,[t]),r.forEach(t=>Dt(mt.debug,e,[t]));return}mt.info>wt()||((wt()>=mt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,vt,yt),r.forEach(e=>console.log(e)),console.groupEnd())}}}var At=new Set;function jt(e,t,...n){At.has(t)||(At.add(t),e.warn(...n))}function Mt(){return Ot.getLevel()}var Nt=kt(`gpu`);function Pt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(W,W);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Ft=()=>Pt(),It=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=Ft(),this.writeNormalDepth=Ft(),this.writeAlbedo=Ft(),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`,Nt.debug(`storage texture pool ${J.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}},Lt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},Rt=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`,U.bounces,`int`),i(`maxSamples`,U.maxSamples,`int`),i(`transmissiveBounces`,U.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,U.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,U.maxTransparentBounces,`int`),i(`visMode`,U.debugMode,`int`),i(`debugVisScale`,U.debugVisScale,`float`),a(`useAdaptiveSampling`,U.useAdaptiveSampling),i(`noiseThreshold`,U.noiseThreshold,`float`),i(`adaptiveMinSamples`,U.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,U.adaptiveStopFraction,`float`),a(`usePixelFreeze`,U.usePixelFreeze),i(`pixelFreezeThreshold`,U.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,U.pixelFreezeStability,`int`),a(`convergenceOverlay`,U.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,U.environmentIntensity,`float`),i(`backgroundIntensity`,U.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,U.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,U.backgroundBlurSamples,`int`),a(`showBackground`,U.showBackground),a(`transparentBackground`,U.transparentBackground),a(`enableEnvironment`,U.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`,U.groundProjectionEnabled),i(`groundProjectionRadius`,U.groundProjectionRadius,`float`),i(`groundProjectionHeight`,U.groundProjectionHeight,`float`),i(`groundProjectionLevel`,U.groundProjectionLevel,`float`),a(`enableGroundCatcher`,U.enableGroundCatcher),i(`groundCatcherHeight`,U.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,U.globalIlluminationIntensity,`float`),i(`exposure`,U.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`,+(U.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(U.panoramaLonRange),`vec2`),i(`panoLatRange`,o(U.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,U.panoramaLevelHorizon),a(`enableDOF`,U.enableDOF),i(`focusDistance`,U.focusDistance,`float`),i(`focalLength`,U.focalLength,`float`),i(`aperture`,U.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,U.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,A),A.value=U.samplingTechnique,i(`fireflyThreshold`,U.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,U.enableEmissiveTriangleSampling),i(`emissiveBoost`,U.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,U.renderMode,`int`),a(`enableAlphaShadows`,U.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Lt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},zt=kt(`material`),Bt=K.SLOTS_PER_MATERIAL,Vt=G.UV_C_MAT_OFFSET+2,Ht=G.NORMAL_C_OFFSET+3,Ut=G.NORMAL_A_OFFSET+3,Wt=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Gt={ior:K.IOR,transmission:K.TRANSMISSION,thickness:K.THICKNESS,emissiveIntensity:K.EMISSIVE_INTENSITY,attenuationDistance:K.ATTENUATION_DISTANCE,opacity:K.OPACITY,alphaTest:K.ALPHA_TEST,metalness:K.METALNESS,roughness:K.ROUGHNESS,clearcoat:K.CLEARCOAT,clearcoatRoughness:K.CLEARCOAT_ROUGHNESS,dispersion:K.DISPERSION,sheen:K.SHEEN,sheenRoughness:K.SHEEN_ROUGHNESS,specularIntensity:K.SPECULAR_INTENSITY,iridescence:K.IRIDESCENCE,iridescenceIOR:K.IRIDESCENCE_IOR,subsurface:K.SUBSURFACE,subsurfaceRadiusScale:K.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:K.SUBSURFACE_ANISOTROPY,anisotropy:K.ANISOTROPY,anisotropyRotation:K.ANISOTROPY_ROTATION},Kt=class{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={}}setMaterialData(e){if(!e)return;let r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/Bt),zt.debug(`${J.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=Gt[t];if(r===void 0)return;let i=e*K.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*K.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+K.COLOR]=n[0],r[i+K.COLOR+1]=n[1],r[i+K.COLOR+2]=n[2]):(r[i+K.COLOR]=n.r,r[i+K.COLOR+1]=n.g,r[i+K.COLOR+2]=n.b);break;case`metalness`:r[i+K.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+K.EMISSIVE]=n[0],r[i+K.EMISSIVE+1]=n[1],r[i+K.EMISSIVE+2]=n[2]):(r[i+K.EMISSIVE]=n.r,r[i+K.EMISSIVE+1]=n.g,r[i+K.EMISSIVE+2]=n.b);break;case`roughness`:r[i+K.ROUGHNESS]=n;break;case`ior`:r[i+K.IOR]=n;break;case`transmission`:r[i+K.TRANSMISSION]=n;break;case`thickness`:r[i+K.THICKNESS]=n;break;case`emissiveIntensity`:r[i+K.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.ATTENUATION_COLOR]=n[0],r[i+K.ATTENUATION_COLOR+1]=n[1],r[i+K.ATTENUATION_COLOR+2]=n[2]):(r[i+K.ATTENUATION_COLOR]=n.r,r[i+K.ATTENUATION_COLOR+1]=n.g,r[i+K.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+K.ATTENUATION_DISTANCE]=Ze(n);break;case`dispersion`:r[i+K.DISPERSION]=n;break;case`sheen`:r[i+K.SHEEN]=n;break;case`sheenRoughness`:r[i+K.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SHEEN_COLOR]=n[0],r[i+K.SHEEN_COLOR+1]=n[1],r[i+K.SHEEN_COLOR+2]=n[2]):(r[i+K.SHEEN_COLOR]=n.r,r[i+K.SHEEN_COLOR+1]=n.g,r[i+K.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+K.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SPECULAR_COLOR]=n[0],r[i+K.SPECULAR_COLOR+1]=n[1],r[i+K.SPECULAR_COLOR+2]=n[2]):(r[i+K.SPECULAR_COLOR]=n.r,r[i+K.SPECULAR_COLOR+1]=n.g,r[i+K.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+K.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+K.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+K.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+K.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+K.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+K.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+K.OPACITY]=n;break;case`side`:r[i+K.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+K.TRANSPARENT]=n;break;case`alphaTest`:r[i+K.ALPHA_TEST]=n;break;case`alphaMode`:r[i+K.ALPHA_MODE]=n;break;case`depthWrite`:r[i+K.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+K.NORMAL_SCALE]=n,r[i+K.NORMAL_SCALE+1]=n):(r[i+K.NORMAL_SCALE]=n.x,r[i+K.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+K.BUMP_SCALE]=n;break;case`displacementScale`:r[i+K.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+K.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+K.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+K.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+K.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+K.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SUBSURFACE_COLOR]=n[0],r[i+K.SUBSURFACE_COLOR+1]=n[1],r[i+K.SUBSURFACE_COLOR+2]=n[2]):(r[i+K.SUBSURFACE_COLOR]=n.r,r[i+K.SUBSURFACE_COLOR+1]=n.g,r[i+K.SUBSURFACE_COLOR+2]=n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+K.SUBSURFACE_RADIUS]=n[0],r[i+K.SUBSURFACE_RADIUS+1]=n[1],r[i+K.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+K.SUBSURFACE_RADIUS]=n.x,r[i+K.SUBSURFACE_RADIUS+1]=n.y,r[i+K.SUBSURFACE_RADIUS+2]=n.z);break;default:zt.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Wt.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*K.FLOATS_PER_MATERIAL;t.color&&(n[r+K.COLOR]=t.color.r??t.color[0]??1,n[r+K.COLOR+1]=t.color.g??t.color[1]??1,n[r+K.COLOR+2]=t.color.b??t.color[2]??1),n[r+K.METALNESS]=t.metalness??0,t.emissive&&(n[r+K.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+K.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+K.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+K.ROUGHNESS]=t.roughness??1,n[r+K.IOR]=t.ior??1.5,n[r+K.TRANSMISSION]=t.transmission??0,n[r+K.THICKNESS]=t.thickness??.1,n[r+K.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+K.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+K.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+K.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+K.ATTENUATION_DISTANCE]=Ze(t.attenuationDistance),n[r+K.DISPERSION]=t.dispersion??0,n[r+K.VISIBLE]=1,n[r+K.SHEEN]=t.sheen??0,n[r+K.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+K.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+K.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+K.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+K.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+K.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+K.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+K.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+K.IRIDESCENCE]=t.iridescence??0,n[r+K.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+K.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+K.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+K.ALBEDO_MAP_INDEX]=t.map??-1,n[r+K.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+K.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+K.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+K.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+K.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+K.CLEARCOAT]=t.clearcoat??0,n[r+K.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+K.OPACITY]=t.opacity??1,n[r+K.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+K.TRANSPARENT]=t.transparent??0,n[r+K.ALPHA_TEST]=t.alphaTest??0,n[r+K.ALPHA_MODE]=t.alphaMode??0,n[r+K.DEPTH_WRITE]=t.depthWrite??1,n[r+K.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+K.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+K.BUMP_SCALE]=t.bumpScale??1,n[r+K.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+K.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1,n[r+K.SUBSURFACE]=t.subsurface??0,t.subsurfaceColor&&(n[r+K.SUBSURFACE_COLOR]=t.subsurfaceColor.r??t.subsurfaceColor[0]??1,n[r+K.SUBSURFACE_COLOR+1]=t.subsurfaceColor.g??t.subsurfaceColor[1]??1,n[r+K.SUBSURFACE_COLOR+2]=t.subsurfaceColor.b??t.subsurfaceColor[2]??1),t.subsurfaceRadius&&(n[r+K.SUBSURFACE_RADIUS]=t.subsurfaceRadius[0]??1,n[r+K.SUBSURFACE_RADIUS+1]=t.subsurfaceRadius[1]??.2,n[r+K.SUBSURFACE_RADIUS+2]=t.subsurfaceRadius[2]??.1),n[r+K.SUBSURFACE_RADIUS_SCALE]=t.subsurfaceRadiusScale??1,n[r+K.SUBSURFACE_ANISOTROPY]=t.subsurfaceAnisotropy??0,n[r+K.ANISOTROPY]=t.anisotropy??0,n[r+K.ANISOTROPY_ROTATION]=t.anisotropyRotation??0,n[r+K.ANISOTROPY_MAP_INDEX]=t.anisotropyMap??-1,n[r+K.TRANSMISSION_MAP_INDEX]=t.transmissionMap??-1,n[r+K.CLEARCOAT_MAP_INDEX]=t.clearcoatMap??-1,n[r+K.CLEARCOAT_ROUGHNESS_MAP_INDEX]=t.clearcoatRoughnessMap??-1,n[r+K.SHEEN_COLOR_MAP_INDEX]=t.sheenColorMap??-1,n[r+K.SHEEN_ROUGHNESS_MAP_INDEX]=t.sheenRoughnessMap??-1,n[r+K.IRIDESCENCE_MAP_INDEX]=t.iridescenceMap??-1,n[r+K.IRIDESCENCE_THICKNESS_MAP_INDEX]=t.iridescenceThicknessMap??-1,n[r+K.SPECULAR_INTENSITY_MAP_INDEX]=t.specularIntensityMap??-1,n[r+K.SPECULAR_COLOR_MAP_INDEX]=t.specularColorMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:K.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:K.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:K.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:K.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:K.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:K.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:K.DISPLACEMENT_TRANSFORM}];for(let{key:e,offset:o}of a){let a=t[e]??i;for(let e=0;e<8;e++)r+o+e<n.length&&(n[r+o+e]=a[e])}this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);(this._srgbTexPacked||this._linearTexPacked)&&(n.map=this.getPackedTextureIndex(t.map,!0),n.emissiveMap=this.getPackedTextureIndex(t.emissiveMap,!0),n.normalMap=this.getPackedTextureIndex(t.normalMap,!1),n.bumpMap=this.getPackedTextureIndex(t.bumpMap,!1),n.roughnessMap=this.getPackedTextureIndex(t.roughnessMap,!1),n.metalnessMap=this.getPackedTextureIndex(t.metalnessMap,!1),n.displacementMap=this.getPackedTextureIndex(t.displacementMap,!1),n.anisotropyMap=this.getPackedTextureIndex(t.anisotropyMap,!1),n.transmissionMap=this.getPackedTextureIndex(t.transmissionMap,!1),n.clearcoatMap=this.getPackedTextureIndex(t.clearcoatMap,!1),n.clearcoatRoughnessMap=this.getPackedTextureIndex(t.clearcoatRoughnessMap,!1),n.sheenColorMap=this.getPackedTextureIndex(t.sheenColorMap,!0),n.sheenRoughnessMap=this.getPackedTextureIndex(t.sheenRoughnessMap,!1),n.iridescenceMap=this.getPackedTextureIndex(t.iridescenceMap,!1),n.iridescenceThicknessMap=this.getPackedTextureIndex(t.iridescenceThicknessMap,!1),n.specularIntensityMap=this.getPackedTextureIndex(t.specularIntensityMap,!1),n.specularColorMap=this.getPackedTextureIndex(t.specularColorMap,!0)),this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*K.FLOATS_PER_MATERIAL,a={map:K.ALBEDO_TRANSFORM,normalMap:K.NORMAL_TRANSFORM,roughnessMap:K.ROUGHNESS_TRANSFORM,metalnessMap:K.METALNESS_TRANSFORM,emissiveMap:K.EMISSIVE_TRANSFORM,bumpMap:K.BUMP_TRANSFORM,displacementMap:K.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){zt.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*K.FLOATS_PER_MATERIAL,r=t[n+K.ALPHA_MODE]|0,i=t[n+K.TRANSPARENT]|0,a=t[n+K.TRANSMISSION]||0,o=t[n+K.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,Ut,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=G.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+Vt]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ht,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null}},qt=`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})}};`,Jt=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,qt],{type:`text/javascript;charset=utf-8`});function Yt(e){let t;try{if(t=Jt&&(self.URL||self.webkitURL).createObjectURL(Jt),!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(qt),{type:`module`,name:e?.name})}}function Xt(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 Zt(e,t,n){return .2126*e+.7152*t+.0722*n}function Qt(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function $t(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]=Qt(o[e]),o[e+1]=Qt(o[e+1]),o[e+2]=Qt(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 en=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}=$t(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}=$t(e);this._worker=new Yt;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=Zt(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]=Zt(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]=(Xt(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]=(Xt(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},tn=Math.PI,nn=Math.PI*2,rn=Math.E,an=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],on=[183999185144339.78,277980239196605.28,407904795438610.94],sn=1.6110731556870734,cn=1.5,ln=1e3,un=8400,dn=1250,fn=.9999566769464484,pn=.05968310365946075,mn=.07957747154594767;function hn(e){return ln*Math.max(0,1-rn**+(-(sn-Math.acos(Math.max(-1,Math.min(1,e))))/cn))}function gn(e){let t=.2*e*1e-17;return[.434*t*on[0],.434*t*on[1],.434*t*on[2]]}function _n(e){return pn*(1+e**2)}function vn(e,t){let n=t*t;return mn*((1-n)/(1-2*t*e+n)**1.5)}function yn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function bn(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 xn(e,t,n,r,i,a,o,s){let c=(1-t)*tn,l=(e-.5)*nn,u=Math.sin(c),d=bn([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=bn(n),p=hn(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[an[0]*m,an[1]*m,an[2]*m],g=gn(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/tn*v)**-1.253,b=un/y,x=dn/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=yn(d,f),w=_n(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=vn(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=Sn(fn,fn+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 Sn(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var Cn=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=xn((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},wn=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tn=kt(`env`),En=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new en,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType,void 0,void 0,void 0,r.LinearFilter,r.LinearFilter),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFTexture=null,this._initCDFTexture(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new r.Color(U.gradientZenithColor),gradientHorizonColor:new r.Color(U.gradientHorizonColor),gradientGroundColor:new r.Color(U.gradientGroundColor),solidSkyColor:new r.Color(U.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:U.skySunIntensity,skyRayleighDensity:U.skyRayleighDensity,skyTurbidity:U.skyTurbidity,skyMieAnisotropy:U.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFTexture(){this.envCDFTexture=new r.DataTexture(new Float32Array([0]),1,1,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}_updateCDFTexture(){let e=this.equirectHdrInfo.marginalData,t=this.equirectHdrInfo.conditionalData;if(!e||!t)return;let n=this.equirectHdrInfo.width,i=this.equirectHdrInfo.height,a=n+1,o=new Float32Array(a*i);for(let r=0;r<i;r++){let i=r*a;o.set(t.subarray(r*n,r*n+n),i),o[i+n]=e[r]}this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(o,a,i,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),Tn.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${e?``:` (main thread)`}`]))}catch(e){Tn.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e,{buildCDF:t=!0}={}){let n=this.environmentTexture;e&&n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&n.dispose?.(),this.scene.environment=e,this.setEnvironmentTexture(e),e?t&&await this.buildEnvironmentCDF():(this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0));let r=this.callbacks.getSceneTextureNodes?.();r&&e&&r.envTex&&(r.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}beginHDRI(e=null){this._previousHDRI&&this._previousHDRI!==e&&this._previousHDRI.dispose?.(),this._previousHDRI=null,this.envParams.mode=`hdri`}async applyHDRI(e,{buildCDF:t=!0}={}){this.beginHDRI(e),await this.setEnvironmentMap(e,{buildCDF:t})}async generateGradientTexture(){this.simpleSkyRenderer||=new wn(512,256);let e={zenithColor:this.envParams.gradientZenithColor,horizonColor:this.envParams.gradientHorizonColor,groundColor:this.envParams.gradientGroundColor};try{let t=this.simpleSkyRenderer.renderGradient(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Tn.error(`gradient sky generation failed:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new wn(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Tn.error(`solid color sky generation failed:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new Cn(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),Tn.debug(`sun synced · dir ${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){Tn.error(`procedural sky generation failed:`,e)}}_calculateInitialSunDirection(){let e=U.skySunAzimuth*(Math.PI/180),t=U.skySunElevation*(Math.PI/180);return new r.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envCDFTexture?.dispose?.(),this.envCDFTexture=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}},Dn=C({origin:`vec3`,direction:`vec3`}),On=C({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`}),kn=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`}),An=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),jn=C({shadowed:`vec3`,unoccluded:`vec3`});C({position:`vec3`,radius:`float`,material:On});var Mn=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:On,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`});var Nn=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`}),Pn=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Fn=C({Ta:`vec3`,Ba:`vec3`}),In=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),Ln=C({compensation:`vec3`,E_total:`vec3`}),Rn=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),zn=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Bn=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Vn=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`});var Hn=3.14159,Un=1/Hn,Wn=2*Hn,Gn=1e-6,Kn=.05,qn=.089,Jn=.001,Yn=(0,n.vec3)(.2126,.7152,.0722),Xn=65504,Zn=(e,t=1e7)=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,t),Qn=(e,t=1e7)=>(0,n.vec3)(Zn(e.x,t),Zn(e.y,t),Zn(e.z,t)),Y=K.SLOTS_PER_MATERIAL,$n=K.SLOT,X=$n,er=(0,n.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,n.wgslFn)(`
|
|
116
|
+
`,[te,L]),ge={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},_e=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ge.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 ge.ALWAYS:return!0;case ge.PER_CYCLE:return t===0?!0:n===!0;case ge.PER_TILE:return!0;case ge.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},ve=class{constructor(e,t,n={}){this.renderer=e,this.material=t,this.interactionModeEnabled=n.enabled===void 0?!0:n.enabled,this.interactionDelay=n.delay||100,this.interactionMode=!1,this.interactionTimeout=null,this.originalValues={},this.wasAccumulationEnabled=!0,this.interactionQualitySettings={maxBounceCount:1,enableAccumulation:!1,...n.qualitySettings},this.onEnterCallback=n.onEnter||null,this.onExitCallback=n.onExit||null,this.onResetCallback=n.onReset||null}enterInteractionMode(){this.interactionModeEnabled&&(this.interactionMode?clearTimeout(this.interactionTimeout):(this.interactionMode=!0,this.originalValues={},this.material.uniforms.enableAccumulation&&(this.wasAccumulationEnabled=this.material.uniforms.enableAccumulation.value),Object.keys(this.interactionQualitySettings).forEach(e=>{e===`pixelRatio`?(this.originalValues.dpr=this.renderer.getPixelRatio(),this.renderer.setPixelRatio(this.interactionQualitySettings.pixelRatio)):e===`enableAccumulation`||this.material.uniforms[e]&&(this.originalValues[e]=this.material.uniforms[e].value,this.material.uniforms[e].value=this.interactionQualitySettings[e])}),this.material.uniforms.enableAccumulation&&(this.originalValues.enableAccumulation=this.material.uniforms.enableAccumulation.value,this.material.uniforms.enableAccumulation.value=!1),this.material.uniforms.cameraIsMoving&&(this.originalValues.cameraIsMoving=this.material.uniforms.cameraIsMoving.value,this.material.uniforms.cameraIsMoving.value=!0),this.onEnterCallback&&this.onEnterCallback()),this.interactionTimeout=setTimeout(()=>{this.exitInteractionMode()},this.interactionDelay))}exitInteractionMode(){this.interactionMode&&(Object.keys(this.originalValues).forEach(e=>{e===`dpr`?this.renderer.setPixelRatio(this.originalValues.dpr):this.material.uniforms[e]&&(this.material.uniforms[e].value=this.originalValues[e])}),this.interactionMode=!1,this.originalValues={},this.onExitCallback&&this.onExitCallback(),this.onResetCallback&&this.onResetCallback())}updateInteractionMode(e){e&&this.enterInteractionMode()}setInteractionModeEnabled(e){this.interactionModeEnabled=e,!e&&this.interactionMode&&(clearTimeout(this.interactionTimeout),this.exitInteractionMode())}updateQualitySettings(e){Object.assign(this.interactionQualitySettings,e),this.interactionMode&&Object.keys(e).forEach(t=>{t===`pixelRatio`?this.renderer.setPixelRatio(e.pixelRatio):this.material.uniforms[t]&&(this.material.uniforms[t].value=e[t])})}setInteractionDelay(e){this.interactionDelay=e}getState(){return{interactionMode:this.interactionMode,interactionModeEnabled:this.interactionModeEnabled,interactionDelay:this.interactionDelay,hasTimeout:this.interactionTimeout!==null,qualitySettings:{...this.interactionQualitySettings},originalValues:{...this.originalValues},wasAccumulationEnabled:this.wasAccumulationEnabled}}forceExitInteractionMode(){this.interactionTimeout&&=(clearTimeout(this.interactionTimeout),null),this.exitInteractionMode()}isInInteractionMode(){return this.interactionMode}setCallbacks(e){e.onEnter&&(this.onEnterCallback=e.onEnter),e.onExit&&(this.onExitCallback=e.onExit),e.onReset&&(this.onResetCallback=e.onReset)}static createQualityPreset(e){let t={"ultra-low":{maxBounceCount:1,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}},V={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`},ye=new t.QuadMesh(null).geometry,be=null;function xe(e){be=e}var Se=()=>be?.({type:V.LOADING_RESET}),H=e=>{be?.({type:V.LOADING_UPDATE,...e})},Ce=e=>{be?.({type:V.STATS_UPDATE,...e})};function we(e){return e.frameCount||0}function Te(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(Ee(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;Ee(e),e.dispose()}}function Ee(e){e&&[`alphaMap`,`aoMap`,`bumpMap`,`clearcoatMap`,`clearcoatNormalMap`,`clearcoatRoughnessMap`,`displacementMap`,`emissiveMap`,`envMap`,`gradientMap`,`lightMap`,`map`,`metalnessMap`,`normalMap`,`roughnessMap`,`specularMap`,`sheenColorMap`,`sheenRoughnessMap`,`specularIntensityMap`,`specularColorMap`,`thicknessMap`,`transmissionMap`].forEach(t=>{e[t]&&(e[t].dispose(),e[t]=null)})}function De({material:e,geometry:t,children:n}){if(e&&Te(e),t&&t.dispose(),n.length>0)for(let e of n)De(e)}function Oe(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize),e.dispose(),e._canvasTarget=null;let t=ye._listeners?.dispose;t&&(t.length=0)}function ke(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Te(e);return}for(;e.children.length>0;)for(let t of e.children)ke(t);De(e),e.removeFromParent(),e.clear()}}function Ae(e){e?.traverse(e=>{e.geometry?.userData?.__rayzeeOwned&&e.geometry.dispose()})}function je(e,t){return t}function Me(e,t=!1){return t?1:1/(e+1)}function Ne(){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 Pe=Object.freeze({viewer:Object.freeze({areaLightIntensityScale:.1,environmentRotation:270,toneMapping:4,saturation:1.2}),physical:Object.freeze({areaLightIntensityScale:1,environmentRotation:0,toneMapping:6,saturation:1})});function Fe(e=`viewer`){let t=Pe[e];if(!t)throw Error(`unknown render profile "${e}" — expected one of ${Object.keys(Pe).join(`, `)}`);return t}var U={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:Pe.viewer.toneMapping,exposure:1,saturation:Pe.viewer.saturation,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:Pe.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,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,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},Ie=6e4,Le=3,Re=.1,ze=.01,Be=4096,W=2048;function Ve(e){return W=Math.max(256,Math.min(Be,Math.floor(e)||256)),W}var He={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}},Ue={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},We=[`maxAccumulatedFrameNum`,`maxFastAccumulatedFrameNum`,`maxStabilizedFrameNum`,`historyFixFrameNum`,`prepassBlurRadius`,`maxBlurRadius`,`enableAntiFirefly`],Ge={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}},Ke={fov:{min:10,max:90,default:U.fov},focusDistance:{min:.3,max:100,default:U.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:U.aperture},focalLength:{min:0,max:200,default:U.focalLength}},qe={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}},Je={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}},Ye={MANUAL:`manual`,AUTO:`auto`},Xe={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},G={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},K={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}},Ze=e=>Number.isFinite(e)&&e>0?e:0,Qe={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},q={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},$e=64;function et(e,t){let n=Math.ceil(Math.max(1,e)/$e)*$e;return Math.min(t,Math.max(q.MIN_TEXTURE_WIDTH,n))}function tt(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 nt(e,t){return et(e.width,t)*e.height*e.count*4}function rt(e,t){return e.reduce((e,n)=>e+nt(n,t),0)}function it(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=tt(r[t].units.concat(r[i].units)),o=nt(a,n)-nt(r[t],n)-nt(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 at(e,t,n){let r=[];for(let e=t-1;e>=0;e--)r.push(Math.max(q.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(tt)}function ot(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(tt(t))}else e===a?o.push(tt(n[e].units.concat([r]))):o.push(n[e]);if(rt(o,t)<rt(n,t)){n=o,e=!0;break}}}if(!e)break}return n}function st(e,t,n=q.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=>tt([e]));if(a.length>n){let e=at(i,n,t),r=it(a,n,t);a=rt(e,t)<rt(r,t)?e:r,a=ot(a,t)}return a.map(e=>({width:et(e.width,t),height:e.height})).sort((e,t)=>e.width*e.height-t.width*t.height)}function ct(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 lt(e,t){return e*q.BUCKET_LAYER_STRIDE+t}var ut=[0,0,1,1,0,0,0,1],dt={maxSamples:150,bounces:20,transmissiveBounces:8,maxSubsurfaceSteps:64,renderMode:1,enableAlphaShadows:!0,enableOIDN:!0,oidnQuality:`high`,interactionModeEnabled:!1,useAdaptiveSampling:!0,noiseThreshold:.02,adaptiveStopFraction:.94,usePixelFreeze:!0},ft={maxSamples:U.maxSamples,bounces:U.bounces,renderMode:U.renderMode,enableAlphaShadows:U.enableAlphaShadows,transmissiveBounces:U.transmissiveBounces,maxSubsurfaceSteps:U.maxSubsurfaceSteps,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0},pt={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},mt={silent:0,error:1,warn:2,info:3,debug:4},ht=`info`,gt=`rayzeeLogLevel`,_t=`rayzeeLogNamespaces`,vt=`color:#7c8494`,yt=`color:inherit`,bt=null,xt=null;function St(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function Ct(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function wt(){if(bt!==null)return bt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in mt?(bt=mt[e],bt):(bt=mt[St(gt)]??mt[ht],bt)}function Tt(){if(xt!==null)return xt;let e=globalThis.__RAYZEE_LOG_NS__??St(_t);return xt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],xt}function Et(e,t){if(t<mt.debug)return!0;let n=Tt();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function Dt(e,t,n){if(e>wt()||!Et(t,e))return;let r=e===mt.error?console.error:e===mt.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,vt,yt,...n.slice(1)):r(`%c${i}`,vt,...n)}var J={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`)=>`${J.n(e)} ${Number(e)===1?t:n}`,list:e=>e.filter(Boolean).join(` · `)},Ot={levels:mt,setLevel(e){return e in mt?(globalThis.__RAYZEE_LOG_LEVEL__=e,bt=mt[e],Ct(gt,e===ht?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(mt).join(`, `)}`),this.getLevel())},getLevel(){let e=wt();return Object.keys(mt).find(t=>mt[t]===e)},isEnabled(e){return(mt[e]??mt.debug)<=wt()},only(...e){let t=e.flat().filter(Boolean);return xt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),Ct(_t,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return bt=null,xt=null,this.getLevel()}};function kt(e){return{namespace:e,error:(...t)=>Dt(mt.error,e,t),warn:(...t)=>Dt(mt.warn,e,t),info:(...t)=>Dt(mt.info,e,t),debug:(...t)=>Dt(mt.debug,e,t),isEnabled:e=>Ot.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){Dt(mt.info,e,[t]),r.forEach(t=>Dt(mt.debug,e,[t]));return}mt.info>wt()||((wt()>=mt.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,vt,yt),r.forEach(e=>console.log(e)),console.groupEnd())}}}var At=new Set;function jt(e,t,...n){At.has(t)||(At.add(t),e.warn(...n))}function Mt(){return Ot.getLevel()}var Nt=kt(`gpu`);function Pt(e=r.FloatType,n=r.LinearFilter){let i=new t.StorageTexture(W,W);return i.type=e,i.format=r.RGBAFormat,i.minFilter=n,i.magFilter=n,i}var Ft=()=>Pt(),It=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=Ft(),this.writeNormalDepth=Ft(),this.writeAlbedo=Ft(),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`,Nt.debug(`storage texture pool ${J.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}},Lt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},Rt=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`,U.bounces,`int`),i(`maxSamples`,U.maxSamples,`int`),i(`transmissiveBounces`,U.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,U.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,U.maxTransparentBounces,`int`),i(`visMode`,U.debugMode,`int`),i(`debugVisScale`,U.debugVisScale,`float`),a(`useAdaptiveSampling`,U.useAdaptiveSampling),i(`noiseThreshold`,U.noiseThreshold,`float`),i(`adaptiveMinSamples`,U.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,U.adaptiveStopFraction,`float`),a(`usePixelFreeze`,U.usePixelFreeze),i(`pixelFreezeThreshold`,U.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,U.pixelFreezeStability,`int`),a(`convergenceOverlay`,U.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,U.environmentIntensity,`float`),i(`backgroundIntensity`,U.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,U.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,U.backgroundBlurSamples,`int`),a(`showBackground`,U.showBackground),a(`transparentBackground`,U.transparentBackground),a(`enableEnvironment`,U.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`,U.groundProjectionEnabled),i(`groundProjectionRadius`,U.groundProjectionRadius,`float`),i(`groundProjectionHeight`,U.groundProjectionHeight,`float`),i(`groundProjectionLevel`,U.groundProjectionLevel,`float`),a(`enableGroundCatcher`,U.enableGroundCatcher),i(`groundCatcherHeight`,U.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,U.globalIlluminationIntensity,`float`),i(`exposure`,U.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`,+(U.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(U.panoramaLonRange),`vec2`),i(`panoLatRange`,o(U.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,U.panoramaLevelHorizon),a(`enableDOF`,U.enableDOF),i(`focusDistance`,U.focusDistance,`float`),i(`focalLength`,U.focalLength,`float`),i(`aperture`,U.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,U.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,A),A.value=U.samplingTechnique,i(`fireflyThreshold`,U.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,U.enableEmissiveTriangleSampling),i(`emissiveBoost`,U.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,U.renderMode,`int`),a(`enableAlphaShadows`,U.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=Lt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._arrayWarned.clear(),this._lightBuffers={})}},zt=kt(`material`),Bt=K.SLOTS_PER_MATERIAL,Vt=G.UV_C_MAT_OFFSET+2,Ht=G.NORMAL_C_OFFSET+3,Ut=G.NORMAL_A_OFFSET+3,Wt=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Gt={ior:K.IOR,transmission:K.TRANSMISSION,thickness:K.THICKNESS,emissiveIntensity:K.EMISSIVE_INTENSITY,attenuationDistance:K.ATTENUATION_DISTANCE,opacity:K.OPACITY,alphaTest:K.ALPHA_TEST,metalness:K.METALNESS,roughness:K.ROUGHNESS,clearcoat:K.CLEARCOAT,clearcoatRoughness:K.CLEARCOAT_ROUGHNESS,dispersion:K.DISPERSION,sheen:K.SHEEN,sheenRoughness:K.SHEEN_ROUGHNESS,specularIntensity:K.SPECULAR_INTENSITY,iridescence:K.IRIDESCENCE,iridescenceIOR:K.IRIDESCENCE_IOR,subsurface:K.SUBSURFACE,subsurfaceRadiusScale:K.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:K.SUBSURFACE_ANISOTROPY,anisotropy:K.ANISOTROPY,anisotropyRotation:K.ANISOTROPY_ROTATION},Kt=class{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={}}setMaterialData(e){if(!e)return;let r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/Bt),zt.debug(`${J.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=Gt[t];if(r===void 0)return;let i=e*K.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*K.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+K.COLOR]=n[0],r[i+K.COLOR+1]=n[1],r[i+K.COLOR+2]=n[2]):(r[i+K.COLOR]=n.r,r[i+K.COLOR+1]=n.g,r[i+K.COLOR+2]=n.b);break;case`metalness`:r[i+K.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+K.EMISSIVE]=n[0],r[i+K.EMISSIVE+1]=n[1],r[i+K.EMISSIVE+2]=n[2]):(r[i+K.EMISSIVE]=n.r,r[i+K.EMISSIVE+1]=n.g,r[i+K.EMISSIVE+2]=n.b);break;case`roughness`:r[i+K.ROUGHNESS]=n;break;case`ior`:r[i+K.IOR]=n;break;case`transmission`:r[i+K.TRANSMISSION]=n;break;case`thickness`:r[i+K.THICKNESS]=n;break;case`emissiveIntensity`:r[i+K.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.ATTENUATION_COLOR]=n[0],r[i+K.ATTENUATION_COLOR+1]=n[1],r[i+K.ATTENUATION_COLOR+2]=n[2]):(r[i+K.ATTENUATION_COLOR]=n.r,r[i+K.ATTENUATION_COLOR+1]=n.g,r[i+K.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+K.ATTENUATION_DISTANCE]=Ze(n);break;case`dispersion`:r[i+K.DISPERSION]=n;break;case`sheen`:r[i+K.SHEEN]=n;break;case`sheenRoughness`:r[i+K.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SHEEN_COLOR]=n[0],r[i+K.SHEEN_COLOR+1]=n[1],r[i+K.SHEEN_COLOR+2]=n[2]):(r[i+K.SHEEN_COLOR]=n.r,r[i+K.SHEEN_COLOR+1]=n.g,r[i+K.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+K.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SPECULAR_COLOR]=n[0],r[i+K.SPECULAR_COLOR+1]=n[1],r[i+K.SPECULAR_COLOR+2]=n[2]):(r[i+K.SPECULAR_COLOR]=n.r,r[i+K.SPECULAR_COLOR+1]=n.g,r[i+K.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+K.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+K.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+K.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+K.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+K.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+K.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+K.OPACITY]=n;break;case`side`:r[i+K.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+K.TRANSPARENT]=n;break;case`alphaTest`:r[i+K.ALPHA_TEST]=n;break;case`alphaMode`:r[i+K.ALPHA_MODE]=n;break;case`depthWrite`:r[i+K.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+K.NORMAL_SCALE]=n,r[i+K.NORMAL_SCALE+1]=n):(r[i+K.NORMAL_SCALE]=n.x,r[i+K.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+K.BUMP_SCALE]=n;break;case`displacementScale`:r[i+K.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+K.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+K.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+K.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+K.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+K.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&(r[i+K.SUBSURFACE_COLOR]=n[0],r[i+K.SUBSURFACE_COLOR+1]=n[1],r[i+K.SUBSURFACE_COLOR+2]=n[2]):(r[i+K.SUBSURFACE_COLOR]=n.r,r[i+K.SUBSURFACE_COLOR+1]=n.g,r[i+K.SUBSURFACE_COLOR+2]=n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+K.SUBSURFACE_RADIUS]=n[0],r[i+K.SUBSURFACE_RADIUS+1]=n[1],r[i+K.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+K.SUBSURFACE_RADIUS]=n.x,r[i+K.SUBSURFACE_RADIUS+1]=n.y,r[i+K.SUBSURFACE_RADIUS+2]=n.z);break;default:zt.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Wt.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*K.FLOATS_PER_MATERIAL;t.color&&(n[r+K.COLOR]=t.color.r??t.color[0]??1,n[r+K.COLOR+1]=t.color.g??t.color[1]??1,n[r+K.COLOR+2]=t.color.b??t.color[2]??1),n[r+K.METALNESS]=t.metalness??0,t.emissive&&(n[r+K.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+K.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+K.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+K.ROUGHNESS]=t.roughness??1,n[r+K.IOR]=t.ior??1.5,n[r+K.TRANSMISSION]=t.transmission??0,n[r+K.THICKNESS]=t.thickness??.1,n[r+K.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+K.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+K.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+K.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+K.ATTENUATION_DISTANCE]=Ze(t.attenuationDistance),n[r+K.DISPERSION]=t.dispersion??0,n[r+K.VISIBLE]=1,n[r+K.SHEEN]=t.sheen??0,n[r+K.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+K.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+K.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+K.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+K.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+K.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+K.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+K.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+K.IRIDESCENCE]=t.iridescence??0,n[r+K.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+K.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+K.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+K.ALBEDO_MAP_INDEX]=t.map??-1,n[r+K.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+K.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+K.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+K.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+K.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+K.CLEARCOAT]=t.clearcoat??0,n[r+K.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+K.OPACITY]=t.opacity??1,n[r+K.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+K.TRANSPARENT]=t.transparent??0,n[r+K.ALPHA_TEST]=t.alphaTest??0,n[r+K.ALPHA_MODE]=t.alphaMode??0,n[r+K.DEPTH_WRITE]=t.depthWrite??1,n[r+K.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+K.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+K.BUMP_SCALE]=t.bumpScale??1,n[r+K.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+K.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1,n[r+K.SUBSURFACE]=t.subsurface??0,t.subsurfaceColor&&(n[r+K.SUBSURFACE_COLOR]=t.subsurfaceColor.r??t.subsurfaceColor[0]??1,n[r+K.SUBSURFACE_COLOR+1]=t.subsurfaceColor.g??t.subsurfaceColor[1]??1,n[r+K.SUBSURFACE_COLOR+2]=t.subsurfaceColor.b??t.subsurfaceColor[2]??1),t.subsurfaceRadius&&(n[r+K.SUBSURFACE_RADIUS]=t.subsurfaceRadius[0]??1,n[r+K.SUBSURFACE_RADIUS+1]=t.subsurfaceRadius[1]??.2,n[r+K.SUBSURFACE_RADIUS+2]=t.subsurfaceRadius[2]??.1),n[r+K.SUBSURFACE_RADIUS_SCALE]=t.subsurfaceRadiusScale??1,n[r+K.SUBSURFACE_ANISOTROPY]=t.subsurfaceAnisotropy??0,n[r+K.ANISOTROPY]=t.anisotropy??0,n[r+K.ANISOTROPY_ROTATION]=t.anisotropyRotation??0,n[r+K.ANISOTROPY_MAP_INDEX]=t.anisotropyMap??-1,n[r+K.TRANSMISSION_MAP_INDEX]=t.transmissionMap??-1,n[r+K.CLEARCOAT_MAP_INDEX]=t.clearcoatMap??-1,n[r+K.CLEARCOAT_ROUGHNESS_MAP_INDEX]=t.clearcoatRoughnessMap??-1,n[r+K.SHEEN_COLOR_MAP_INDEX]=t.sheenColorMap??-1,n[r+K.SHEEN_ROUGHNESS_MAP_INDEX]=t.sheenRoughnessMap??-1,n[r+K.IRIDESCENCE_MAP_INDEX]=t.iridescenceMap??-1,n[r+K.IRIDESCENCE_THICKNESS_MAP_INDEX]=t.iridescenceThicknessMap??-1,n[r+K.SPECULAR_INTENSITY_MAP_INDEX]=t.specularIntensityMap??-1,n[r+K.SPECULAR_COLOR_MAP_INDEX]=t.specularColorMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:K.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:K.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:K.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:K.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:K.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:K.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:K.DISPLACEMENT_TRANSFORM}];for(let{key:e,offset:o}of a){let a=t[e]??i;for(let e=0;e<8;e++)r+o+e<n.length&&(n[r+o+e]=a[e])}this.materialStorageAttr.needsUpdate=!0,this._notifyReset()}updateMaterial(e,t){let n=this.sdfs.geometryExtractor.createMaterialObject(t);(this._srgbTexPacked||this._linearTexPacked)&&(n.map=this.getPackedTextureIndex(t.map,!0),n.emissiveMap=this.getPackedTextureIndex(t.emissiveMap,!0),n.normalMap=this.getPackedTextureIndex(t.normalMap,!1),n.bumpMap=this.getPackedTextureIndex(t.bumpMap,!1),n.roughnessMap=this.getPackedTextureIndex(t.roughnessMap,!1),n.metalnessMap=this.getPackedTextureIndex(t.metalnessMap,!1),n.displacementMap=this.getPackedTextureIndex(t.displacementMap,!1),n.anisotropyMap=this.getPackedTextureIndex(t.anisotropyMap,!1),n.transmissionMap=this.getPackedTextureIndex(t.transmissionMap,!1),n.clearcoatMap=this.getPackedTextureIndex(t.clearcoatMap,!1),n.clearcoatRoughnessMap=this.getPackedTextureIndex(t.clearcoatRoughnessMap,!1),n.sheenColorMap=this.getPackedTextureIndex(t.sheenColorMap,!0),n.sheenRoughnessMap=this.getPackedTextureIndex(t.sheenRoughnessMap,!1),n.iridescenceMap=this.getPackedTextureIndex(t.iridescenceMap,!1),n.iridescenceThicknessMap=this.getPackedTextureIndex(t.iridescenceThicknessMap,!1),n.specularIntensityMap=this.getPackedTextureIndex(t.specularIntensityMap,!1),n.specularColorMap=this.getPackedTextureIndex(t.specularColorMap,!0)),this.updateMaterialDataFromObject(e,n)}updateTextureTransform(e,t,n){if(!this.materialStorageAttr){zt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*K.FLOATS_PER_MATERIAL,a={map:K.ALBEDO_TRANSFORM,normalMap:K.NORMAL_TRANSFORM,roughnessMap:K.ROUGHNESS_TRANSFORM,metalnessMap:K.METALNESS_TRANSFORM,emissiveMap:K.EMISSIVE_TRANSFORM,bumpMap:K.BUMP_TRANSFORM,displacementMap:K.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){zt.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*K.FLOATS_PER_MATERIAL,r=t[n+K.ALPHA_MODE]|0,i=t[n+K.TRANSPARENT]|0,a=t[n+K.TRANSMISSION]||0,o=t[n+K.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,Ut,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=G.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+Vt]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ht,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null}},qt=`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})}};`,Jt=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,qt],{type:`text/javascript;charset=utf-8`});function Yt(e){let t;try{if(t=Jt&&(self.URL||self.webkitURL).createObjectURL(Jt),!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(qt),{type:`module`,name:e?.name})}}function Xt(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 Zt(e,t,n){return .2126*e+.7152*t+.0722*n}function Qt(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function $t(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]=Qt(o[e]),o[e+1]=Qt(o[e+1]),o[e+2]=Qt(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 en=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}=$t(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}=$t(e);this._worker=new Yt;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=Zt(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]=Zt(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]=(Xt(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]=(Xt(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},tn=Math.PI,nn=Math.PI*2,rn=Math.E,an=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],on=[183999185144339.78,277980239196605.28,407904795438610.94],sn=1.6110731556870734,cn=1.5,ln=1e3,un=8400,dn=1250,fn=.9999566769464484,pn=.05968310365946075,mn=.07957747154594767;function hn(e){return ln*Math.max(0,1-rn**+(-(sn-Math.acos(Math.max(-1,Math.min(1,e))))/cn))}function gn(e){let t=.2*e*1e-17;return[.434*t*on[0],.434*t*on[1],.434*t*on[2]]}function _n(e){return pn*(1+e**2)}function vn(e,t){let n=t*t;return mn*((1-n)/(1-2*t*e+n)**1.5)}function yn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function bn(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 xn(e,t,n,r,i,a,o,s){let c=(1-t)*tn,l=(e-.5)*nn,u=Math.sin(c),d=bn([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=bn(n),p=hn(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[an[0]*m,an[1]*m,an[2]*m],g=gn(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/tn*v)**-1.253,b=un/y,x=dn/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=yn(d,f),w=_n(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=vn(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=Sn(fn,fn+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 Sn(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var Cn=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=xn((l+.5)/c,t,n,r,i,a,o,s),f=(e*c+l)*4;u[f]=d[0],u[f+1]=d[1],u[f+2]=d[2],u[f+3]=d[3]}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},wn=class{constructor(e=512,t=256){this.width=e,this.height=t,this.lastRenderTime=0,this._pixels=new Float32Array(e*t*4),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1}renderGradient(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.zenithColor.r,o=e.zenithColor.g,s=e.zenithColor.b,c=e.horizonColor.r,l=e.horizonColor.g,u=e.horizonColor.b,d=e.groundColor.r,f=e.groundColor.g,p=e.groundColor.b;for(let e=0;e<r;e++){let t=(e+.5)/r,m,h,g;if(t>.5){let e=(t-.5)*2;m=c+(a-c)*e,h=l+(o-l)*e,g=u+(s-u)*e}else{let e=t*2;m=d+(c-d)*e,h=f+(l-f)*e,g=p+(u-p)*e}for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=m,i[r+1]=h,i[r+2]=g,i[r+3]=1}}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}renderSolid(e){let t=performance.now(),{width:n,height:r}=this,i=this._pixels,a=e.color.r,o=e.color.g,s=e.color.b;for(let e=0;e<r;e++)for(let t=0;t<n;t++){let r=(e*n+t)*4;i[r]=a,i[r+1]=o,i[r+2]=s,i[r+3]=1}return this._texture.needsUpdate=!0,this.lastRenderTime=performance.now()-t,this._texture}setResolution(e,t){this.width===e&&this.height===t||(this.width=e,this.height=t,this._pixels=new Float32Array(e*t*4),this._texture.dispose(),this._texture=new r.DataTexture(this._pixels,e,t,r.RGBAFormat,r.FloatType),this._texture.mapping=r.EquirectangularReflectionMapping,this._texture.colorSpace=r.LinearSRGBColorSpace,this._texture.minFilter=r.LinearFilter,this._texture.magFilter=r.LinearFilter,this._texture.wrapS=r.RepeatWrapping,this._texture.wrapT=r.ClampToEdgeWrapping,this._texture.generateMipmaps=!1)}getLastRenderTime(){return this.lastRenderTime}dispose(){this._texture.dispose()}},Tn=kt(`env`),En=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new en,this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this._envPlaceholder=new r.DataTexture(new Float32Array([0,0,0,1]),1,1,r.RGBAFormat,r.FloatType,void 0,void 0,void 0,r.LinearFilter,r.LinearFilter),this._envPlaceholder.needsUpdate=!0,this.environmentTexture=this._envPlaceholder,this.envTexSize=new r.Vector2,this.envCDFTexture=null,this._initCDFTexture(),this.environmentRotationMatrix=new r.Matrix4,this.cdfBuildTime=0,this.envParams={mode:`hdri`,gradientZenithColor:new r.Color(U.gradientZenithColor),gradientHorizonColor:new r.Color(U.gradientHorizonColor),gradientGroundColor:new r.Color(U.gradientGroundColor),solidSkyColor:new r.Color(U.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:U.skySunIntensity,skyRayleighDensity:U.skyRayleighDensity,skyTurbidity:U.skyTurbidity,skyMieAnisotropy:U.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_initCDFTexture(){this.envCDFTexture=new r.DataTexture(new Float32Array([0]),1,1,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}_updateCDFTexture(){let e=this.equirectHdrInfo.marginalData,t=this.equirectHdrInfo.conditionalData;if(!e||!t)return;let n=this.equirectHdrInfo.width,i=this.equirectHdrInfo.height,a=n+1,o=new Float32Array(a*i);for(let r=0;r<i;r++){let i=r*a;o.set(t.subarray(r*n,r*n+n),i),o[i+n]=e[r]}this.envCDFTexture?.dispose?.(),this.envCDFTexture=new r.DataTexture(o,a,i,r.RedFormat,r.FloatType),this.envCDFTexture.needsUpdate=!0}setEnvironmentTexture(e){e&&(this.environmentTexture=e,this.envTexSize.set(e.image.width,e.image.height))}getEnvironmentTexture(){return this.environmentTexture}setEnvironmentRotation(e){let t=Math.PI/180*e;this.environmentRotationMatrix.makeRotationY(t),this.uniforms.get(`environmentMatrix`).value.copy(this.environmentRotationMatrix)}async buildEnvironmentCDF({useWorker:e=!0}={}){if(!this.scene.environment){this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0);return}try{let t=performance.now(),n=this.scene.environment;if(!n.image){this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0);return}e?await this.equirectHdrInfo.updateFromAsync(n):this.equirectHdrInfo.updateFrom(n),this.cdfBuildTime=performance.now()-t,this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,this.equirectHdrInfo.totalSum),this.uniforms.set(`envCompensationDelta`,this.equirectHdrInfo.compensationDelta);let{width:r,height:i}=this.equirectHdrInfo;r&&i&&this.uniforms.get(`envResolution`).value.set(r,i),Tn.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${e?``:` (main thread)`}`]))}catch(e){Tn.error(`CDF build failed:`,e),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0)}}applyCDFResults(){let e=this.scene.environment,t=this.callbacks.getSceneTextureNodes?.();t&&e&&t.envTex&&(t.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0)}async setEnvironmentMap(e,{buildCDF:t=!0}={}){let n=this.environmentTexture;e&&n&&n!==e&&n!==this._envPlaceholder&&n!==this._previousHDRI&&n.dispose?.(),this.scene.environment=e,this.setEnvironmentTexture(e),e?t&&await this.buildEnvironmentCDF():(this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0));let r=this.callbacks.getSceneTextureNodes?.();r&&e&&r.envTex&&(r.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}beginHDRI(e=null){this._previousHDRI&&this._previousHDRI!==e&&this._previousHDRI.dispose?.(),this._previousHDRI=null,this.envParams.mode=`hdri`}async applyHDRI(e,{buildCDF:t=!0}={}){this.beginHDRI(e),await this.setEnvironmentMap(e,{buildCDF:t})}async generateGradientTexture(){this.simpleSkyRenderer||=new wn(512,256);let e={zenithColor:this.envParams.gradientZenithColor,horizonColor:this.envParams.gradientHorizonColor,groundColor:this.envParams.gradientGroundColor};try{let t=this.simpleSkyRenderer.renderGradient(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Tn.error(`gradient sky generation failed:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new wn(512,256);let e={color:this.envParams.solidSkyColor};try{let t=this.simpleSkyRenderer.renderSolid(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.set(`hasSun`,0)}catch(e){Tn.error(`solid color sky generation failed:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new Cn(512,256);let e={sunDirection:this.envParams.skySunDirection.clone(),sunIntensity:this.envParams.skySunIntensity*.05,rayleighDensity:this.envParams.skyRayleighDensity*2,mieDensity:this.envParams.skyTurbidity*.005,mieAnisotropy:this.envParams.skyMieAnisotropy,turbidity:this.envParams.skyTurbidity*2};try{let t=this.proceduralSkyRenderer.render(e);t._isGeneratedProcedural=!0,await this.setEnvironmentMap(t),this.uniforms.get(`sunDirection`).value.copy(this.envParams.skySunDirection),this.uniforms.set(`sunAngularSize`,.0087),this.uniforms.set(`hasSun`,1),Tn.debug(`sun synced · dir ${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){Tn.error(`procedural sky generation failed:`,e)}}_calculateInitialSunDirection(){let e=U.skySunAzimuth*(Math.PI/180),t=U.skySunElevation*(Math.PI/180);return new r.Vector3(Math.cos(t)*Math.sin(e),Math.sin(t),Math.cos(t)*Math.cos(e)).normalize()}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}dispose(){this.proceduralSkyRenderer=null,this.simpleSkyRenderer=null,this.envCDFTexture?.dispose?.(),this.envCDFTexture=null,this.environmentTexture&&this.environmentTexture!==this._envPlaceholder&&this.environmentTexture.dispose?.(),this._envPlaceholder?.dispose(),this._envPlaceholder=null,this.environmentTexture=null,this._previousHDRI=null}},Dn=C({origin:`vec3`,direction:`vec3`}),On=C({color:`vec4`,emissive:`vec3`,emissiveIntensity:`float`,roughness:`float`,metalness:`float`,ior:`float`,transmission:`float`,thickness:`float`,clearcoat:`float`,clearcoatRoughness:`float`,opacity:`float`,transparent:`bool`,attenuationColor:`vec3`,attenuationDistance:`float`,dispersion:`float`,sheen:`float`,sheenRoughness:`float`,sheenColor:`vec3`,specularIntensity:`float`,specularColor:`vec3`,alphaTest:`float`,alphaMode:`int`,side:`int`,depthWrite:`int`,albedoMapIndex:`int`,emissiveMapIndex:`int`,normalMapIndex:`int`,bumpMapIndex:`int`,bumpScale:`float`,displacementScale:`float`,metalnessMapIndex:`int`,roughnessMapIndex:`int`,displacementMapIndex:`int`,normalScale:`vec2`,albedoTransform:`mat3`,emissiveTransform:`mat3`,normalTransform:`mat3`,bumpTransform:`mat3`,metalnessTransform:`mat3`,roughnessTransform:`mat3`,displacementTransform:`mat3`,iridescence:`float`,iridescenceIOR:`float`,iridescenceThicknessRange:`vec2`,subsurface:`float`,subsurfaceColor:`vec3`,subsurfaceRadius:`vec3`,subsurfaceRadiusScale:`float`,subsurfaceAnisotropy:`float`,anisotropy:`float`,anisotropyRotation:`float`,anisotropyMapIndex:`int`,transmissionMapIndex:`int`,clearcoatMapIndex:`int`,clearcoatRoughnessMapIndex:`int`,sheenColorMapIndex:`int`,sheenRoughnessMapIndex:`int`,iridescenceMapIndex:`int`,iridescenceThicknessMapIndex:`int`,specularIntensityMapIndex:`int`,specularColorMapIndex:`int`}),kn=C({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`}),An=C({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),jn=C({shadowed:`vec3`,unoccluded:`vec3`});C({position:`vec3`,radius:`float`,material:On});var Mn=C({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});C({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:On,materialIndex:`int`,meshIndex:`int`}),C({color:`vec4`,samples:`int`});var Nn=C({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`}),Pn=C({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),Fn=C({Ta:`vec3`,Ba:`vec3`}),In=C({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),Ln=C({compensation:`vec3`,E_total:`vec3`}),Rn=C({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),zn=C({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),Bn=C({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Vn=C({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});C({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`});var Hn=3.14159,Un=1/Hn,Wn=2*Hn,Gn=1e-6,Kn=.05,qn=.089,Jn=.001,Yn=(0,n.vec3)(.2126,.7152,.0722),Xn=65504,Zn=(e,t=1e7)=>(0,n.select)(e.equal(e),e,(0,n.float)(0)).clamp(0,t),Qn=(e,t=1e7)=>(0,n.vec3)(Zn(e.x,t),Zn(e.y,t),Zn(e.z,t)),Y=K.SLOTS_PER_MATERIAL,$n=K.SLOT,X=$n,er=(0,n.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,n.wgslFn)(`
|
|
117
117
|
fn sRGBToLinear( srgbColor: vec3f ) -> vec3f {
|
|
118
118
|
|
|
119
119
|
return pow( srgbColor, vec3f( 2.2 ) );
|
|
@@ -468,7 +468,7 @@
|
|
|
468
468
|
let p = o + xu * x + yv * y + z0 * z;
|
|
469
469
|
return vec4f( p, 1.0f / S );
|
|
470
470
|
}
|
|
471
|
-
`),Ta=kt(`shader`),Ea=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),Ta.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;Ji(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();ha(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();ya(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}},Da=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 Oa;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 Oa;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}}},Oa=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}},ka=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}},Aa=kt(`bvh`),ja=null;function Ma(e){ja=e}var Na={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},Pa=Na.FLOATS_PER_TRIANGLE,Fa=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}},Ia=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=this.triangles,n=Na.POSITION_A_OFFSET,r=Na.POSITION_B_OFFSET,i=Na.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Pa,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Pa*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&ja&&typeof Worker<`u`?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;Aa.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Pa*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(ja())}catch(i){Aa.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Pa*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new Da(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){Aa.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 ka(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){Aa.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 Float32Array(a*Pa);for(let e=0;e<a;e++){let t=this.indices[e]*Pa,n=e*Pa;f.set(d.subarray(t,t+Pa),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return Aa.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.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 Fa;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 Fa;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Q={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},La=Q.FLOATS_PER_TRIANGLE,Ra=16,za=-1,Ba=-2,Va=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length;for(let i=0;i<r;i++){let r=n[i],a=i*La,o=r*9,s=t[o],c=t[o+1],l=t[o+2],u=t[o+3],d=t[o+4],f=t[o+5],p=t[o+6],m=t[o+7],h=t[o+8];e[a+Q.POSITION_A_OFFSET]=s,e[a+Q.POSITION_A_OFFSET+1]=c,e[a+Q.POSITION_A_OFFSET+2]=l,e[a+Q.POSITION_B_OFFSET]=u,e[a+Q.POSITION_B_OFFSET+1]=d,e[a+Q.POSITION_B_OFFSET+2]=f,e[a+Q.POSITION_C_OFFSET]=p,e[a+Q.POSITION_C_OFFSET+1]=m,e[a+Q.POSITION_C_OFFSET+2]=h;let g=u-s,_=d-c,v=f-l,y=p-s,b=m-c,x=h-l,S=_*x-v*b,C=v*y-g*x,w=g*b-_*y;e[a+Q.NORMAL_A_OFFSET]=S,e[a+Q.NORMAL_A_OFFSET+1]=C,e[a+Q.NORMAL_A_OFFSET+2]=w,e[a+Q.NORMAL_B_OFFSET]=S,e[a+Q.NORMAL_B_OFFSET+1]=C,e[a+Q.NORMAL_B_OFFSET+2]=w,e[a+Q.NORMAL_C_OFFSET]=S,e[a+Q.NORMAL_C_OFFSET+1]=C,e[a+Q.NORMAL_C_OFFSET+2]=w}}refitRange(e,t,n,r){r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let i=this._bounds,a=n+r;for(let r=a-1;r>=n;r--){let a=r*Ra,o=(r-n)*6;if(e[a+3]===za){let n=e[a],r=e[a+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<r;e++){let r=(n+e)*La,i=t[r+Q.POSITION_A_OFFSET],a=t[r+Q.POSITION_A_OFFSET+1],o=t[r+Q.POSITION_A_OFFSET+2],p=t[r+Q.POSITION_B_OFFSET],m=t[r+Q.POSITION_B_OFFSET+1],h=t[r+Q.POSITION_B_OFFSET+2],g=t[r+Q.POSITION_C_OFFSET],_=t[r+Q.POSITION_C_OFFSET+1],v=t[r+Q.POSITION_C_OFFSET+2];s=Math.min(s,i,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,i,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}i[o]=s,i[o+1]=c,i[o+2]=l,i[o+3]=u,i[o+4]=d,i[o+5]=f}else{let t=e[a+3],r=e[a+7],s=(t-n)*6,c=(r-n)*6,l=i[s],u=i[s+1],d=i[s+2],f=i[s+3],p=i[s+4],m=i[s+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];e[a]=l,e[a+1]=u,e[a+2]=d,e[a+4]=f,e[a+5]=p,e[a+6]=m,e[a+8]=h,e[a+9]=g,e[a+10]=_,e[a+12]=v,e[a+13]=y,e[a+14]=b,i[o]=Math.min(l,h),i[o+1]=Math.min(u,g),i[o+2]=Math.min(d,_),i[o+3]=Math.max(f,v),i[o+4]=Math.max(p,y),i[o+5]=Math.max(m,b)}}}refit(e,t,n){n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let r=this._bounds;for(let i=n-1;i>=0;i--){let n=i*Ra,a=i*6,o=e[n+3];if(o===za){let i=e[n],o=e[n+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<o;e++){let n=(i+e)*La,r=t[n+Q.POSITION_A_OFFSET],a=t[n+Q.POSITION_A_OFFSET+1],o=t[n+Q.POSITION_A_OFFSET+2],p=t[n+Q.POSITION_B_OFFSET],m=t[n+Q.POSITION_B_OFFSET+1],h=t[n+Q.POSITION_B_OFFSET+2],g=t[n+Q.POSITION_C_OFFSET],_=t[n+Q.POSITION_C_OFFSET+1],v=t[n+Q.POSITION_C_OFFSET+2];s=Math.min(s,r,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,r,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}r[a]=s,r[a+1]=c,r[a+2]=l,r[a+3]=u,r[a+4]=d,r[a+5]=f}else if(o===Ba){let t=e[n]*6;r[a]=r[t],r[a+1]=r[t+1],r[a+2]=r[t+2],r[a+3]=r[t+3],r[a+4]=r[t+4],r[a+5]=r[t+5]}else{let t=e[n+3],i=e[n+7],o=t*6,s=i*6,c=r[o],l=r[o+1],u=r[o+2],d=r[o+3],f=r[o+4],p=r[o+5],m=r[s],h=r[s+1],g=r[s+2],_=r[s+3],v=r[s+4],y=r[s+5];e[n]=c,e[n+1]=l,e[n+2]=u,e[n+4]=d,e[n+5]=f,e[n+6]=p,e[n+8]=m,e[n+9]=h,e[n+10]=g,e[n+12]=_,e[n+13]=v,e[n+14]=y,r[a]=Math.min(c,m),r[a+1]=Math.min(l,h),r[a+2]=Math.min(u,g),r[a+3]=Math.max(d,_),r[a+4]=Math.max(f,v),r[a+5]=Math.max(p,y)}}}},Ha="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={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},C=S.FLOATS_PER_TRIANGLE;var w=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}},T=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=this.triangles,n=S.POSITION_A_OFFSET,r=S.POSITION_B_OFFSET,i=S.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*C,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/(C*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/(C*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 Float32Array(s*C);for(let e=0;e<s;e++){let t=this.indices[e]*C,n=e*C;m.set(p.subarray(t,t+C),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 w;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,T=m.rMinZ,E=m.rMaxX,D=m.rMaxY,O=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,T,E,D,O),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new w;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,T=p.rMaxX,E=p.rMaxY,D=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,T,E,D),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const E=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?D(t):n===`assemble`?O(t):k(t)};function D(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 T;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Float32Array(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;E.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){E.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function O(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 T().assembleParallelBVH(t,n,r,i),u=new Uint32Array(o),d=new Float32Array(a),f=new Float32Array(s);for(let e=0;e<c;e++){let t=u[e]*32,n=e*32;f.set(d.subarray(t,t+32),n)}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[u[e]]=e;let m=performance.now()-e;E.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){E.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function k(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 T;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 Float32Array(t):new Float32Array(t,n,r/4),u=c?new Float32Array(c):null,d=p.buildSync(l,i,e,u),f=performance.now(),m=p.flattenBVH(d),h=performance.now()-f;E.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/32,treeletStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/128,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){E.error(`build failed:`,e),self.postMessage({error:e.message})}}",Ua=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ha],{type:`text/javascript;charset=utf-8`});function Wa(e){let t;try{if(t=Ua&&(self.URL||self.webkitURL).createObjectURL(Ua),!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(Ha),{type:`module`,name:e?.name})}}var Ga="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={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},S=x.FLOATS_PER_TRIANGLE;var C=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}},w=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=this.triangles,n=x.POSITION_A_OFFSET,r=x.POSITION_B_OFFSET,i=x.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*S,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/(S*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/(S*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 Float32Array(s*S);for(let e=0;e<s;e++){let t=this.indices[e]*S,n=e*S;m.set(p.subarray(t,t+S),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 C;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,w=m.rMinY,T=m.rMinZ,E=m.rMaxX,D=m.rMaxY,O=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,w,T,E,D,O),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new C;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,w=p.rMinZ,T=p.rMaxX,E=p.rMaxY,D=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,w,T,E,D),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};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 w;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})}}};",Ka=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ga],{type:`text/javascript;charset=utf-8`});function qa(e){let t;try{if(t=Ka&&(self.URL||self.webkitURL).createObjectURL(Ka),!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(Ga),{type:`module`,name:e?.name})}}Ma(()=>new Wa);var Ja=kt(`bvh`),Ya=32,Xa=5e4,Za=8;function Qa(e,t,n,r){let i=e.byteLength/(Ya*4),a=Math.min(navigator.hardwareConcurrency||4,Za),o=Math.ceil(Math.log2(a*2.5+1));return Ja.debug(`parallel build ${J.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let c=new SharedArrayBuffer(e.byteLength);new Float32Array(c).set(e);let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*Ya*4),h=new Wa,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,Ja.warn(`parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Float32Array(i).set(new Float32Array(c)),s(eo(new Float32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,$a(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r).catch(e=>x(e.message));return}if(t.type===`assembleResult`){y=!0,b();let e=new Float32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{Ja.warn(`parallel build setup failed:`,e),c(e)})})}async function $a(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){Ja.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}Ja.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 qa;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 eo(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=new Wa,s=e.byteLength/(Ya*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*Ya*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])})().catch(e=>{Ja.warn(`single worker fallback failed:`,e),a(e)})})}function to(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Xa}var no=16,ro=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.entryIndex=-1}},io=class{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){if(e.length===0)return{root:null,nodeCount:0};let t=[];for(let n=0;n<e.length;n++)t.push(n);let n=this._buildRecursive(e,t);return{root:n,nodeCount:this._countNodes(n)}}_buildRecursive(e,t){let n=new ro;if(t.length===1){let r=e[t[0]].worldAABB;return n.minX=r.minX,n.minY=r.minY,n.minZ=r.minZ,n.maxX=r.maxX,n.maxY=r.maxY,n.maxZ=r.maxZ,n.entryIndex=t[0],n}let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let n of t){let t=e[n].worldAABB;t.minX<r&&(r=t.minX),t.minY<i&&(i=t.minY),t.minZ<a&&(a=t.minZ),t.maxX>o&&(o=t.maxX),t.maxY>s&&(s=t.maxY),t.maxZ>c&&(c=t.maxZ)}if(n.minX=r,n.minY=i,n.minZ=a,n.maxX=o,n.maxY=s,n.maxZ=c,t.length===2)return n.leftChild=this._buildRecursive(e,[t[0]]),n.rightChild=this._buildRecursive(e,[t[1]]),n;let l=this._surfaceArea(r,i,a,o,s,c),u=1/0,d=0,f=0;if(l>0&&isFinite(l))for(let n=0;n<3;n++){let r=t.slice().sort((t,r)=>{let i=e[t].worldAABB,a=e[r].worldAABB;return this._centroid(i,n)-this._centroid(a,n)});for(let t=1;t<r.length;t++){let i=this._computeGroupAABB(e,r,0,t),a=this._computeGroupAABB(e,r,t,r.length),o=this._surfaceArea(i.minX,i.minY,i.minZ,i.maxX,i.maxY,i.maxZ),s=this._surfaceArea(a.minX,a.minY,a.minZ,a.maxX,a.maxY,a.maxZ),c=1+(o*t+s*(r.length-t))/l;c<u&&(u=c,d=n,f=t)}}if(f<=0||f>=t.length){d=0;let e=o-r,n=s-i,l=c-a;n>e&&n>l?d=1:l>e&&(d=2),f=t.length>>1}let p=t.slice().sort((t,n)=>this._centroid(e[t].worldAABB,d)-this._centroid(e[n].worldAABB,d)),m=p.slice(0,f),h=p.slice(f);return n.leftChild=this._buildRecursive(e,m),n.rightChild=this._buildRecursive(e,h),n}flatten(e,t){if(!e)return new Float32Array;let n=[],r=[e];for(;r.length>0;){let e=r.pop();e._flatIndex=n.length,n.push(e),e.rightChild&&r.push(e.rightChild),e.leftChild&&r.push(e.leftChild)}let i=n.length*no;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer;a.fill(0,0,i);for(let e=0;e<n.length;e++){let r=n[e],i=e*no;if(r.leftChild){let e=r.leftChild,t=r.rightChild;a[i]=e.minX,a[i+1]=e.minY,a[i+2]=e.minZ,a[i+3]=e._flatIndex,a[i+4]=e.maxX,a[i+5]=e.maxY,a[i+6]=e.maxZ,a[i+7]=t._flatIndex,a[i+8]=t.minX,a[i+9]=t.minY,a[i+10]=t.minZ,a[i+12]=t.maxX,a[i+13]=t.maxY,a[i+14]=t.maxZ}else{let n=t[r.entryIndex];a[i]=n.blasOffset,a[i+1]=r.entryIndex,a[i+2]=n.visible===!1?0:1,a[i+3]=Qe.BLAS_POINTER_LEAF,n.tlasLeafIndex=e}}return a.subarray(0,i)}_centroid(e,t){return t===0?(e.minX+e.maxX)*.5:t===1?(e.minY+e.maxY)*.5:(e.minZ+e.maxZ)*.5}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}_computeGroupAABB(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=e[t[u]].worldAABB;n.minX<i&&(i=n.minX),n.minY<a&&(a=n.minY),n.minZ<o&&(o=n.minZ),n.maxX>s&&(s=n.maxX),n.maxY>c&&(c=n.maxY),n.maxZ>l&&(l=n.maxZ)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l}}_countNodes(e){if(!e)return 0;let t=0,n=[e];for(;n.length>0;){let e=n.pop();t++,e.leftChild&&n.push(e.leftChild),e.rightChild&&n.push(e.rightChild)}return t}},ao=class{constructor(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}allocate(e){this.entries=Array(e).fill(null)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a}){this.entries[e]={meshIndex:e,blasOffset:0,blasNodeCount:t,triOffset:n,triCount:r,worldAABB:null,originalToBvhMap:i,bvhData:a,visible:!0,tlasLeafIndex:-1}}setVisibility(e,t){let n=this.entries[e];n&&(n.visible=t)}computeAABBs(e){for(let t of this.entries)t&&(t.worldAABB=this._readRootAABB(t.bvhData,t,e))}recomputeAABB(e,t,n){let r=this.entries[e],i=t.subarray(r.blasOffset*16,r.blasOffset*16+16);r.worldAABB=this._readRootAABB(i,r,n)}_readRootAABB(e,t,n){if(e[3]===-1)return this._computeAABBFromTriangles(t,n);let r=e[0],i=e[1],a=e[2],o=e[4],s=e[5],c=e[6],l=e[8],u=e[9],d=e[10],f=e[12],p=e[13],m=e[14];return{minX:Math.min(r,l),minY:Math.min(i,u),minZ:Math.min(a,d),maxX:Math.max(o,f),maxY:Math.max(s,p),maxZ:Math.max(c,m)}}_computeAABBFromTriangles(e,t){let n=G.FLOATS_PER_TRIANGLE,r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let l=0;l<e.triCount;l++){let u=(e.triOffset+l)*n;for(let e=0;e<=8;e+=4){let n=t[u+e],l=t[u+e+1],d=t[u+e+2];n<r&&(r=n),l<i&&(i=l),d<a&&(a=d),n>o&&(o=n),l>s&&(s=l),d>c&&(c=d)}}return{minX:r,minY:i,minZ:a,maxX:o,maxY:s,maxZ:c}}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e of this.entries)e&&(e.blasOffset=t,t+=e.blasNodeCount);this.totalBLASNodes=t-e}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}get count(){return this.entries.length}clear(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}},oo="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))}}",so=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,oo],{type:`text/javascript;charset=utf-8`});function co(e){let t;try{if(t=so&&(self.URL||self.webkitURL).createObjectURL(so),!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(oo),{type:`module`,name:e?.name})}}var lo=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,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`}),uo=Object.freeze({ERROR:`error`,WARNING:`warning`}),fo=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},po=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=uo.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===uo.ERROR)throw new fo(i);return i}warn(e,t,n){return this.record(e,t,n,uo.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===uo.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},mo=e=>Math.min(Math.max(e,0),1);function ho(e,t,n,r,i){i[0]=mo(e),i[1]=mo(t),i[2]=mo(n)}function go(e,t,n,r,i){i[0]=mo(e*r),i[1]=mo(t*r),i[2]=mo(n*r)}function _o(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=mo(e/(e+1)),i[1]=mo(t/(t+1)),i[2]=mo(n/(n+1))}function vo(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 yo(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]=mo(1.60475*a-.53108*o-.07367*s),i[1]=mo(-.10208*a+1.10813*o-.00605*s),i[2]=mo(-.00327*a-.07276*o+1.07602*s)}function bo(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=mo((Math.log2(Math.max(c,1e-10))-d)/f),l=mo((Math.log2(Math.max(l,1e-10))-d)/f),u=mo((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]=mo(1.6605*m-.5876*h-.0728*g),i[1]=mo(-.1246*m+1.1329*h-.0083*g),i[2]=mo(-.0182*m-.1006*h+1.1187*g)}function xo(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 So=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),Co=new Map([[r.NoToneMapping,So(ho)],[r.LinearToneMapping,So(go)],[r.ReinhardToneMapping,So(_o)],[r.CineonToneMapping,So(vo)],[r.ACESFilmicToneMapping,So(yo)],[r.AgXToneMapping,So(bo)],[r.NeutralToneMapping,So(xo)]]),wo=1/2.2;function To(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Eo(e,t){return t===r.NoToneMapping?1:e}var Do=.2126,Oo=.7152,ko=.0722;function Ao(e,t){if(t===1)return;let n=e[0]*Do+e[1]*Oo+e[2]*ko;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function jo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=Co.get(n)??Co.get(r.NoToneMapping),s=Eo(t,n),c=new Uint8ClampedArray(e.length),l=[0,0,0];for(let t=0;t<e.length;t+=4)l[0]=e[t]*s,l[1]=e[t+1]*s,l[2]=e[t+2]*s,Ao(l,i),o(l[0],l[1],l[2],1,l),c[t]=To(l[0])*255+.5,c[t+1]=To(l[1])*255+.5,c[t+2]=To(l[2])*255+.5,c[t+3]=a?e[t+3]*255+.5:255;return c}var Mo=kt(`textures`),No={toSRGB:null,toLinear:null};function Po(e){if(!No[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?To(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}No[e]=t}return No[e]}var Fo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=q.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=[]}},Io=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||pt.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*pt.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<q.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`}},Lo=class{constructor(e=q.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`;t+=`${e}x${r}_${i.slice(-8)}_${a}_`}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=[]}},Ro=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=q.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??q.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Fo,this.bufferPool=new Io({maxMemory:e.maxBufferMemory||pt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Lo,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){this._issues?.record(lo.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)||q.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(q.MIN_TEXTURE_WIDTH,Math.min(t,q.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Lo,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`}_harmonizeTransfer(e,t,n){let i=e?.image?.data;if(!i)return;let a=t.filter(e=>e?.image),o=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,s=e.image.width*e.image.height*4,c=[];for(let e=0;e<a.length;e++){let t=a[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===o)continue;let l=Po(n?`toSRGB`:`toLinear`),u=e*s,d=Math.min(u+s,i.length);for(let e=u;e<d;e+=4)i[e]=l[i[e]],i[e+1]=l[i[e+1]],i[e+2]=l[i[e+2]];c.push(a[e].name||a[e].source?.uuid?.slice(0,8)||`layer ${e}`)}if(c.length===0)return;e.needsUpdate=!0;let l=c.slice(0,4).join(`, `)+(c.length>4?`, +${c.length-4} more`:``);n?Mo.info(`re-encoded ${c.length}/${a.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${l}`):Mo.warn(`decoded ${c.length}/${a.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${l}`)}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=`${t?`s`:`l`}:${this.textureCache.generateHash(e)}`,r=this.textureCache.get(n);if(r)return r;let{normalized:i,bitmapsToClose:a}=await this._normalizeTexturesForProcessing(e),o=this.selectProcessingStrategy(i),s;try{switch(o.method){case`worker-direct`:s=await this.processWithWorkerDirect(i);break;case`main-batch`:s=await this.processOnMainThreadBatch(i,o.batchSize);break;case`main-streaming`:s=await this.processOnMainThreadStreaming(i);break;default:s=await this.processOnMainThreadSync(i)}return s&&(this._harmonizeTransfer(s,e,t),this.textureCache.set(n,s)),s}catch(n){this._issues?.warn(lo.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(i);return this._harmonizeTransfer(r,e,t),r}finally{for(let e of a)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>pt.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 co,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%pt.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=K.FLOATS_PER_MATERIAL,n=e.length,r=n*t,i=new Float32Array(r);for(let r=0;r<n;r++){let n=e[r],a=r*t,o=n.mapMatrix??ut,s=n.normalMapMatrices??ut,c=n.roughnessMapMatrices??ut,l=n.metalnessMapMatrices??ut,u=n.emissiveMapMatrices??ut,d=n.bumpMapMatrices??ut,f=n.displacementMapMatrices??ut,p=[n.ior,n.transmission,n.thickness,n.emissiveIntensity,n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b,Ze(n.attenuationDistance),n.opacity,n.side,n.transparent,n.alphaTest,n.alphaMode,n.depthWrite,n.normalScale?.x??1,n.normalScale?.y??1,n.color.r,n.color.g,n.color.b,n.metalness,n.emissive.r,n.emissive.g,n.emissive.b,n.roughness,n.map,n.normalMap,n.roughnessMap,n.metalnessMap,n.emissiveMap,n.bumpMap,n.clearcoat,n.clearcoatRoughness,n.dispersion,n.visible,n.sheen,n.sheenRoughness,n.sheenColor.r,n.sheenColor.g,n.sheenColor.b,1,n.specularIntensity,n.specularColor.r,n.specularColor.g,n.specularColor.b,n.iridescence,n.iridescenceIOR,n.iridescenceThicknessRange[0],n.iridescenceThicknessRange[1],n.bumpScale,n.displacementScale,n.displacementMap,0,o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7],s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],c[0],c[1],c[2],c[3],c[4],c[5],c[6],c[7],l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],n.subsurfaceColor?.r??1,n.subsurfaceColor?.g??1,n.subsurfaceColor?.b??1,n.subsurface??0,n.subsurfaceRadius?.[0]??1,n.subsurfaceRadius?.[1]??.2,n.subsurfaceRadius?.[2]??.1,n.subsurfaceRadiusScale??1,n.subsurfaceAnisotropy??0,n.anisotropy??0,n.anisotropyRotation??0,n.anisotropyMap??-1,n.transmissionMap??-1,n.clearcoatMap??-1,n.clearcoatRoughnessMap??-1,n.sheenColorMap??-1,n.sheenRoughnessMap??-1,n.iridescenceMap??-1,n.iridescenceThicknessMap??-1,n.specularIntensityMap??-1,n.specularColorMap??-1,0,0,0];i.set(p,a)}return i}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=q.VEC4_PER_BVH_NODE*q.FLOATS_PER_VEC4,i=t.length*r,a=new Float32Array(i);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,o=t[e],s=t[r];a[n]=o.boundsMin.x,a[n+1]=o.boundsMin.y,a[n+2]=o.boundsMin.z,a[n+3]=e,a[n+4]=o.boundsMax.x,a[n+5]=o.boundsMax.y,a[n+6]=o.boundsMax.z,a[n+7]=r,a[n+8]=s.boundsMin.x,a[n+9]=s.boundsMin.y,a[n+10]=s.boundsMin.z,a[n+12]=s.boundsMax.x,a[n+13]=s.boundsMax.y,a[n+14]=s.boundsMax.z}else a[n]=i.triangleOffset,a[n+1]=i.triangleCount,a[n+3]=-1}return a}async createMaterialTextures(e){let{materials:t,maps: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 Lo;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:et(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:zo(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:zo(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 zo(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var Bo=kt(`geometry`),Vo=q.MAX_TEXTURES_LIMIT;function Ho(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}var Uo=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._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.triangleData=new Float32Array(this._triangleCapacity*G.FLOATS_PER_TRIANGLE),this.currentTriangleIndex=0,this.traverseObject(e),this.logStats(),this.getExtractedData()}_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=new Float32Array(e*G.FLOATS_PER_TRIANGLE);t.set(this.triangleData),this.triangleData=t,this._triangleCapacity=e}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=this.currentTriangleIndex;this.extractGeometry(e,t,n),this.meshTriangleRanges.push({start:r,count:this.currentTriangleIndex-r})}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,jt(Bo,`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(){return{emissive:new r.Color(0,0,0),emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:.1,attenuationColor:new r.Color(16777215),attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:new r.Color(0),specularIntensity:1,specularColor:new r.Color(16777215),clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:{x:1,y:1},bumpScale:1,displacementScale:1,alphaTest:0,subsurface:0,subsurfaceColor:new r.Color(16777215),subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0}}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;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.r*.299+e.specular.g*.587+e.specular.b*.114;n.specularIntensity=Math.min(t*2,1),n.specularColor=e.specular.clone()}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),i=this.mapLegacyMaterialToPhysical(e,n),a=(e.transmission??0)>0,o=(e.metalness??i.metalness??0)>.1&&!a?2.5:t.ior,s=e.color||new r.Color(16777215);return n===`basic`&&!e.map&&(s=new r.Color(0)),{uuid:e.uuid,color:s,emissive:i.emissive??e.emissive??t.emissive,emissiveIntensity:i.emissiveIntensity??e.emissiveIntensity??t.emissiveIntensity,roughness:Math.max(.02,i.roughness??e.roughness??t.roughness),metalness:i.metalness??e.metalness??t.metalness,ior:e.ior??o,opacity:e.opacity??t.opacity,transmission:e.transmission??t.transmission,thickness:e.thickness??t.thickness,attenuationColor:e.attenuationColor??t.attenuationColor,attenuationDistance:e.attenuationDistance??t.attenuationDistance,dispersion:e.dispersion??t.dispersion,sheen:e.sheen??t.sheen,sheenRoughness:e.sheenRoughness??t.sheenRoughness,sheenColor:e.sheenColor??t.sheenColor,clearcoat:e.clearcoat??t.clearcoat,clearcoatRoughness:e.clearcoatRoughness??t.clearcoatRoughness,iridescence:e.iridescence??t.iridescence,iridescenceIOR:e.iridescenceIOR??t.iridescenceIOR,iridescenceThicknessRange:e.iridescenceThicknessRange??t.iridescenceThicknessRange,subsurface:e.subsurface??t.subsurface,subsurfaceColor:e.subsurfaceColor??t.subsurfaceColor,subsurfaceRadius:e.subsurfaceRadius??t.subsurfaceRadius,subsurfaceRadiusScale:e.subsurfaceRadiusScale??t.subsurfaceRadiusScale,subsurfaceAnisotropy:e.subsurfaceAnisotropy??t.subsurfaceAnisotropy,anisotropy:e.anisotropy??t.anisotropy,anisotropyRotation:e.anisotropyRotation??t.anisotropyRotation,specularIntensity:i.specularIntensity??e.specularIntensity??t.specularIntensity,specularColor:i.specularColor??e.specularColor??t.specularColor,normalScale:e.normalScale??t.normalScale,bumpScale:e.bumpScale??t.bumpScale,displacementScale:e.displacementScale??t.displacementScale,transparent:+!!e.transparent,alphaTest:e.alphaTest??t.alphaTest,alphaMode:Ho(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(e.map,this.maps),normalMap:this.processTexture(e.normalMap,this.normalMaps),bumpMap:this.processTexture(e.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(e.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(e.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(e.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(e.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(e.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(e.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(e.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(e.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(e.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(e.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(e.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(e.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(e.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(e.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(e.map),normalMapMatrices:this.getTextureMatrix(e.normalMap),bumpMapMatrices:this.getTextureMatrix(e.bumpMap),roughnessMapMatrices:this.getTextureMatrix(e.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(e.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(e.emissiveMap),displacementMapMatrices:this.getTextureMatrix(e.displacementMap),originalType:n}}getTextureMatrix(e){return e?(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<Vo){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(lo.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${Vo} distinct textures for one map type; the rest render untextured`,{limit:Vo,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n){e.updateMatrix(),e.updateMatrixWorld();let r=e.geometry;r.attributes.normal||r.computeVertexNormals();let i=r.attributes.position,a=r.attributes.normal,o=r.attributes.uv,s=r.index?r.index.array:null;this._matrixPool.mat4.copy(e.matrixWorld),this._matrixPool.mat3.getNormalMatrix(this._matrixPool.mat4);let c=s?s.length/3:i.count/3;this.extractTrianglesInBatch(i,a,o,s,c,t,n)}extractTrianglesInBatch(e,t,n,r,i,a,o){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let s=this._getVec3(0),c=this._getVec3(1),l=this._getVec3(2),u=this._getVec3(3),d=this._getVec3(4),f=this._getVec3(5),p=this._getVec2(0),m=this._getVec2(1),h=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);for(let g=0;g<i;g++){let i=g*3,_=r?r[i+0]:i+0,v=r?r[i+1]:i+1,y=r?r[i+2]:i+2;this.getVertex(e,_,s),this.getVertex(e,v,c),this.getVertex(e,y,l),this.getVertex(t,_,u),this.getVertex(t,v,d),this.getVertex(t,y,f),n?(this.getVertex(n,_,p),this.getVertex(n,v,m),this.getVertex(n,y,h)):(p.set(0,0),m.set(0,0),h.set(0,0)),s.applyMatrix4(this._matrixPool.mat4),c.applyMatrix4(this._matrixPool.mat4),l.applyMatrix4(this._matrixPool.mat4),u.applyMatrix3(this._matrixPool.mat3).normalize(),d.applyMatrix3(this._matrixPool.mat3).normalize(),f.applyMatrix3(this._matrixPool.mat3).normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,s,c,l,u,d,f,p,m,h,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=e*G.FLOATS_PER_TRIANGLE;this.triangleData[f+G.POSITION_A_OFFSET+0]=t.x,this.triangleData[f+G.POSITION_A_OFFSET+1]=t.y,this.triangleData[f+G.POSITION_A_OFFSET+2]=t.z,this.triangleData[f+G.POSITION_A_OFFSET+3]=0,this.triangleData[f+G.POSITION_B_OFFSET+0]=n.x,this.triangleData[f+G.POSITION_B_OFFSET+1]=n.y,this.triangleData[f+G.POSITION_B_OFFSET+2]=n.z,this.triangleData[f+G.POSITION_B_OFFSET+3]=0,this.triangleData[f+G.POSITION_C_OFFSET+0]=r.x,this.triangleData[f+G.POSITION_C_OFFSET+1]=r.y,this.triangleData[f+G.POSITION_C_OFFSET+2]=r.z,this.triangleData[f+G.POSITION_C_OFFSET+3]=0,this.triangleData[f+G.NORMAL_A_OFFSET+0]=i.x,this.triangleData[f+G.NORMAL_A_OFFSET+1]=i.y,this.triangleData[f+G.NORMAL_A_OFFSET+2]=i.z;{let e=this.materials[u],t=e&&!(e.alphaMode|0)&&!(e.transparent|0)&&(e.transmission||0)===0&&(e.opacity??1)>=1?1:0;this.triangleData[f+G.NORMAL_A_OFFSET+3]=t}this.triangleData[f+G.NORMAL_B_OFFSET+0]=a.x,this.triangleData[f+G.NORMAL_B_OFFSET+1]=a.y,this.triangleData[f+G.NORMAL_B_OFFSET+2]=a.z,this.triangleData[f+G.NORMAL_B_OFFSET+3]=0,this.triangleData[f+G.NORMAL_C_OFFSET+0]=o.x,this.triangleData[f+G.NORMAL_C_OFFSET+1]=o.y,this.triangleData[f+G.NORMAL_C_OFFSET+2]=o.z,this.triangleData[f+G.NORMAL_C_OFFSET+3]=this.materials[u]?.side??0,this.triangleData[f+G.UV_AB_OFFSET+0]=s.x,this.triangleData[f+G.UV_AB_OFFSET+1]=s.y,this.triangleData[f+G.UV_AB_OFFSET+2]=c.x,this.triangleData[f+G.UV_AB_OFFSET+3]=c.y,this.triangleData[f+G.UV_C_MAT_OFFSET+0]=l.x,this.triangleData[f+G.UV_C_MAT_OFFSET+1]=l.y,this.triangleData[f+G.UV_C_MAT_OFFSET+2]=u,this.triangleData[f+G.UV_C_MAT_OFFSET+3]=d}getTriangleData(){return this.triangleData?this.triangleData.subarray(0,this.currentTriangleIndex*G.FLOATS_PER_TRIANGLE):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*G.FLOATS_PER_TRIANGLE*4;Bo.debug(J.list([`${J.count(this.currentTriangleIndex,`tri`)} (${J.mb(e)})`,J.count(this.materials.length,`material`),J.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.triangleData=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],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,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}}},Wo=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=Ko(E,Go(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=Ko(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 Go(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 Ko(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)}}var qo=kt(`emissive`),Jo=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){this.emissiveTriangles=[],this.totalEmissivePower=0,this._totalTriangleCount=n;let r=G.FLOATS_PER_TRIANGLE,i=G.UV_C_MAT_OFFSET+2,a=G.UV_C_MAT_OFFSET+3;for(let o=0;o<n;o++){let n=o*r,s=Math.floor(e[n+i]),c=Math.floor(e[n+a]),l=t[s];if(!l)continue;let u=l.emissive||{r:0,g:0,b:0},d=l.emissiveIntensity||0;if(d>0&&(u.r>0||u.g>0||u.b>0)){let t=e[n+0],r=e[n+1],i=e[n+2],a=e[n+4],f=e[n+5],p=e[n+6],m=e[n+8],h=e[n+9],g=e[n+10],_=this._calculateTriangleArea(t,r,i,a,f,p,m,h,g),v=(.2126*u.r+.7152*u.g+.0722*u.b)*d*_,y=(f-r)*(g-i)-(p-i)*(h-r),b=(p-i)*(m-t)-(a-t)*(g-i),x=(a-t)*(h-r)-(f-r)*(m-t),S=Math.sqrt(y*y+b*b+x*x)||1,C=l.side===1?-1:1;y=y/S*C,b=b/S*C,x=x/S*C;let w=l.side===2,T=(t+a+m)/3,E=(r+f+h)/3,D=(i+p+g)/3,O=Math.min(t,a,m),k=Math.min(r,f,h),A=Math.min(i,p,g),j=Math.max(t,a,m),M=Math.max(r,f,h),N=Math.max(i,p,g);this.emissiveTriangles.push({triangleIndex:o,materialIndex:s,meshIndex:c,power:v,area:_,emissive:{r:u.r,g:u.g,b:u.b},emissiveIntensity:d,cx:T,cy:E,cz:D,bMinX:O,bMinY:k,bMinZ:A,bMaxX:j,bMaxY:M,bMaxZ:N,nx:y,ny:b,nz:x,twoSided:w}),this.totalEmissivePower+=v}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&qo.debug(`${J.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,qo.debug(`emissive texture ${J.px(t,n)} · ${J.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]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return qo.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.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=t.emissive||{r:0,g:0,b:0},o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.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 Wo().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]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,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,qo.debug(`rebuilt sorted emissive data · ${J.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}},Yo=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=kt(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=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Xo="const e={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},t=e.FLOATS_PER_TRIANGLE,n=new class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(n,r,i){let a=i.length;for(let o=0;o<a;o++){let a=i[o],s=o*t,c=a*9,l=r[c],u=r[c+1],d=r[c+2],f=r[c+3],p=r[c+4],m=r[c+5],h=r[c+6],g=r[c+7],_=r[c+8];n[s+e.POSITION_A_OFFSET]=l,n[s+e.POSITION_A_OFFSET+1]=u,n[s+e.POSITION_A_OFFSET+2]=d,n[s+e.POSITION_B_OFFSET]=f,n[s+e.POSITION_B_OFFSET+1]=p,n[s+e.POSITION_B_OFFSET+2]=m,n[s+e.POSITION_C_OFFSET]=h,n[s+e.POSITION_C_OFFSET+1]=g,n[s+e.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=y*C-b*S,T=b*x-v*C,E=v*S-y*x;n[s+e.NORMAL_A_OFFSET]=w,n[s+e.NORMAL_A_OFFSET+1]=T,n[s+e.NORMAL_A_OFFSET+2]=E,n[s+e.NORMAL_B_OFFSET]=w,n[s+e.NORMAL_B_OFFSET+1]=T,n[s+e.NORMAL_B_OFFSET+2]=E,n[s+e.NORMAL_C_OFFSET]=w,n[s+e.NORMAL_C_OFFSET+1]=T,n[s+e.NORMAL_C_OFFSET+2]=E}}refitRange(n,r,i,a){a>this._boundsNodeCount&&(this._bounds=new Float32Array(a*6),this._boundsNodeCount=a);let o=this._bounds,s=i+a;for(let a=s-1;a>=i;a--){let s=a*16,c=(a-i)*6;if(n[s+3]===-1){let i=n[s],a=n[s+1],l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0;for(let n=0;n<a;n++){let a=(i+n)*t,o=r[a+e.POSITION_A_OFFSET],s=r[a+e.POSITION_A_OFFSET+1],c=r[a+e.POSITION_A_OFFSET+2],h=r[a+e.POSITION_B_OFFSET],g=r[a+e.POSITION_B_OFFSET+1],_=r[a+e.POSITION_B_OFFSET+2],v=r[a+e.POSITION_C_OFFSET],y=r[a+e.POSITION_C_OFFSET+1],b=r[a+e.POSITION_C_OFFSET+2];l=Math.min(l,o,h,v),u=Math.min(u,s,g,y),d=Math.min(d,c,_,b),f=Math.max(f,o,h,v),p=Math.max(p,s,g,y),m=Math.max(m,c,_,b)}o[c]=l,o[c+1]=u,o[c+2]=d,o[c+3]=f,o[c+4]=p,o[c+5]=m}else{let e=n[s+3],t=n[s+7],r=(e-i)*6,a=(t-i)*6,l=o[r],u=o[r+1],d=o[r+2],f=o[r+3],p=o[r+4],m=o[r+5],h=o[a],g=o[a+1],_=o[a+2],v=o[a+3],y=o[a+4],b=o[a+5];n[s]=l,n[s+1]=u,n[s+2]=d,n[s+4]=f,n[s+5]=p,n[s+6]=m,n[s+8]=h,n[s+9]=g,n[s+10]=_,n[s+12]=v,n[s+13]=y,n[s+14]=b,o[c]=Math.min(l,h),o[c+1]=Math.min(u,g),o[c+2]=Math.min(d,_),o[c+3]=Math.max(f,v),o[c+4]=Math.max(p,y),o[c+5]=Math.max(m,b)}}}refit(n,r,i){i!==this._boundsNodeCount&&(this._bounds=new Float32Array(i*6),this._boundsNodeCount=i);let a=this._bounds;for(let o=i-1;o>=0;o--){let i=o*16,s=o*6,c=n[i+3];if(c===-1){let o=n[i],c=n[i+1],l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0;for(let n=0;n<c;n++){let i=(o+n)*t,a=r[i+e.POSITION_A_OFFSET],s=r[i+e.POSITION_A_OFFSET+1],c=r[i+e.POSITION_A_OFFSET+2],h=r[i+e.POSITION_B_OFFSET],g=r[i+e.POSITION_B_OFFSET+1],_=r[i+e.POSITION_B_OFFSET+2],v=r[i+e.POSITION_C_OFFSET],y=r[i+e.POSITION_C_OFFSET+1],b=r[i+e.POSITION_C_OFFSET+2];l=Math.min(l,a,h,v),u=Math.min(u,s,g,y),d=Math.min(d,c,_,b),f=Math.max(f,a,h,v),p=Math.max(p,s,g,y),m=Math.max(m,c,_,b)}a[s]=l,a[s+1]=u,a[s+2]=d,a[s+3]=f,a[s+4]=p,a[s+5]=m}else if(c===-2){let e=n[i]*6;a[s]=a[e],a[s+1]=a[e+1],a[s+2]=a[e+2],a[s+3]=a[e+3],a[s+4]=a[e+4],a[s+5]=a[e+5]}else{let e=n[i+3],t=n[i+7],r=e*6,o=t*6,c=a[r],l=a[r+1],u=a[r+2],d=a[r+3],f=a[r+4],p=a[r+5],m=a[o],h=a[o+1],g=a[o+2],_=a[o+3],v=a[o+4],y=a[o+5];n[i]=c,n[i+1]=l,n[i+2]=u,n[i+4]=d,n[i+5]=f,n[i+6]=p,n[i+8]=m,n[i+9]=h,n[i+10]=g,n[i+12]=_,n[i+13]=v,n[i+14]=y,a[s]=Math.min(c,m),a[s+1]=Math.min(l,h),a[s+2]=Math.min(u,g),a[s+3]=Math.max(d,_),a[s+4]=Math.max(f,v),a[s+5]=Math.max(p,y)}}}};let r=null,i=null,a=null,o=null,s=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){r=new Float32Array(e.data.sharedBvhBuf),i=new Float32Array(e.data.sharedTriBuf),a=new Float32Array(e.data.sharedPosBuf),o=e.data.bvhToOriginal,s=r.length/16;return}if(t===`refit`)try{let e=performance.now();n.updateTrianglePositions(i,a,o),n.refit(r,i,s),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-e})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Zo=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Xo],{type:`text/javascript;charset=utf-8`});function Qo(e){let t;try{if(t=Zo&&(self.URL||self.webkitURL).createObjectURL(Zo),!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(Xo),{type:`module`,name:e?.name})}}var $o=kt(`scene`),es=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:q.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,...e},this.triangleData=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.bvhData=null,this.materialData=null,this.instanceTable=null,this.originalToBvhMap=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.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.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Uo({issues:this.config.issues}),this.bvhBuilder=new Ia,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 Ro({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Jo,this.tlasBuilder=new io}_log(e,t){t===void 0?$o.debug(e):$o.debug(e,t)}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`;let t=new Yo(e.name??``,{namespace:`scene`});try{this._reset(),this._log(`Starting scene processing`),this.processingStage=`extraction`,t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,H({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||H({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvhData&&(this.bvhData=this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,H({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,$o.error(`processing failed:`,e),H({status:`Error: ${e.message}`,progress:100}),e}finally{this.isProcessing=!1}}async _extractGeometry(e){H({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this.triangleData=n.triangleData,this.triangleCount=n.triangleCount,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangleData.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.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}),H({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw $o.error(`geometry extraction failed:`,e),H({status:`Extraction error: ${e.message}`,progress:25}),e}}async _buildBVH(){if(H({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`);let e=performance.now();try{let t=G.FLOATS_PER_TRIANGLE,n=this.meshTriangleRanges;if(!n||n.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);this.instanceTable=new ao,this.instanceTable.allocate(n.length);let r=n.length,i=this.config.enableTreeletOptimization,a=[],o=[];for(let e=0;e<r;e++){let t=n[e];t.count!==0&&(t.count>=2e5&&to(t.count)?o.push({m:e,range:t}):a.push({m:e,range:t}))}let s={depth:this.config.bvhDepth,treeletOptimization:{enabled:i!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,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:Mt()},c=a.length+o.length,l=this._buildBLASesWithPool(a,s,e=>{H({status:`Building BLAS ${e+o.length}/${c}...`,progress:25+Math.floor(e/c*45)})}),u=o.map(({m:e,range:n})=>Qa(this.triangleData.slice(n.start*t,(n.start+n.count)*t),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...s}).then(t=>({m:e,range:n,result:t}))),[d,f]=await Promise.all([l,Promise.all(u)]),p={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:n,result:r}of[...d,...f]){r.reorderedTriangles&&this.triangleData.set(r.reorderedTriangles,n.start*t);let i=r.splitStats;i&&(p.sah+=i.sahSplits??0,p.objMed+=i.objectMedianSplits??0,p.spatMed+=i.spatialMedianSplits??0,p.failed+=i.failedSplits??0,p.treeletsImproved+=i.treeletsImproved??0,p.treeletsProcessed+=i.treeletsProcessed??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:n.start,triCount:n.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData})}H({status:`Built all BLASes`,progress:70}),H({status:`Building TLAS...`,progress:72});let m=this.instanceTable.entries.filter(e=>e!==null);this.instanceTable.computeAABBs(this.triangleData);let{root:h,nodeCount:g}=this.tlasBuilder.build(m);this.instanceTable.assignOffsets(g);let _=this.instanceTable.totalNodeCount,v=this.tlasBuilder.flatten(h,m);this.bvhData=new Float32Array(_*16),this.bvhData.set(v);for(let e of m){let t=e.blasOffset*16;this.bvhData.set(e.bvhData,t),this._offsetBLASInPlace(t,e.bvhData.length/16,e.blasOffset,e.triOffset)}this._buildGlobalOriginalToBvhMap();for(let e of m)e.originalToBvhMap=null,e.bvhData=null;this.bvhRoot=!0,this._disposeRefitWorker();let y=performance.now()-e;$o.debug(J.list([`${J.n(m.length)} BLASes + TLAS`,`${J.n(this.bvhData.length/16)} nodes`,`SAH ${J.n(p.sah)} · objMed ${p.objMed} · spatMed ${p.spatMed} · failed ${p.failed}`,p.treeletsProcessed?`treelets ${p.treeletsImproved}/${p.treeletsProcessed} improved`:null,J.ms(y)])),H({status:`BVH construction complete`,progress:75})}catch(e){throw $o.error(`BVH build failed:`,e),H({status:`BVH error: ${e.message}`,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){for(let i=0;i<t;i++){let t=e+i*16;this.bvhData[t+3]===-1?this.bvhData[t]+=r:(this.bvhData[t+3]+=n,this.bvhData[t+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=G.FLOATS_PER_TRIANGLE,i=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),a=[],o=0,s=0;return new Promise((c,l)=>{let u=[],d=n=>{if(o>=e.length){n.terminate(),u.splice(u.indexOf(n),1),u.length===0&&c(a);return}let{m:i,range:s}=e[o++],l=this.triangleData.slice(s.start*r,(s.start+s.count)*r),d=s.count,f=d<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:i,range:s},n.postMessage({triangleData:l.buffer,triangleByteOffset:l.byteOffset,triangleByteLength:l.byteLength,triangleCount:d,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:f,reinsertionOptimization:t.reinsertionOptimization,maxLeafSize:t.maxLeafSize,numBins:t.numBins,maxBins:t.maxBins,minBins:t.minBins,logLevel:t.logLevel},[l.buffer])},f=(e,t)=>{let r=t.data;if(r.error){u.forEach(e=>e.terminate()),l(Error(r.error));return}if(r.progress!==void 0)return;let{m:i,range:o}=e._currentTask;a.push({m:i,range:o,result:{bvhData:r.bvhData,reorderedTriangles:r.triangles||null,originalToBvh:r.originalToBvh||null,splitStats:r.treeletStats||null}}),s++,n?.(s),d(e)};(async()=>{for(let e=0;e<i;e++){let e;try{e=new Wa}catch(e){l(e);return}e.onmessage=t=>f(e,t),e.onerror=e=>{u.forEach(e=>e.terminate()),l(e)},u.push(e),d(e)}})().catch(l)})}_buildGlobalOriginalToBvhMap(){this.originalToBvhMap=new Uint32Array(this.triangleCount);for(let e of this.instanceTable.entries){if(!e)continue;let t=new Uint32Array(e.triCount);if(e.originalToBvhMap)for(let n=0;n<e.triCount;n++){let r=e.originalToBvhMap[n];this.originalToBvhMap[e.triOffset+n]=e.triOffset+r,t[r]=n}else for(let n=0;n<e.triCount;n++)this.originalToBvhMap[e.triOffset+n]=e.triOffset+n,t[n]=n;e.bvhToOriginal=t}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{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 $o.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=q.MATERIAL_BUCKET_COUNT,n=q.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=st(r(i),e,t),s=st(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=(e,t,r,i,a)=>{if(!e||!e.image)return-1;let o=ct(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return lt(o,c);if(t[o].length>=n)return $o.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(lo.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=lt(o,l);return i.set(s,u),u},m=(e,t,n,r,i)=>(e||[]).map(e=>p(e,t,n,r,i));return{srgbLists:c,linearLists:l,remap:{albedo:m(this.maps,c,u,this._srgbTexPacked,o),emissive:m(this.emissiveMaps,c,u,this._srgbTexPacked,o),normal:m(this.normalMaps,l,d,this._linearTexPacked,s),bump:m(this.bumpMaps,l,d,this._linearTexPacked,s),roughness:m(this.roughnessMaps,l,d,this._linearTexPacked,s),metalness:m(this.metalnessMaps,l,d,this._linearTexPacked,s),displacement:m(this.displacementMaps,l,d,this._linearTexPacked,s),anisotropy:m(this.anisotropyMaps,l,d,this._linearTexPacked,s),transmission:m(this.transmissionMaps,l,d,this._linearTexPacked,s),clearcoat:m(this.clearcoatMaps,l,d,this._linearTexPacked,s),clearcoatRoughness:m(this.clearcoatRoughnessMaps,l,d,this._linearTexPacked,s),sheenColor:m(this.sheenColorMaps,c,u,this._srgbTexPacked,o),sheenRoughness:m(this.sheenRoughnessMaps,l,d,this._linearTexPacked,s),iridescence:m(this.iridescenceMaps,l,d,this._linearTexPacked,s),iridescenceThickness:m(this.iridescenceThicknessMaps,l,d,this._linearTexPacked,s),specularIntensity:m(this.specularIntensityMaps,l,d,this._linearTexPacked,s),specularColor:m(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.triangleData,this.materials,this.triangleCount),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this.triangleData=null,this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.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.bvhData=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime: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){$o.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 $o.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.bvhData,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangleData?(this.triangleData.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}async refitBVH(e,t){if(!this.bvhData||!this.triangleData||!this.originalToBvhMap)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this.triangleCount*9;if(e?.length!==n)throw Error(`SceneProcessor.refitBVH: expected ${n} position floats (${this.triangleCount} triangles × 9), got ${e?.length??`none`}. Positions must cover every triangle in the scene, meshes in this.meshes order.`);if(t&&t.length!==n)throw Error(`SceneProcessor.refitBVH: expected ${n} normal floats, got ${t.length}.`);if(this._refitWorker||=new Qo,!this._refitSharedBuffers){let t=new SharedArrayBuffer(this.bvhData.byteLength),n=new SharedArrayBuffer(this.triangleData.byteLength),r=new SharedArrayBuffer(e.byteLength),i=new Float32Array(t),a=new Float32Array(n);i.set(this.bvhData),a.set(this.triangleData),this.bvhData=i,this.triangleData=a;let o=this.originalToBvhMap.length,s=new Uint32Array(o);for(let e=0;e<o;e++)s[this.originalToBvhMap[e]]=e;this._refitSharedBuffers={bvhBuf:t,triBuf:n,posBuf:r,posView:new Float32Array(r)},this._refitWorker.postMessage({type:`init`,sharedBvhBuf:t,sharedTriBuf:n,sharedPosBuf:r,bvhToOriginal:s},[s.buffer])}return this._refitSharedBuffers.posView.set(e),new Promise((e,n)=>{this._refitWorker.onmessage=r=>{let i=r.data;i.type===`refitComplete`?(t&&this._patchSmoothNormals(t),e({refitTimeMs:i.refitTimeMs})):i.type===`error`&&n(Error(i.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){this._patchNormalsRange(e,0,this.originalToBvhMap.length)}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvhData||!this.triangleData)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this.triangleCount*9;if(t?.length!==r)throw Error(`SceneProcessor.refitBLASes: expected ${r} position floats (${this.triangleCount} triangles × 9, full scene), got ${t?.length??`none`}.`);if(n&&n.length!==r)throw Error(`SceneProcessor.refitBLASes: expected ${r} normal floats, got ${n.length}.`);let i=performance.now();this._blasRefitter||=new Va;for(let r of e){let e=this.instanceTable.entries[r];e&&(this._updateMeshTrianglePositions(e,t),n&&this._patchMeshSmoothNormals(e,n),this._blasRefitter.refitRange(this.bvhData,this.triangleData,e.blasOffset,e.blasNodeCount),this.instanceTable.recomputeAABB(r,this.bvhData,this.triangleData))}return this._refitTLAS(),{refitTimeMs:performance.now()-i}}computeBLASDirtyRanges(e){let t=G.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable.entries[i];e&&(n.push({offset:e.triOffset*t,count:e.triCount*t}),r.push({offset:e.blasOffset*16,count:e.blasNodeCount*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangleData?(e.setTriangleData(this.triangleData,this.triangleCount),this.bvhData?(e.setBVHData(this.bvhData),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData):$o.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):($o.error(`failed to get BVH data`),!1)):($o.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.triangleData,this.materials,this.triangleCount))?null: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}}_updateMeshTrianglePositions(e,t){let n=G.FLOATS_PER_TRIANGLE,r=G.POSITION_A_OFFSET,i=G.POSITION_B_OFFSET,a=G.POSITION_C_OFFSET,o=G.NORMAL_A_OFFSET,s=G.NORMAL_B_OFFSET,c=G.NORMAL_C_OFFSET,l=e.bvhToOriginal;for(let u=0;u<e.triCount;u++){let d=l[u],f=(e.triOffset+u)*n,p=(e.triOffset+d)*9,m=t[p],h=t[p+1],g=t[p+2],_=t[p+3],v=t[p+4],y=t[p+5],b=t[p+6],x=t[p+7],S=t[p+8];this.triangleData[f+r]=m,this.triangleData[f+r+1]=h,this.triangleData[f+r+2]=g,this.triangleData[f+i]=_,this.triangleData[f+i+1]=v,this.triangleData[f+i+2]=y,this.triangleData[f+a]=b,this.triangleData[f+a+1]=x,this.triangleData[f+a+2]=S;let C=_-m,w=v-h,T=y-g,E=b-m,D=x-h,O=S-g,k=w*O-T*D,A=T*E-C*O,j=C*D-w*E;this.triangleData[f+o]=k,this.triangleData[f+o+1]=A,this.triangleData[f+o+2]=j,this.triangleData[f+s]=k,this.triangleData[f+s+1]=A,this.triangleData[f+s+2]=j,this.triangleData[f+c]=k,this.triangleData[f+c+1]=A,this.triangleData[f+c+2]=j}}_patchMeshSmoothNormals(e,t){this._patchNormalsRange(t,e.triOffset,e.triCount)}_patchNormalsRange(e,t,n){let r=G.FLOATS_PER_TRIANGLE,i=G.NORMAL_A_OFFSET,a=G.NORMAL_B_OFFSET,o=G.NORMAL_C_OFFSET;for(let s=0;s<n;s++){let n=t+s,c=this.originalToBvhMap[n]*r,l=n*9;this.triangleData[c+i]=e[l],this.triangleData[c+i+1]=e[l+1],this.triangleData[c+i+2]=e[l+2],this.triangleData[c+a]=e[l+3],this.triangleData[c+a+1]=e[l+4],this.triangleData[c+a+2]=e[l+5],this.triangleData[c+o]=e[l+6],this.triangleData[c+o+1]=e[l+7],this.triangleData[c+o+2]=e[l+8]}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6)),this._blasOffsetMap||=new Map,this._blasOffsetMap.clear();for(let e of this.instanceTable.entries)e&&this._blasOffsetMap.set(e.blasOffset,e);for(let t=e-1;t>=0;t--){let e=t*16,n=this.bvhData[e+3];if(n===-2){let n=this.bvhData[e],r=this._blasOffsetMap.get(n);if(r&&r.worldAABB){let e=t*6;this._tlasBounds[e]=r.worldAABB.minX,this._tlasBounds[e+1]=r.worldAABB.minY,this._tlasBounds[e+2]=r.worldAABB.minZ,this._tlasBounds[e+3]=r.worldAABB.maxX,this._tlasBounds[e+4]=r.worldAABB.maxY,this._tlasBounds[e+5]=r.worldAABB.maxZ}}else if(n>=0){let n=this.bvhData[e+3],r=this.bvhData[e+7],i=n*6,a=r*6,o=this._tlasBounds;this.bvhData[e]=o[i],this.bvhData[e+1]=o[i+1],this.bvhData[e+2]=o[i+2],this.bvhData[e+4]=o[i+3],this.bvhData[e+5]=o[i+4],this.bvhData[e+6]=o[i+5],this.bvhData[e+8]=o[a],this.bvhData[e+9]=o[a+1],this.bvhData[e+10]=o[a+2],this.bvhData[e+12]=o[a+3],this.bvhData[e+13]=o[a+4],this.bvhData[e+14]=o[a+5];let s=t*6;o[s]=Math.min(o[i],o[a]),o[s+1]=Math.min(o[i+1],o[a+1]),o[s+2]=Math.min(o[i+2],o[a+2]),o[s+3]=Math.max(o[i+3],o[a+3]),o[s+4]=Math.max(o[i+4],o[a+4]),o[s+5]=Math.max(o[i+5],o[a+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangleData)return;let n=G.FLOATS_PER_TRIANGLE;this._rebuildGeneration++;let r=this._rebuildGeneration,i=(e,i,a)=>{let o=this.triangleData.slice(i.triOffset*n,(i.triOffset+i.triCount)*n);this._pendingRebuilds.set(e,a),a.onmessage=n=>{let o=n.data;if(a.terminate(),this._pendingRebuilds.delete(e),o.error){$o.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}r===this._rebuildGeneration&&this._swapBLAS(e,i,o,t)},a.onerror=t=>{$o.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),a.terminate(),this._pendingRebuilds.delete(e)};let s=i.triCount>500;a.postMessage({triangleData:o.buffer,triangleByteOffset:o.byteOffset,triangleByteLength:o.byteLength,triangleCount:i.triCount,depth:this.config.bvhDepth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:s,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[o.buffer])};for(let t of e){let e=this.instanceTable.entries[t];if(!e)continue;let n=this._pendingRebuilds.get(t);n&&n.terminate(),i(t,e,new Wa)}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a!==t.blasNodeCount){$o.warn(`background rebuild node count mismatch for mesh ${e} (${a} vs ${t.blasNodeCount}), skipping swap`);return}let o=t.blasOffset*16;this.bvhData.set(i,o),this._offsetBLASInPlace(o,a,t.blasOffset,t.triOffset);let s=G.FLOATS_PER_TRIANGLE,c=n.triangles;c&&this.triangleData.set(c,t.triOffset*s);let l=n.originalToBvh;if(l){for(let e=0;e<t.triCount;e++)this.originalToBvhMap[t.triOffset+e]=t.triOffset+l[e];let e=new Uint32Array(t.triCount);for(let n=0;n<t.triCount;n++)e[l[n]]=n;t.bvhToOriginal=e}this.instanceTable.recomputeAABB(e,this.bvhData,this.triangleData),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.()}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},ts=[[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]],ns=[[-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]],rs=[[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 is(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=ts[i],o=ns[i],s=rs[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 as=1/(4*Math.PI);function os(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=e.color.r,a=e.color.g,o=e.color.b;if(t.useTemperature){let[e,n,r]=is(t.temperature??6500);i*=e,a*=n,o*=r}return{r:i,g:a,b:o,intensity:r}}var ss=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=os(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=os(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=os(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*as,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=os(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*as,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}))}}},cs={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://cdn.jsdelivr.net/npm/denoiser/tzas/`,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,cacheNamespace:`rayzee`};function ls(e){e&&Object.assign(cs,e)}function us(){return{...cs}}var ds=kt(`pathtracer`),fs=4,ps=class extends _e{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:ge.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 es,this.lightSerializer=new ss,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Ne(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new It(0,0),this.uniforms=new Rt(a,o),this._defineUniformGetters(),this.materialData=new Kt(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this.triangleStorageAttr?.array,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleStorageAttr&&(this.triangleStorageAttr.needsUpdate=!0)},this.environment=new En(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new Ea,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.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.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 ve(this.renderer,{uniforms:{maxBounceCount:{get value(){return e.maxBounces.value},set value(t){e.maxBounces.value=t}},enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},enableEmissiveTriangleSampling:{get value(){return e.enableEmissiveTriangleSampling.value},set value(t){e.enableEmissiveTriangleSampling.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:U.interactionModeEnabled,qualitySettings:{maxBounceCount:1,enableAccumulation:!1,enableEmissiveTriangleSampling:!1},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}=us(),a=e.loadAsync(n).then(e=>{this.stbnScalarTexture=t(e),P.value=e,ds.debug(`STBN scalar atlas ${J.px(e.image.width,e.image.height)}`)}),o=e.loadAsync(i).then(e=>{this.stbnVec2Texture=t(e),F.value=e,ds.debug(`STBN vec2 atlas ${J.px(e.image.width,e.image.height)}`)});this.blueNoiseReady=Promise.allSettled([a,o]).then(e=>{for(let t of e)t.status===`rejected`&&ds.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.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,ds.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}setTriangleData(e,r){if(!e)return;let i=e.length/4;this.triangleStorageNode?(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=i):(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode=(0,n.storage)(this.triangleStorageAttr,`vec4`,i).toReadOnly()),this.triangleCount=r,ds.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let r=e.length/4;this.bvhStorageNode?(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=r):(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,r).toReadOnly()),this.bvhNodeCount=Math.floor(r/fs),ds.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){if(!(!e||e.length===0||!this._instanceTable)){for(let t=0;t<e.length;t++)this._patchTLASLeafVisibility(t,this._isWorldVisible(e[t]));this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}updateAllMeshVisibility(){if(!(!this._meshRefs||!this._instanceTable)){for(let e=0;e<this._meshRefs.length;e++)this._patchTLASLeafVisibility(e,this._isWorldVisible(this._meshRefs[e]));this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}}_patchTLASLeafVisibility(e,t){let n=this._instanceTable?.entries?.[e];return!n||n.tlasLeafIndex<0||!this.bvhStorageAttr?!1:(n.visible=t,this.bvhStorageAttr.array[n.tlasLeafIndex*16+2]=+!!t,!0)}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){this._updateStorageBuffer(this.triangleStorageAttr,e)}updateBVHData(e){this._updateStorageBuffer(this.bvhStorageAttr,e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0){this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0){this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){ds.error(`triangle data required`);return}if(!this.bvhStorageNode){ds.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=Me(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=je(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&&(P.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(),ds.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),ds.debug(`light BVH ${J.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{ds.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),ds.debug(`material rebuild complete`)}catch(e){ds.error(`material rebuild failed:`,e);try{ds.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){ds.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.triangleStorageNode=null,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}},ms=kt(`gpu`),hs={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},gs={DIST_TRI_BARY:0,NORMAL_MAT:1},_s=0,vs=(e,t)=>t===0?e:e.add(t*_s);function ys(e,t){t&&e?._attributes?.delete?.(t)}var bs=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,_s=e;let r=e*7,i=new t.StorageInstancedBufferAttribute(new Float32Array(r*4),4);this._attrs.ray=i,this.rayBuffer={rw:(0,n.storage)(i,`vec4`),ro:(0,n.storage)(i,`vec4`).toReadOnly()};let a=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);this._attrs.rng=a,this.rngBuffer={rw:(0,n.storage)(a,`uint`),ro:(0,n.storage)(a,`uint`).toReadOnly()};let o=e*2,s=new t.StorageInstancedBufferAttribute(new Float32Array(o*4),4);this._attrs.hit=s,this.hitBuffer={rw:(0,n.storage)(s,`vec4`),ro:(0,n.storage)(s,`vec4`).toReadOnly()},this.rayBytes=r*16+e*4,this.hitBytes=o*16,this.totalBytes=this.rayBytes+this.hitBytes,ms.debug(`ray pool capacity ${J.n(e)} · ${J.mb(this.totalBytes)} (rays ${J.mb(this.rayBytes)} · hits ${J.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){ys(this._renderer,this._attrs.ray),ys(this._renderer,this._attrs.rng),ys(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,this.capacity=0}},xs=(e,t)=>e.element(vs(t,hs.ORIGIN_META)).xyz,Ss=(e,t)=>e.element(vs(t,hs.DIR_FLAGS)).xyz,Cs=(e,t)=>(0,n.floatBitsToUint)(e.element(vs(t,hs.DIR_FLAGS)).w),ws=(e,t)=>e.element(vs(t,hs.THROUGHPUT_PDF)).xyz,Ts=(e,t)=>e.element(vs(t,hs.THROUGHPUT_PDF)).w,Es=(e,t)=>e.element(vs(t,hs.RADIANCE_ALPHA)),Ds=e=>(0,n.uint)(e).mul(1),Os=(e,t,r,i,a,o=null)=>{let s=Ds(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))))},ks=(e,t,r)=>{let i=Ds(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))))},As=(e,t)=>e.element(Ds(t)),js=e=>(0,n.unpackUnorm2x16)(e.w).y,Ms=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)},Ns=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),Ps=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)))},Fs=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(vs(t,hs.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)))},Is=(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(Ps(s).shiftLeft(22))),e.element(vs(t,hs.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Ls=(e,t,r,i)=>e.element(vs(t,hs.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Rs=(e,t,r,i)=>e.element(vs(t,hs.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),zs=(e,t,n)=>e.element(vs(t,hs.RADIANCE_ALPHA)).assign(n),Bs=(e,t)=>e.element(vs(t,gs.DIST_TRI_BARY)).x,Vs=(e,t)=>(0,n.floatBitsToUint)(e.element(vs(t,gs.DIST_TRI_BARY)).y),Hs=(e,t)=>e.element(vs(t,gs.DIST_TRI_BARY)).zw,Us=(e,t)=>e.element(vs(t,gs.NORMAL_MAT)).xyz,Ws=(e,t)=>(0,n.uint)((0,n.floatBitsToUint)(e.element(vs(t,gs.NORMAL_MAT)).w).bitAnd(65535)),Gs=(e,t,r,i,a,o,s,c,l)=>{e.element(vs(t,gs.DIST_TRI_BARY)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i),a,o)),e.element(vs(t,gs.NORMAL_MAT)).assign((0,n.vec4)(s,(0,n.uintBitsToFloat)(c.bitOr(l.shiftLeft(16)))))},Ks=(e,t)=>{let r=e.element(vs(t,hs.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}},qs=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(vs(t,hs.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),Js=(e,t)=>e.element(vs(t,hs.MEDIUM_SIGMA_A)).xyz,Ys=(e,t,r)=>{let i=e.element(vs(t,hs.MEDIUM_SIGMA_A)).w.toVar();e.element(vs(t,hs.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},Xs=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))},Zs=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),Qs=(e,t)=>Zs((0,n.floatBitsToUint)(e.element(vs(t,hs.MEDIUM_SIGMA_A)).w)),$s=(e,t,r)=>{let i=e.element(vs(t,hs.MEDIUM_SIGMA_A)).xyz.toVar();e.element(vs(t,hs.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(Xs(r))))},ec=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).bitAnd(255)),tc=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),nc=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),rc=(e,t)=>{let n=e.element(vs(t,hs.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},ic=(e,t,r,i)=>e.element(vs(t,hs.SSS_SIGMA_S)).assign((0,n.vec4)(r,i)),ac=kt(`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},oc=65535,sc={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},cc=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=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1),i=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);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=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);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,ac.debug(`queues capacity ${J.n(e)} · ${J.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(){ys(this._renderer,this._countersAttr),ys(this._renderer,this._bounceCountsAttr),ys(this._renderer,this._attrA),ys(this._renderer,this._attrB),ys(this._renderer,this._sortAttr),ys(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}},lc={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},uc={[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 dc(e){return(lc[e.format]??4)*(uc[e.type]??4)}function fc(e){return e?.array?.byteLength||0}function pc(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*dc(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*dc(e)}var mc=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.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: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*dc(e));return a}return this._isResident(e)?pc(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(` `)}]`}},hc=kt(`wavefront`),gc=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);hc.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>hc.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.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()}},_c=(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}),vc=(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(),_=_c(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=re(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(ar({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)))}),Dn({origin:v,direction:y})});function yc(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=L({state:he({pixelCoord:S,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),T=me(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=Dn.wrap(vc(E,w,s,c,l,u,d,f,p,m,h,g,_,v,y));Is(t,x,D.origin,(0,n.int)(0),(0,n.int)(0)),Ls(t,x,D.direction,(0,n.uint)(sc.ACTIVE)),Rs(t,x,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),zs(t,x,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(k,()=>{Os(i,x,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),$s(t,x,(0,n.vec3)(1))}),qs(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 bc=32,xc=4096,Sc=4,Cc=8,wc=1e8,Tc=()=>(0,n.array)(`int`,bc).toVar(),Ec=(0,n.wgslFn)(`
|
|
471
|
+
`),Ta=kt(`shader`),Ea=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),Ta.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;Ji(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();ha(d);let f=e.iesProfiles?(0,n.texture)(e.iesProfiles):u();ya(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}},Da=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 Oa;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 Oa;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}}},Oa=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}},ka=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}},Aa=kt(`bvh`),ja=null;function Ma(e){ja=e}var Na={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},Pa=Na.FLOATS_PER_TRIANGLE,Fa=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}},Ia=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=this.triangles,n=Na.POSITION_A_OFFSET,r=Na.POSITION_B_OFFSET,i=Na.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*Pa,o=t[e+n],s=t[e+n+1],c=t[e+n+2],l=t[e+r],u=t[e+r+1],d=t[e+r+2],f=t[e+i],p=t[e+i+1],m=t[e+i+2],h=a*3;this.centroids[h]=(o+l+f)/3,this.centroids[h+1]=(s+u+p)/3,this.centroids[h+2]=(c+d+m)/3,this.bMin[h]=o<l?o<f?o:f:l<f?l:f,this.bMin[h+1]=s<u?s<p?s:p:u<p?u:p,this.bMin[h+2]=c<d?c<m?c:m:d<m?d:m,this.bMax[h]=o>l?o>f?o:f:l>f?l:f,this.bMax[h+1]=s>u?s>p?s:p:u>p?u:p,this.bMax[h+2]=c>d?c>m?c:m:d>m?d:m,this.indices[a]=a}}expandBits(e){return e=e*65537&4278190335,e=e*257&251719695,e=e*17&3272356035,e=e*5&1227133513,e}morton3D(e,t,n){return(this.expandBits(n)<<2)+(this.expandBits(t)<<1)+this.expandBits(e)}computeMortonCodeForIndex(e,t,n,r,i,a,o){let s=this.centroids,c=e*3,l=(1<<this.mortonBits)-1,u=i>0?(s[c]-t)/i:0,d=a>0?(s[c+1]-n)/a:0,f=o>0?(s[c+2]-r)/o:0,p=Math.max(0,Math.min(l,Math.floor(u*l))),m=Math.max(0,Math.min(l,Math.floor(d*l))),h=Math.max(0,Math.min(l,Math.floor(f*l)));return this.morton3D(p,m,h)}sortTrianglesByMortonCode(){let e=this.totalTriangles;if(!this.useMortonCodes||e<this.mortonClusterThreshold)return;let t=performance.now(),n=this.centroids,r=this.indices,i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let t=0;t<e;t++){let e=r[t]*3,u=n[e],d=n[e+1],f=n[e+2];u<i&&(i=u),d<a&&(a=d),f<o&&(o=f),u>s&&(s=u),d>c&&(c=d),f>l&&(l=f)}let u=s-i,d=c-a,f=l-o,p=this.mortonCodes,m=(1<<this.mortonBits)-1,h=u>0?m/u:0,g=d>0?m/d:0,_=f>0?m/f:0;for(let t=0;t<e;t++){let e=r[t],s=e*3,c=(n[s]-i)*h,l=(n[s+1]-a)*g,u=(n[s+2]-o)*_;c=c<0?0:(c>m?m:c)|0,l=l<0?0:(l>m?m:l)|0,u=u<0?0:(u>m?m:u)|0,c=c*65537&4278190335,c=c*257&251719695,c=c*17&3272356035,c=c*5&1227133513,l=l*65537&4278190335,l=l*257&251719695,l=l*17&3272356035,l=l*5&1227133513,u=u*65537&4278190335,u=u*257&251719695,u=u*17&3272356035,u=u*5&1227133513,p[e]=(u<<2)+(l<<1)+c}let v=new Uint32Array(e),y=new Uint32Array(256);for(let t=0;t<32;t+=8){y.fill(0);for(let n=0;n<e;n++)y[p[r[n]]>>>t&255]++;let n=0;for(let e=0;e<256;e++){let t=y[e];y[e]=n,n+=t}for(let n=0;n<e;n++){let e=p[r[n]]>>>t&255;v[y[e]++]=r[n]}r.set(v)}this.splitStats.mortonSortTime+=performance.now()-t}build(e,t=30,n=null){return this.totalTriangles=e.byteLength/(Pa*4),this.processedTriangles=0,this.lastProgressUpdate=performance.now(),this.useWorker&&ja&&typeof Worker<`u`?new Promise((r,i)=>{let a=a=>{let o=this.totalTriangles,s=typeof SharedArrayBuffer<`u`;Aa.debug(`SharedArrayBuffer ${s?`enabled`:`unavailable (using transfer fallback)`}`);let c=s?new SharedArrayBuffer(o*Pa*4):null;a.onmessage=e=>{let{bvhData:t,triangles:o,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){a.terminate(),i(Error(l));return}if(u!==void 0&&n){n(u);return}d&&(this.splitStats=d),a.terminate(),r({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):o,originalToBvh:s||null})},a.onerror=e=>{a.terminate(),i(e)};let l=e.buffer,u={triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:o,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:{enabled:this.enableTreeletOptimization,size:this.treeletSize,passes:this.treeletOptimizationPasses,minImprovement:this.treeletMinImprovement},reinsertionOptimization:{enabled:this.enableReinsertionOptimization,batchSizeRatio:this.reinsertionBatchSizeRatio,maxIterations:this.reinsertionMaxIterations}};a.postMessage(u,[l])};try{a(ja())}catch(i){Aa.warn(`worker creation failed, falling back to synchronous build:`,i),r(this._buildSyncAndFlatten(e,t,n))}}):new Promise(r=>{r(this._buildSyncAndFlatten(e,t,n))})}_buildSyncAndFlatten(e,t,n){let r=this.buildSync(e,t,n);return{bvhData:this.flattenBVH(r),bvhRoot:!0,reorderedTriangles:this.reorderedTriangleData||null,originalToBvh:this.originalToBvhMap||null}}buildSync(e,t=30,n=null,r=null){let i=performance.now();this.totalNodes=0,this.processedTriangles=0,this.triangles=e,this.totalTriangles=e.byteLength/(Pa*4),this.lastProgressUpdate=performance.now(),this.splitStats={sahSplits:0,objectMedianSplits:0,spatialMedianSplits:0,failedSplits:0,avgBinsUsed:0,totalSplitAttempts:0,mortonSortTime:0,totalBuildTime:0,treeletOptimizationTime:0,treeletsProcessed:0,treeletsImproved:0,averageSAHImprovement:0,reinsertionOptimizationTime:0,reinsertionsApplied:0,reinsertionIterations:0,saOrderTime:0,initTime:0,sahBuildTime:0,reorderTime:0};let a=this.totalTriangles,o=performance.now();this.centroids=new Float32Array(a*3),this.bMin=new Float32Array(a*3),this.bMax=new Float32Array(a*3),this.indices=new Uint32Array(a),this.mortonCodes=new Uint32Array(a),this.initializeTriangleArrays(),this.splitStats.initTime=performance.now()-o,this.sortTrianglesByMortonCode();let s=performance.now(),c=this.buildNodeRecursive(0,a,t,n);if(this.splitStats.sahBuildTime=performance.now()-s,this.enableTreeletOptimization&&this.totalTriangles>1e3){let e=this.totalTriangles>this.treeletComplexityThreshold?3:this.treeletSize,t=new Da(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){Aa.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 ka(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){Aa.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 Float32Array(a*Pa);for(let e=0;e<a;e++){let t=this.indices[e]*Pa,n=e*Pa;f.set(d.subarray(t,t+Pa),n)}this.reorderedTriangleData=f;let p=new Uint32Array(a);for(let e=0;e<a;e++)p[this.indices[e]]=e;this.originalToBvhMap=p,this.splitStats.reorderTime=performance.now()-u,this.splitStats.totalBuildTime=performance.now()-i;let m=this.splitStats.totalBuildTime,h=this.splitStats;return Aa.debug(`${J.n(a)} tris → ${J.n(this.totalNodes)} nodes in ${J.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 Fa;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 Fa;this.totalNodes++;let d=t-e;if(i===void 0?this.updateNodeBounds(u,e,t):(u.minX=i,u.minY=a,u.minZ=o,u.maxX=s,u.maxY=c,u.maxZ=l),d<=this.maxLeafSize||n<=0)return u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;let f=this.findBestSplitPositionSAH(e,t,u);if(!f.success)return this.splitStats.failedSplits++,u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u;f.method===`SAH`?this.splitStats.sahSplits++:f.method===`object_median`?this.splitStats.objectMedianSplits++:f.method===`spatial_median`&&this.splitStats.spatialMedianSplits++,this.partitionWithBounds(e,t,f.axis,f.pos);let p=this._partResult,m=p.mid,h=p.lMinX,g=p.lMinY,_=p.lMinZ,v=p.lMaxX,y=p.lMaxY,b=p.lMaxZ,x=p.rMinX,S=p.rMinY,C=p.rMinZ,w=p.rMaxX,T=p.rMaxY,E=p.rMaxZ;return m===e||m===t?(u.triangleOffset=e,u.triangleCount=d,this.updateProgress(d,r),u):(u.leftChild=this.buildNodeRecursive(e,m,n-1,r,h,g,_,v,y,b),u.rightChild=this.buildNodeRecursive(m,t,n-1,r,x,S,C,w,T,E),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}},Q={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},La=Q.FLOATS_PER_TRIANGLE,Ra=16,za=-1,Ba=-2,Va=class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(e,t,n){let r=n.length;for(let i=0;i<r;i++){let r=n[i],a=i*La,o=r*9,s=t[o],c=t[o+1],l=t[o+2],u=t[o+3],d=t[o+4],f=t[o+5],p=t[o+6],m=t[o+7],h=t[o+8];e[a+Q.POSITION_A_OFFSET]=s,e[a+Q.POSITION_A_OFFSET+1]=c,e[a+Q.POSITION_A_OFFSET+2]=l,e[a+Q.POSITION_B_OFFSET]=u,e[a+Q.POSITION_B_OFFSET+1]=d,e[a+Q.POSITION_B_OFFSET+2]=f,e[a+Q.POSITION_C_OFFSET]=p,e[a+Q.POSITION_C_OFFSET+1]=m,e[a+Q.POSITION_C_OFFSET+2]=h;let g=u-s,_=d-c,v=f-l,y=p-s,b=m-c,x=h-l,S=_*x-v*b,C=v*y-g*x,w=g*b-_*y;e[a+Q.NORMAL_A_OFFSET]=S,e[a+Q.NORMAL_A_OFFSET+1]=C,e[a+Q.NORMAL_A_OFFSET+2]=w,e[a+Q.NORMAL_B_OFFSET]=S,e[a+Q.NORMAL_B_OFFSET+1]=C,e[a+Q.NORMAL_B_OFFSET+2]=w,e[a+Q.NORMAL_C_OFFSET]=S,e[a+Q.NORMAL_C_OFFSET+1]=C,e[a+Q.NORMAL_C_OFFSET+2]=w}}refitRange(e,t,n,r){r>this._boundsNodeCount&&(this._bounds=new Float32Array(r*6),this._boundsNodeCount=r);let i=this._bounds,a=n+r;for(let r=a-1;r>=n;r--){let a=r*Ra,o=(r-n)*6;if(e[a+3]===za){let n=e[a],r=e[a+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<r;e++){let r=(n+e)*La,i=t[r+Q.POSITION_A_OFFSET],a=t[r+Q.POSITION_A_OFFSET+1],o=t[r+Q.POSITION_A_OFFSET+2],p=t[r+Q.POSITION_B_OFFSET],m=t[r+Q.POSITION_B_OFFSET+1],h=t[r+Q.POSITION_B_OFFSET+2],g=t[r+Q.POSITION_C_OFFSET],_=t[r+Q.POSITION_C_OFFSET+1],v=t[r+Q.POSITION_C_OFFSET+2];s=Math.min(s,i,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,i,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}i[o]=s,i[o+1]=c,i[o+2]=l,i[o+3]=u,i[o+4]=d,i[o+5]=f}else{let t=e[a+3],r=e[a+7],s=(t-n)*6,c=(r-n)*6,l=i[s],u=i[s+1],d=i[s+2],f=i[s+3],p=i[s+4],m=i[s+5],h=i[c],g=i[c+1],_=i[c+2],v=i[c+3],y=i[c+4],b=i[c+5];e[a]=l,e[a+1]=u,e[a+2]=d,e[a+4]=f,e[a+5]=p,e[a+6]=m,e[a+8]=h,e[a+9]=g,e[a+10]=_,e[a+12]=v,e[a+13]=y,e[a+14]=b,i[o]=Math.min(l,h),i[o+1]=Math.min(u,g),i[o+2]=Math.min(d,_),i[o+3]=Math.max(f,v),i[o+4]=Math.max(p,y),i[o+5]=Math.max(m,b)}}}refit(e,t,n){n!==this._boundsNodeCount&&(this._bounds=new Float32Array(n*6),this._boundsNodeCount=n);let r=this._bounds;for(let i=n-1;i>=0;i--){let n=i*Ra,a=i*6,o=e[n+3];if(o===za){let i=e[n],o=e[n+1],s=1/0,c=1/0,l=1/0,u=-1/0,d=-1/0,f=-1/0;for(let e=0;e<o;e++){let n=(i+e)*La,r=t[n+Q.POSITION_A_OFFSET],a=t[n+Q.POSITION_A_OFFSET+1],o=t[n+Q.POSITION_A_OFFSET+2],p=t[n+Q.POSITION_B_OFFSET],m=t[n+Q.POSITION_B_OFFSET+1],h=t[n+Q.POSITION_B_OFFSET+2],g=t[n+Q.POSITION_C_OFFSET],_=t[n+Q.POSITION_C_OFFSET+1],v=t[n+Q.POSITION_C_OFFSET+2];s=Math.min(s,r,p,g),c=Math.min(c,a,m,_),l=Math.min(l,o,h,v),u=Math.max(u,r,p,g),d=Math.max(d,a,m,_),f=Math.max(f,o,h,v)}r[a]=s,r[a+1]=c,r[a+2]=l,r[a+3]=u,r[a+4]=d,r[a+5]=f}else if(o===Ba){let t=e[n]*6;r[a]=r[t],r[a+1]=r[t+1],r[a+2]=r[t+2],r[a+3]=r[t+3],r[a+4]=r[t+4],r[a+5]=r[t+5]}else{let t=e[n+3],i=e[n+7],o=t*6,s=i*6,c=r[o],l=r[o+1],u=r[o+2],d=r[o+3],f=r[o+4],p=r[o+5],m=r[s],h=r[s+1],g=r[s+2],_=r[s+3],v=r[s+4],y=r[s+5];e[n]=c,e[n+1]=l,e[n+2]=u,e[n+4]=d,e[n+5]=f,e[n+6]=p,e[n+8]=m,e[n+9]=h,e[n+10]=g,e[n+12]=_,e[n+13]=v,e[n+14]=y,r[a]=Math.min(c,m),r[a+1]=Math.min(l,h),r[a+2]=Math.min(u,g),r[a+3]=Math.max(d,_),r[a+4]=Math.max(f,v),r[a+5]=Math.max(p,y)}}}},Ha="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={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},C=S.FLOATS_PER_TRIANGLE;var w=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}},T=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=this.triangles,n=S.POSITION_A_OFFSET,r=S.POSITION_B_OFFSET,i=S.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*C,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/(C*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/(C*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 Float32Array(s*C);for(let e=0;e<s;e++){let t=this.indices[e]*C,n=e*C;m.set(p.subarray(t,t+C),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 w;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,T=m.rMinZ,E=m.rMaxX,D=m.rMaxY,O=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,T,E,D,O),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new w;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,T=p.rMaxX,E=p.rMaxY,D=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,T,E,D),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};const E=y(`bvh`);self.onmessage=function(e){let t=e.data,n=t.type;b(t.logLevel),n===`buildPhase1`?D(t):n===`assemble`?O(t):k(t)};function D(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 T;d&&e.setTreeletConfig(d);let f=u?e=>{self.postMessage({type:`progress`,progress:e})}:null;e.triangles=new Float32Array(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;E.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){E.error(`phase 1 failed:`,e),self.postMessage({type:`error`,error:e.message})}}function O(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 T().assembleParallelBVH(t,n,r,i),u=new Uint32Array(o),d=new Float32Array(a),f=new Float32Array(s);for(let e=0;e<c;e++){let t=u[e]*32,n=e*32;f.set(d.subarray(t,t+32),n)}let p=new Uint32Array(c);for(let e=0;e<c;e++)p[u[e]]=e;let m=performance.now()-e;E.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){E.error(`assembly failed:`,e),self.postMessage({type:`error`,error:e.message})}}function k(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 T;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 Float32Array(t):new Float32Array(t,n,r/4),u=c?new Float32Array(c):null,d=p.buildSync(l,i,e,u),f=performance.now(),m=p.flattenBVH(d),h=performance.now()-f;E.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/32,treeletStats:p.splitStats},e)}else{let e=p.reorderedTriangleData,t=e.byteLength/128,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){E.error(`build failed:`,e),self.postMessage({error:e.message})}}",Ua=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ha],{type:`text/javascript;charset=utf-8`});function Wa(e){let t;try{if(t=Ua&&(self.URL||self.webkitURL).createObjectURL(Ua),!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(Ha),{type:`module`,name:e?.name})}}var Ga="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={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20,UV_AB_OFFSET:24,UV_C_MAT_OFFSET:28},S=x.FLOATS_PER_TRIANGLE;var C=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}},w=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=this.triangles,n=x.POSITION_A_OFFSET,r=x.POSITION_B_OFFSET,i=x.POSITION_C_OFFSET;for(let a=0;a<e;a++){let e=a*S,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/(S*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/(S*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 Float32Array(s*S);for(let e=0;e<s;e++){let t=this.indices[e]*S,n=e*S;m.set(p.subarray(t,t+S),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 C;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,w=m.rMinY,T=m.rMinZ,E=m.rMaxX,D=m.rMaxY,O=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,w,T,E,D,O),d)}buildNodeRecursive(e,t,n,r,i,a,o,s,c,l){let u=new C;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,w=p.rMinZ,T=p.rMaxX,E=p.rMaxY,D=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,w,T,E,D),u)}partitionWithBounds(e,t,n,r){let i=this.indices,a=this.centroids,o=this.bMin,s=this.bMax,c=e,l=t-1,u=1/0,d=1/0,f=1/0,p=-1/0,m=-1/0,h=-1/0,g=1/0,_=1/0,v=1/0,y=-1/0,b=-1/0,x=-1/0;for(;c<=l;){let e=i[c],t=e*3;a[t+n]<=r?(o[t]<u&&(u=o[t]),o[t+1]<d&&(d=o[t+1]),o[t+2]<f&&(f=o[t+2]),s[t]>p&&(p=s[t]),s[t+1]>m&&(m=s[t+1]),s[t+2]>h&&(h=s[t+2]),c++):(o[t]<g&&(g=o[t]),o[t+1]<_&&(_=o[t+1]),o[t+2]<v&&(v=o[t+2]),s[t]>y&&(y=s[t]),s[t+1]>b&&(b=s[t+1]),s[t+2]>x&&(x=s[t+2]),i[c]=i[l],i[l]=e,l--)}let S=this._partResult;return S.mid=c,S.lMinX=u,S.lMinY=d,S.lMinZ=f,S.lMaxX=p,S.lMaxY=m,S.lMaxZ=h,S.rMinX=g,S.rMinY=_,S.rMinZ=v,S.rMaxX=y,S.rMaxY=b,S.rMaxZ=x,S}updateNodeBounds(e,t,n){let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0,l=this.indices,u=this.bMin,d=this.bMax;for(let e=t;e<n;e++){let t=l[e]*3;u[t]<r&&(r=u[t]),u[t+1]<i&&(i=u[t+1]),u[t+2]<a&&(a=u[t+2]),d[t]>o&&(o=d[t]),d[t+1]>s&&(s=d[t+1]),d[t+2]>c&&(c=d[t+2])}e.minX=r,e.minY=i,e.minZ=a,e.maxX=o,e.maxY=s,e.maxZ=c}findBestSplitPositionSAH(e,t,n){let r=1/0,i=-1,a=0,o=this.computeSurfaceAreaFlat(n.minX,n.minY,n.minZ,n.maxX,n.maxY,n.maxZ),s=t-e,c=this.intersectionCost*s,l=this.getOptimalBinCount(s);this.splitStats.totalSplitAttempts++,this.splitStats.avgBinsUsed=(this.splitStats.avgBinsUsed*(this.splitStats.totalSplitAttempts-1)+l)/this.splitStats.totalSplitAttempts;let u=this.indices,d=this.centroids,f=this.bMin,p=this.bMax,m=this.binBoundsMin,h=this.binBoundsMax,g=this.binCounts,_=this.leftPrefixMin,v=this.leftPrefixMax,y=this.leftPrefixCount,b=this.rightPrefixMin,x=this.rightPrefixMax,S=this.rightPrefixCount,C=1/0,w=-1/0,T=1/0,E=-1/0,D=1/0,O=-1/0;for(let n=e;n<t;n++){let e=u[n]*3,t=d[e],r=d[e+1],i=d[e+2];t<C&&(C=t),t>w&&(w=t),r<T&&(T=r),r>E&&(E=r),i<D&&(D=i),i>O&&(O=i)}let k=[C,T,D],A=[w,E,O];for(let n=0;n<3;n++){let s=k[n],C=A[n];if(C-s<1e-6)continue;for(let e=0;e<l;e++){g[e]=0;let t=e*3;m[t]=1/0,m[t+1]=1/0,m[t+2]=1/0,h[t]=-1/0,h[t+1]=-1/0,h[t+2]=-1/0}let w=l/(C-s);for(let r=e;r<t;r++){let e=u[r],t=d[e*3+n],i=Math.floor((t-s)*w);i>=l&&(i=l-1),g[i]++;let a=i*3,o=e*3;f[o]<m[a]&&(m[a]=f[o]),f[o+1]<m[a+1]&&(m[a+1]=f[o+1]),f[o+2]<m[a+2]&&(m[a+2]=f[o+2]),p[o]>h[a]&&(h[a]=p[o]),p[o+1]>h[a+1]&&(h[a+1]=p[o+1]),p[o+2]>h[a+2]&&(h[a+2]=p[o+2])}y[0]=g[0],_[0]=m[0],_[1]=m[1],_[2]=m[2],v[0]=h[0],v[1]=h[1],v[2]=h[2];for(let e=1;e<l;e++){let t=e*3,n=(e-1)*3;y[e]=y[e-1]+g[e];let r=_[n],i=m[t],a=_[n+1],o=m[t+1],s=_[n+2],c=m[t+2];_[t]=r<i?r:i,_[t+1]=a<o?a:o,_[t+2]=s<c?s:c;let l=v[n],u=h[t],d=v[n+1],f=h[t+1],p=v[n+2],b=h[t+2];v[t]=l>u?l:u,v[t+1]=d>f?d:f,v[t+2]=p>b?p:b}let T=l-1,E=T*3;S[T]=g[T],b[E]=m[E],b[E+1]=m[E+1],b[E+2]=m[E+2],x[E]=h[E],x[E+1]=h[E+1],x[E+2]=h[E+2];for(let e=T-1;e>=0;e--){let t=e*3,n=(e+1)*3;S[e]=S[e+1]+g[e];let r=b[n],i=m[t],a=b[n+1],o=m[t+1],s=b[n+2],c=m[t+2];b[t]=r<i?r:i,b[t+1]=a<o?a:o,b[t+2]=s<c?s:c;let l=x[n],u=h[t],d=x[n+1],f=h[t+1],p=x[n+2],_=h[t+2];x[t]=l>u?l:u,x[t+1]=d>f?d:f,x[t+2]=p>_?p:_}for(let e=1;e<l;e++){let t=(e-1)*3,u=e*3,d=y[e-1],f=S[e];if(d===0||f===0)continue;let p=v[t]-_[t],m=v[t+1]-_[t+1],h=v[t+2]-_[t+2],g=2*(p*m+m*h+h*p),w=x[u]-b[u],T=x[u+1]-b[u+1],E=x[u+2]-b[u+2],D=2*(w*T+T*E+E*w),O=this.traversalCost+g/o*d*this.intersectionCost+D/o*f*this.intersectionCost;O<r&&O<c&&(r=O,i=n,a=s+(C-s)*e/l)}}return i===-1?this.enableObjectMedianFallback?this.findObjectMedianSplit(e,t):this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`fallbacks_disabled`}:{success:!0,axis:i,pos:a,method:`SAH`,binsUsed:l}}findObjectMedianSplit(e,t){let n=this.indices,r=this.centroids,i=-1,a=-1;for(let o=0;o<3;o++){let s=1/0,c=-1/0;for(let i=e;i<t;i++){let e=r[n[i]*3+o];e<s&&(s=e),e>c&&(c=e)}let l=c-s;l>a&&(a=l,i=o)}if(i===-1||a<1e-10)return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_failed`};let o=t-e,s=e+Math.floor(o/2);this.quickselect(e,t,s,i);let c=r[n[s]*3+i],l=!0;for(let e=s+1;e<t;e++)if(r[n[e]*3+i]>c){l=!1;break}if(l){let a=-1/0;for(let t=e;t<s;t++){let e=r[n[t]*3+i];e>a&&(a=e)}if(a<c)c=(a+c)*.5;else return this.enableSpatialMedianFallback?this.findSpatialMedianSplit(e,t):{success:!1,method:`object_median_degenerate`}}return{success:!0,axis:i,pos:c,method:`object_median`}}findSpatialMedianSplit(e,t){let n=this.indices,r=this.centroids,i=this.bMin,a=this.bMax,o=-1,s=-1,c=0,l=0;for(let r=0;r<3;r++){let u=1/0,d=-1/0;for(let o=e;o<t;o++){let e=n[o]*3+r;i[e]<u&&(u=i[e]),a[e]>d&&(d=a[e])}let f=d-u;f>s&&(s=f,o=r,c=u,l=d)}if(o===-1||s<1e-12)return{success:!1,method:`spatial_median_failed`};let u=(c+l)*.5,d=t-e,f=0;for(let i=e;i<t;i++)r[n[i]*3+o]<=u&&f++;if(f===0||f===d){let i=e+Math.floor(d/2);this.quickselect(e,t,i,o);let a=r[n[i]*3+o],s=!0;for(let i=e;i<t;i++)if(r[n[i]*3+o]!==a){s=!1;break}if(s)return{success:!1,method:`spatial_median_degenerate`};let c=-1/0;for(let t=e;t<i;t++){let e=r[n[t]*3+o];e>c&&(c=e)}if(c<a)u=(c+a)*.5;else{let e=1/0;for(let a=i+1;a<t;a++){let t=r[n[a]*3+o];t<e&&(e=t)}u=(a+e)*.5}}return{success:!0,axis:o,pos:u,method:`spatial_median`}}quickselect(e,t,n,r){let i=this.indices,a=this.centroids,o=e,s=t-1;for(;o<s;){let e=o+s>>>1,t=a[i[o]*3+r],c=a[i[e]*3+r],l=a[i[s]*3+r];if(t>c){let t=i[o];i[o]=i[e],i[e]=t}if(t>l){let e=i[o];i[o]=i[s],i[s]=e}if(c>l){let t=i[e];i[e]=i[s],i[s]=t}let u=a[i[e]*3+r],d=o,f=s;for(;d<=f;){for(;a[i[d]*3+r]<u;)d++;for(;a[i[f]*3+r]>u;)f--;if(d<=f){let e=i[d];i[d]=i[f],i[f]=e,d++,f--}}f<n&&(o=d),d>n&&(s=f)}}applySAOrdering(e){if(!e||!e.leftChild)return;let t=[e],n=[];for(;t.length>0;){let e=t.pop();!e.leftChild||!e.rightChild||(n.push(e),t.push(e.leftChild),t.push(e.rightChild))}for(let e=n.length-1;e>=0;e--){let t=n[e],r=t.leftChild,i=t.rightChild,a=r.maxX-r.minX,o=r.maxY-r.minY,s=r.maxZ-r.minZ,c=i.maxX-i.minX,l=i.maxY-i.minY,u=i.maxZ-i.minZ;c*l+l*u+u*c>a*o+o*s+s*a&&(t.leftChild=i,t.rightChild=r)}}flattenBVH(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e],i=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[i]=e.minX,r[i+1]=e.minY,r[i+2]=e.minZ,r[i+3]=e._flatIndex,r[i+4]=e.maxX,r[i+5]=e.maxY,r[i+6]=e.maxZ,r[i+7]=t._flatIndex,r[i+8]=t.minX,r[i+9]=t.minY,r[i+10]=t.minZ,r[i+12]=t.maxX,r[i+13]=t.maxY,r[i+14]=t.maxZ}else r[i]=n.triangleOffset,r[i+1]=n.triangleCount,r[i+3]=-1}return r}flattenBVHWithFrontier(e){let t=[],n=[e];for(;n.length>0;){let e=n.pop();e._flatIndex=t.length,t.push(e),e.rightChild&&n.push(e.rightChild),e.leftChild&&n.push(e.leftChild)}let r=new Float32Array(t.length*16),i=[];for(let e=0;e<t.length;e++){let n=t[e],a=e*16;if(n.leftChild){let e=n.leftChild,t=n.rightChild;r[a]=e.minX,r[a+1]=e.minY,r[a+2]=e.minZ,r[a+3]=e._flatIndex,r[a+4]=e.maxX,r[a+5]=e.maxY,r[a+6]=e.maxZ,r[a+7]=t._flatIndex,r[a+8]=t.minX,r[a+9]=t.minY,r[a+10]=t.minZ,r[a+12]=t.maxX,r[a+13]=t.maxY,r[a+14]=t.maxZ}else if(n.isFrontier){let t=n.frontierTaskId;r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+2]=t,r[a+3]=-2,i.push({taskId:t,flatIndex:e})}else r[a]=n.triangleOffset,r[a+1]=n.triangleCount,r[a+3]=-1}return{flatData:r,frontierMap:i,nodeCount:t.length}}assembleParallelBVH(e,t,n,r){let i=[...r].sort((e,t)=>e.taskId-t.taskId),a=t;for(let e=0;e<i.length;e++)a+=i[e].nodeCount;let o=new Float32Array(a*16);o.set(e);let s=new Map;for(let e of n)s.set(e.taskId,e.flatIndex);let c=t;for(let e=0;e<i.length;e++){let t=i[e],n=t.flatData,r=t.nodeCount,a=c*16;o.set(n,a);for(let e=0;e<r;e++){let t=a+e*16;o[t+3]!==-1&&(o[t+3]+=c,o[t+7]+=c)}let l=s.get(t.taskId);if(l!==void 0){let e=l*16,t=a;for(let n=0;n<16;n++)o[e+n]=o[t+n]}c+=r}return o}computeSurfaceAreaFlat(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}};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 w;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})}}};",Ka=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ga],{type:`text/javascript;charset=utf-8`});function qa(e){let t;try{if(t=Ka&&(self.URL||self.webkitURL).createObjectURL(Ka),!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(Ga),{type:`module`,name:e?.name})}}Ma(()=>new Wa);var Ja=kt(`bvh`),Ya=32,Xa=5e4,Za=8;function Qa(e,t,n,r){let i=e.byteLength/(Ya*4),a=Math.min(navigator.hardwareConcurrency||4,Za),o=Math.ceil(Math.log2(a*2.5+1));return Ja.debug(`parallel build ${J.n(i)} triangles · ${a} workers · parallelDepth ${o}`),new Promise((s,c)=>{(async()=>{let c=new SharedArrayBuffer(e.byteLength);new Float32Array(c).set(e);let l=new SharedArrayBuffer(i*3*4),u=new SharedArrayBuffer(i*3*4),d=new SharedArrayBuffer(i*3*4),f=new SharedArrayBuffer(i*4),p=new SharedArrayBuffer(i*4),m=new SharedArrayBuffer(i*Ya*4),h=new Wa,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,Ja.warn(`parallel build failed (${e}), falling back to single worker`),b();let i=new ArrayBuffer(c.byteLength);new Float32Array(i).set(new Float32Array(c)),s(eo(new Float32Array(i),t,n,r))};h.onerror=e=>{x(`coordinator error: ${e.message}`)},h.onmessage=e=>{let t=e.data;if(t.error||t.type===`error`){x(t.error);return}if(t.type===`progress`&&n){n(Math.floor(t.progress*.3));return}if(t.type===`phase1Result`){g=t.splitStats,$a(t,a,c,l,u,d,f,m,i,n,h,_,b,x,s,v,r).catch(e=>x(e.message));return}if(t.type===`assembleResult`){y=!0,b();let e=new Float32Array(m);s({bvhData:t.bvhData,bvhRoot:!0,reorderedTriangles:e,originalToBvh:t.originalToBvh||null,splitStats:g||{}});return}},n&&n(0),h.postMessage({type:`buildPhase1`,sharedTriangleData:c,sharedCentroids:l,sharedBMin:u,sharedBMax:d,sharedIndices:f,sharedMortonCodes:p,triangleCount:i,depth:t,parallelDepth:o,reportProgress:!!n,treeletOptimization:r.treeletOptimization})})().catch(e=>{Ja.warn(`parallel build setup failed:`,e),c(e)})})}async function $a(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){Ja.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}Ja.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 qa;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 eo(e,t,n,r){return new Promise((i,a)=>{(async()=>{let o=new Wa,s=e.byteLength/(Ya*4),c=typeof SharedArrayBuffer<`u`?new SharedArrayBuffer(s*Ya*4):null;o.onmessage=e=>{let{bvhData:t,triangles:r,originalToBvh:s,error:l,progress:u,treeletStats:d}=e.data;if(l){o.terminate(),a(Error(l));return}if(u!==void 0&&n){n(u);return}o.terminate(),i({bvhData:t,bvhRoot:!0,reorderedTriangles:c?new Float32Array(c):r,originalToBvh:s||null,splitStats:d||{}})},o.onerror=e=>{o.terminate(),a(e)};let l=e.buffer;o.postMessage({triangleData:l,triangleByteOffset:e.byteOffset,triangleByteLength:e.byteLength,triangleCount:s,depth:t,reportProgress:!!n,sharedReorderBuffer:c,treeletOptimization:r.treeletOptimization,reinsertionOptimization:r.reinsertionOptimization},[l])})().catch(e=>{Ja.warn(`single worker fallback failed:`,e),a(e)})})}function to(e){return typeof Worker<`u`&&typeof SharedArrayBuffer<`u`&&e>=Xa}var no=16,ro=class{constructor(){this.minX=0,this.minY=0,this.minZ=0,this.maxX=0,this.maxY=0,this.maxZ=0,this.leftChild=null,this.rightChild=null,this.entryIndex=-1}},io=class{constructor(){this._flatBuffer=null,this._flatBufferCapacity=0}build(e){if(e.length===0)return{root:null,nodeCount:0};let t=[];for(let n=0;n<e.length;n++)t.push(n);let n=this._buildRecursive(e,t);return{root:n,nodeCount:this._countNodes(n)}}_buildRecursive(e,t){let n=new ro;if(t.length===1){let r=e[t[0]].worldAABB;return n.minX=r.minX,n.minY=r.minY,n.minZ=r.minZ,n.maxX=r.maxX,n.maxY=r.maxY,n.maxZ=r.maxZ,n.entryIndex=t[0],n}let r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let n of t){let t=e[n].worldAABB;t.minX<r&&(r=t.minX),t.minY<i&&(i=t.minY),t.minZ<a&&(a=t.minZ),t.maxX>o&&(o=t.maxX),t.maxY>s&&(s=t.maxY),t.maxZ>c&&(c=t.maxZ)}if(n.minX=r,n.minY=i,n.minZ=a,n.maxX=o,n.maxY=s,n.maxZ=c,t.length===2)return n.leftChild=this._buildRecursive(e,[t[0]]),n.rightChild=this._buildRecursive(e,[t[1]]),n;let l=this._surfaceArea(r,i,a,o,s,c),u=1/0,d=0,f=0;if(l>0&&isFinite(l))for(let n=0;n<3;n++){let r=t.slice().sort((t,r)=>{let i=e[t].worldAABB,a=e[r].worldAABB;return this._centroid(i,n)-this._centroid(a,n)});for(let t=1;t<r.length;t++){let i=this._computeGroupAABB(e,r,0,t),a=this._computeGroupAABB(e,r,t,r.length),o=this._surfaceArea(i.minX,i.minY,i.minZ,i.maxX,i.maxY,i.maxZ),s=this._surfaceArea(a.minX,a.minY,a.minZ,a.maxX,a.maxY,a.maxZ),c=1+(o*t+s*(r.length-t))/l;c<u&&(u=c,d=n,f=t)}}if(f<=0||f>=t.length){d=0;let e=o-r,n=s-i,l=c-a;n>e&&n>l?d=1:l>e&&(d=2),f=t.length>>1}let p=t.slice().sort((t,n)=>this._centroid(e[t].worldAABB,d)-this._centroid(e[n].worldAABB,d)),m=p.slice(0,f),h=p.slice(f);return n.leftChild=this._buildRecursive(e,m),n.rightChild=this._buildRecursive(e,h),n}flatten(e,t){if(!e)return new Float32Array;let n=[],r=[e];for(;r.length>0;){let e=r.pop();e._flatIndex=n.length,n.push(e),e.rightChild&&r.push(e.rightChild),e.leftChild&&r.push(e.leftChild)}let i=n.length*no;i>this._flatBufferCapacity&&(this._flatBuffer=new Float32Array(i),this._flatBufferCapacity=i);let a=this._flatBuffer;a.fill(0,0,i);for(let e=0;e<n.length;e++){let r=n[e],i=e*no;if(r.leftChild){let e=r.leftChild,t=r.rightChild;a[i]=e.minX,a[i+1]=e.minY,a[i+2]=e.minZ,a[i+3]=e._flatIndex,a[i+4]=e.maxX,a[i+5]=e.maxY,a[i+6]=e.maxZ,a[i+7]=t._flatIndex,a[i+8]=t.minX,a[i+9]=t.minY,a[i+10]=t.minZ,a[i+12]=t.maxX,a[i+13]=t.maxY,a[i+14]=t.maxZ}else{let n=t[r.entryIndex];a[i]=n.blasOffset,a[i+1]=r.entryIndex,a[i+2]=n.visible===!1?0:1,a[i+3]=Qe.BLAS_POINTER_LEAF,n.tlasLeafIndex=e}}return a.subarray(0,i)}_centroid(e,t){return t===0?(e.minX+e.maxX)*.5:t===1?(e.minY+e.maxY)*.5:(e.minZ+e.maxZ)*.5}_surfaceArea(e,t,n,r,i,a){let o=r-e,s=i-t,c=a-n;return 2*(o*s+s*c+c*o)}_computeGroupAABB(e,t,n,r){let i=1/0,a=1/0,o=1/0,s=-1/0,c=-1/0,l=-1/0;for(let u=n;u<r;u++){let n=e[t[u]].worldAABB;n.minX<i&&(i=n.minX),n.minY<a&&(a=n.minY),n.minZ<o&&(o=n.minZ),n.maxX>s&&(s=n.maxX),n.maxY>c&&(c=n.maxY),n.maxZ>l&&(l=n.maxZ)}return{minX:i,minY:a,minZ:o,maxX:s,maxY:c,maxZ:l}}_countNodes(e){if(!e)return 0;let t=0,n=[e];for(;n.length>0;){let e=n.pop();t++,e.leftChild&&n.push(e.leftChild),e.rightChild&&n.push(e.rightChild)}return t}},ao=class{constructor(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}allocate(e){this.entries=Array(e).fill(null)}setEntry({meshIndex:e,blasNodeCount:t,triOffset:n,triCount:r,originalToBvhMap:i,bvhData:a}){this.entries[e]={meshIndex:e,blasOffset:0,blasNodeCount:t,triOffset:n,triCount:r,worldAABB:null,originalToBvhMap:i,bvhData:a,visible:!0,tlasLeafIndex:-1}}setVisibility(e,t){let n=this.entries[e];n&&(n.visible=t)}computeAABBs(e){for(let t of this.entries)t&&(t.worldAABB=this._readRootAABB(t.bvhData,t,e))}recomputeAABB(e,t,n){let r=this.entries[e],i=t.subarray(r.blasOffset*16,r.blasOffset*16+16);r.worldAABB=this._readRootAABB(i,r,n)}_readRootAABB(e,t,n){if(e[3]===-1)return this._computeAABBFromTriangles(t,n);let r=e[0],i=e[1],a=e[2],o=e[4],s=e[5],c=e[6],l=e[8],u=e[9],d=e[10],f=e[12],p=e[13],m=e[14];return{minX:Math.min(r,l),minY:Math.min(i,u),minZ:Math.min(a,d),maxX:Math.max(o,f),maxY:Math.max(s,p),maxZ:Math.max(c,m)}}_computeAABBFromTriangles(e,t){let n=G.FLOATS_PER_TRIANGLE,r=1/0,i=1/0,a=1/0,o=-1/0,s=-1/0,c=-1/0;for(let l=0;l<e.triCount;l++){let u=(e.triOffset+l)*n;for(let e=0;e<=8;e+=4){let n=t[u+e],l=t[u+e+1],d=t[u+e+2];n<r&&(r=n),l<i&&(i=l),d<a&&(a=d),n>o&&(o=n),l>s&&(s=l),d>c&&(c=d)}}return{minX:r,minY:i,minZ:a,maxX:o,maxY:s,maxZ:c}}assignOffsets(e){this.tlasNodeCount=e;let t=e;for(let e of this.entries)e&&(e.blasOffset=t,t+=e.blasNodeCount);this.totalBLASNodes=t-e}get totalNodeCount(){return this.tlasNodeCount+this.totalBLASNodes}get count(){return this.entries.length}clear(){this.entries=[],this.totalBLASNodes=0,this.tlasNodeCount=0}},oo="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))}}",so=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,oo],{type:`text/javascript;charset=utf-8`});function co(e){let t;try{if(t=so&&(self.URL||self.webkitURL).createObjectURL(so),!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(oo),{type:`module`,name:e?.name})}}var lo=Object.freeze({ADAPTER_SOFTWARE:`adapter.software`,ASSET_UNREACHABLE:`asset.unreachable`,ASSET_AMBIGUOUS_ENTRY:`asset.ambiguous_entry`,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`}),uo=Object.freeze({ERROR:`error`,WARNING:`warning`}),fo=class extends Error{constructor(e){super(`[${e.code}] ${e.message}`),this.name=`EngineIssueError`,this.code=e.code,this.detail=e.detail}},po=class{constructor({strict:e=!1,onIssue:t=null}={}){this.strict=e===!0,this._onIssue=t,this._entries=[]}record(e,t,n={},r=uo.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===uo.ERROR)throw new fo(i);return i}warn(e,t,n){return this.record(e,t,n,uo.WARNING)}get list(){return this._entries.slice()}get errors(){return this._entries.filter(e=>e.severity===uo.ERROR)}clear(){this._entries.length=0}detach(){this._onIssue=null,this.strict=!1}},mo=e=>Math.min(Math.max(e,0),1);function ho(e,t,n,r,i){i[0]=mo(e),i[1]=mo(t),i[2]=mo(n)}function go(e,t,n,r,i){i[0]=mo(e*r),i[1]=mo(t*r),i[2]=mo(n*r)}function _o(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=mo(e/(e+1)),i[1]=mo(t/(t+1)),i[2]=mo(n/(n+1))}function vo(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 yo(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]=mo(1.60475*a-.53108*o-.07367*s),i[1]=mo(-.10208*a+1.10813*o-.00605*s),i[2]=mo(-.00327*a-.07276*o+1.07602*s)}function bo(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=mo((Math.log2(Math.max(c,1e-10))-d)/f),l=mo((Math.log2(Math.max(l,1e-10))-d)/f),u=mo((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]=mo(1.6605*m-.5876*h-.0728*g),i[1]=mo(-.1246*m+1.1329*h-.0083*g),i[2]=mo(-.0182*m-.1006*h+1.1187*g)}function xo(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 So=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),Co=new Map([[r.NoToneMapping,So(ho)],[r.LinearToneMapping,So(go)],[r.ReinhardToneMapping,So(_o)],[r.CineonToneMapping,So(vo)],[r.ACESFilmicToneMapping,So(yo)],[r.AgXToneMapping,So(bo)],[r.NeutralToneMapping,So(xo)]]),wo=1/2.2;function To(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function Eo(e,t){return t===r.NoToneMapping?1:e}var Do=.2126,Oo=.7152,ko=.0722;function Ao(e,t){if(t===1)return;let n=e[0]*Do+e[1]*Oo+e[2]*ko;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}function jo(e,{exposure:t,toneMapping:n,saturation:i=1,preserveAlpha:a=!1}){let o=Co.get(n)??Co.get(r.NoToneMapping),s=Eo(t,n),c=new Uint8ClampedArray(e.length),l=[0,0,0];for(let t=0;t<e.length;t+=4)l[0]=e[t]*s,l[1]=e[t+1]*s,l[2]=e[t+2]*s,Ao(l,i),o(l[0],l[1],l[2],1,l),c[t]=To(l[0])*255+.5,c[t+1]=To(l[1])*255+.5,c[t+2]=To(l[2])*255+.5,c[t+3]=a?e[t+3]*255+.5:255;return c}var Mo=kt(`textures`),No={toSRGB:null,toLinear:null};function Po(e){if(!No[e]){let t=new Uint8Array(256);for(let n=0;n<256;n++){let r=n/255,i=e===`toSRGB`?To(r):r<=.04045?r/12.92:((r+.055)/1.055)**2.4;t[n]=Math.max(0,Math.min(255,Math.round(i*255)))}No[e]=t}return No[e]}var Fo=class{constructor(){this.canvasContextPairs=[],this.maxPoolSize=q.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=[]}},Io=class{constructor(e={}){this.pools=new Map,this.memoryUsage=0,this.maxMemoryUsage=e.maxMemory||pt.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*pt.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<q.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`}},Lo=class{constructor(e=q.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`;t+=`${e}x${r}_${i.slice(-8)}_${a}_`}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=[]}},Ro=class{constructor(e={}){this.useWorkers=typeof Worker<`u`,this.maxConcurrentWorkers=q.MAX_CONCURRENT_WORKERS,this.activeWorkers=0,this._issues=e.issues??null,this.maxTextureSize=this._clampTextureSize(e.maxTextureSize??q.DEFAULT_MAX_TEXTURE_SIZE),this.canvasPool=new Fo,this.bufferPool=new Io({maxMemory:e.maxBufferMemory||pt.MAX_BUFFER_MEMORY,sizeStrategy:e.bufferSizeStrategy||`adaptive`}),this.textureCache=new Lo,this.capabilities=this.detectCapabilities(),this.optimalMethod=this.selectOptimalMethod()}_reportTextureFailure(e,t){this._issues?.record(lo.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)||q.DEFAULT_MAX_TEXTURE_SIZE);return Math.max(q.MIN_TEXTURE_WIDTH,Math.min(t,q.MAX_TEXTURE_SIZE))}setMaxTextureSize(e){let t=this._clampTextureSize(e);return t===this.maxTextureSize?t:(this.maxTextureSize=t,this.textureCache?.dispose(),this.textureCache=new Lo,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`}_harmonizeTransfer(e,t,n){let i=e?.image?.data;if(!i)return;let a=t.filter(e=>e?.image),o=n?r.SRGBColorSpace:r.LinearSRGBColorSpace,s=e.image.width*e.image.height*4,c=[];for(let e=0;e<a.length;e++){let t=a[e].colorSpace;if(t!==r.SRGBColorSpace&&t!==r.LinearSRGBColorSpace||t===o)continue;let l=Po(n?`toSRGB`:`toLinear`),u=e*s,d=Math.min(u+s,i.length);for(let e=u;e<d;e+=4)i[e]=l[i[e]],i[e+1]=l[i[e+1]],i[e+2]=l[i[e+2]];c.push(a[e].name||a[e].source?.uuid?.slice(0,8)||`layer ${e}`)}if(c.length===0)return;e.needsUpdate=!0;let l=c.slice(0,4).join(`, `)+(c.length>4?`, +${c.length-4} more`:``);n?Mo.info(`re-encoded ${c.length}/${a.length} linear-declared colour map(s) to sRGB so the GPU decode round-trips: ${l}`):Mo.warn(`decoded ${c.length}/${a.length} sRGB-declared data map(s) to linear — precision is lost in the darks, check the asset: ${l}`)}async createTexturesToDataTexture(e,{srgbPool:t=!1}={}){if(!e||e.length===0)return null;let n=`${t?`s`:`l`}:${this.textureCache.generateHash(e)}`,r=this.textureCache.get(n);if(r)return r;let{normalized:i,bitmapsToClose:a}=await this._normalizeTexturesForProcessing(e),o=this.selectProcessingStrategy(i),s;try{switch(o.method){case`worker-direct`:s=await this.processWithWorkerDirect(i);break;case`main-batch`:s=await this.processOnMainThreadBatch(i,o.batchSize);break;case`main-streaming`:s=await this.processOnMainThreadStreaming(i);break;default:s=await this.processOnMainThreadSync(i)}return s&&(this._harmonizeTransfer(s,e,t),this.textureCache.set(n,s)),s}catch(n){this._issues?.warn(lo.TEXTURE_PROCESSING_FALLBACK,`worker texture processing failed — retrying on the main thread`,{cause:String(n?.message??n)});let r=await this.processOnMainThreadSync(i);return this._harmonizeTransfer(r,e,t),r}finally{for(let e of a)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>pt.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 co,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%pt.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=K.FLOATS_PER_MATERIAL,n=e.length,r=n*t,i=new Float32Array(r);for(let r=0;r<n;r++){let n=e[r],a=r*t,o=n.mapMatrix??ut,s=n.normalMapMatrices??ut,c=n.roughnessMapMatrices??ut,l=n.metalnessMapMatrices??ut,u=n.emissiveMapMatrices??ut,d=n.bumpMapMatrices??ut,f=n.displacementMapMatrices??ut,p=[n.ior,n.transmission,n.thickness,n.emissiveIntensity,n.attenuationColor.r,n.attenuationColor.g,n.attenuationColor.b,Ze(n.attenuationDistance),n.opacity,n.side,n.transparent,n.alphaTest,n.alphaMode,n.depthWrite,n.normalScale?.x??1,n.normalScale?.y??1,n.color.r,n.color.g,n.color.b,n.metalness,n.emissive.r,n.emissive.g,n.emissive.b,n.roughness,n.map,n.normalMap,n.roughnessMap,n.metalnessMap,n.emissiveMap,n.bumpMap,n.clearcoat,n.clearcoatRoughness,n.dispersion,n.visible,n.sheen,n.sheenRoughness,n.sheenColor.r,n.sheenColor.g,n.sheenColor.b,1,n.specularIntensity,n.specularColor.r,n.specularColor.g,n.specularColor.b,n.iridescence,n.iridescenceIOR,n.iridescenceThicknessRange[0],n.iridescenceThicknessRange[1],n.bumpScale,n.displacementScale,n.displacementMap,0,o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7],s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],c[0],c[1],c[2],c[3],c[4],c[5],c[6],c[7],l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],u[0],u[1],u[2],u[3],u[4],u[5],u[6],u[7],d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7],f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],n.subsurfaceColor?.r??1,n.subsurfaceColor?.g??1,n.subsurfaceColor?.b??1,n.subsurface??0,n.subsurfaceRadius?.[0]??1,n.subsurfaceRadius?.[1]??.2,n.subsurfaceRadius?.[2]??.1,n.subsurfaceRadiusScale??1,n.subsurfaceAnisotropy??0,n.anisotropy??0,n.anisotropyRotation??0,n.anisotropyMap??-1,n.transmissionMap??-1,n.clearcoatMap??-1,n.clearcoatRoughnessMap??-1,n.sheenColorMap??-1,n.sheenRoughnessMap??-1,n.iridescenceMap??-1,n.iridescenceThicknessMap??-1,n.specularIntensityMap??-1,n.specularColorMap??-1,0,0,0];i.set(p,a)}return i}createBVHRawData(e){let t=[],n=e=>{let r=t.length;if(t.push(e),e.leftChild){let t=n(e.leftChild),r=n(e.rightChild);e.leftChild=t,e.rightChild=r}return r};n(e);let r=q.VEC4_PER_BVH_NODE*q.FLOATS_PER_VEC4,i=t.length*r,a=new Float32Array(i);for(let e=0;e<t.length;e++){let n=e*r,i=t[e];if(i.leftChild!==null){let e=i.leftChild,r=i.rightChild,o=t[e],s=t[r];a[n]=o.boundsMin.x,a[n+1]=o.boundsMin.y,a[n+2]=o.boundsMin.z,a[n+3]=e,a[n+4]=o.boundsMax.x,a[n+5]=o.boundsMax.y,a[n+6]=o.boundsMax.z,a[n+7]=r,a[n+8]=s.boundsMin.x,a[n+9]=s.boundsMin.y,a[n+10]=s.boundsMin.z,a[n+12]=s.boundsMax.x,a[n+13]=s.boundsMax.y,a[n+14]=s.boundsMax.z}else a[n]=i.triangleOffset,a[n+1]=i.triangleCount,a[n+3]=-1}return a}async createMaterialTextures(e){let{materials:t,maps: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 Lo;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:et(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:zo(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:zo(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 zo(e,t,n){let r=new Uint8ClampedArray(e.buffer,e.byteOffset,e.byteLength);return createImageBitmap(new ImageData(r,t,n))}var Bo=kt(`geometry`),Vo=q.MAX_TEXTURES_LIMIT;function Ho(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}var Uo=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._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.triangleData=new Float32Array(this._triangleCapacity*G.FLOATS_PER_TRIANGLE),this.currentTriangleIndex=0,this.traverseObject(e),this.logStats(),this.getExtractedData()}_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=new Float32Array(e*G.FLOATS_PER_TRIANGLE);t.set(this.triangleData),this.triangleData=t,this._triangleCapacity=e}traverseObject(e){if(e.isMesh?this.processMesh(e):e.isDirectionalLight?this.directionalLights.push(e):e.isCamera&&this.cameras.push(e),e.children)for(let t of e.children)this.traverseObject(t)}processMesh(e){if(!e.geometry||!e.material){console.warn(`Skipping mesh with missing geometry or material:`,e);return}let t=this.processMaterial(e.material);e.userData.materialIndex=t;let n=this.meshes.length;this.meshes.push(e),e.userData.meshIndex=n;let r=this.currentTriangleIndex;this.extractGeometry(e,t,n),this.meshTriangleRanges.push({start:r,count:this.currentTriangleIndex-r})}processMaterial(e){let t=this._materialUuidMap.get(e.uuid)??-1;if(t===-1){e.depthWrite===!1&&(e.depthWrite=!0,jt(Bo,`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(){return{emissive:new r.Color(0,0,0),emissiveIntensity:1,roughness:1,metalness:0,ior:1.5,opacity:1,transmission:0,thickness:.1,attenuationColor:new r.Color(16777215),attenuationDistance:1/0,dispersion:0,sheen:0,sheenRoughness:1,sheenColor:new r.Color(0),specularIntensity:1,specularColor:new r.Color(16777215),clearcoat:0,clearcoatRoughness:0,iridescence:0,iridescenceIOR:1.3,iridescenceThicknessRange:[100,400],normalScale:{x:1,y:1},bumpScale:1,displacementScale:1,alphaTest:0,subsurface:0,subsurfaceColor:new r.Color(16777215),subsurfaceRadius:[1,.2,.1],subsurfaceRadiusScale:1,subsurfaceAnisotropy:0,anisotropy:0,anisotropyRotation:0}}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;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.r*.299+e.specular.g*.587+e.specular.b*.114;n.specularIntensity=Math.min(t*2,1),n.specularColor=e.specular.clone()}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),i=this.mapLegacyMaterialToPhysical(e,n),a=(e.transmission??0)>0,o=(e.metalness??i.metalness??0)>.1&&!a?2.5:t.ior,s=e.color||new r.Color(16777215);return n===`basic`&&!e.map&&(s=new r.Color(0)),{uuid:e.uuid,color:s,emissive:i.emissive??e.emissive??t.emissive,emissiveIntensity:i.emissiveIntensity??e.emissiveIntensity??t.emissiveIntensity,roughness:Math.max(.02,i.roughness??e.roughness??t.roughness),metalness:i.metalness??e.metalness??t.metalness,ior:e.ior??o,opacity:e.opacity??t.opacity,transmission:e.transmission??t.transmission,thickness:e.thickness??t.thickness,attenuationColor:e.attenuationColor??t.attenuationColor,attenuationDistance:e.attenuationDistance??t.attenuationDistance,dispersion:e.dispersion??t.dispersion,sheen:e.sheen??t.sheen,sheenRoughness:e.sheenRoughness??t.sheenRoughness,sheenColor:e.sheenColor??t.sheenColor,clearcoat:e.clearcoat??t.clearcoat,clearcoatRoughness:e.clearcoatRoughness??t.clearcoatRoughness,iridescence:e.iridescence??t.iridescence,iridescenceIOR:e.iridescenceIOR??t.iridescenceIOR,iridescenceThicknessRange:e.iridescenceThicknessRange??t.iridescenceThicknessRange,subsurface:e.subsurface??t.subsurface,subsurfaceColor:e.subsurfaceColor??t.subsurfaceColor,subsurfaceRadius:e.subsurfaceRadius??t.subsurfaceRadius,subsurfaceRadiusScale:e.subsurfaceRadiusScale??t.subsurfaceRadiusScale,subsurfaceAnisotropy:e.subsurfaceAnisotropy??t.subsurfaceAnisotropy,anisotropy:e.anisotropy??t.anisotropy,anisotropyRotation:e.anisotropyRotation??t.anisotropyRotation,specularIntensity:i.specularIntensity??e.specularIntensity??t.specularIntensity,specularColor:i.specularColor??e.specularColor??t.specularColor,normalScale:e.normalScale??t.normalScale,bumpScale:e.bumpScale??t.bumpScale,displacementScale:e.displacementScale??t.displacementScale,transparent:+!!e.transparent,alphaTest:e.alphaTest??t.alphaTest,alphaMode:Ho(e),side:this.getMaterialSide(e),depthWrite:e.depthWrite??!0?1:0,map:this.processTexture(e.map,this.maps),normalMap:this.processTexture(e.normalMap,this.normalMaps),bumpMap:this.processTexture(e.bumpMap,this.bumpMaps),roughnessMap:this.processTexture(e.roughnessMap,this.roughnessMaps),metalnessMap:this.processTexture(e.metalnessMap,this.metalnessMaps),emissiveMap:this.processTexture(e.emissiveMap,this.emissiveMaps),displacementMap:this.processTexture(e.displacementMap,this.displacementMaps),anisotropyMap:this.processTexture(e.anisotropyMap,this.anisotropyMaps),clearcoatMap:this.processTexture(e.clearcoatMap,this.clearcoatMaps),clearcoatRoughnessMap:this.processTexture(e.clearcoatRoughnessMap,this.clearcoatRoughnessMaps),transmissionMap:this.processTexture(e.transmissionMap,this.transmissionMaps),thicknessMap:this.processTexture(e.thicknessMap,[]),sheenColorMap:this.processTexture(e.sheenColorMap,this.sheenColorMaps),sheenRoughnessMap:this.processTexture(e.sheenRoughnessMap,this.sheenRoughnessMaps),specularIntensityMap:this.processTexture(e.specularIntensityMap,this.specularIntensityMaps),specularColorMap:this.processTexture(e.specularColorMap,this.specularColorMaps),iridescenceMap:this.processTexture(e.iridescenceMap,this.iridescenceMaps),iridescenceThicknessMap:this.processTexture(e.iridescenceThicknessMap,this.iridescenceThicknessMaps),mapMatrix:this.getTextureMatrix(e.map),normalMapMatrices:this.getTextureMatrix(e.normalMap),bumpMapMatrices:this.getTextureMatrix(e.bumpMap),roughnessMapMatrices:this.getTextureMatrix(e.roughnessMap),metalnessMapMatrices:this.getTextureMatrix(e.metalnessMap),emissiveMapMatrices:this.getTextureMatrix(e.emissiveMap),displacementMapMatrices:this.getTextureMatrix(e.displacementMap),originalType:n}}getTextureMatrix(e){return e?(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<Vo){t.push(e);let i=t.length-1;return n.set(r,i),i}return this._droppedTextures++,this._droppedTextures===1&&this._issues?.record(lo.TEXTURE_LIMIT_EXCEEDED,`scene needs more than ${Vo} distinct textures for one map type; the rest render untextured`,{limit:Vo,firstDropped:e.name||e.source?.uuid}),-1}extractGeometry(e,t,n){e.updateMatrix(),e.updateMatrixWorld();let r=e.geometry;r.attributes.normal||r.computeVertexNormals();let i=r.attributes.position,a=r.attributes.normal,o=r.attributes.uv,s=r.index?r.index.array:null;this._matrixPool.mat4.copy(e.matrixWorld),this._matrixPool.mat3.getNormalMatrix(this._matrixPool.mat4);let c=s?s.length/3:i.count/3;this.extractTrianglesInBatch(i,a,o,s,c,t,n)}extractTrianglesInBatch(e,t,n,r,i,a,o){for(;this.materialTriangleCounts.length<=a;)this.materialTriangleCounts.push(0);this.materialTriangleCounts[a]+=i;let s=this._getVec3(0),c=this._getVec3(1),l=this._getVec3(2),u=this._getVec3(3),d=this._getVec3(4),f=this._getVec3(5),p=this._getVec2(0),m=this._getVec2(1),h=this._getVec2(2);this._ensureCapacity(this.currentTriangleIndex+i);for(let g=0;g<i;g++){let i=g*3,_=r?r[i+0]:i+0,v=r?r[i+1]:i+1,y=r?r[i+2]:i+2;this.getVertex(e,_,s),this.getVertex(e,v,c),this.getVertex(e,y,l),this.getVertex(t,_,u),this.getVertex(t,v,d),this.getVertex(t,y,f),n?(this.getVertex(n,_,p),this.getVertex(n,v,m),this.getVertex(n,y,h)):(p.set(0,0),m.set(0,0),h.set(0,0)),s.applyMatrix4(this._matrixPool.mat4),c.applyMatrix4(this._matrixPool.mat4),l.applyMatrix4(this._matrixPool.mat4),u.applyMatrix3(this._matrixPool.mat3).normalize(),d.applyMatrix3(this._matrixPool.mat3).normalize(),f.applyMatrix3(this._matrixPool.mat3).normalize(),this.packTriangleDataTextureFormat(this.currentTriangleIndex,s,c,l,u,d,f,p,m,h,a,o),this.currentTriangleIndex++}}packTriangleDataTextureFormat(e,t,n,r,i,a,o,s,c,l,u,d){let f=e*G.FLOATS_PER_TRIANGLE;this.triangleData[f+G.POSITION_A_OFFSET+0]=t.x,this.triangleData[f+G.POSITION_A_OFFSET+1]=t.y,this.triangleData[f+G.POSITION_A_OFFSET+2]=t.z,this.triangleData[f+G.POSITION_A_OFFSET+3]=0,this.triangleData[f+G.POSITION_B_OFFSET+0]=n.x,this.triangleData[f+G.POSITION_B_OFFSET+1]=n.y,this.triangleData[f+G.POSITION_B_OFFSET+2]=n.z,this.triangleData[f+G.POSITION_B_OFFSET+3]=0,this.triangleData[f+G.POSITION_C_OFFSET+0]=r.x,this.triangleData[f+G.POSITION_C_OFFSET+1]=r.y,this.triangleData[f+G.POSITION_C_OFFSET+2]=r.z,this.triangleData[f+G.POSITION_C_OFFSET+3]=0,this.triangleData[f+G.NORMAL_A_OFFSET+0]=i.x,this.triangleData[f+G.NORMAL_A_OFFSET+1]=i.y,this.triangleData[f+G.NORMAL_A_OFFSET+2]=i.z;{let e=this.materials[u],t=e&&!(e.alphaMode|0)&&!(e.transparent|0)&&(e.transmission||0)===0&&(e.opacity??1)>=1?1:0;this.triangleData[f+G.NORMAL_A_OFFSET+3]=t}this.triangleData[f+G.NORMAL_B_OFFSET+0]=a.x,this.triangleData[f+G.NORMAL_B_OFFSET+1]=a.y,this.triangleData[f+G.NORMAL_B_OFFSET+2]=a.z,this.triangleData[f+G.NORMAL_B_OFFSET+3]=0,this.triangleData[f+G.NORMAL_C_OFFSET+0]=o.x,this.triangleData[f+G.NORMAL_C_OFFSET+1]=o.y,this.triangleData[f+G.NORMAL_C_OFFSET+2]=o.z,this.triangleData[f+G.NORMAL_C_OFFSET+3]=this.materials[u]?.side??0,this.triangleData[f+G.UV_AB_OFFSET+0]=s.x,this.triangleData[f+G.UV_AB_OFFSET+1]=s.y,this.triangleData[f+G.UV_AB_OFFSET+2]=c.x,this.triangleData[f+G.UV_AB_OFFSET+3]=c.y,this.triangleData[f+G.UV_C_MAT_OFFSET+0]=l.x,this.triangleData[f+G.UV_C_MAT_OFFSET+1]=l.y,this.triangleData[f+G.UV_C_MAT_OFFSET+2]=u,this.triangleData[f+G.UV_C_MAT_OFFSET+3]=d}getTriangleData(){return this.triangleData?this.triangleData.subarray(0,this.currentTriangleIndex*G.FLOATS_PER_TRIANGLE):null}getTriangleCount(){return this.currentTriangleIndex}getVertex(e,t,n){return e.itemSize===2?(n.x=e.getX(t),n.y=e.getY(t)):e.itemSize>=3&&(n.x=e.getX(t),n.y=e.getY(t),n.z=e.getZ(t)),n}logStats(){let e=this.currentTriangleIndex*G.FLOATS_PER_TRIANGLE*4;Bo.debug(J.list([`${J.count(this.currentTriangleIndex,`tri`)} (${J.mb(e)})`,J.count(this.materials.length,`material`),J.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.triangleData=null,this.triangleCount=0,this.currentTriangleIndex=0,this.materials=[],this.materialTriangleCounts=[],this.meshes=[],this.meshTriangleRanges=[],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,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}}},Wo=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=Ko(E,Go(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=Ko(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 Go(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 Ko(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)}}var qo=kt(`emissive`),Jo=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){this.emissiveTriangles=[],this.totalEmissivePower=0,this._totalTriangleCount=n;let r=G.FLOATS_PER_TRIANGLE,i=G.UV_C_MAT_OFFSET+2,a=G.UV_C_MAT_OFFSET+3;for(let o=0;o<n;o++){let n=o*r,s=Math.floor(e[n+i]),c=Math.floor(e[n+a]),l=t[s];if(!l)continue;let u=l.emissive||{r:0,g:0,b:0},d=l.emissiveIntensity||0;if(d>0&&(u.r>0||u.g>0||u.b>0)){let t=e[n+0],r=e[n+1],i=e[n+2],a=e[n+4],f=e[n+5],p=e[n+6],m=e[n+8],h=e[n+9],g=e[n+10],_=this._calculateTriangleArea(t,r,i,a,f,p,m,h,g),v=(.2126*u.r+.7152*u.g+.0722*u.b)*d*_,y=(f-r)*(g-i)-(p-i)*(h-r),b=(p-i)*(m-t)-(a-t)*(g-i),x=(a-t)*(h-r)-(f-r)*(m-t),S=Math.sqrt(y*y+b*b+x*x)||1,C=l.side===1?-1:1;y=y/S*C,b=b/S*C,x=x/S*C;let w=l.side===2,T=(t+a+m)/3,E=(r+f+h)/3,D=(i+p+g)/3,O=Math.min(t,a,m),k=Math.min(r,f,h),A=Math.min(i,p,g),j=Math.max(t,a,m),M=Math.max(r,f,h),N=Math.max(i,p,g);this.emissiveTriangles.push({triangleIndex:o,materialIndex:s,meshIndex:c,power:v,area:_,emissive:{r:u.r,g:u.g,b:u.b},emissiveIntensity:d,cx:T,cy:E,cz:D,bMinX:O,bMinY:k,bMinZ:A,bMaxX:j,bMaxY:M,bMaxZ:N,nx:y,ny:b,nz:x,twoSided:w}),this.totalEmissivePower+=v}}return this.emissiveCount=this.emissiveTriangles.length,this.emissiveCount>0&&qo.debug(`${J.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,qo.debug(`emissive texture ${J.px(t,n)} · ${J.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]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,e[r+4]=n.emissive.r*n.emissiveIntensity,e[r+5]=n.emissive.g*n.emissiveIntensity,e[r+6]=n.emissive.b*n.emissiveIntensity,e[r+7]=n.area}return qo.debug(`emissive raw data ${J.n(this.emissiveCount)} entries (${J.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=t.emissive||{r:0,g:0,b:0},o=t.emissiveIntensity||0,s=o>0&&(a.r>0||a.g>0||a.b>0);if(s!==this.emissiveTriangles.some(t=>t.materialIndex===e))return this.extractEmissiveTriangles(n,r,i),!0;if(!s)return!1;let c=.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 Wo().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]=this.totalEmissivePower>0?n.power/this.totalEmissivePower:0,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,qo.debug(`rebuilt sorted emissive data · ${J.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}},Yo=class{constructor(e=`Build`,{namespace:t=`build`,level:n=`debug`}={}){this.label=e,this.level=n,this.logger=kt(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=J.list([this.label,...e,J.ms(t)]);return this.level===`info`?this.logger.summary(r,n):this.logger.debug(J.list([r,n.join(` · `)])),{steps:Object.fromEntries(this.order.map(e=>[e,Math.round(this.entries.get(e)?.duration??0)])),total:Math.round(t)}}},Xo="const e={FLOATS_PER_TRIANGLE:32,POSITION_A_OFFSET:0,POSITION_B_OFFSET:4,POSITION_C_OFFSET:8,NORMAL_A_OFFSET:12,NORMAL_B_OFFSET:16,NORMAL_C_OFFSET:20},t=e.FLOATS_PER_TRIANGLE,n=new class{constructor(){this._bounds=null,this._boundsNodeCount=0}updateTrianglePositions(n,r,i){let a=i.length;for(let o=0;o<a;o++){let a=i[o],s=o*t,c=a*9,l=r[c],u=r[c+1],d=r[c+2],f=r[c+3],p=r[c+4],m=r[c+5],h=r[c+6],g=r[c+7],_=r[c+8];n[s+e.POSITION_A_OFFSET]=l,n[s+e.POSITION_A_OFFSET+1]=u,n[s+e.POSITION_A_OFFSET+2]=d,n[s+e.POSITION_B_OFFSET]=f,n[s+e.POSITION_B_OFFSET+1]=p,n[s+e.POSITION_B_OFFSET+2]=m,n[s+e.POSITION_C_OFFSET]=h,n[s+e.POSITION_C_OFFSET+1]=g,n[s+e.POSITION_C_OFFSET+2]=_;let v=f-l,y=p-u,b=m-d,x=h-l,S=g-u,C=_-d,w=y*C-b*S,T=b*x-v*C,E=v*S-y*x;n[s+e.NORMAL_A_OFFSET]=w,n[s+e.NORMAL_A_OFFSET+1]=T,n[s+e.NORMAL_A_OFFSET+2]=E,n[s+e.NORMAL_B_OFFSET]=w,n[s+e.NORMAL_B_OFFSET+1]=T,n[s+e.NORMAL_B_OFFSET+2]=E,n[s+e.NORMAL_C_OFFSET]=w,n[s+e.NORMAL_C_OFFSET+1]=T,n[s+e.NORMAL_C_OFFSET+2]=E}}refitRange(n,r,i,a){a>this._boundsNodeCount&&(this._bounds=new Float32Array(a*6),this._boundsNodeCount=a);let o=this._bounds,s=i+a;for(let a=s-1;a>=i;a--){let s=a*16,c=(a-i)*6;if(n[s+3]===-1){let i=n[s],a=n[s+1],l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0;for(let n=0;n<a;n++){let a=(i+n)*t,o=r[a+e.POSITION_A_OFFSET],s=r[a+e.POSITION_A_OFFSET+1],c=r[a+e.POSITION_A_OFFSET+2],h=r[a+e.POSITION_B_OFFSET],g=r[a+e.POSITION_B_OFFSET+1],_=r[a+e.POSITION_B_OFFSET+2],v=r[a+e.POSITION_C_OFFSET],y=r[a+e.POSITION_C_OFFSET+1],b=r[a+e.POSITION_C_OFFSET+2];l=Math.min(l,o,h,v),u=Math.min(u,s,g,y),d=Math.min(d,c,_,b),f=Math.max(f,o,h,v),p=Math.max(p,s,g,y),m=Math.max(m,c,_,b)}o[c]=l,o[c+1]=u,o[c+2]=d,o[c+3]=f,o[c+4]=p,o[c+5]=m}else{let e=n[s+3],t=n[s+7],r=(e-i)*6,a=(t-i)*6,l=o[r],u=o[r+1],d=o[r+2],f=o[r+3],p=o[r+4],m=o[r+5],h=o[a],g=o[a+1],_=o[a+2],v=o[a+3],y=o[a+4],b=o[a+5];n[s]=l,n[s+1]=u,n[s+2]=d,n[s+4]=f,n[s+5]=p,n[s+6]=m,n[s+8]=h,n[s+9]=g,n[s+10]=_,n[s+12]=v,n[s+13]=y,n[s+14]=b,o[c]=Math.min(l,h),o[c+1]=Math.min(u,g),o[c+2]=Math.min(d,_),o[c+3]=Math.max(f,v),o[c+4]=Math.max(p,y),o[c+5]=Math.max(m,b)}}}refit(n,r,i){i!==this._boundsNodeCount&&(this._bounds=new Float32Array(i*6),this._boundsNodeCount=i);let a=this._bounds;for(let o=i-1;o>=0;o--){let i=o*16,s=o*6,c=n[i+3];if(c===-1){let o=n[i],c=n[i+1],l=1/0,u=1/0,d=1/0,f=-1/0,p=-1/0,m=-1/0;for(let n=0;n<c;n++){let i=(o+n)*t,a=r[i+e.POSITION_A_OFFSET],s=r[i+e.POSITION_A_OFFSET+1],c=r[i+e.POSITION_A_OFFSET+2],h=r[i+e.POSITION_B_OFFSET],g=r[i+e.POSITION_B_OFFSET+1],_=r[i+e.POSITION_B_OFFSET+2],v=r[i+e.POSITION_C_OFFSET],y=r[i+e.POSITION_C_OFFSET+1],b=r[i+e.POSITION_C_OFFSET+2];l=Math.min(l,a,h,v),u=Math.min(u,s,g,y),d=Math.min(d,c,_,b),f=Math.max(f,a,h,v),p=Math.max(p,s,g,y),m=Math.max(m,c,_,b)}a[s]=l,a[s+1]=u,a[s+2]=d,a[s+3]=f,a[s+4]=p,a[s+5]=m}else if(c===-2){let e=n[i]*6;a[s]=a[e],a[s+1]=a[e+1],a[s+2]=a[e+2],a[s+3]=a[e+3],a[s+4]=a[e+4],a[s+5]=a[e+5]}else{let e=n[i+3],t=n[i+7],r=e*6,o=t*6,c=a[r],l=a[r+1],u=a[r+2],d=a[r+3],f=a[r+4],p=a[r+5],m=a[o],h=a[o+1],g=a[o+2],_=a[o+3],v=a[o+4],y=a[o+5];n[i]=c,n[i+1]=l,n[i+2]=u,n[i+4]=d,n[i+5]=f,n[i+6]=p,n[i+8]=m,n[i+9]=h,n[i+10]=g,n[i+12]=_,n[i+13]=v,n[i+14]=y,a[s]=Math.min(c,m),a[s+1]=Math.min(l,h),a[s+2]=Math.min(u,g),a[s+3]=Math.max(d,_),a[s+4]=Math.max(f,v),a[s+5]=Math.max(p,y)}}}};let r=null,i=null,a=null,o=null,s=0;self.onmessage=function(e){let{type:t}=e.data;if(t===`init`){r=new Float32Array(e.data.sharedBvhBuf),i=new Float32Array(e.data.sharedTriBuf),a=new Float32Array(e.data.sharedPosBuf),o=e.data.bvhToOriginal,s=r.length/16;return}if(t===`refit`)try{let e=performance.now();n.updateTrianglePositions(i,a,o),n.refit(r,i,s),self.postMessage({type:`refitComplete`,refitTimeMs:performance.now()-e})}catch(e){console.error(`[BVHRefitWorker] Refit error:`,e),self.postMessage({type:`error`,error:e.message})}};",Zo=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Xo],{type:`text/javascript;charset=utf-8`});function Qo(e){let t;try{if(t=Zo&&(self.URL||self.webkitURL).createObjectURL(Zo),!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(Xo),{type:`module`,name:e?.name})}}var $o=kt(`scene`),es=class{constructor(e={}){this.config={useWorkers:!0,bvhDepth:30,maxLeafSize:4,verbose:!1,useFloat32Array:!0,textureQuality:`adaptive`,maxTextureSize:q.DEFAULT_MAX_TEXTURE_SIZE,enableTextureCache:!0,maxConcurrentTextureTasks:Math.min(navigator.hardwareConcurrency||4,6),enableTreeletOptimization:!1,treeletSize:7,treeletOptimizationPasses:1,treeletMinImprovement:.01,treeletComplexityThreshold:5e4,...e},this.triangleData=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.bvhData=null,this.materialData=null,this.instanceTable=null,this.originalToBvhMap=null,this._refitWorker=null,this._refitSharedBuffers=null,this._rebuildGeneration=0,this._pendingRebuilds=new Map,this.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.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime:0,totalProcessingTime:0}}setMaxTextureSize(e){return this.config.maxTextureSize=e,this.textureCreator?.setMaxTextureSize(e)}_initProcessors(){this.geometryExtractor=new Uo({issues:this.config.issues}),this.bvhBuilder=new Ia,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 Ro({maxTextureSize:this.config.maxTextureSize,issues:this.config.issues}),this.emissiveTriangleBuilder=new Jo,this.tlasBuilder=new io}_log(e,t){t===void 0?$o.debug(e):$o.debug(e,t)}async buildBVH(e){if(this.isProcessing)throw Error(`Already processing a scene. Call dispose() first.`);this.isProcessing=!0,this.processingStage=`init`;let t=new Yo(e.name??``,{namespace:`scene`});try{this._reset(),this._log(`Starting scene processing`),this.processingStage=`extraction`,t.start(`Geometry extraction`),await this._extractGeometry(e),t.end(`Geometry extraction`),this.performanceMetrics.geometryExtractionTime=t.getDuration(`Geometry extraction`),this.processingStage=`bvh`,t.start(`BVH construction (worker)`),t.start(`Material textures (parallel)`);let n=!1,r=this._buildBVH().then(()=>t.end(`BVH construction (worker)`)),i=this._createMaterialTextures().then(()=>{t.end(`Material textures (parallel)`),n=!0});return await r,H({status:`Building light data...`,progress:77}),t.start(`Emissive extraction + Light BVH`),this._buildEmissiveData(),t.end(`Emissive extraction + Light BVH`),n||H({status:`Processing material textures...`,progress:80}),await i,this.performanceMetrics.bvhBuildTime=t.getDuration(`BVH construction (worker)`),this.performanceMetrics.textureCreationTime=t.getDuration(`Material textures (parallel)`),this.processingStage=`finalize`,t.start(`BVH data packing`),this.bvhRoot&&!this.bvhData&&(this.bvhData=this.textureCreator.createBVHRawData(this.bvhRoot)),t.end(`BVH data packing`),this.spheres=this._createSpheres(),this.performanceMetrics.totalProcessingTime=performance.now()-t.totalStart,t.print(),this.processingStage=`complete`,H({status:`Scene data ready`,progress:85}),this}catch(e){throw this.processingStage=`error`,$o.error(`processing failed:`,e),H({status:`Error: ${e.message}`,progress:100}),e}finally{this.isProcessing=!1}}async _extractGeometry(e){H({isLoading:!0,title:`Processing`,status:`Extracting geometry...`,progress:15}),await new Promise(e=>setTimeout(e,0)),this._log(`Extracting geometry`);let t=performance.now();try{let n=this.geometryExtractor.extract(e);this.triangleData=n.triangleData,this.triangleCount=n.triangleCount,this._log(`Using Float32Array format: ${this.triangleCount} triangles, ${(this.triangleData.byteLength/(1024*1024)).toFixed(2)}MB`),this.materials=n.materials,this.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}),H({status:`Extracted ${this.triangleCount.toLocaleString()} triangles`,progress:25})}catch(e){throw $o.error(`geometry extraction failed:`,e),H({status:`Extraction error: ${e.message}`,progress:25}),e}}async _buildBVH(){if(H({status:`Building BVH...`,progress:25}),this.triangleCount===0)throw Error(`No triangles to build BVH from`);this._log(`Building two-level BVH (TLAS/BLAS)`);let e=performance.now();try{let t=G.FLOATS_PER_TRIANGLE,n=this.meshTriangleRanges;if(!n||n.length===0)throw Error(`No mesh triangle ranges available for TLAS/BLAS build`);this.instanceTable=new ao,this.instanceTable.allocate(n.length);let r=n.length,i=this.config.enableTreeletOptimization,a=[],o=[];for(let e=0;e<r;e++){let t=n[e];t.count!==0&&(t.count>=2e5&&to(t.count)?o.push({m:e,range:t}):a.push({m:e,range:t}))}let s={depth:this.config.bvhDepth,treeletOptimization:{enabled:i!==!1,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,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:Mt()},c=a.length+o.length,l=this._buildBLASesWithPool(a,s,e=>{H({status:`Building BLAS ${e+o.length}/${c}...`,progress:25+Math.floor(e/c*45)})}),u=o.map(({m:e,range:n})=>Qa(this.triangleData.slice(n.start*t,(n.start+n.count)*t),this.config.bvhDepth,null,{maxLeafSize:this.bvhBuilder.maxLeafSize,numBins:this.bvhBuilder.numBins,maxBins:this.bvhBuilder.maxBins,minBins:this.bvhBuilder.minBins,...s}).then(t=>({m:e,range:n,result:t}))),[d,f]=await Promise.all([l,Promise.all(u)]),p={sah:0,objMed:0,spatMed:0,failed:0,treeletsImproved:0,treeletsProcessed:0};for(let{m:e,range:n,result:r}of[...d,...f]){r.reorderedTriangles&&this.triangleData.set(r.reorderedTriangles,n.start*t);let i=r.splitStats;i&&(p.sah+=i.sahSplits??0,p.objMed+=i.objectMedianSplits??0,p.spatMed+=i.spatialMedianSplits??0,p.failed+=i.failedSplits??0,p.treeletsImproved+=i.treeletsImproved??0,p.treeletsProcessed+=i.treeletsProcessed??0),this.instanceTable.setEntry({meshIndex:e,blasNodeCount:r.bvhData.length/16,triOffset:n.start,triCount:n.count,originalToBvhMap:r.originalToBvh||null,bvhData:r.bvhData})}H({status:`Built all BLASes`,progress:70}),H({status:`Building TLAS...`,progress:72});let m=this.instanceTable.entries.filter(e=>e!==null);this.instanceTable.computeAABBs(this.triangleData);let{root:h,nodeCount:g}=this.tlasBuilder.build(m);this.instanceTable.assignOffsets(g);let _=this.instanceTable.totalNodeCount,v=this.tlasBuilder.flatten(h,m);this.bvhData=new Float32Array(_*16),this.bvhData.set(v);for(let e of m){let t=e.blasOffset*16;this.bvhData.set(e.bvhData,t),this._offsetBLASInPlace(t,e.bvhData.length/16,e.blasOffset,e.triOffset)}this._buildGlobalOriginalToBvhMap();for(let e of m)e.originalToBvhMap=null,e.bvhData=null;this.bvhRoot=!0,this._disposeRefitWorker();let y=performance.now()-e;$o.debug(J.list([`${J.n(m.length)} BLASes + TLAS`,`${J.n(this.bvhData.length/16)} nodes`,`SAH ${J.n(p.sah)} · objMed ${p.objMed} · spatMed ${p.spatMed} · failed ${p.failed}`,p.treeletsProcessed?`treelets ${p.treeletsImproved}/${p.treeletsProcessed} improved`:null,J.ms(y)])),H({status:`BVH construction complete`,progress:75})}catch(e){throw $o.error(`BVH build failed:`,e),H({status:`BVH error: ${e.message}`,progress:75}),e}}_offsetBLASInPlace(e,t,n,r){for(let i=0;i<t;i++){let t=e+i*16;this.bvhData[t+3]===-1?this.bvhData[t]+=r:(this.bvhData[t+3]+=n,this.bvhData[t+7]+=n)}}_buildBLASesWithPool(e,t,n){if(e.length===0)return Promise.resolve([]);let r=G.FLOATS_PER_TRIANGLE,i=Math.min(e.length,this.config.maxConcurrentTextureTasks||4),a=[],o=0,s=0;return new Promise((c,l)=>{let u=[],d=n=>{if(o>=e.length){n.terminate(),u.splice(u.indexOf(n),1),u.length===0&&c(a);return}let{m:i,range:s}=e[o++],l=this.triangleData.slice(s.start*r,(s.start+s.count)*r),d=s.count,f=d<=500?{...t.treeletOptimization,enabled:!1}:t.treeletOptimization;n._currentTask={m:i,range:s},n.postMessage({triangleData:l.buffer,triangleByteOffset:l.byteOffset,triangleByteLength:l.byteLength,triangleCount:d,depth:t.depth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:f,reinsertionOptimization:t.reinsertionOptimization,maxLeafSize:t.maxLeafSize,numBins:t.numBins,maxBins:t.maxBins,minBins:t.minBins,logLevel:t.logLevel},[l.buffer])},f=(e,t)=>{let r=t.data;if(r.error){u.forEach(e=>e.terminate()),l(Error(r.error));return}if(r.progress!==void 0)return;let{m:i,range:o}=e._currentTask;a.push({m:i,range:o,result:{bvhData:r.bvhData,reorderedTriangles:r.triangles||null,originalToBvh:r.originalToBvh||null,splitStats:r.treeletStats||null}}),s++,n?.(s),d(e)};(async()=>{for(let e=0;e<i;e++){let e;try{e=new Wa}catch(e){l(e);return}e.onmessage=t=>f(e,t),e.onerror=e=>{u.forEach(e=>e.terminate()),l(e)},u.push(e),d(e)}})().catch(l)})}_buildGlobalOriginalToBvhMap(){this.originalToBvhMap=new Uint32Array(this.triangleCount);for(let e of this.instanceTable.entries){if(!e)continue;let t=new Uint32Array(e.triCount);if(e.originalToBvhMap)for(let n=0;n<e.triCount;n++){let r=e.originalToBvhMap[n];this.originalToBvhMap[e.triOffset+n]=e.triOffset+r,t[r]=n}else for(let n=0;n<e.triCount;n++)this.originalToBvhMap[e.triOffset+n]=e.triOffset+n,t[n]=n;e.bvhToOriginal=t}}async _createMaterialTextures(){this._log(`Creating material textures (parallel with BVH)`);try{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 $o.error(`texture creation failed:`,e),e}}_bucketTextures(){let e=this.config.maxTextureSize,t=q.MATERIAL_BUCKET_COUNT,n=q.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=st(r(i),e,t),s=st(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(lo.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=ct(e.image.width,e.image.height,a),s=e.source?.uuid??e.uuid,c=r[o].get(s);if(c!==void 0)return lt(o,c);if(t[o].length>=n)return $o.warn(`texture bucket ${o} full (${n}); dropping a map`),f||this.config.issues?.record(lo.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=lt(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.triangleData,this.materials,this.triangleCount),this.emissiveTriangleData=this.emissiveTriangleBuilder.createEmissiveRawData(),this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower,this._log(`Emissive triangle extraction complete`,this.emissiveTriangleBuilder.getStats()),this.emissiveTriangleBuilder.buildLightBVH(),this.lightBVHNodeData=this.emissiveTriangleBuilder.lightBVHNodeData,this.lightBVHNodeCount=this.emissiveTriangleBuilder.lightBVHNodeCount,this.emissiveTriangleData=this.emissiveTriangleBuilder.emissiveTriangleData||this.emissiveTriangleData,this.emissiveBitTrailMap=this.emissiveTriangleBuilder.emissiveBitTrailMap,this.emissiveTriangleCount=this.emissiveTriangleBuilder.emissiveCount,this.emissiveTotalPower=this.emissiveTriangleBuilder.totalEmissivePower}_createSpheres(){return[]}_reset(){this._disposeTextures(),this.triangles=[],this.triangleData=null,this.triangleCount=0,this.materials=[],this.meshTriangleRanges=null,this.maps=[],this.normalMaps=[],this.bumpMaps=[],this.roughnessMaps=[],this.metalnessMaps=[],this.emissiveMaps=[],this.displacementMaps=[],this.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.bvhData=null,this.instanceTable=null,this.lightBVHNodeData=null,this.lightBVHNodeCount=0,this.emissiveBitTrailMap=null,this.performanceMetrics={textureCreationTime:0,geometryExtractionTime:0,bvhBuildTime: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){$o.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 $o.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.bvhData,useFloat32Array:this.config.useFloat32Array,triangleDataSize:this.triangleData?(this.triangleData.byteLength/(1024*1024)).toFixed(2)+`MB`:`0MB`};return this.performanceMetrics.totalProcessingTime>0&&(e.performance={totalTime:this.performanceMetrics.totalProcessingTime,textureTime:this.performanceMetrics.textureCreationTime,bvhTime:this.performanceMetrics.bvhBuildTime,extractionTime:this.performanceMetrics.geometryExtractionTime,texturePercentage:(this.performanceMetrics.textureCreationTime/this.performanceMetrics.totalProcessingTime*100).toFixed(1)+`%`}),this.textureCreator&&this.textureCreator.capabilities&&(e.textureCapabilities=this.textureCreator.capabilities),e}updateConfig(e){Object.assign(this.config,e),this.bvhBuilder&&(this.bvhBuilder.maxLeafSize=this.config.maxLeafSize,this.bvhBuilder.setTreeletConfig({enabled:this.config.enableTreeletOptimization,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold})),this._log(`Configuration updated`,this.config)}async refitBVH(e,t){if(!this.bvhData||!this.triangleData||!this.originalToBvhMap)throw Error(`No BVH data available for refit. Run buildBVH() first.`);let n=this.triangleCount*9;if(e?.length!==n)throw Error(`SceneProcessor.refitBVH: expected ${n} position floats (${this.triangleCount} triangles × 9), got ${e?.length??`none`}. Positions must cover every triangle in the scene, meshes in this.meshes order.`);if(t&&t.length!==n)throw Error(`SceneProcessor.refitBVH: expected ${n} normal floats, got ${t.length}.`);if(this._refitWorker||=new Qo,!this._refitSharedBuffers){let t=new SharedArrayBuffer(this.bvhData.byteLength),n=new SharedArrayBuffer(this.triangleData.byteLength),r=new SharedArrayBuffer(e.byteLength),i=new Float32Array(t),a=new Float32Array(n);i.set(this.bvhData),a.set(this.triangleData),this.bvhData=i,this.triangleData=a;let o=this.originalToBvhMap.length,s=new Uint32Array(o);for(let e=0;e<o;e++)s[this.originalToBvhMap[e]]=e;this._refitSharedBuffers={bvhBuf:t,triBuf:n,posBuf:r,posView:new Float32Array(r)},this._refitWorker.postMessage({type:`init`,sharedBvhBuf:t,sharedTriBuf:n,sharedPosBuf:r,bvhToOriginal:s},[s.buffer])}return this._refitSharedBuffers.posView.set(e),new Promise((e,n)=>{this._refitWorker.onmessage=r=>{let i=r.data;i.type===`refitComplete`?(t&&this._patchSmoothNormals(t),e({refitTimeMs:i.refitTimeMs})):i.type===`error`&&n(Error(i.error))},this._refitWorker.postMessage({type:`refit`})})}_patchSmoothNormals(e){this._patchNormalsRange(e,0,this.originalToBvhMap.length)}refitBLASes(e,t,n){if(!this.instanceTable||!this.bvhData||!this.triangleData)throw Error(`No TLAS/BLAS data available. Run buildBVH() first.`);let r=this.triangleCount*9;if(t?.length!==r)throw Error(`SceneProcessor.refitBLASes: expected ${r} position floats (${this.triangleCount} triangles × 9, full scene), got ${t?.length??`none`}.`);if(n&&n.length!==r)throw Error(`SceneProcessor.refitBLASes: expected ${r} normal floats, got ${n.length}.`);let i=performance.now();this._blasRefitter||=new Va;for(let r of e){let e=this.instanceTable.entries[r];e&&(this._updateMeshTrianglePositions(e,t),n&&this._patchMeshSmoothNormals(e,n),this._blasRefitter.refitRange(this.bvhData,this.triangleData,e.blasOffset,e.blasNodeCount),this.instanceTable.recomputeAABB(r,this.bvhData,this.triangleData))}return this._refitTLAS(),{refitTimeMs:performance.now()-i}}computeBLASDirtyRanges(e){let t=G.FLOATS_PER_TRIANGLE,n=[],r=[];for(let i of e){let e=this.instanceTable.entries[i];e&&(n.push({offset:e.triOffset*t,count:e.triCount*t}),r.push({offset:e.blasOffset*16,count:e.blasNodeCount*16}))}return r.push({offset:0,count:this.instanceTable.tlasNodeCount*16}),{triRanges:n,bvhRanges:r}}uploadToPathTracer(e,t,n,r){return this.triangleData?(e.setTriangleData(this.triangleData,this.triangleCount),this.bvhData?(e.setBVHData(this.bvhData),e.setInstanceTable(this.instanceTable),this.materialData?e.materialData.setMaterialData(this.materialData):$o.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):($o.error(`failed to get BVH data`),!1)):($o.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.triangleData,this.materials,this.triangleCount))?null: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}}_updateMeshTrianglePositions(e,t){let n=G.FLOATS_PER_TRIANGLE,r=G.POSITION_A_OFFSET,i=G.POSITION_B_OFFSET,a=G.POSITION_C_OFFSET,o=G.NORMAL_A_OFFSET,s=G.NORMAL_B_OFFSET,c=G.NORMAL_C_OFFSET,l=e.bvhToOriginal;for(let u=0;u<e.triCount;u++){let d=l[u],f=(e.triOffset+u)*n,p=(e.triOffset+d)*9,m=t[p],h=t[p+1],g=t[p+2],_=t[p+3],v=t[p+4],y=t[p+5],b=t[p+6],x=t[p+7],S=t[p+8];this.triangleData[f+r]=m,this.triangleData[f+r+1]=h,this.triangleData[f+r+2]=g,this.triangleData[f+i]=_,this.triangleData[f+i+1]=v,this.triangleData[f+i+2]=y,this.triangleData[f+a]=b,this.triangleData[f+a+1]=x,this.triangleData[f+a+2]=S;let C=_-m,w=v-h,T=y-g,E=b-m,D=x-h,O=S-g,k=w*O-T*D,A=T*E-C*O,j=C*D-w*E;this.triangleData[f+o]=k,this.triangleData[f+o+1]=A,this.triangleData[f+o+2]=j,this.triangleData[f+s]=k,this.triangleData[f+s+1]=A,this.triangleData[f+s+2]=j,this.triangleData[f+c]=k,this.triangleData[f+c+1]=A,this.triangleData[f+c+2]=j}}_patchMeshSmoothNormals(e,t){this._patchNormalsRange(t,e.triOffset,e.triCount)}_patchNormalsRange(e,t,n){let r=G.FLOATS_PER_TRIANGLE,i=G.NORMAL_A_OFFSET,a=G.NORMAL_B_OFFSET,o=G.NORMAL_C_OFFSET;for(let s=0;s<n;s++){let n=t+s,c=this.originalToBvhMap[n]*r,l=n*9;this.triangleData[c+i]=e[l],this.triangleData[c+i+1]=e[l+1],this.triangleData[c+i+2]=e[l+2],this.triangleData[c+a]=e[l+3],this.triangleData[c+a+1]=e[l+4],this.triangleData[c+a+2]=e[l+5],this.triangleData[c+o]=e[l+6],this.triangleData[c+o+1]=e[l+7],this.triangleData[c+o+2]=e[l+8]}}_refitTLAS(){let e=this.instanceTable.tlasNodeCount;(!this._tlasBounds||this._tlasBounds.length<e*6)&&(this._tlasBounds=new Float32Array(e*6)),this._blasOffsetMap||=new Map,this._blasOffsetMap.clear();for(let e of this.instanceTable.entries)e&&this._blasOffsetMap.set(e.blasOffset,e);for(let t=e-1;t>=0;t--){let e=t*16,n=this.bvhData[e+3];if(n===-2){let n=this.bvhData[e],r=this._blasOffsetMap.get(n);if(r&&r.worldAABB){let e=t*6;this._tlasBounds[e]=r.worldAABB.minX,this._tlasBounds[e+1]=r.worldAABB.minY,this._tlasBounds[e+2]=r.worldAABB.minZ,this._tlasBounds[e+3]=r.worldAABB.maxX,this._tlasBounds[e+4]=r.worldAABB.maxY,this._tlasBounds[e+5]=r.worldAABB.maxZ}}else if(n>=0){let n=this.bvhData[e+3],r=this.bvhData[e+7],i=n*6,a=r*6,o=this._tlasBounds;this.bvhData[e]=o[i],this.bvhData[e+1]=o[i+1],this.bvhData[e+2]=o[i+2],this.bvhData[e+4]=o[i+3],this.bvhData[e+5]=o[i+4],this.bvhData[e+6]=o[i+5],this.bvhData[e+8]=o[a],this.bvhData[e+9]=o[a+1],this.bvhData[e+10]=o[a+2],this.bvhData[e+12]=o[a+3],this.bvhData[e+13]=o[a+4],this.bvhData[e+14]=o[a+5];let s=t*6;o[s]=Math.min(o[i],o[a]),o[s+1]=Math.min(o[i+1],o[a+1]),o[s+2]=Math.min(o[i+2],o[a+2]),o[s+3]=Math.max(o[i+3],o[a+3]),o[s+4]=Math.max(o[i+4],o[a+4]),o[s+5]=Math.max(o[i+5],o[a+5])}}}scheduleBackgroundRebuild(e,t){if(!this.instanceTable||!this.triangleData)return;let n=G.FLOATS_PER_TRIANGLE;this._rebuildGeneration++;let r=this._rebuildGeneration,i=(e,i,a)=>{let o=this.triangleData.slice(i.triOffset*n,(i.triOffset+i.triCount)*n);this._pendingRebuilds.set(e,a),a.onmessage=n=>{let o=n.data;if(a.terminate(),this._pendingRebuilds.delete(e),o.error){$o.error(`background BLAS rebuild failed (mesh ${e}):`,o.error);return}r===this._rebuildGeneration&&this._swapBLAS(e,i,o,t)},a.onerror=t=>{$o.error(`background BLAS rebuild worker failed (mesh ${e}):`,t),a.terminate(),this._pendingRebuilds.delete(e)};let s=i.triCount>500;a.postMessage({triangleData:o.buffer,triangleByteOffset:o.byteOffset,triangleByteLength:o.byteLength,triangleCount:i.triCount,depth:this.config.bvhDepth,reportProgress:!1,sharedReorderBuffer:null,treeletOptimization:{enabled:s,size:this.config.treeletSize,passes:this.config.treeletOptimizationPasses,minImprovement:this.config.treeletMinImprovement,complexityThreshold:this.config.treeletComplexityThreshold},reinsertionOptimization:{enabled:this.bvhBuilder.enableReinsertionOptimization,batchSizeRatio:this.bvhBuilder.reinsertionBatchSizeRatio,maxIterations:this.bvhBuilder.reinsertionMaxIterations}},[o.buffer])};for(let t of e){let e=this.instanceTable.entries[t];if(!e)continue;let n=this._pendingRebuilds.get(t);n&&n.terminate(),i(t,e,new Wa)}}_swapBLAS(e,t,n,r){let i=n.bvhData,a=i.length/16;if(a!==t.blasNodeCount){$o.warn(`background rebuild node count mismatch for mesh ${e} (${a} vs ${t.blasNodeCount}), skipping swap`);return}let o=t.blasOffset*16;this.bvhData.set(i,o),this._offsetBLASInPlace(o,a,t.blasOffset,t.triOffset);let s=G.FLOATS_PER_TRIANGLE,c=n.triangles;c&&this.triangleData.set(c,t.triOffset*s);let l=n.originalToBvh;if(l){for(let e=0;e<t.triCount;e++)this.originalToBvhMap[t.triOffset+e]=t.triOffset+l[e];let e=new Uint32Array(t.triCount);for(let n=0;n<t.triCount;n++)e[l[n]]=n;t.bvhToOriginal=e}this.instanceTable.recomputeAABB(e,this.bvhData,this.triangleData),this._refitTLAS(),this._log(`Background BLAS rebuild complete for mesh ${e}`),r?.()}cancelBackgroundRebuilds(){for(let e of this._pendingRebuilds.values())e.terminate();this._pendingRebuilds.clear()}_disposeRefitWorker(){this._refitWorker&&=(this._refitWorker.terminate(),null),this._refitSharedBuffers=null,this.cancelBackgroundRebuilds()}dispose(){this._log(`Disposing resources`),this._disposeRefitWorker(),this._disposeTextures(),this._reset(),this.textureCreator&&=(this.textureCreator.dispose(),null),this.geometryExtractor=null,this.bvhBuilder=null,this.tlasBuilder=null,this._blasRefitter=null}},ts=[[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]],ns=[[-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]],rs=[[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 is(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=ts[i],o=ns[i],s=rs[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 as=1/(4*Math.PI);function os(e){let t=e.userData||{},n=Number.isFinite(t.exposure)?t.exposure:0,r=e.intensity*2**n,i=e.color.r,a=e.color.g,o=e.color.b;if(t.useTemperature){let[e,n,r]=is(t.temperature??6500);i*=e,a*=n,o*=r}return{r:i,g:a,b:o,intensity:r}}var ss=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=os(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=os(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=os(e);this.pointLightCache.push({data:[t.x,t.y,t.z,i.r,i.g,i.b,i.intensity*as,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=os(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*as,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}))}}},cs={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://cdn.jsdelivr.net/npm/denoiser/tzas/`,upscalerModelBaseUrl:`https://huggingface.co/notaneimu/onnx-image-models/resolve/main/`,cacheNamespace:`rayzee`};function ls(e){e&&Object.assign(cs,e)}function us(){return{...cs}}var ds=kt(`pathtracer`),fs=4,ps=class extends _e{constructor(e,t,n,i={}){super(`PathTracer`,{...i,executionMode:ge.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 es,this.lightSerializer=new ss,this.accumulationEnabled=!0,this.isComplete=!1,this.cameras=[],this.performanceMonitor=Ne(),this.completionThreshold=0,this.renderLimitMode=`frames`,this._initDataTextures(),this.storageTextures=new It(0,0),this.uniforms=new Rt(a,o),this._defineUniformGetters(),this.materialData=new Kt(this.sdfs),this.materialData.callbacks.onReset=()=>this.reset(),this.materialData.callbacks.getTriangleData=()=>({array:this.triangleStorageAttr?.array,count:this.triangleCount}),this.materialData.callbacks.onTriangleDataChanged=()=>{this.triangleStorageAttr&&(this.triangleStorageAttr.needsUpdate=!0)},this.environment=new En(this.scene,this.uniforms),this.environment.callbacks.onReset=()=>this.reset(),this.environment.callbacks.getSceneTextureNodes=()=>this.shaderBuilder.getSceneTextureNodes(),this.shaderBuilder=new Ea,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.updateCompletionThreshold()}_initDataTextures(){this.triangleStorageAttr=null,this.triangleStorageNode=null,this.triangleCount=0,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.bvhNodeCount=0,this.directionalLightsData=null,this.pointLightsData=null,this.spotLightsData=null,this.areaLightsData=null,this.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 ve(this.renderer,{uniforms:{maxBounceCount:{get value(){return e.maxBounces.value},set value(t){e.maxBounces.value=t}},enableAccumulation:{get value(){return e.enableAccumulation.value},set value(t){e.enableAccumulation.value=t}},enableEmissiveTriangleSampling:{get value(){return e.enableEmissiveTriangleSampling.value},set value(t){e.enableEmissiveTriangleSampling.value=t}},cameraIsMoving:{get value(){return e.cameraIsMoving.value},set value(t){e.cameraIsMoving.value=t}}}},{enabled:U.interactionModeEnabled,qualitySettings:{maxBounceCount:1,enableAccumulation:!1,enableEmissiveTriangleSampling:!1},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}=us(),a=e.loadAsync(n).then(e=>{this.stbnScalarTexture=t(e),P.value=e,ds.debug(`STBN scalar atlas ${J.px(e.image.width,e.image.height)}`)}),o=e.loadAsync(i).then(e=>{this.stbnVec2Texture=t(e),F.value=e,ds.debug(`STBN vec2 atlas ${J.px(e.image.width,e.image.height)}`)});this.blueNoiseReady=Promise.allSettled([a,o]).then(e=>{for(let t of e)t.status===`rejected`&&ds.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.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,ds.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}setTriangleData(e,r){if(!e)return;let i=e.length/4;this.triangleStorageNode?(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode.value=this.triangleStorageAttr,this.triangleStorageNode.bufferCount=i):(this.triangleStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.triangleStorageNode=(0,n.storage)(this.triangleStorageAttr,`vec4`,i).toReadOnly()),this.triangleCount=r,ds.debug(`${J.n(this.triangleCount)} triangles (storage buffer)`)}setBVHData(e){if(!e)return;let r=e.length/4;this.bvhStorageNode?(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode.value=this.bvhStorageAttr,this.bvhStorageNode.bufferCount=r):(this.bvhStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.bvhStorageNode=(0,n.storage)(this.bvhStorageAttr,`vec4`,r).toReadOnly()),this.bvhNodeCount=Math.floor(r/fs),ds.debug(`${J.n(this.bvhNodeCount)} BVH nodes (storage buffer)`)}setInstanceTable(e){this._instanceTable=e}setMeshVisibilityData(e){if(!(!e||e.length===0||!this._instanceTable)){for(let t=0;t<e.length;t++)this._patchTLASLeafVisibility(t,this._isWorldVisible(e[t]));this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}}updateMeshVisibility(e,t){this._patchTLASLeafVisibility(e,t)&&this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}updateAllMeshVisibility(){if(!(!this._meshRefs||!this._instanceTable)){for(let e=0;e<this._meshRefs.length;e++)this._patchTLASLeafVisibility(e,this._isWorldVisible(this._meshRefs[e]));this.bvhStorageAttr&&(this.bvhStorageAttr.needsUpdate=!0)}}_patchTLASLeafVisibility(e,t){let n=this._instanceTable?.entries?.[e];return!n||n.tlasLeafIndex<0||!this.bvhStorageAttr?!1:(n.visible=t,this.bvhStorageAttr.array[n.tlasLeafIndex*16+2]=+!!t,!0)}_collectMeshRefs(e){if(!e)return[];let t=[];return e.traverse(e=>{e.isMesh&&e.userData.meshIndex!==void 0&&(t[e.userData.meshIndex]=e)}),t}_isWorldVisible(e){for(;e;){if(!e.visible)return!1;e=e.parent}return!0}_updateStorageBuffer(e,t){e&&(e.array.set(t),e.needsUpdate=!0)}updateTriangleData(e){this._updateStorageBuffer(this.triangleStorageAttr,e)}updateBVHData(e){this._updateStorageBuffer(this.bvhStorageAttr,e)}updateBufferRanges(e,t){if(this.triangleStorageAttr&&e.length>0){this.triangleStorageAttr.clearUpdateRanges();for(let t of e)this.triangleStorageAttr.addUpdateRange(t.offset,t.count);this.triangleStorageAttr.version++}if(this.bvhStorageAttr&&t.length>0){this.bvhStorageAttr.clearUpdateRanges();for(let e of t)this.bvhStorageAttr.addUpdateRange(e.offset,e.count);this.bvhStorageAttr.version++}}createStorageTextures(e,t){this.storageTextures.writeColor?this.storageTextures.setSize(e,t):this.storageTextures.create(e,t),this.resolution.value.set(e,t)}setupMaterial(){if(this.cameraOptimizer||this._initCameraOptimizer(),!this.triangleStorageNode){ds.error(`triangle data required`);return}if(!this.bvhStorageNode){ds.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=Me(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=je(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&&(P.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(),ds.debug(`${J.n(t)} emissive triangles · totalPower ${n.toFixed(4)} (storage buffer)`))}setLightBVHData(e,t){e&&(this._lbvhDataCache=e,this.lightBVHNodeCount.value=t,this._rebuildLightBuffer(),ds.debug(`light BVH ${J.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{ds.debug(`material rebuild started`),await this.sdfs.rebuildMaterials(e),this.updateSceneUniforms(),this.shaderBuilder.updateSceneTextures(this),this.updateLights(),this.reset(),ds.debug(`material rebuild complete`)}catch(e){ds.error(`material rebuild failed:`,e);try{ds.warn(`attempting recovery by resetting the path tracer`),this.reset()}catch(e){ds.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.triangleStorageNode=null,this.bvhStorageAttr=null,this.bvhStorageNode=null,this.placeholderTexture=null,this.isReady=!1}},ms=kt(`gpu`),hs={ORIGIN_META:0,DIR_FLAGS:1,THROUGHPUT_PDF:2,RADIANCE_ALPHA:3,MEDIUM_STACK:4,MEDIUM_SIGMA_A:5,SSS_SIGMA_S:6},gs={DIST_TRI_BARY:0,NORMAL_MAT:1},_s=0,vs=(e,t)=>t===0?e:e.add(t*_s);function ys(e,t){t&&e?._attributes?.delete?.(t)}var bs=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,_s=e;let r=e*7,i=new t.StorageInstancedBufferAttribute(new Float32Array(r*4),4);this._attrs.ray=i,this.rayBuffer={rw:(0,n.storage)(i,`vec4`),ro:(0,n.storage)(i,`vec4`).toReadOnly()};let a=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);this._attrs.rng=a,this.rngBuffer={rw:(0,n.storage)(a,`uint`),ro:(0,n.storage)(a,`uint`).toReadOnly()};let o=e*2,s=new t.StorageInstancedBufferAttribute(new Float32Array(o*4),4);this._attrs.hit=s,this.hitBuffer={rw:(0,n.storage)(s,`vec4`),ro:(0,n.storage)(s,`vec4`).toReadOnly()},this.rayBytes=r*16+e*4,this.hitBytes=o*16,this.totalBytes=this.rayBytes+this.hitBytes,ms.debug(`ray pool capacity ${J.n(e)} · ${J.mb(this.totalBytes)} (rays ${J.mb(this.rayBytes)} · hits ${J.mb(this.hitBytes)})`)}resize(e){return e<=this.capacity&&this.capacity>0?!1:(this.allocate(e),!0)}dispose(){ys(this._renderer,this._attrs.ray),ys(this._renderer,this._attrs.rng),ys(this._renderer,this._attrs.hit),this._attrs={},this.rayBuffer=null,this.rngBuffer=null,this.hitBuffer=null,this.capacity=0}},xs=(e,t)=>e.element(vs(t,hs.ORIGIN_META)).xyz,Ss=(e,t)=>e.element(vs(t,hs.DIR_FLAGS)).xyz,Cs=(e,t)=>(0,n.floatBitsToUint)(e.element(vs(t,hs.DIR_FLAGS)).w),ws=(e,t)=>e.element(vs(t,hs.THROUGHPUT_PDF)).xyz,Ts=(e,t)=>e.element(vs(t,hs.THROUGHPUT_PDF)).w,Es=(e,t)=>e.element(vs(t,hs.RADIANCE_ALPHA)),Ds=e=>(0,n.uint)(e).mul(1),Os=(e,t,r,i,a,o=null)=>{let s=Ds(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))))},ks=(e,t,r)=>{let i=Ds(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))))},As=(e,t)=>e.element(Ds(t)),js=e=>(0,n.unpackUnorm2x16)(e.w).y,Ms=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)},Ns=e=>(0,n.vec3)((0,n.unpackUnorm2x16)(e.z),(0,n.unpackUnorm2x16)(e.w).x),Ps=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)))},Fs=(e,t)=>{let r=(0,n.floatBitsToUint)(e.element(vs(t,hs.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)))},Is=(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(Ps(s).shiftLeft(22))),e.element(vs(t,hs.ORIGIN_META)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(c)))},Ls=(e,t,r,i)=>e.element(vs(t,hs.DIR_FLAGS)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i))),Rs=(e,t,r,i)=>e.element(vs(t,hs.THROUGHPUT_PDF)).assign((0,n.vec4)(r,i)),zs=(e,t,n)=>e.element(vs(t,hs.RADIANCE_ALPHA)).assign(n),Bs=(e,t)=>e.element(vs(t,gs.DIST_TRI_BARY)).x,Vs=(e,t)=>(0,n.floatBitsToUint)(e.element(vs(t,gs.DIST_TRI_BARY)).y),Hs=(e,t)=>e.element(vs(t,gs.DIST_TRI_BARY)).zw,Us=(e,t)=>e.element(vs(t,gs.NORMAL_MAT)).xyz,Ws=(e,t)=>(0,n.uint)((0,n.floatBitsToUint)(e.element(vs(t,gs.NORMAL_MAT)).w).bitAnd(65535)),Gs=(e,t,r,i,a,o,s,c,l)=>{e.element(vs(t,gs.DIST_TRI_BARY)).assign((0,n.vec4)(r,(0,n.uintBitsToFloat)(i),a,o)),e.element(vs(t,gs.NORMAL_MAT)).assign((0,n.vec4)(s,(0,n.uintBitsToFloat)(c.bitOr(l.shiftLeft(16)))))},Ks=(e,t)=>{let r=e.element(vs(t,hs.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}},qs=(e,t,r,i,a,o,s,c=(0,n.uint)(0))=>e.element(vs(t,hs.MEDIUM_STACK)).assign((0,n.vec4)((0,n.uintBitsToFloat)(r.bitOr(i.shiftLeft(8)).bitOr(c.shiftLeft(16))),a,o,s)),Js=(e,t)=>e.element(vs(t,hs.MEDIUM_SIGMA_A)).xyz,Ys=(e,t,r)=>{let i=e.element(vs(t,hs.MEDIUM_SIGMA_A)).w.toVar();e.element(vs(t,hs.MEDIUM_SIGMA_A)).assign((0,n.vec4)(r,i))},Xs=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))},Zs=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),Qs=(e,t)=>Zs((0,n.floatBitsToUint)(e.element(vs(t,hs.MEDIUM_SIGMA_A)).w)),$s=(e,t,r)=>{let i=e.element(vs(t,hs.MEDIUM_SIGMA_A)).xyz.toVar();e.element(vs(t,hs.MEDIUM_SIGMA_A)).assign((0,n.vec4)(i,(0,n.uintBitsToFloat)(Xs(r))))},ec=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).bitAnd(255)),tc=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).shiftRight(8).bitAnd(255)),nc=(e,t)=>(0,n.int)((0,n.floatBitsToUint)(e.element(vs(t,hs.ORIGIN_META)).w).shiftRight(16).bitAnd((0,n.uint)(63))),rc=(e,t)=>{let n=e.element(vs(t,hs.SSS_SIGMA_S));return{sigmaS:n.xyz,g:n.w}},ic=(e,t,r,i)=>e.element(vs(t,hs.SSS_SIGMA_S)).assign((0,n.vec4)(r,i)),ac=kt(`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},oc=65535,sc={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},cc=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=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1),i=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);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=new t.StorageInstancedBufferAttribute(new Uint32Array(e),1);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,ac.debug(`queues capacity ${J.n(e)} · ${J.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(){ys(this._renderer,this._countersAttr),ys(this._renderer,this._bounceCountsAttr),ys(this._renderer,this._attrA),ys(this._renderer,this._attrB),ys(this._renderer,this._sortAttr),ys(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}},lc={[r.RGBAFormat]:4,[r.RGBFormat]:3,[r.RGFormat]:2,[r.RedFormat]:1},uc={[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 dc(e){return(lc[e.format]??4)*(uc[e.type]??4)}function fc(e){return e?.array?.byteLength||0}function pc(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*dc(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*dc(e)}var mc=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.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: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*dc(e));return a}return this._isResident(e)?pc(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(` `)}]`}},hc=kt(`wavefront`),gc=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);hc.info(J.list([`${e.length} kernel${e.length===1?``:`s`} compiled in ${J.ms(t)}`,`slowest ${n.slice(0,2).map(e=>`${e.name} ${J.ms(e.ms)}`).join(`, `)}`])),e.forEach(e=>hc.debug(`kernel '${e.name}' first dispatch (incl. compilation) ${J.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()}},_c=(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}),vc=(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(),_=_c(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=re(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(ar({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)))}),Dn({origin:v,direction:y})});function yc(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=L({state:he({pixelCoord:S,rayIndex:(0,n.int)(0),frame:o}).toVar()}).toVar(),T=me(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=Dn.wrap(vc(E,w,s,c,l,u,d,f,p,m,h,g,_,v,y));Is(t,x,D.origin,(0,n.int)(0),(0,n.int)(0)),Ls(t,x,D.direction,(0,n.uint)(sc.ACTIVE)),Rs(t,x,(0,n.vec4)(1,1,1,0).xyz,(0,n.float)(0)),zs(t,x,(0,n.vec4)((0,n.vec3)(0),(0,n.float)(1))),(0,n.If)(k,()=>{Os(i,x,(0,n.vec3)(0,0,1),(0,n.float)(1),(0,n.vec3)(0),(0,n.float)(0)),$s(t,x,(0,n.vec3)(1))}),qs(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 bc=32,xc=4096,Sc=4,Cc=8,wc=1e8,Tc=()=>(0,n.array)(`int`,bc).toVar(),Ec=(0,n.wgslFn)(`
|
|
472
472
|
fn RayTriangleGeometry( rayOrigin: vec3f, rayDir: vec3f, pA: vec3f, pB: vec3f, pC: vec3f, closestHitDst: f32, woopParams: vec4f ) -> vec4f {
|
|
473
473
|
|
|
474
474
|
// Returns vec4(t, u, v, hit) where hit > 0.5 means intersection.
|
|
@@ -727,10 +727,196 @@
|
|
|
727
727
|
}
|
|
728
728
|
`),_d=class extends _e{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:ge.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)(dd,`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=nr((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)(fd)).div((0,n.float)(pd)).mul((0,n.float)(dd)).floor().clamp(0,(0,n.float)(dd-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)(hd)));(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)(dd,({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)(dd,({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)(fd).add((0,n.float)(t).add(.5).mul((0,n.float)(md)));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=gd(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()}},vd=class extends _e{constructor(e,i={}){super(`Compositor`,{...i,executionMode:ge.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,Yn)),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`)||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,Yn).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}},yd=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={}}},bd=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):[]}},xd=!1,Sd=[],Cd=new WeakMap;function wd(e){xd=!!e}function Td(){return Sd.slice()}function Ed(){Sd.length=0}function Dd(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var Od=e=>!e||!e.image||!(e.image.width>0);function kd(e,t,n){if(!xd){n();return}let r=Cd.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},Cd.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&Ad(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=Dd(e).filter(t=>Od(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 Ad(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(Od(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&Sd.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 jd=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(lo.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 yd,this.eventBus=new bd,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(kd(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()}},Md=kt(`engine`),Nd=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,Md.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}},Pd=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:V.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:V.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:V.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:V.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:V.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:V.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}},Fd={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},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},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`}},Id=Object.freeze({DEFAULT:`default`,HOST:`host`,SCENE_METADATA:`scene-metadata`,MODE_PRESET:`mode-preset`}),Ld={bounces:`maxBounces`,debugMode:`visMode`},Rd=class extends r.EventDispatcher{constructor(e=U,{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}){let s=new r.Vector2,c=(t,n)=>{s.set(n?.[0]??0,n?.[1]??0).multiplyScalar(r.MathUtils.DEG2RAD),e.pathTracer?.setUniform(t,s)};return{handleCameraProjection:t=>{let n=t===`equirectangular`;e.pathTracer?.setUniform(`cameraProjection`,+!!n),n&&(a?.requiresMotionVectors&&a.setDenoiserStrategy(`edgeaware`),o?.setAutoFocusMode(`manual`))},handlePanoramaLonRange:e=>c(`panoLonRange`,e),handlePanoramaLatRange:e=>c(`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)}}}set(e,t,{reset:n,silent:r,source:i=Id.HOST}={}){let a=this._applyOne(e,t,i);a?.route&&((n===void 0?a.route.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:V.SETTING_CHANGED,key:e,value:t,prev:a.prev}))}setMany(e,{silent:t,reset:n,source:r=Id.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:V.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=Fd[e];return i?(this._applyRoute(i,t,r),{route:i,prev:r}):(this._reportUnknownKey(e),{route:null,prev:r})}_reportUnknownKey(e){this._issues?.record(lo.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)??Id.DEFAULT,routed:Fd[t]!==void 0};return e}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=Fd[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(Fd))t in e&&(this._values.set(t,e[t]),this._sources.set(t,Id.DEFAULT));for(let[t,n]of Object.entries(Ld))t in e&&(this._values.set(n,e[t]),this._sources.set(n,Id.DEFAULT))}},zd={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},Bd=e=>e===` `||e===` `||e===`
|
|
729
729
|
`||e===`\r`||e===`\f`,Vd=e=>e>=`0`&&e<=`9`,Hd=(e,t,n)=>!!(Vd(e)||e===`.`&&Vd(t)||(e===`-`||e===`+`)&&(Vd(t)||t===`.`&&Vd(n)));function Ud(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e[r];if(Bd(i)){r++;continue}if(i===`#`){for(;r<n&&e[r]!==`
|
|
730
|
-
`;)r++;continue}if(i===`[`){t.push({type:zd.LBRACKET}),r++;continue}if(i===`]`){t.push({type:zd.RBRACKET}),r++;continue}if(i===`"`){r++;let i=r;for(;r<n&&e[r]!==`"`;)r++;if(r>=n)throw Error(`PBRT tokenizer: unterminated string literal`);t.push({type:zd.STRING,value:e.slice(i,r)}),r++;continue}if(Hd(i,e[r+1],e[r+2])){let i=r;for(r++;r<n;){let t=e[r];if(t>=`0`&&t<=`9`||t===`.`||t===`e`||t===`E`||t===`-`||t===`+`)r++;else break}let a=e.slice(i,r),o=Number(a);if(Number.isNaN(o))throw Error(`PBRT tokenizer: invalid number "${a}"`);t.push({type:zd.NUMBER,value:o});continue}{let i=r;for(;r<n&&!Bd(e[r])&&e[r]!==`"`&&e[r]!==`[`&&e[r]!==`]`&&e[r]!==`#`;)r++;t.push({type:zd.WORD,value:e.slice(i,r)})}}return t}function Wd(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Gd(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 Kd(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function qd(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function Jd(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 Yd(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Xd(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 Zd(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function Qd(e,t,n){let r=Zd(Yd(t,e)),i=Zd(Xd(Zd(n),r)),a=Xd(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 $d(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 Wd();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 ef=class{constructor(e={}){this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:[],objects:new Map,warnings:[]},this.ctm=Wd(),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.tokens=[],this.pos=0,this._warnedUnknown=new Set}parse(e,t=``){return this.dirStack=[t],this._run(Ud(e)),this.ir}_peek(){return this.tokens[this.pos]}_next(){return this.tokens[this.pos++]}_expectNumber(e){let t=this._next();if(!t||t.type!==zd.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!==zd.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===zd.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==zd.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===zd.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()}}return e}_parseParamValue(){let e=[];if(this._peek()&&this._peek().type===zd.LBRACKET){for(this._next();this._peek()&&this._peek().type!==zd.RBRACKET;)e.push(this._coerceValueToken(this._next()));this._next()}else e.push(this._coerceValueToken(this._next()));return e}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===zd.NUMBER||e.type===zd.STRING)return e.value;if(e.type===zd.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}_run(e){let t=this.tokens,n=this.pos;for(this.tokens=e,this.pos=0;this.pos<this.tokens.length;){let e=this._next();if(e.type!==zd.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);this._directive(e.value)}this.tokens=t,this.pos=n}_directive(e){switch(e){case`Identity`:this.ctm=Wd();break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this.ctm=Gd(this.ctm,Kd(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this.ctm=Gd(this.ctm,qd(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this.ctm=Gd(this.ctm,Jd(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=Qd([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this.ctm=Gd(this.ctm,$d(t));break}case`Transform`:this.ctm=this._readBracketedOrBareNumbers(16);break;case`ConcatTransform`:{let e=this._readBracketedOrBareNumbers(16);this.ctm=Gd(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:$d(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=Wd(),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===zd.STRING&&this._next(),this._peek()&&this._peek().type===zd.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.ctm.slice()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this.ctm.slice(),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.ir.instances.push({name:e,ctm:this.ctm.slice()});break}case`Include`:case`Import`:{let t=this._expectString(e);this._include(t);break}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=Gd($d(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}_include(e){let t=this.resolveInclude(e,this.dirStack[this.dirStack.length-1]);if(t==null){this._warn(`Include target not found: ${e}`);return}let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(n),this._run(Ud(t)),this.dirStack.pop()}_skipTypeAndParams(){this._peek()&&this._peek().type===zd.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===zd.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}`))}},tf={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]},nf=[.92,.92,.92];function rf(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 af(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function of(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function sf(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:rf(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=cf(i.value[0]);return e&&tf[e]?{rgb:tf[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 cf(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(tf))if(e.toLowerCase().includes(t))return t;return null}function lf(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=af(e,`uroughness`,null),r=af(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function uf(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 sf(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await sf(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 sf(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await sf(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 sf(i,`eta`,t,nf)).rgb||nf:tf.cu);a.metalness=1,a.roughness=lf(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=af(i,`eta`,1.5),a.roughness=lf(i,0),a.thickness=n===`thindielectric`?0:af(i,`thickness`,0);break;case`coateddiffuse`:s(await sf(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=lf(i,0);break;case`diffusetransmission`:{let e=await sf(i,`transmittance`,t,[.25,.25,.25]);s(await sf(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,af(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([uf(o,t),uf(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 sf(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}var df=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],ff=class{constructor(e={}){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}warn(e){this.warnings.push(e)}async build(e){this.ir=e;let t=new r.Group;t.name=`PBRTScene`;for(let n=0;n<e.shapes.length;n++){let r=await this._buildShapeMesh(e.shapes[n],e.shapes[n].ctm,`shape_${n}`);r&&t.add(r)}await this._buildInstances(e,t);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),{group:t,camera:n,environment:i,report:this.report,warnings:this.warnings.concat(e.warnings||[])}}async _buildInstances(e,t){let n=0;for(let r of e.instances){let i=e.objects.get(r.name);if(!i){this.warn(`ObjectInstance "${r.name}" has no template`);continue}for(let e of i){let i=Gd(r.ctm,e.relativeCTM||e.ctm),a=await this._buildShapeMesh(e,i,`instance_${n++}`);a&&t.add(a)}}}async _buildShapeMesh(e,t,n){let[i,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!i)return null;let o=!!i.getAttribute(`uv`),s=a;a.map&&!o&&(this.warn(`${n} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),s=a.clone(),s.map=null);let c=new r.Mesh(i,s);c.name=n;let l=this.convertHandedness?Gd(df,t):t;new r.Matrix4().fromArray(l).decompose(c.position,c.quaternion,c.scale),c.updateMatrix(),i.computeBoundingBox();let u=i.boundingBox?i.boundingBox.clone().applyMatrix4(c.matrix).getSize(new r.Vector3):new r.Vector3;return this.report.push({mesh:n,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o?`yes`:`NO`,normals:i.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:i.index?i.index.count/3:i.getAttribute(`position`).count/3}),c}async _buildGeometry(e){switch(e.type){case`trianglemesh`:return this._triangleMesh(e.params);case`bilinearmesh`:return this._bilinearMesh(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(Float32Array.from(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(Float32Array.from(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(Float32Array.from(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(o),i||n.computeVertexNormals(),n}_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}async _plyMesh(e){let t=of(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;try{let e=await this.resolvePLY(t);return e?(e.getAttribute(`normal`)||e.computeVertexNormals(),e):(this.warn(`plymesh file not found: ${t}`),null)}catch(e){return this.warn(`failed to load plymesh ${t}: ${e.message}`),null}}_sphere(e){return new r.SphereGeometry(af(e,`radius`,1),48,32)}_disk(e){let t=af(e,`radius`,1),n=af(e,`innerradius`,0),i=af(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 uf(e.material,n);return e.areaLight&&await this._applyAreaLight(r,e.areaLight,n),t.set(e.areaLight,r),r}async _applyAreaLight(e,t,n){let r=await sf(t.params,`L`,n,[1,1,1]),i=af(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=of(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 t.class===`scale`?n=await this._resolveScaleTexture(e,t):this.warn(`texture class "${t.class}" not supported (texture "${e}")`);return this._textureCache.set(e,n),n}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),l.updateMatrixWorld(!0),l}_verticalFov(e,t){let n=af(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}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=af(t.params,`scale`,1),i=of(t.params,`filename`,null);if(i)try{let e=await this.resolveEnvironment(i);if(e)return 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 sf(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)`)}},pf=new TextDecoder;function mf(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 hf(e,t){return!e||t.startsWith(`/`)?mf(t):mf(`${e}/${t}`)}var gf=class{constructor(e){this.byPath=new Map,this.byBase=new Map;for(let t in e){let n=mf(t).toLowerCase(),r={norm:n,bytes:e[t]};this.byPath.set(n,r);let i=n.split(`/`).pop(),a=this.byBase.get(i);a?a.push(r):this.byBase.set(i,[r])}}find(e){let t=mf(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t).bytes;let n=this.byBase.get(t.split(`/`).pop());return n?(n.find(e=>e.norm.endsWith(`/`+t))||n[0]).bytes:null}};function _f(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length===0)return null;let n=t.filter(e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),r=n.length?n:t;return r.sort((e,t)=>{let n=e.split(`/`).length,r=t.split(`/`).length;return n===r?e.length-t.length:n-r}),r[0]}async function vf(e){let{vfs:t,plyParser:n,imageFromBytes:r,envFromBytes:i,convertHandedness:a}=e,o=new gf(t),s=e.entryPath||_f(t);if(!s)throw Error(`PBRT loader: no .pbrt file found in archive`);let c=o.find(s);if(!c)throw Error(`PBRT loader: entry "${s}" not readable`);let l=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,u=new ef({resolveInclude:(e,t)=>{let n=o.find(hf(t,e))||o.find(e);return n?pf.decode(n):null}}).parse(pf.decode(c),l),d=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{...await new ff({convertHandedness:a,resolvePLY:async e=>{let t=o.find(e);return t?n(d(t)):null},resolveImage:async e=>{let t=o.find(e);return t?r(t,e):null},resolveEnvironment:async e=>{let t=o.find(e);return t?(i||r)(t,e):null}}).build(u),entryPath:s}}var yf=[`sourceFile`,`url`,`file`];function bf(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 xf(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Sf(e){let t=bf(e);if(!t)return null;let n=bf(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function Cf(e){let t=bf(e);if(!t)return null;let n=yf.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=xf(t.rotation),i=xf(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function wf(e){let t=Sf(e);if(!t)return null;let n=Cf(t.environment);return n?{environment:n}:null}function Tf(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=wf(e);if(t)return t}return null}var Ef={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`}},Df=/\.(usd|usda|usdc)$/i,Of=/\.(png|jpg|jpeg|avif)$/i;function kf(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}function Af(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 jf=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??Fe(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(lo.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;H({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){H({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 Ef[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);H({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`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 loadArchiveFromFile(e,t){try{let n=await this.readFileAsArrayBuffer(e),r=(0,m.unzipSync)(new Uint8Array(n));return _f(r)?await this.loadPBRTFromZip(r,t):await this.processObjMtlPairsInZip(r,t)||await this.findAndLoadModelFromZip(r,t)}catch(e){throw console.error(`Error loading ZIP archive:`,e),e}}async loadPBRTFromZip(e,t){if(H({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{group:n,environment:r,report:i,warnings:a,entryPath:o}=await vf({vfs:e,plyParser:e=>this.loaderCache.ply.parse(e),imageFromBytes:(e,t)=>this._pbrtTextureFromBytes(e,t),envFromBytes: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)}}});return i&&i.length&&typeof console.table==`function`&&(console.groupCollapsed(`PBRT loader: ${i.length} mesh(es) from "${o}"`),console.table(i),console.groupEnd()),a&&a.length&&(console.warn(`PBRT loader: ${a.length} warning(s) parsing "${o}"`),a.forEach(e=>console.warn(` •`,e))),r?.texture&&(r.texture.generateMipmaps=!0,this.applyEnvironmentToScene(r.texture)),n.name=o||t,this.releaseTargetModel(),this.targetModel=n,H({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:`${o} (from ZIP)`}),n}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(Ef[n]&&Ef[n].type===`model`)return Df.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=>Df.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&&(Df.test(e)||Of.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(Df,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{H({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=Tf(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 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 s.preload(),s}return null}resolveZipResource(e,t,n){let r=e.replace(/^\.\/|^\//,``),i=[r,`${t}/${r}`,r.split(`/`).pop()];for(let e of i)if(n[e]){let t=new Blob([n[e].buffer],{type:`application/octet-stream`});return URL.createObjectURL(t)}return console.warn(`Resource not found in ZIP: ${e}`),e}async loadOBJMTLPairFromZip(e,t,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);f.preload();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}=us(),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{H({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=Tf(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{H({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?(Ae(e),e.parent?.remove(e)):ke(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{H({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=Tf(r),H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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,H({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 Yo(`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),(!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*=Af(e,e.width,e.height,n),n.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI,n.__candelaConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let t=n.normalize??!0,i=n.shape??`rectangle`,a=n.intensity*Af(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=kf(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(Ef))r.type===e&&(t[n]=r);return t}return Ef}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}},Mf=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=Xe.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Xe.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.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(),fov:this.camera.fov,near:this.camera.near,far:this.camera.far,target:this.controls?this.controls.target.clone():null}),this.currentCameraIndex=e,e===0&&this._defaultCameraState){let e=this._defaultCameraState;this.camera.position.copy(e.position),this.camera.quaternion.copy(e.quaternion),this.camera.fov=e.fov,this.camera.near=e.near,this.camera.far=e.far,this.camera.updateProjectionMatrix(),this.camera.updateMatrixWorld(!0),this.controls&&e.target&&(this.controls.target.copy(e.target),this.controls.update())}else{let n=this.cameras[e];if(this.camera.position.copy(n.position),this.camera.quaternion.copy(n.quaternion),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=Xe.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>Xe.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:V.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Xe.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()}},Nf=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}},Pf=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=>Ff(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:If(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 Ff(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 If(e){return Math.max(0,Math.min(1,e))}function Lf(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
|
|
731
|
-
`,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=
|
|
730
|
+
`;)r++;continue}if(i===`[`){t.push({type:zd.LBRACKET}),r++;continue}if(i===`]`){t.push({type:zd.RBRACKET}),r++;continue}if(i===`"`){r++;let i=r;for(;r<n&&e[r]!==`"`;)r++;if(r>=n)throw Error(`PBRT tokenizer: unterminated string literal`);t.push({type:zd.STRING,value:e.slice(i,r)}),r++;continue}if(Hd(i,e[r+1],e[r+2])){let i=r;for(r++;r<n;){let t=e[r];if(t>=`0`&&t<=`9`||t===`.`||t===`e`||t===`E`||t===`-`||t===`+`)r++;else break}let a=e.slice(i,r),o=Number(a);if(Number.isNaN(o))throw Error(`PBRT tokenizer: invalid number "${a}"`);t.push({type:zd.NUMBER,value:o});continue}{let i=r;for(;r<n&&!Bd(e[r])&&e[r]!==`"`&&e[r]!==`[`&&e[r]!==`]`&&e[r]!==`#`;)r++;t.push({type:zd.WORD,value:e.slice(i,r)})}}return t}function Wd(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function Gd(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 Kd(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 qd(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function Jd(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function Yd(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 Xd(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function Zd(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 Qd(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function $d(e,t,n){let r=Qd(Xd(t,e)),i=Qd(Zd(Qd(n),r)),a=Zd(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 ef(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 Wd();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 tf=class{constructor(e={}){this.resolveInclude=e.resolveInclude||(()=>{throw Error(`PBRTParser: Include used but no resolveInclude provided`)}),this.ir={film:null,camera:null,namedMaterials:new Map,namedTextures:new Map,shapes:[],lights:[],instances:[],objects:new Map,warnings:[]},this.ctm=Wd(),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.tokens=[],this.pos=0,this._warnedUnknown=new Set}parse(e,t=``){return this.dirStack=[t],this._run(Ud(e)),this.ir}_peek(){return this.tokens[this.pos]}_next(){return this.tokens[this.pos++]}_expectNumber(e){let t=this._next();if(!t||t.type!==zd.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!==zd.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===zd.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==zd.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===zd.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()}}return e}_parseParamValue(){let e=[];if(this._peek()&&this._peek().type===zd.LBRACKET){for(this._next();this._peek()&&this._peek().type!==zd.RBRACKET;)e.push(this._coerceValueToken(this._next()));this._next()}else e.push(this._coerceValueToken(this._next()));return e}_coerceValueToken(e){if(!e)throw Error(`PBRT parser: unexpected EOF in parameter value`);if(e.type===zd.NUMBER||e.type===zd.STRING)return e.value;if(e.type===zd.WORD)return e.value===`true`?!0:e.value===`false`?!1:e.value;throw Error(`PBRT parser: unexpected token in parameter value: ${e.type}`)}_run(e){let t=this.tokens,n=this.pos;for(this.tokens=e,this.pos=0;this.pos<this.tokens.length;){let e=this._next();if(e.type!==zd.WORD)throw Error(`PBRT parser: expected directive, got ${e.type} ${e.value??``}`);this._directive(e.value)}this.tokens=t,this.pos=n}_directive(e){switch(e){case`Identity`:this.ctm=Wd();break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this.ctm=Kd(this.ctm,qd(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this.ctm=Kd(this.ctm,Jd(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this.ctm=Kd(this.ctm,Yd(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=$d([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this.ctm=Kd(this.ctm,ef(t));break}case`Transform`:this.ctm=this._readBracketedOrBareNumbers(16);break;case`ConcatTransform`:{let e=this._readBracketedOrBareNumbers(16);this.ctm=Kd(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:ef(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=Wd(),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===zd.STRING&&this._next(),this._peek()&&this._peek().type===zd.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.ctm.slice()});break}case`Shape`:{let e={type:this._expectString(`Shape type`),params:this._parseParams(),ctm:this.ctm.slice(),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.ir.instances.push({name:e,ctm:this.ctm.slice()});break}case`Include`:case`Import`:{let t=this._expectString(e);this._include(t);break}default:this._warnUnknown(e),this._parseParams();break}}_emitShape(e){this.currentObject===null?this.ir.shapes.push(e):(e.relativeCTM=Kd(ef(this.objectBeginCTM),e.ctm),this.ir.objects.get(this.currentObject).push(e))}_include(e){let t=this.resolveInclude(e,this.dirStack[this.dirStack.length-1]);if(t==null){this._warn(`Include target not found: ${e}`);return}let n=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;this.dirStack.push(n),this._run(Ud(t)),this.dirStack.pop()}_skipTypeAndParams(){this._peek()&&this._peek().type===zd.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===zd.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}`))}},nf={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]},rf=[.92,.92,.92];function af(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 of(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function sf(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function cf(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:af(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=lf(i.value[0]);return e&&nf[e]?{rgb:nf[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 lf(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(nf))if(e.toLowerCase().includes(t))return t;return null}function uf(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=of(e,`uroughness`,null),r=of(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function df(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 cf(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await cf(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 cf(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await cf(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 cf(i,`eta`,t,rf)).rgb||rf:nf.cu);a.metalness=1,a.roughness=uf(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=of(i,`eta`,1.5),a.roughness=uf(i,0),a.thickness=n===`thindielectric`?0:of(i,`thickness`,0);break;case`coateddiffuse`:s(await cf(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=uf(i,0);break;case`diffusetransmission`:{let e=await cf(i,`transmittance`,t,[.25,.25,.25]);s(await cf(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,of(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([df(o,t),df(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 cf(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 ff(e){return e===3?3/16:3/(8*e)}function pf(e){return 1/(e+3/(8*ff(e)))}function mf(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 hf(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 gf(e,t){let n=e.length/3,r=mf(n,t),i=r.edgeV0.length,a=hf(e,r,n,ff,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 _f(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=gf(i,a);i=e.positions,a=e.indices,o++}let s=i.length/3,c=hf(i,mf(s,a),s,pf,1/5);return{positions:Float32Array.from(c),indices:Uint32Array.from(a),levels:o}}function vf(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)]}function yf(e,t,n,r,i,a,o){let s=Math.min(Math.max(i*t-.5,0),t-1),c=Math.min(Math.max(a*n-.5,0),n-1),l=Math.floor(s),u=Math.floor(c),d=Math.min(l+1,t-1),f=Math.min(u+1,n-1),p=s-l,m=c-u,h=(u*t+l)*r,g=(u*t+d)*r,_=(f*t+l)*r,v=(f*t+d)*r;for(let t=0;t<3;t++){let n=e[h+t]*(1-p)+e[g+t]*p,r=e[_+t]*(1-p)+e[v+t]*p;o[t]=n*(1-m)+r*m}}function bf(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?ef(t):null,c=[0,0,0];for(let t=0;t<a;t++){let r=(1-(t+.5)/a)*Math.PI,l=Math.sin(r),u=Math.cos(r);for(let r=0;r<i;r++){let a=((r+.5)/i-.5)*2*Math.PI,d=l*Math.cos(a),f=u,p=l*Math.sin(a);if(s){let e=s,t=e[0]*d+e[4]*f+e[8]*p,n=e[1]*d+e[5]*f+e[9]*p,r=e[2]*d+e[6]*f+e[10]*p,i=Math.hypot(t,n,r)||1;d=t/i,f=n/i,p=r/i}let[m,h]=vf(d,f,p);yf(e.data,e.width,e.height,e.channels,m,e.bottomUp?1-h:h,c);let g=(t*i+r)*4;o[g]=c[0]*n,o[g+1]=c[1]*n,o[g+2]=c[2]*n,o[g+3]=1}}return{data:o,width:i,height:a}}var xf=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],Sf=class{constructor(e={}){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}warn(e){this.warnings.push(e)}async build(e){this.ir=e;let t=new r.Group;t.name=`PBRTScene`;for(let n=0;n<e.shapes.length;n++){let r=await this._buildShapeMesh(e.shapes[n],e.shapes[n].ctm,`shape_${n}`);r&&t.add(r)}await this._buildInstances(e,t);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),{group:t,camera:n,environment:i,report:this.report,warnings:this.warnings.concat(e.warnings||[])}}async _buildInstances(e,t){let n=0;for(let r of e.instances){let i=e.objects.get(r.name);if(!i){this.warn(`ObjectInstance "${r.name}" has no template`);continue}for(let e of i){let i=Kd(r.ctm,e.relativeCTM||e.ctm),a=await this._buildShapeMesh(e,i,`instance_${n++}`);a&&t.add(a)}}}async _buildShapeMesh(e,t,n){let[i,a]=await Promise.all([this._buildGeometry(e),this._getMaterial(e)]);if(!i)return null;let o=!!i.getAttribute(`uv`),s=a;a.map&&!o&&(this.warn(`${n} (${e.type}, "${e.material?.type||`diffuse`}") has a texture map but no UVs — dropping map, using base color`),s=a.clone(),s.map=null);let c=new r.Mesh(i,s);c.name=n;let l=this.convertHandedness?Kd(xf,t):t;new r.Matrix4().fromArray(l).decompose(c.position,c.quaternion,c.scale),c.updateMatrix(),i.computeBoundingBox();let u=i.boundingBox?i.boundingBox.clone().applyMatrix4(c.matrix).getSize(new r.Vector3):new r.Vector3;return this.report.push({mesh:n,shape:e.type,material:e.material?.type||`diffuse`,color:`#`+s.color.getHexString(),map:s.map?`yes`:`-`,uv:o?`yes`:`NO`,normals:i.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:i.index?i.index.count/3:i.getAttribute(`position`).count/3}),c}async _buildGeometry(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`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(Float32Array.from(t),3));let i=e.N?.value;i&&i.length===t.length&&n.setAttribute(`normal`,new r.Float32BufferAttribute(Float32Array.from(i),3));let a=(e.uv||e.st)?.value;a&&a.length===t.length/3*2&&n.setAttribute(`uv`,new r.Float32BufferAttribute(Float32Array.from(a),2));let o=e.indices?.value;return o&&o.length&&n.setIndex(o),i||n.computeVertexNormals(),n}_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(of(e,`levels`,3)))),{positions:a,indices:o,levels:s}=_f(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}async _plyMesh(e){let t=sf(e,`filename`,null);if(!t)return this.warn(`plymesh missing filename`),null;try{let e=await this.resolvePLY(t);return e?(e.getAttribute(`normal`)||e.computeVertexNormals(),e):(this.warn(`plymesh file not found: ${t}`),null)}catch(e){return this.warn(`failed to load plymesh ${t}: ${e.message}`),null}}_sphere(e){return new r.SphereGeometry(of(e,`radius`,1),48,32)}_disk(e){let t=of(e,`radius`,1),n=of(e,`innerradius`,0),i=of(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 df(e.material,n);return e.areaLight&&await this._applyAreaLight(r,e.areaLight,n),t.set(e.areaLight,r),r}async _applyAreaLight(e,t,n){let r=await cf(t.params,`L`,n,[1,1,1]),i=of(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=sf(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 t.class===`scale`?n=await this._resolveScaleTexture(e,t):this.warn(`texture class "${t.class}" not supported (texture "${e}")`);return this._textureCache.set(e,n),n}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),Gd(e.cameraToWorld)>0!==this.convertHandedness&&(l.scale.x=-1),l.updateMatrixWorld(!0),l}_verticalFov(e,t){let n=of(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,o=a?.data;if(!o||!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 s=o.length/(a.width*a.height);if(!Number.isInteger(s)||s<3)return null;let{data:c,width:l,height:u}=bf({data:o,width:a.width,height:a.height,channels:s,bottomUp:!0},t.ctm,n),d=new r.DataTexture(c,l,u,r.RGBAFormat,r.FloatType);return d.mapping=r.EquirectangularReflectionMapping,d.minFilter=r.LinearFilter,d.magFilter=r.LinearFilter,d.needsUpdate=!0,d}async _buildEnvironment(e){let t=e.find(e=>e.type===`infinite`);if(!t)return null;let n=of(t.params,`scale`,1),i=sf(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 cf(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)`)}},Cf=new TextDecoder;function wf(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 Tf(e,t){return!e||t.startsWith(`/`)?wf(t):wf(`${e}/${t}`)}var Ef=class{constructor(e){this.byPath=new Map,this.byBase=new Map;for(let t in e){let n=wf(t).toLowerCase(),r={norm:n,bytes:e[t]};this.byPath.set(n,r);let i=n.split(`/`).pop(),a=this.byBase.get(i);a?a.push(r):this.byBase.set(i,[r])}}find(e){let t=wf(e).toLowerCase();if(this.byPath.has(t))return this.byPath.get(t).bytes;let n=this.byBase.get(t.split(`/`).pop());return n?(n.find(e=>e.norm.endsWith(`/`+t))||n[0]).bytes:null}};function Df(e){try{return Cf.decode(e)}catch{return``}}function Of(e){let t=Object.keys(e).filter(e=>e.toLowerCase().endsWith(`.pbrt`));if(t.length<=1)return t;let n=new Map(t.map(t=>[t,Df(e[t])])),r=new Set;for(let e of n.values())for(let t of e.matchAll(/^[ \t]*(?:Include|Import)[ \t]+"([^"]+)"/gm))r.add(wf(t[1]).toLowerCase().split(`/`).pop());let i=(e,t)=>{let n=e.filter(t);return n.length?n:e},a=i(t,e=>/^[ \t]*WorldBegin\b/m.test(n.get(e)));return a=i(a,e=>!r.has(e.toLowerCase().split(`/`).pop())),a=i(a,e=>/(^|\/)(scene|main)\.pbrt$/i.test(e)),a.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 kf(e){return Of(e)[0]||null}async function Af(e){let{vfs:t,plyParser:n,imageFromBytes:r,envFromBytes:i,convertHandedness:a}=e,o=new Ef(t),s=e.entryPath||kf(t);if(!s)throw Error(`PBRT loader: no .pbrt file found in archive`);let c=o.find(s);if(!c)throw Error(`PBRT loader: entry "${s}" not readable`);let l=s.includes(`/`)?s.slice(0,s.lastIndexOf(`/`)):``,u=new tf({resolveInclude:(e,t)=>{let n=o.find(Tf(t,e))||o.find(e);return n?Cf.decode(n):null}}).parse(Cf.decode(c),l),d=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{...await new Sf({convertHandedness:a,resolvePLY:async e=>{let t=o.find(e);return t?n(d(t)):null},resolveImage:async e=>{let t=o.find(e);return t?r(t,e):null},resolveEnvironment:async e=>{let t=o.find(e);return t?(i||r)(t,e):null}}).build(u),entryPath:s}}var jf=[`sourceFile`,`url`,`file`];function Mf(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 Nf(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Pf(e){let t=Mf(e);if(!t)return null;let n=Mf(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function Ff(e){let t=Mf(e);if(!t)return null;let n=jf.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=Nf(t.rotation),i=Nf(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function If(e){let t=Pf(e);if(!t)return null;let n=Ff(t.environment);return n?{environment:n}:null}function Lf(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=If(e);if(t)return t}return null}var Rf={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`}},zf=/\.(usd|usda|usdc)$/i,Bf=/\.(png|jpg|jpeg|avif)$/i,Vf=3e4;function Hf(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}function Uf(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 Wf=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??Fe(),this._loadingManager.onError=e=>{this._loadCancelled||this._issues?.record(lo.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;H({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){H({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 Rf[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);H({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`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 loadArchiveFromFile(e,t,{pbrtEntry:n=null}={}){try{let r=await this.readFileAsArrayBuffer(e),i=(0,m.unzipSync)(new Uint8Array(r));return kf(i)?await this.loadPBRTFromZip(i,t,n):await this.processObjMtlPairsInZip(i,t)||await this.findAndLoadModelFromZip(i,t)}catch(e){throw console.error(`Error loading ZIP archive:`,e),e}}async loadPBRTFromZip(e,t,n=null){if(H({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 r=e=>this.loaderCache.ply.parse(e),i=(e,t)=>this._pbrtTextureFromBytes(e,t),a=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)}},o=n&&Of(e).includes(n)?n:null;n&&!o&&console.warn(`PBRT entry "${n}" is not a scene in this archive — auto-detecting instead`);let{group:s,environment:c,report:l,warnings:u,entryPath:d}=await Af({vfs:e,entryPath:o,plyParser:r,imageFromBytes:i,envFromBytes:a}),f=Of(e);if(f.length>1){let e=f.filter(e=>e!==d);console.warn(`PBRT archive holds ${f.length} scenes; loaded "${d}". Others: ${e.join(`, `)}`),this._issues?.record(lo.ASSET_AMBIGUOUS_ENTRY,`archive holds ${f.length} pbrt scenes; loaded "${d}"`,{loaded:d,alternatives:e},uo.WARNING)}return l&&l.length&&typeof console.table==`function`&&(console.groupCollapsed(`PBRT loader: ${l.length} mesh(es) from "${d}"`),console.table(l),console.groupEnd()),u&&u.length&&(console.warn(`PBRT loader: ${u.length} warning(s) parsing "${d}"`),u.forEach(e=>console.warn(` •`,e))),c?.texture&&(c.texture.generateMipmaps=!0,this.applyEnvironmentToScene(c.texture)),s.name=d||t,this.releaseTargetModel(),this.targetModel=s,c?.texture&&(this.sceneMetadata={environment:{rotation:0,intensity:1}}),H({isLoading:!0,status:`Processing PBRT geometry...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:s,filename:`${d} (from ZIP)`}),s}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(Rf[n]&&Rf[n].type===`model`)return zf.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=>zf.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&&(zf.test(e)||Bf.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(zf,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{H({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=Lf(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),Vf))]);return clearTimeout(r),i||this._issues?.record(lo.TEXTURE_BUILD_FAILED,`MTL textures did not decode within ${Vf}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}=us(),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{H({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=Lf(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{H({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?(Ae(e),e.parent?.remove(e)):ke(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{H({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=Lf(r),H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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(H({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,H({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,H({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 Yo(`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*=Uf(e,e.width,e.height,n),n.__radianceConverted=!0),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI,n.__candelaConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let t=n.normalize??!0,i=n.shape??`rectangle`,a=n.intensity*Uf(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=Hf(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(Rf))r.type===e&&(t[n]=r);return t}return Rf}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}},Gf=Object.freeze(new r.Vector3(1,1,1)),Kf=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=Xe.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=Xe.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??Gf),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=Xe.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>Xe.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:V.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>Xe.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()}},qf=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}},Jf=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=>Yf(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:Xf(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 Yf(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 Xf(e){return Math.max(0,Math.min(1,e))}function Zf(e,t=`ies`){let n=e.search(/TILT\s*=/i);if(n<0)throw Error(`IES (${t}): missing TILT line`);let r=e.indexOf(`
|
|
731
|
+
`,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=tp(o),t=2+2*Number(e[1]);o=np(o,t)}let s=tp(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 Qf(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=rp(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=ip(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=rp(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=ip(ip(f,h,d),ip(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function $f(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 ep(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 tp(e){return e.split(/\s+/).filter(e=>e.length>0)}function np(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function rp(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 ip(e,t,n){return e+(t-e)*n}var ap=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=Zf(await r.text(),e.name);return{it:e,profile:i,grid:Qf(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=$f(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:ep(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:op(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 op(e){return Math.max(0,Math.min(1,e))}var sp=new Set([r.NoToneMapping,r.LinearToneMapping,r.ReinhardToneMapping,r.CineonToneMapping,r.ACESFilmicToneMapping,r.AgXToneMapping,r.NeutralToneMapping]);function cp(e){return sp.has(e)?e:r.ACESFilmicToneMapping}var lp=`
|
|
732
|
+
fn tmSaturation( c: vec3f, saturation: f32 ) -> vec3f {
|
|
733
|
+
if ( saturation == 1.0 ) { return c; }
|
|
734
|
+
let luma = dot( c, vec3f( 0.2126, 0.7152, 0.0722 ) );
|
|
735
|
+
return vec3f( luma ) + ( c - vec3f( luma ) ) * saturation;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
fn tmSrgb1( c: f32 ) -> f32 {
|
|
739
|
+
if ( c <= 0.0031308 ) { return 12.92 * c; }
|
|
740
|
+
return 1.055 * pow( c, 1.0 / 2.4 ) - 0.055;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
fn tmSrgb( c: vec3f ) -> vec3f {
|
|
744
|
+
return vec3f( tmSrgb1( c.r ), tmSrgb1( c.g ), tmSrgb1( c.b ) );
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
fn tmReinhard( c: vec3f ) -> vec3f {
|
|
748
|
+
return clamp( c / ( c + vec3f( 1.0 ) ), vec3f( 0.0 ), vec3f( 1.0 ) );
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
fn tmCineon1( x: f32 ) -> f32 {
|
|
752
|
+
let c = max( x - 0.004, 0.0 );
|
|
753
|
+
return pow( ( c * ( 6.2 * c + 0.5 ) ) / ( c * ( 6.2 * c + 1.7 ) + 0.06 ), 2.2 );
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
fn tmCineon( c: vec3f ) -> vec3f {
|
|
757
|
+
return vec3f( tmCineon1( c.r ), tmCineon1( c.g ), tmCineon1( c.b ) );
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
fn tmAcesFit( c: f32 ) -> f32 {
|
|
761
|
+
return ( c * ( c + 0.0245786 ) - 0.000090537 ) / ( c * ( 0.983729 * c + 0.4329510 ) + 0.238081 );
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
fn tmAces( cIn: vec3f ) -> vec3f {
|
|
765
|
+
let c = cIn / 0.6;
|
|
766
|
+
var i = vec3f(
|
|
767
|
+
0.59719 * c.r + 0.35458 * c.g + 0.04823 * c.b,
|
|
768
|
+
0.07600 * c.r + 0.90834 * c.g + 0.01566 * c.b,
|
|
769
|
+
0.02840 * c.r + 0.13383 * c.g + 0.83777 * c.b
|
|
770
|
+
);
|
|
771
|
+
i = vec3f( tmAcesFit( i.r ), tmAcesFit( i.g ), tmAcesFit( i.b ) );
|
|
772
|
+
let o = vec3f(
|
|
773
|
+
1.60475 * i.r - 0.53108 * i.g - 0.07367 * i.b,
|
|
774
|
+
-0.10208 * i.r + 1.10813 * i.g - 0.00605 * i.b,
|
|
775
|
+
-0.00327 * i.r - 0.07276 * i.g + 1.07602 * i.b
|
|
776
|
+
);
|
|
777
|
+
return clamp( o, vec3f( 0.0 ), vec3f( 1.0 ) );
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
fn tmAgxApprox( x: f32 ) -> f32 {
|
|
781
|
+
let x2 = x * x;
|
|
782
|
+
let x4 = x2 * x2;
|
|
783
|
+
return 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
fn tmAgx( r: vec3f ) -> vec3f {
|
|
787
|
+
let c = vec3f(
|
|
788
|
+
0.6274 * r.r + 0.3293 * r.g + 0.0433 * r.b,
|
|
789
|
+
0.0691 * r.r + 0.9195 * r.g + 0.0113 * r.b,
|
|
790
|
+
0.0164 * r.r + 0.0880 * r.g + 0.8956 * r.b
|
|
791
|
+
);
|
|
792
|
+
var a = vec3f(
|
|
793
|
+
0.856627153315983 * c.r + 0.0951212405381588 * c.g + 0.0482516061458583 * c.b,
|
|
794
|
+
0.137318972929847 * c.r + 0.761241990602591 * c.g + 0.101439036467562 * c.b,
|
|
795
|
+
0.11189821299995 * c.r + 0.0767994186031903 * c.g + 0.811302368396859 * c.b
|
|
796
|
+
);
|
|
797
|
+
|
|
798
|
+
let agxMinEv = -12.47393;
|
|
799
|
+
let agxMaxEv = 4.026069;
|
|
800
|
+
let range = agxMaxEv - agxMinEv;
|
|
801
|
+
a = clamp( ( log2( max( a, vec3f( 1e-10 ) ) ) - vec3f( agxMinEv ) ) / range, vec3f( 0.0 ), vec3f( 1.0 ) );
|
|
802
|
+
a = vec3f( tmAgxApprox( a.r ), tmAgxApprox( a.g ), tmAgxApprox( a.b ) );
|
|
803
|
+
|
|
804
|
+
var o = vec3f(
|
|
805
|
+
1.1271005818144368 * a.r - 0.11060664309660323 * a.g - 0.016493938717834573 * a.b,
|
|
806
|
+
-0.1413297634984383 * a.r + 1.157823702216272 * a.g - 0.016493938717834257 * a.b,
|
|
807
|
+
-0.14132976349843826 * a.r - 0.11060664309660294 * a.g + 1.2519364065950405 * a.b
|
|
808
|
+
);
|
|
809
|
+
o = pow( max( o, vec3f( 0.0 ) ), vec3f( 2.2 ) );
|
|
810
|
+
|
|
811
|
+
return clamp( vec3f(
|
|
812
|
+
1.6605 * o.r - 0.5876 * o.g - 0.0728 * o.b,
|
|
813
|
+
-0.1246 * o.r + 1.1329 * o.g - 0.0083 * o.b,
|
|
814
|
+
-0.0182 * o.r - 0.1006 * o.g + 1.1187 * o.b
|
|
815
|
+
), vec3f( 0.0 ), vec3f( 1.0 ) );
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
fn tmNeutral( cIn: vec3f ) -> vec3f {
|
|
819
|
+
let startCompression = 0.8 - 0.04;
|
|
820
|
+
let desaturation = 0.15;
|
|
821
|
+
|
|
822
|
+
let x = min( cIn.r, min( cIn.g, cIn.b ) );
|
|
823
|
+
var offset = 0.04;
|
|
824
|
+
if ( x < 0.08 ) { offset = x - 6.25 * x * x; }
|
|
825
|
+
|
|
826
|
+
var c = cIn - vec3f( offset );
|
|
827
|
+
let peak = max( c.r, max( c.g, c.b ) );
|
|
828
|
+
if ( peak < startCompression ) { return c; }
|
|
829
|
+
|
|
830
|
+
let d = 1.0 - startCompression;
|
|
831
|
+
let newPeak = 1.0 - d * d / ( peak + d - startCompression );
|
|
832
|
+
c = c * ( newPeak / peak );
|
|
833
|
+
let gFactor = 1.0 - 1.0 / ( desaturation * ( peak - newPeak ) + 1.0 );
|
|
834
|
+
|
|
835
|
+
return c + ( vec3f( newPeak ) - c ) * gFactor;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
fn tmCurve( cIn: vec3f, mode: u32 ) -> vec3f {
|
|
839
|
+
// Three.js clamps the fragment output before tone mapping ("force unsigned floats"), and
|
|
840
|
+
// AgX/Neutral mix negatives across channels rather than clipping them.
|
|
841
|
+
let c = max( cIn, vec3f( 0.0 ) );
|
|
842
|
+
switch mode {
|
|
843
|
+
case 0u, 1u: { return clamp( c, vec3f( 0.0 ), vec3f( 1.0 ) ); }
|
|
844
|
+
case 2u: { return tmReinhard( c ); }
|
|
845
|
+
case 3u: { return tmCineon( c ); }
|
|
846
|
+
case 6u: { return tmAgx( c ); }
|
|
847
|
+
case 7u: { return tmNeutral( c ); }
|
|
848
|
+
default: { return tmAces( c ); }
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
fn toneMapPixel( linear: vec3f, gain: f32, saturation: f32, mode: u32 ) -> vec3f {
|
|
853
|
+
var c = linear * gain;
|
|
854
|
+
c = tmSaturation( c, saturation );
|
|
855
|
+
c = tmCurve( c, mode );
|
|
856
|
+
return tmSrgb( c );
|
|
857
|
+
}
|
|
858
|
+
`,up=kt(`oidn`),dp=null;async function fp(){return dp||=(await import(`oidn-web`)).initUNetFromURL,dp}var pp={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}},mp=.18,hp=256,gp=256,_p=`
|
|
859
|
+
const WG: u32 = ${hp}u;
|
|
860
|
+
const GROUPS: u32 = ${gp}u;
|
|
861
|
+
|
|
862
|
+
@group(0) @binding(0) var<storage, read> col: array<vec4<f32>>;
|
|
863
|
+
@group(0) @binding(1) var<storage, read_write> partials: array<f32>;
|
|
864
|
+
@group(0) @binding(2) var<uniform> params: vec4<u32>;
|
|
865
|
+
@group(0) @binding(3) var<storage, read_write> scaleOut: array<f32>;
|
|
866
|
+
|
|
867
|
+
var<workgroup> sdata: array<f32, WG>;
|
|
868
|
+
|
|
869
|
+
fn treeSum( lid: u32 ) {
|
|
870
|
+
var s: u32 = WG >> 1u;
|
|
871
|
+
loop {
|
|
872
|
+
if ( s == 0u ) { break; }
|
|
873
|
+
if ( lid < s ) { sdata[ lid ] = sdata[ lid ] + sdata[ lid + s ]; }
|
|
874
|
+
workgroupBarrier();
|
|
875
|
+
s = s >> 1u;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
@compute @workgroup_size(${hp})
|
|
880
|
+
fn reduce( @builtin(global_invocation_id) gid: vec3<u32>,
|
|
881
|
+
@builtin(local_invocation_id) lid: vec3<u32>,
|
|
882
|
+
@builtin(workgroup_id) wid: vec3<u32> ) {
|
|
883
|
+
|
|
884
|
+
let total = params.x;
|
|
885
|
+
var sum = 0.0;
|
|
886
|
+
var i = gid.x;
|
|
887
|
+
loop {
|
|
888
|
+
if ( i >= total ) { break; }
|
|
889
|
+
let c = col[ i ].xyz;
|
|
890
|
+
let lum = 0.212671 * c.r + 0.71516 * c.g + 0.072169 * c.b;
|
|
891
|
+
sum = sum + log2( max( lum, 0.0 ) + 0.0001 );
|
|
892
|
+
i = i + WG * GROUPS;
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
sdata[ lid.x ] = sum;
|
|
896
|
+
workgroupBarrier();
|
|
897
|
+
treeSum( lid.x );
|
|
898
|
+
|
|
899
|
+
if ( lid.x == 0u ) { partials[ wid.x ] = sdata[ 0 ]; }
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
@compute @workgroup_size(${hp})
|
|
903
|
+
fn finalize( @builtin(local_invocation_id) lid: vec3<u32> ) {
|
|
904
|
+
|
|
905
|
+
var v = 0.0;
|
|
906
|
+
if ( lid.x < GROUPS ) { v = partials[ lid.x ]; }
|
|
907
|
+
sdata[ lid.x ] = v;
|
|
908
|
+
workgroupBarrier();
|
|
909
|
+
treeSum( lid.x );
|
|
910
|
+
|
|
911
|
+
if ( lid.x == 0u ) {
|
|
912
|
+
let scale = ${mp} / exp2( sdata[ 0 ] / f32( params.x ) );
|
|
913
|
+
// Mirrors the CPU guard: a non-finite or non-positive scale means no scaling at all.
|
|
914
|
+
scaleOut[ 0 ] = select( 1.0, scale, scale > 0.0 && scale < 3.4e38 );
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
`,vp=`
|
|
732
918
|
@group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;
|
|
733
|
-
@group(0) @binding(1) var<
|
|
919
|
+
@group(0) @binding(1) var<storage, read> scaleBuf: array<f32>;
|
|
734
920
|
|
|
735
921
|
@compute @workgroup_size(64)
|
|
736
922
|
fn main( @builtin(global_invocation_id) gid: vec3<u32>,
|
|
@@ -738,6 +924,45 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32>,
|
|
|
738
924
|
let i = gid.y * nwg.x * 64u + gid.x;
|
|
739
925
|
if ( i >= arrayLength( &col ) ) { return; }
|
|
740
926
|
let c = col[ i ];
|
|
741
|
-
col[ i ] = vec4<f32>( c.xyz *
|
|
927
|
+
col[ i ] = vec4<f32>( c.xyz * scaleBuf[ 0 ], c.w );
|
|
928
|
+
}
|
|
929
|
+
`,yp=64,bp=32768,xp=16,Sp=48,Cp=`
|
|
930
|
+
${lp}
|
|
931
|
+
|
|
932
|
+
struct PackParams {
|
|
933
|
+
srcWidth: u32,
|
|
934
|
+
tileX: u32,
|
|
935
|
+
tileY: u32,
|
|
936
|
+
tileW: u32,
|
|
937
|
+
tileH: u32,
|
|
938
|
+
mode: u32,
|
|
939
|
+
useAlpha: u32,
|
|
940
|
+
pad0: u32,
|
|
941
|
+
exposure: f32,
|
|
942
|
+
saturation: f32,
|
|
943
|
+
pad1: vec2<f32>,
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
@group(0) @binding(0) var<storage, read> src: array<vec4<f32>>;
|
|
947
|
+
@group(0) @binding(1) var<storage, read_write> dst: array<u32>;
|
|
948
|
+
@group(0) @binding(2) var<uniform> P: PackParams;
|
|
949
|
+
@group(0) @binding(3) var<storage, read> scaleBuf: array<f32>;
|
|
950
|
+
@group(0) @binding(4) var<storage, read> inColor: array<vec4<f32>>;
|
|
951
|
+
|
|
952
|
+
@compute @workgroup_size(${xp}, ${xp})
|
|
953
|
+
fn main( @builtin(global_invocation_id) gid: vec3<u32> ) {
|
|
954
|
+
|
|
955
|
+
if ( gid.x >= P.tileW || gid.y >= P.tileH ) { return; }
|
|
956
|
+
|
|
957
|
+
let si = ( P.tileY + gid.y ) * P.srcWidth + ( P.tileX + gid.x );
|
|
958
|
+
let di = gid.y * P.tileW + gid.x;
|
|
959
|
+
|
|
960
|
+
let rgb = toneMapPixel( src[ si ].xyz, P.exposure / scaleBuf[ 0 ], P.saturation, P.mode );
|
|
961
|
+
|
|
962
|
+
var a: u32 = 255u;
|
|
963
|
+
if ( P.useAlpha == 1u ) { a = u32( clamp( inColor[ si ].w, 0.0, 1.0 ) * 255.0 + 0.5 ); }
|
|
964
|
+
|
|
965
|
+
let q = vec3<u32>( clamp( rgb, vec3f( 0.0 ), vec3f( 1.0 ) ) * 255.0 + vec3f( 0.5 ) );
|
|
966
|
+
dst[ di ] = q.x | ( q.y << 8u ) | ( q.z << 16u ) | ( a << 24u );
|
|
742
967
|
}
|
|
743
|
-
`,$f=64,ep=32768,tp=.18;function np(e,t){let n=0;for(let r=0;r<t;r++){let t=r*4,i=.212671*e[t]+.71516*e[t+1]+.072169*e[t+2];n+=Math.log2(Math.max(i,0)+1e-4)}let r=tp/2**(n/t);return Number.isFinite(r)&&r>0?r:1}var rp=class extends r.EventDispatcher{constructor(e,t,n,i,a={}){if(super(),!e||!t||!n||!i)throw Error(`OIDNDenoiser requires output canvas, renderer, scene, and camera`);this.renderer=t,this.scene=n,this.camera=i,this.input=t.domElement,this.output=e,this.extractGBufferData=a.extractGBufferData||null,this.getMRTRenderTarget=a.getMRTRenderTarget||null,this.backendParamsGetter=a.backendParams||null,this.getGPUTextures=a.getGPUTextures||null,this.refreshInput=a.refreshInput||null,this.getExposure=a.getExposure||(()=>1),this.getToneMapping=a.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=a.getSaturation||(()=>1),this.getTransparentBackground=a.getTransparentBackground||(()=>!1),this.isGPUMode=!!this.backendParamsGetter,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._colorScalePipeline=null,this._colorScaleBindGroup=null,this._colorScaleUniform=null,this._oidnInputScale=1,this._alphaReadbackBuffer=null,this._alphaReadbackMapped=!1,this._cachedAlpha=null,this._cachedAlphaWidth=0,this.config={...Zf.DEFAULT_OPTIONS,...a},this.enabled=this.config.enableOIDN,this.quality=this.config.oidnQuality,this.debugGbufferMaps=this.config.debugGbufferMaps,this.maxTileSize=this.config.tileSize,this._activeTileSize=0,this.state={isDenoising:!1,isLoading:!1,abortController:null},this._pendingStagingBuffers=new Set,this._pendingTileBlits=[],this.currentTZAUrl=null,this.unet=null,this._pendingStart=!1,this._initialize().catch(e=>{qf.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{this._setupCanvas(),await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}_setupCanvas(){if(!this.output.getContext)throw Error(`Output must be a valid Canvas element`);this.output.willReadFrequently=!0,this.output.width=this.input.width,this.output.height=this.input.height,Object.assign(this.output.style,{position:`absolute`,top:`0`,left:`0`,width:`100%`,height:`100%`,borderRadius:`5px`,background:`repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 20px 20px`}),this.ctx=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0})}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=Zf;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.output?.width||0,this.output?.height||0);return e?Math.min(e,this.maxTileSize):this.maxTileSize}async _setupUNetDenoiser(){if(this.state.isLoading)return;this.state.isLoading=!0;let e=this._generateTzaUrl(),t=this._resolveTileSize();if(this.currentTZAUrl===e&&this._activeTileSize===t&&this.unet){this.state.isLoading=!1;return}try{this.dispatchEvent({type:`loading`,message:`Loading UNet denoiser...`}),this.unet&&=(this.unet.dispose(),null);let n;if(this.isGPUMode&&this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await Yf())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),qf.debug(`UNet weights loaded:`,e)}catch(e){qf.error(`UNet weights failed to load:`,e),this.dispatchEvent({type:`error`,error:Error(`Denoiser loading failed: ${e.message}`)})}finally{this.state.isLoading=!1,this._pendingStart&&this.unet&&this.enabled&&(this._pendingStart=!1,this.start())}}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=us(),{QUALITY_MODELS:t}=Zf;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.debugGbufferMaps=this.config.debugGbufferMaps,this.maxTileSize=this.config.tileSize,await this._setupUNetDenoiser())}async updateQuality(e){if(!Object.prototype.hasOwnProperty.call(Zf.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(Zf.QUALITY_MODELS).join(`, `)}`);await this.updateConfiguration({oidnQuality:e})}async start(){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._pendingStart=!0,!1;this.dispatchEvent({type:`start`});let e=performance.now(),t=await this.execute();if(t){this.renderer?.resetState?.(),this.input.style.opacity=`0`;let t=performance.now()-e;qf.debug(`denoise complete in ${J.ms(t)} · quality ${this.quality}`)}return t}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}async execute(){if(!this.enabled||!this.unet)return!1;this.state.abortController=new AbortController,this.state.isDenoising=!0;try{return await this._executeUNet(),!0}catch(e){return e.name===`AbortError`?qf.debug(`denoise aborted`):qf.error(`denoise error:`,e),this.input.style.opacity=`1`,!1}finally{this.state.isDenoising=!1,this.state.abortController=null,this.dispatchEvent({type:`end`})}}async _executeUNet(){return this._executeUNetGPU()}async _executeUNetGPU(){let{width:e,height:t}=this.output;if(!this.getGPUTextures)return qf.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let n=this.getGPUTextures();if(!n?.color)return qf.warn(`GPU textures not ready yet`),!1;let r=this.gpuDevice;if(!r)return qf.warn(`gpuDevice not available`),!1;this.refreshInput?.(),this.ctx.drawImage(this.input,0,0,e,t),this._revealOutput(),this._ensureGPUInputBuffers(e,t);let i=r.createCommandEncoder({label:`oidn-tex-to-buf`}),a=e*16,o=this._gpuInputPaddedRowBytes,s=o>a,c=this._gpuInputPadBuffer,l=(n,r)=>{if(!s)i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:r,offset:0,bytesPerRow:a,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});else{i.copyTextureToBuffer({texture:n,mipLevel:0},{buffer:c,offset:0,bytesPerRow:o,rowsPerImage:t},{width:e,height:t,depthOrArrayLayers:1});for(let e=0;e<t;e++)i.copyBufferToBuffer(c,e*o,r,e*a,a)}};l(n.color,this._gpuInputBuffers.color),l(n.albedo,this._gpuInputBuffers.albedo),l(n.normal,this._gpuInputBuffers.normal),r.queue.submit([i.finish()]),await this._readbackColor(r,e,t),globalThis.__OIDN_NO_INPUT_SCALE&&(this._oidnInputScale=1),this._applyColorScale(r,e*t);let u={color:{data:this._gpuInputBuffers.color,width:e,height:t},albedo:{data:this._gpuInputBuffers.albedo,width:e,height:t},normal:{data:this._gpuInputBuffers.normal,width:e,height:t}};return this._executeWithAbortGPU(u)}_ensureGPUInputBuffers(e,t){let{width:n,height:r}=this._gpuInputBufferSize;if(n===e&&r===t&&this._gpuInputBuffers.color)return;this._destroyGPUInputBuffers();let i=this.gpuDevice,a=e*t*16,o=GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC;this._gpuInputBuffers.color=i.createBuffer({label:`oidn-in-color`,size:a,usage:o}),this._gpuInputBuffers.albedo=i.createBuffer({label:`oidn-in-albedo`,size:a,usage:o}),this._gpuInputBuffers.normal=i.createBuffer({label:`oidn-in-normal`,size:a,usage:o}),this._gpuInputBufferSize={width:e,height:t};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(){if(this._gpuInputBuffers.color?.destroy(),this._gpuInputBuffers.albedo?.destroy(),this._gpuInputBuffers.normal?.destroy(),this._gpuInputPadBuffer?.destroy(),this._alphaReadbackMapped&&this._alphaReadbackBuffer)try{this._alphaReadbackBuffer.unmap()}catch{}this._alphaReadbackBuffer?.destroy(),this._alphaReadbackMapped=!1,this._colorScaleBindGroup=null,this._colorScaleUniform?.destroy(),this._colorScaleUniform=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputPadBuffer=null,this._gpuInputPaddedRowBytes=0,this._alphaReadbackBuffer=null,this._gpuInputBufferSize={width:0,height:0}}async _readbackColor(e,t,n){let r=t*n*16;this._alphaReadbackBuffer===null&&(this._alphaReadbackBuffer=e.createBuffer({label:`oidn-alpha-readback`,size:r,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}));let i=this._alphaReadbackBuffer,a=e.createCommandEncoder();a.copyBufferToBuffer(this._gpuInputBuffers.color,0,i,0,r),e.queue.submit([a.finish()]),this._alphaReadbackMapped=!0;try{await i.mapAsync(GPUMapMode.READ)}catch{this._alphaReadbackMapped=!1;return}let o=new Float32Array(i.getMappedRange()),s=t*n;this._oidnInputScale=np(o,s);let c=null;if(this.getTransparentBackground()){c=new Uint8Array(s);for(let e=0;e<s;e++)c[e]=Math.min(Math.max(o[e*4+3]*255,0),255)|0}i.unmap(),this._alphaReadbackMapped=!1,this._cachedAlpha=c,this._cachedAlphaWidth=t}_outputExposure(){return Eo(this.getExposure(),this.getToneMapping())/this._oidnInputScale}_applyColorScale(e,t){let n=this._oidnInputScale;if(!this._ensureColorScalePipeline(e))return;e.queue.writeBuffer(this._colorScaleUniform,0,new Float32Array([n]));let r=Math.ceil(t/$f),i=Math.min(r,ep),a=Math.ceil(r/i),o=e.createCommandEncoder({label:`oidn-color-scale`}),s=o.beginComputePass({label:`oidn-color-scale`});s.setPipeline(this._colorScalePipeline),s.setBindGroup(0,this._colorScaleBindGroup),s.dispatchWorkgroups(i,a,1),s.end(),e.queue.submit([o.finish()])}_ensureColorScalePipeline(e){let t=this._gpuInputBuffers.color;return!e||!t?null:(this._colorScalePipeline||=e.createComputePipeline({label:`oidn-color-scale`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-color-scale`,code:Qf}),entryPoint:`main`}}),this._colorScaleUniform||=e.createBuffer({label:`oidn-color-scale-uniform`,size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this._colorScaleBindGroup||=e.createBindGroup({label:`oidn-color-scale`,layout:this._colorScalePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:{buffer:this._colorScaleUniform}}]}),this._colorScalePipeline)}_executeWithAbortGPU(e){return new Promise((t,n)=>{if(this.state.abortController?.signal.aborted){n(new DOMException(`Aborted`,`AbortError`));return}let i=null;this._pendingTileBlits=[];let a=()=>{i&&=(i(),null),n(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._pendingTileBlits.length>0?await Promise.allSettled(this._pendingTileBlits):await this._displayGPUOutput(e),t()}catch(e){n(e)}},progress:(e,t,n)=>{if(!e?.data||!n)return;let i=this.gpuDevice,a=e.width,o=e.height,s=Math.min(n.width,a-n.x),c=Math.min(n.height,o-n.y);if(s<=0||c<=0)return;let l=s*16,u=s*c*16,d=i.createBuffer({size:u,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});this._pendingStagingBuffers.add(d);let f=i.createCommandEncoder();for(let t=0;t<c;t++){let r=((n.y+t)*a+n.x)*16,i=t*l;f.copyBufferToBuffer(e.data,r,d,i,l)}i.queue.submit([f.finish()]);let p=d.mapAsync(GPUMapMode.READ).then(()=>{let e=new Float32Array(d.getMappedRange()),t=new ImageData(s,c),i=this._outputExposure(),l=this.getSaturation(),u=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),f=this._cachedAlpha,p=this._cachedAlphaWidth;for(let r=0,a=e.length;r<a;r+=4){let a=e[r]*i,o=e[r+1]*i,c=e[r+2]*i;if(l!==1&&(Xf[0]=a,Xf[1]=o,Xf[2]=c,Ao(Xf,l),a=Xf[0],o=Xf[1],c=Xf[2]),u(a,o,c,1,Xf),t.data[r]=To(Xf[0])*255+.5|0,t.data[r+1]=To(Xf[1])*255+.5|0,t.data[r+2]=To(Xf[2])*255+.5|0,f){let e=(r>>2)%s,i=(r>>2)/s|0;t.data[r+3]=f[(n.y+i)*p+n.x+e]}else t.data[r+3]=255}d.unmap(),d.destroy(),this._pendingStagingBuffers.delete(d),this.ctx.putImageData(t,n.x,n.y),this.dispatchEvent({type:`tileProgress`,tile:{x:n.x,y:n.y,width:s,height:c},imageWidth:a,imageHeight:o})}).catch(()=>{d.destroy(),this._pendingStagingBuffers.delete(d)});this._pendingTileBlits.push(p)}})})}async _displayGPUOutput({data:e,width:t,height:n}){let i=this.gpuDevice;if(!i){qf.error(`gpuDevice not available for output readback`);return}let a=t*n*4*4,o=i.createBuffer({label:`oidn-output-staging`,size:a,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST});try{let s=i.createCommandEncoder({label:`oidn-readback`});s.copyBufferToBuffer(e,0,o,0,a),i.queue.submit([s.finish()]),await o.mapAsync(GPUMapMode.READ);let c=new Float32Array(o.getMappedRange()),l=new ImageData(t,n),u=this._outputExposure(),d=this.getSaturation(),f=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),p=this._cachedAlpha;for(let e=0,t=c.length;e<t;e+=4){let t=c[e]*u,n=c[e+1]*u,r=c[e+2]*u;d!==1&&(Xf[0]=t,Xf[1]=n,Xf[2]=r,Ao(Xf,d),t=Xf[0],n=Xf[1],r=Xf[2]),f(t,n,r,1,Xf),l.data[e]=To(Xf[0])*255+.5|0,l.data[e+1]=To(Xf[1])*255+.5|0,l.data[e+2]=To(Xf[2])*255+.5|0,l.data[e+3]=p?p[e>>2]:255}o.unmap(),this.ctx.putImageData(l,0,0)}finally{o.destroy()}}abort(){this._pendingStart=!1,!(!this.enabled||!this.state.isDenoising)&&(this.state.abortController?.abort(),this._destroyPendingStagingBuffers(),this.input.style.opacity=`1`,this.state.isDenoising=!1,this.dispatchEvent({type:`end`}),qf.debug(`denoise aborted`))}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this.output.width=e,this.output.height=t,this._setupUNetDenoiser().catch(e=>{qf.error(`reinitialize after size change failed:`,e)})}_destroyPendingStagingBuffers(){for(let e of this._pendingStagingBuffers)e.destroy();this._pendingStagingBuffers.clear()}dispose(){this.abort(),this._destroyPendingStagingBuffers(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._colorScalePipeline=null,this.output?.parentNode&&this.output.remove(),this.unet=null,this.ctx=null,this.state.abortController=null,this.removeAllListeners?.(),qf.debug(`disposed`)}},ip='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})}};',ap=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,ip],{type:`text/javascript;charset=utf-8`});function op(e){let t;try{if(t=ap&&(self.URL||self.webkitURL).createObjectURL(ap),!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(ip),{type:`module`,name:e?.name})}}var sp={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 cp(){let{upscalerModelBaseUrl:e}=us(),t={};for(let n in sp){t[n]={};for(let r in sp[n])t[n][r]=e+sp[n][r]}return t}var lp={get QUALITY_PRESETS(){return cp()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},up=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||lp.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=lp.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 op,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}=us();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:lp.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=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),this._hdrExposure=Eo(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=lp.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,Ao(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut),l[d]=this._tmOut[0]**+wo,l[c+d]=this._tmOut[1]**+wo,l[2*c+d]=this._tmOut[2]**+wo}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=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),l=Eo(this.getExposure(),this.getToneMapping()),u=this.getSaturation(),d=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;u!==1&&(d[0]=r,d[1]=i,d[2]=a,Ao(d,u),r=d[0],i=d[1],a=d[2]),c(r,i,a,1,d),s[t]=d[0]**+wo*255+.5|0,s[t+1]=d[1]**+wo*255+.5|0,s[t+2]=d[2]**+wo*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(!lp.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`)}},dp=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,scene:n,camera:r,stages:i,pipeline:a,getExposure:o,getSaturation:s,getTransparentBg:c}){super(),this.renderer=e,this.mainCanvas=t,this.denoiserCanvas=this._createDenoiserCanvas(t),this.scene=n,this.camera=r,this.pipeline=a,this._stages=i,this._getExposure=o,this._getSaturation=s,this._getTransparentBg=c,this.denoiser=null,this.upscaler=null,this._onReset=null,this._onPostProcessRefresh=null,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createDenoiserCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this.denoiser?.setSize(e,t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){if(!this.denoiserCanvas||!this._lastRenderWidth||!this._lastRenderHeight)return!1;let e=this.denoiserCanvas.width!==this._lastRenderWidth||this.denoiserCanvas.height!==this._lastRenderHeight;return this.denoiserCanvas.width=this._lastRenderWidth,this.denoiserCanvas.height=this._lastRenderHeight,e}setupDenoiser(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.denoiser=new rp(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...U,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),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(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation(),getTransparentBackground:()=>this._getTransparentBg(),getMRTRenderTarget:()=>e?.storageTextures?.readTarget??null}),this.denoiser.enabled=U.enableOIDN,this._denoiserStartHandler=()=>this.dispatchEvent({type:V.DENOISING_START}),this._denoiserEndHandler=()=>this.dispatchEvent({type:V.DENOISING_END}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler)}setupUpscaler(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.upscaler=new up(this.denoiserCanvas,this.renderer,{scaleFactor:U.upscalerScale||2,quality:U.upscalerQuality||`fast`,getSourceCanvas:()=>this.denoiser?.enabled?null: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=U.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:V.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:V.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:V.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._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(),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?.quality!==`fast`);for(let r of[e.asvgf,e.nrd,e.variance,e.bilateralFilter,e.edgeFilter,t,n])r&&!r.enabled&&r.releaseGPUMemory?.()}_cleanupCompletionListener(){this._pendingStartUpscaler&&this.denoiser&&this.denoiser.removeEventListener(`end`,this._pendingStartUpscaler),this._pendingStartUpscaler=null}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=()=>{this._pendingStartUpscaler=null,e()&&this.upscaler?.enabled&&this.upscaler.start()};this.denoiser?.enabled?(this._pendingStartUpscaler=n,this.denoiser.addEventListener(`end`,n,{once:!0}),this.denoiser.start()):n()}abort(e){this._cleanupCompletionListener(),e&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort(),this.denoiser&&(this.denoiser.enabled&&this.denoiser.abort(),this.denoiser.output&&(this.denoiser.output.style.display=`none`))}dispose(){this._cleanupCompletionListener(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),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(),null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this.denoiserCanvas?.parentNode&&(this.denoiserCanvas.parentNode.removeChild(this.denoiserCanvas),this.denoiserCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=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)}setOIDNEnabled(e){this.denoiser&&(this.denoiser.enabled=e),this._syncGBufferStages(),this._onPostProcessRefresh?.()}setOIDNQuality(e){this.denoiser?.updateQuality(e),this._stages.pathTracer?.setCleanAuxNormal?.(!!this.denoiser?.enabled&&!!this.denoiser?.expectsCleanAux(e)),this._onPostProcessRefresh?.()}setTileHelperEnabled(e){this._setTileHelper(e)}setUpscalerEnabled(e){this.upscaler&&(this.upscaler.enabled=e)}setUpscalerScaleFactor(e){this.upscaler?.setScaleFactor(e)}setUpscalerQuality(e){this.upscaler?.setQuality(e)}setAutoExposure(e){this.setAutoExposureEnabled(e,this._getExposure()),this._onReset?.()}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`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=Ge[e];if(!t)return;let n={};for(let e of We)n[e]=Ue[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=He[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))}},fp=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}},pp=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 mp(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 hp(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 gp=4096,_p=class{constructor(){this.canvas=mp(!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=hp(this._sizeSource,gp);!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(){Oe(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}},vp=kt(`overlay`),yp=(e,t)=>e.visible&&e.layer===t&&e.render,bp=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=mp(),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 _p().init({device:e,sizeSource:t})}catch(e){vp.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 fp;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 pp(t,this.camera);this.register(`outline`,c)}_wireDenoiserTileEvents(e,t){let n=[t?.denoiser,t?.upscaler];for(let t of n)t&&(t.addEventListener(`tileProgress`,t=>{t.tile&&(e.setRenderSize(t.imageWidth,t.imageHeight),e.setActiveTile(t.tile),e.show(),this.refreshHUD())}),t.addEventListener(`end`,()=>{e.hide(),this.refreshHUD()}))}register(e,t){this._helpers.has(e)&&(vp.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())yp(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(yp(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(yp(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?hp(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())yp(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)}},xp=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._posBuffer=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}),this._skinnedCache.push(new Float32Array(a*3)),s+=i}this._posBuffer=new Float32Array(s*9);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:V.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:V.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:V.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:V.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._computePositions(),this._posBuffer}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._computePositions(),this._posBuffer}_computePositions(){let e=this._tempVec,t=this._posBuffer;this._mixerRoot.updateMatrixWorld(!0);for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n],{start:i,count:a,uniqueVerts:o,indices:s}=this._meshTriRanges[n],c=this._skinnedCache[n],l=r.matrixWorld;for(let t=0;t<o;t++)r.getVertexPosition(t,e),e.applyMatrix4(l),c[t*3]=e.x,c[t*3+1]=e.y,c[t*3+2]=e.z;if(s)for(let e=0;e<a;e++){let n=e*3,r=s[n]*3,a=s[n+1]*3,o=s[n+2]*3,l=(i+e)*9;t[l]=c[r],t[l+1]=c[r+1],t[l+2]=c[r+2],t[l+3]=c[a],t[l+4]=c[a+1],t[l+5]=c[a+2],t[l+6]=c[o],t[l+7]=c[o+1],t[l+8]=c[o+2]}else for(let e=0;e<a;e++){let n=e*3*3,r=(e*3+1)*3,a=(e*3+2)*3,o=(i+e)*9;t[o]=c[n],t[o+1]=c[n+1],t[o+2]=c[n+2],t[o+3]=c[r],t[o+4]=c[r+1],t[o+5]=c[r+2],t[o+6]=c[a],t[o+7]=c[a+1],t[o+8]=c[a+2]}}}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._skinnedCache=null,this._clipsCache=null}},Sp=new r.Vector3(0,0,-1),Cp=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._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._tempVec=new r.Vector3,this._normalMatrix=new r.Matrix3,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,this._meshTriRanges=[],this._skinnedCache=[],this._normalCache=[];let t=0;for(let n of e){let e=n.geometry,r=e.attributes.position,i=e.index?e.index.array:null,a=i?i.length/3:r.count/3,o=r.count;this._meshTriRanges.push({start:t,count:a,uniqueVerts:o,indices:i}),this._skinnedCache.push(new Float32Array(o*3)),this._normalCache.push(new Float32Array(o*3)),t+=a}this._posBuffer=new Float32Array(t*9),this._normalBuffer=new Float32Array(t*9),this._baselineComputed=!1}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(Sp,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:V.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:V.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:V.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._posBuffer||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){if(!this._baselineComputed)this._computeAllPositions(),this._baselineComputed=!0;else for(let t of e)this._computeMeshPositions(t);this._refitInFlight=!0;try{this._app.refitBLASes(e,this._posBuffer,this._normalBuffer)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}_computeAllPositions(){for(let e=0;e<this._meshes.length;e++)this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._meshes[e],{start:n,count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._skinnedCache[e],s=this._normalCache[e],c=this._tempVec,l=this._posBuffer,u=this._normalBuffer;t.updateMatrixWorld(!0);let d=t.matrixWorld;this._normalMatrix.getNormalMatrix(d);let f=this._normalMatrix.elements,p=t.geometry.attributes.normal;for(let e=0;e<i;e++)if(t.getVertexPosition(e,c),c.applyMatrix4(d),o[e*3]=c.x,o[e*3+1]=c.y,o[e*3+2]=c.z,p){let t=p.getX(e),n=p.getY(e),r=p.getZ(e);s[e*3]=f[0]*t+f[3]*n+f[6]*r,s[e*3+1]=f[1]*t+f[4]*n+f[7]*r,s[e*3+2]=f[2]*t+f[5]*n+f[8]*r}if(a)for(let e=0;e<r;e++){let t=e*3,r=a[t]*3,i=a[t+1]*3,c=a[t+2]*3,d=(n+e)*9;l[d]=o[r],l[d+1]=o[r+1],l[d+2]=o[r+2],l[d+3]=o[i],l[d+4]=o[i+1],l[d+5]=o[i+2],l[d+6]=o[c],l[d+7]=o[c+1],l[d+8]=o[c+2],u[d]=s[r],u[d+1]=s[r+1],u[d+2]=s[r+2],u[d+3]=s[i],u[d+4]=s[i+1],u[d+5]=s[i+2],u[d+6]=s[c],u[d+7]=s[c+1],u[d+8]=s[c+2]}else for(let e=0;e<r;e++){let t=e*3*3,r=(e*3+1)*3,i=(e*3+2)*3,a=(n+e)*9;l[a]=o[t],l[a+1]=o[t+1],l[a+2]=o[t+2],l[a+3]=o[r],l[a+4]=o[r+1],l[a+5]=o[r+2],l[a+6]=o[i],l[a+7]=o[i+1],l[a+8]=o[i+2],u[a]=s[t],u[a+1]=s[t+1],u[a+2]=s[t+2],u[a+3]=s[r],u[a+4]=s[r+1],u[a+5]=s[r+2],u[a+6]=s[i],u[a+7]=s[i+1],u[a+8]=s[i+2]}}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},wp=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}},Tp=new WeakMap,Ep=kt(`engine`);function Dp(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Op=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function kp(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||Op.test(n)}}var Ap=class extends r.EventDispatcher{constructor(e,t={}){super();try{Tp.get(e)?.dispose()}catch(e){Ep.warn(`prior canvas owner dispose failed`,e)}Tp.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Fe(t.profile),this._issues=new po({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:V.ISSUE,issue:e})}),this.settings=new Rd({...U,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=U.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 xp,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 Nd,this._resizeDebounceTimer=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){Ep.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,Ep.debug(`WebGPU path tracer app initialized`),this}animate(){if(!this._deviceLost){if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:V.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Ep.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}if(this.needsReset&&=(this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}this.pipeline.render(),this.stages.pathTracer.isComplete||this.completion.updateTime(),this._ensureVRAMWiring();let e=this.stages.pathTracer?.vramTracker,t=this.stages.pathTracer?.frameCount??0;if(e&&(t<=1||t%30==0)&&e.measure(),Ce({timeElapsed:this.completion.timeElapsed,samples:we(this.stages.pathTracer),memoryUsed:e?.current??0,memoryPeak:e?.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:V.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:V.FRAME})}}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Ep.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:V.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(),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:V.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:V.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),xe(null),this._issues.detach(),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])ke(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){Ep.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Tp.get(this.canvas)===this&&Tp.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Oe(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.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 loadFile(e){let t=this.assetLoader?.getFileFormat(e?.name||``);if(!t)throw Error(`Unsupported file format: ${e?.name}`);if(t.type!==`environment`&&t.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e),{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?.triangleData&&!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.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}finally{this._loadingInProgress=!1}}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(lo.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:Id.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:V.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 Yo(``,{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(lo.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)`))),t.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),t.end(`BVH build (SceneProcessor)`),H({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`),H({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&&(H({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()),Se(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.entries?.filter(Boolean).length??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[J.count(e.triangleCount,`tri`),t?J.count(t,`mesh`,`meshes`):null,J.count(e.materialData.materialCount,`material`),n?J.count(n,`map`):null,J.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.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,()=>{this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset()}),r}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,W);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(Be,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?Be:2048,a=Ve(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(lo.RENDER_RESERVE_CAPPED,`reserved render size ${J.n(e.requestedPx)}px was capped to ${J.n(t)}px by this device's limits — renders above ${J.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return W}_isRenderSizeSupported(e,t){return e>W||t>W?(this._issues.record(lo.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${W}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:W}),!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.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix();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(e,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.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix(),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}configureForMode(e,t={}){let n=e===`production`,r=n?dt:ft;this.cameraManager.controls.enabled=!n,this.settings.setMany({maxSamples:r.maxSamples,maxBounces:r.bounces,transmissiveBounces:r.transmissiveBounces,maxSubsurfaceSteps:r.maxSubsurfaceSteps,enableAlphaShadows:r.enableAlphaShadows??!1,useAdaptiveSampling:r.useAdaptiveSampling??!1,noiseThreshold:r.noiseThreshold??U.noiseThreshold,adaptiveStopFraction:r.adaptiveStopFraction??U.adaptiveStopFraction,adaptiveMinSamples:r.adaptiveMinSamples??U.adaptiveMinSamples,usePixelFreeze:r.usePixelFreeze??!1,pixelFreezeThreshold:r.pixelFreezeThreshold??U.pixelFreezeThreshold,pixelFreezeStability:r.pixelFreezeStability??U.pixelFreezeStability},{silent:!0,source:Id.MODE_PRESET}),this.stages.pathTracer?.setUniform(`renderMode`,parseInt(r.renderMode)),this.stages.pathTracer?.updateCompletionThreshold?.();let i=this.denoisingManager?.denoiser;if(i&&(i.abort(),i.enabled=r.enableOIDN,i.updateQuality(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(){if(this.denoisingManager?.abort(this.canvas),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}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},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),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),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}={}){if(e!==`linear`&&e!==`srgb`)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb', got "${e}"`);let n=this.stages?.pathTracer,r=n?.storageTextures?.readTarget;if(!r)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:i,height:a}=n,o=await this.renderer.readRenderTargetPixelsAsync(r,0,0,i,a,0);return e===`linear`?{data:o,width:i,height:a,colorSpace:e}:{data:jo(o,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:i,height:a,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;return(e?.denoiser?.enabled||e?.upscaler?.enabled)&&e?.denoiserCanvas&&this.stages.pathTracer?.isComplete?e.denoiserCanvas:(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=>Ep.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:{}}}_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)}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?.entries;if(!e)return;let t=new Set;for(let n of e)n&&n.visible===!1&&t.add(n.meshIndex);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 rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(xe(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=kp(e),this.adapterInfo.isSoftware&&(this._issues.warn(lo.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Ep.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits;if(this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:{maxBufferSize:n.maxBufferSize,maxStorageBufferBindingSize:n.maxStorageBufferBindingSize,maxColorAttachmentBytesPerSample:128,maxStorageBuffersPerShaderStage:Math.min(n.maxStorageBuffersPerShaderStage,10)}}),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 r=this.renderer.backend?.device;r?.lost&&(this._gpuDevice=r,this._deviceLostHolder={app:this},Dp(r,this._deviceLostHolder),r.onuncapturederror=e=>Ep.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)}_initCameraManager(){this.cameraManager=new Mf(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new k}_initAssetPipeline(){this._sdf=new es({issues:this._issues}),this.assetLoader=new jf(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.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new jd(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.pipeline.setSize(n,r)}async _initManagers(){this.interactionManager=new Pd({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 Nf(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new Pf(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new Gf(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Cp({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new wp(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.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,V.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[V.DENOISING_START,V.DENOISING_END,V.UPSCALING_START,V.UPSCALING_PROGRESS,V.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[V.ANIMATION_STARTED,V.ANIMATION_PAUSED,V.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,V.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,V.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}),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),Se()}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:V.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new uu(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new du(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new fu(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new hu(this.renderer,{enabled:!1}),this.stages.nrd=new $u(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new nd(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new id(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ud(this.renderer,{enabled:!1}),this.stages.autoExposure=new _d(this.renderer,{enabled:U.autoExposure??!1}),this.stages.compositor=new vd(this.renderer,{saturation:this.settings.get(`saturation`)??U.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new dp({renderer:this.renderer,mainCanvas:this.canvas,scene:this.scene,camera:this.cameraManager.camera,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,getTransparentBg:()=>this.settings.get(`transparentBackground`)??!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:V.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:V.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new bp(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 jp(e){let t=await Np(e);try{return await Mp(t,e)}finally{t.dispose()}}async function Mp(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 Np({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 Ap(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}}var Pp=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=dt.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?.denoiser?.enabled&&await this._waitForDenoise(l),this._cancelled))break;let c=l.getCanvas();if(c&&o){let t=await createImageBitmap(c);await o(t,e,f),t.close()}let u={frame:e+1,totalFrames:f,percent:(e+1)/f*100};s?.(u),l.dispatchEvent({type:V.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:V.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&&(Ce({samples:we(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(V.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(V.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app;return{maxSamples:e.settings.get(`maxSamples`),maxBounces:e.settings.get(`maxBounces`),transmissiveBounces:e.settings.get(`transmissiveBounces`),renderMode:e.stages.pathTracer?.renderMode?.value,controlsEnabled:e.cameraManager.controls?.enabled,oidnEnabled:e.denoisingManager?.denoiser?.enabled,oidnQuality:e.denoisingManager?.denoiser?.quality,wasPlaying:e.animationManager?.isPlaying,pauseRendering:e.pauseRendering}}_restoreState(e){let t=this._app;t.settings.setMany({maxSamples:e.maxSamples,maxBounces:e.maxBounces,transmissiveBounces:e.transmissiveBounces},{silent:!0}),t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.denoiser.enabled=e.oidnEnabled??!1,e.oidnQuality&&t.denoisingManager.denoiser.updateQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.animationManager?.stop(),t.reset(),t.wake()}};e.AF_DEFAULTS=Xe,e.ASVGF_QUALITY_PRESETS=He,e.AUTO_FOCUS_MODES=Ye,e.AnimationManager=xp,e.BVH_LEAF_MARKERS=Qe,e.CAMERA_PRESETS=Je,e.CAMERA_RANGES=Ke,e.CameraManager=Mf,e.DEFAULT_TEXTURE_MATRIX=ut,e.DenoisingManager=dp,e.ENGINE_DEFAULTS=U,e.EngineEvents=V,e.EngineIssueError=fo,e.GoboManager=Pf,e.IESManager=Gf,e.INTERACTIVE_RENDER_CONFIG=ft,e.ISSUE_CODES=lo,e.ISSUE_SEVERITY=uo,e.InteractionManager=Pd,e.IssueLog=po,e.LOG_LEVELS=mt,e.LightManager=Nf,e.Logger=Ot,e.MAX_RESERVABLE_RENDER_SIZE=Be,e.MEMORY_CONSTANTS=pt,e.NRD_DEFAULTS=Ue,e.NRD_HIT_DIST_A=Le,e.NRD_HIT_DIST_B=Re,e.NRD_PRESET_KEYS=We,e.NRD_QUALITY_PRESETS=Ge,e.OverlayManager=bp,e.PRODUCTION_RENDER_CONFIG=dt,e.PathTracerApp=Ap,e.PipelineContext=yd,e.RENDER_PROFILES=Pe,e.RenderPipeline=jd,e.RenderSettings=Rd,e.RenderStage=_e,e.SETTING_SOURCE=Id,e.SKY_PRESETS=qe,e.StageExecutionMode=ge,e.TEXTURE_CONSTANTS=q,e.TRIANGLE_DATA_LAYOUT=G,e.TransformManager=Cp,e.VRAMTracker=mc,e.VideoRenderManager=Pp,e.bufferBytes=fc,e.captureHeadless=Mp,e.clearBindingAuditFindings=Ed,e.configureAssets=ls,e.createLogger=kt,e.deriveAlphaMode=Ho,e.describeAdapter=kp,e.extractSceneMetadata=Tf,e.fmt=J,e.getAssetConfig=us,e.getBindingAuditFindings=Td,e.getRenderProfile=Fe,e.openHeadless=Np,e.parseSceneMetadata=wf,e.renderHeadless=jp,e.setBindingAudit=wd,e.textureBytes=pc});
|
|
968
|
+
`,wp=class extends r.EventDispatcher{constructor(e,t,n,i,a={}){if(super(),!e||!t||!n||!i)throw Error(`OIDNDenoiser requires output canvas, renderer, scene, and camera`);this.renderer=t,this.scene=n,this.camera=i,this.input=t.domElement,this.output=e,this.backendParamsGetter=a.backendParams||null,this.getGPUTextures=a.getGPUTextures||null,this.refreshInput=a.refreshInput||null,this.getExposure=a.getExposure||(()=>1),this.getToneMapping=a.getToneMapping||(()=>r.ACESFilmicToneMapping),this.getSaturation=a.getSaturation||(()=>1),this.getTransparentBackground=a.getTransparentBackground||(()=>!1),this.isGPUMode=!!this.backendParamsGetter,this.gpuDevice=null,this._gpuInputBuffers={color:null,albedo:null,normal:null},this._gpuInputBufferSize={width:0,height:0},this._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._packPipeline=null,this.config={...pp.DEFAULT_OPTIONS,...a},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._pendingStagingBuffers=new Set,this._pendingTileBlits=[],this._runId=0,this._hasLatchedFrame=!1,this.lastDenoiseMs=0,this.currentTZAUrl=null,this.unet=null,this._pendingStart=!1,this._pendingStartContinuous=!1,this._reloadPending=!1,this._initialize().catch(e=>{up.error(`init failed:`,e),this.dispatchEvent({type:`error`,error:e})})}async _initialize(){try{this._setupCanvas(),await this._setupUNetDenoiser()}catch(e){throw Error(`Initialization failed: ${e.message}`)}}_setupCanvas(){if(!this.output.getContext)throw Error(`Output must be a valid Canvas element`);this.output.willReadFrequently=!0,this.output.width=this.input.width,this.output.height=this.input.height,Object.assign(this.output.style,{position:`absolute`,top:`0`,left:`0`,width:`100%`,height:`100%`,borderRadius:`5px`,background:`repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 20px 20px`}),this.ctx=this.output.getContext(`2d`,{willReadFrequently:!0,alpha:!0})}expectsCleanAux(e=this.quality){let{QUALITY_MODELS:t}=pp;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.output?.width||0,this.output?.height||0);return e?Math.min(e,this.maxTileSize):this.maxTileSize}async _setupUNetDenoiser(){if(this.state.isLoading){this._reloadPending=!0;return}do{this._reloadPending=!1,this.state.isLoading=!0;try{await this._loadUNetWeights()}catch(e){up.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.isGPUMode&&this.backendParamsGetter){let e=this.backendParamsGetter();this.gpuDevice=e?.device??null,n=e?.device?e:void 0}this.unet=await(await fp())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),up.debug(`UNet weights loaded:`,e)}_generateTzaUrl(){let{oidnWeightsBaseUrl:e}=us(),{QUALITY_MODELS:t}=pp;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(pp.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(pp.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._hasLatchedFrame=!0,this.renderer?.resetState?.(),this.input.style.opacity=`0`,this.lastDenoiseMs=performance.now()-t,up.debug(`denoise complete in ${J.ms(this.lastDenoiseMs)} · quality ${this.quality}`)),n}_revealOutput(){this.output.style.display=`block`,this.input.style.opacity=`0`}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._executeUNet(e),!0}catch(e){return e.name===`AbortError`?up.debug(`denoise aborted`):up.error(`denoise error:`,e),this._hasLatchedFrame||(this.input.style.opacity=`1`),!1}finally{this._runId===t&&(this.state.isDenoising=!1,this.state.abortController=null),this.dispatchEvent({type:`end`,continuous:e})}}async _executeUNet(e=!1){return this._executeUNetGPU(e)}async _executeUNetGPU(e=!1){let{width:t,height:n}=this.output;if(!this.getGPUTextures)return up.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let r=this.getGPUTextures();if(!r?.color)return up.warn(`GPU textures not ready yet`),!1;let i=this.gpuDevice;if(!i)return up.warn(`gpuDevice not available`),!1;this._hasLatchedFrame||(this.refreshInput?.(),this.ctx.drawImage(this.input,0,0,t,n)),this._revealOutput(),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);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:_p}),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:vp}),entryPoint:`main`}}),this._packPipeline||=e.createComputePipeline({label:`oidn-output-pack`,layout:`auto`,compute:{module:e.createShaderModule({label:`oidn-output-pack`,code:Cp}),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:gp*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(gp,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/yp),r=Math.min(n,bp),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()])}async _packAndBlit(e,t,n){let r=this.gpuDevice;if(!r||!this._ensureScalePipelines(r))return;let{x:i,y:a,width:o,height:s}=n,c=o*s*4,l=r.createBuffer({label:`oidn-pack-out`,size:c,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),u=r.createBuffer({label:`oidn-pack-staging`,size:c,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),d=r.createBuffer({label:`oidn-pack-params`,size:Sp,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this._pendingStagingBuffers.add(l),this._pendingStagingBuffers.add(u),this._pendingStagingBuffers.add(d);let f=()=>{for(let e of[l,u,d])e.destroy(),this._pendingStagingBuffers.delete(e)};try{let n=new ArrayBuffer(Sp);new Uint32Array(n,0,8).set([t,i,a,o,s,cp(this.getToneMapping()),+!!this.getTransparentBackground(),0]),new Float32Array(n,32,2).set([Eo(this.getExposure(),this.getToneMapping()),this.getSaturation()]),r.queue.writeBuffer(d,0,n);let f=r.createBindGroup({label:`oidn-output-pack`,layout:this._packPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e}},{binding:1,resource:{buffer:l}},{binding:2,resource:{buffer:d}},{binding:3,resource:{buffer:this._inputScaleBuffer}},{binding:4,resource:{buffer:this._gpuInputBuffers.color}}]}),p=r.createCommandEncoder({label:`oidn-output-pack`}),m=p.beginComputePass({label:`oidn-output-pack`});m.setPipeline(this._packPipeline),m.setBindGroup(0,f),m.dispatchWorkgroups(Math.ceil(o/xp),Math.ceil(s/xp),1),m.end(),p.copyBufferToBuffer(l,0,u,0,c),r.queue.submit([p.finish()]),await u.mapAsync(GPUMapMode.READ);let h=new Uint8ClampedArray(u.getMappedRange().slice(0));u.unmap(),this.ctx.putImageData(new ImageData(h,o,s),i,a)}finally{f()}}_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._pendingTileBlits=[];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._pendingTileBlits.length>0?await Promise.allSettled(this._pendingTileBlits):await 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},l=this._packAndBlit(e.data,i,c).then(()=>{this.dispatchEvent({type:`tileProgress`,tile:c,imageWidth:i,imageHeight:a,continuous:t})}).catch(()=>{});this._pendingTileBlits.push(l)}})})}async _displayGPUOutput({data:e,width:t,height:n}){if(!this.gpuDevice){up.error(`gpuDevice not available for output readback`);return}await this._packAndBlit(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._destroyPendingStagingBuffers(),this.input.style.opacity=`1`,this.state.isDenoising=!1,up.debug(`denoise aborted`))}invalidateLatch(){this._hasLatchedFrame=!1}setSize(e,t){if(e<=0||t<=0)throw Error(`Invalid dimensions: ${e}x${t}`);this.output.width=e,this.output.height=t,this._hasLatchedFrame=!1,this._setupUNetDenoiser().catch(e=>{up.error(`reinitialize after size change failed:`,e)})}_destroyPendingStagingBuffers(){for(let e of this._pendingStagingBuffers)e.destroy();this._pendingStagingBuffers.clear()}dispose(){this.abort(),this._destroyPendingStagingBuffers(),this.unet?.dispose(),this._destroyGPUInputBuffers(),this._colorScalePipeline=null,this._lumReducePipeline=null,this._lumFinalizePipeline=null,this._lumLayout=null,this._packPipeline=null,this.output?.parentNode&&this.output.remove(),this.unet=null,this.ctx=null,this.state.abortController=null,this.removeAllListeners?.(),up.debug(`disposed`)}},Tp='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})}};',Ep=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Tp],{type:`text/javascript;charset=utf-8`});function Dp(e){let t;try{if(t=Ep&&(self.URL||self.webkitURL).createObjectURL(Ep),!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(Tp),{type:`module`,name:e?.name})}}var Op={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 kp(){let{upscalerModelBaseUrl:e}=us(),t={};for(let n in Op){t[n]={};for(let r in Op[n])t[n][r]=e+Op[n][r]}return t}var Ap={get QUALITY_PRESETS(){return kp()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},jp=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||Ap.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=Ap.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 Dp,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}=us();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Ap.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=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),this._hdrExposure=Eo(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Ap.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,Ao(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut),l[d]=this._tmOut[0]**+wo,l[c+d]=this._tmOut[1]**+wo,l[2*c+d]=this._tmOut[2]**+wo}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=Co.get(this.getToneMapping())||Co.get(r.ACESFilmicToneMapping),l=Eo(this.getExposure(),this.getToneMapping()),u=this.getSaturation(),d=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;u!==1&&(d[0]=r,d[1]=i,d[2]=a,Ao(d,u),r=d[0],i=d[1],a=d[2]),c(r,i,a,1,d),s[t]=d[0]**+wo*255+.5|0,s[t+1]=d[1]**+wo*255+.5|0,s[t+2]=d[2]**+wo*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(!Ap.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`)}},Mp=120,Np=2,Pp=class extends r.EventDispatcher{constructor({renderer:e,mainCanvas:t,scene:n,camera:r,stages:i,pipeline:a,getExposure:o,getSaturation:s,getTransparentBg:c}){super(),this.renderer=e,this.mainCanvas=t,this.denoiserCanvas=this._createDenoiserCanvas(t),this.scene=n,this.camera=r,this.pipeline=a,this._stages=i,this._getExposure=o,this._getSaturation=s,this._getTransparentBg=c,this.denoiser=null,this.upscaler=null,this._finalQuality=U.oidnQuality,this.finalDenoise=U.enableOIDN,this.continuousDenoise=U.continuousDenoise,this.continuousDenoiseInterval=U.continuousDenoiseInterval,this._lastCadenceAt=-1/0,this._lastCadenceSamples=0,this._onReset=null,this._onPostProcessRefresh=null,this._lastRenderWidth=0,this._lastRenderHeight=0,this._pendingStartUpscaler=null,this._pendingCloseDenoise=null,this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null}_createDenoiserCanvas(e){let t=e.parentNode;if(!t)return null;let n=document.createElement(`canvas`);return n.width=e.width,n.height=e.height,n.style.position=`absolute`,n.style.inset=`0`,n.style.width=`100%`,n.style.height=`100%`,t.insertBefore(n,e),n}setRenderSize(e,t){this._lastRenderWidth=e,this._lastRenderHeight=t,this._cadenceDowngraded=!1,this.denoiser?.setSize(e,t),this.upscaler?.setBaseSize(e,t)}restoreBaseResolution(){if(!this.denoiserCanvas||!this._lastRenderWidth||!this._lastRenderHeight)return!1;let e=this.denoiserCanvas.width!==this._lastRenderWidth||this.denoiserCanvas.height!==this._lastRenderHeight;return this.denoiserCanvas.width=this._lastRenderWidth,this.denoiserCanvas.height=this._lastRenderHeight,e}setupDenoiser(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.denoiser=new wp(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...U,backendParams:()=>({device:this.renderer.backend.device,adapterInfo:null}),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(),{backend:n}=this.renderer;return{color:n.get(t.color).texture,normal:n.get(t.normalDepth).texture,albedo:n.get(t.albedo).texture}},getExposure:()=>this._getEffectiveExposure(),getToneMapping:()=>this._getToneMapping(),getSaturation:()=>this._getSaturation(),getTransparentBackground:()=>this._getTransparentBg()}),this._syncOIDNInUse(),this._denoiserStartHandler=e=>this.dispatchEvent({type:V.DENOISING_START,continuous:!!e.continuous}),this._denoiserEndHandler=e=>this.dispatchEvent({type:V.DENOISING_END,continuous:!!e.continuous}),this.denoiser.addEventListener(`start`,this._denoiserStartHandler),this.denoiser.addEventListener(`end`,this._denoiserEndHandler)}setupUpscaler(){if(!this.denoiserCanvas)return;let e=this._stages.pathTracer;this.upscaler=new jp(this.denoiserCanvas,this.renderer,{scaleFactor:U.upscalerScale||2,quality:U.upscalerQuality||`fast`,getSourceCanvas:()=>this.denoiser?.enabled?null: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=U.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:V.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:V.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:V.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}tickContinuousDenoise(e){let t=this.denoiser;if(!this.continuousDenoise||!t||t.state.isDenoising||t.state.isLoading||this._stages.pathTracer?.interactionMode||e<=this._lastCadenceSamples)return!1;let n=performance.now(),r=Math.max(this.continuousDenoiseInterval,t.lastDenoiseMs*Np);if(n-this._lastCadenceAt<r)return!1;this._lastCadenceAt=n,this._lastCadenceSamples=e,t.lastDenoiseMs>Mp&&(this._cadenceDowngraded=!0);let i=this._cadenceDowngraded?this.previewQuality():this._finalQuality;return t.quality!==i&&t.updateQuality(i),t.start({continuous:!0}),!0}previewQuality(){return this.denoiser?.expectsCleanAux(this._finalQuality)?`fast-clean`:`fast`}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}onRenderComplete({isStillComplete:e,context:t}){this._cleanupCompletionListener();let n=this.finalDenoise?`final`:this.continuousDenoise?`refresh`:null,r=()=>{this.denoiser?.removeEventListener(`end`,r),this._pendingStartUpscaler=null,e()&&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){this._cleanupCompletionListener(),e&&(e.style.opacity=`1`),this.upscaler&&this.upscaler.abort(),this.denoiser&&(this.denoiser.enabled&&this.denoiser.abort(),this.denoiser.output&&(this.denoiser.output.style.display=`none`),this.denoiser.invalidateLatch()),this._resetCadence()}dispose(){this._cleanupCompletionListener(),this.denoiser&&=(this._denoiserStartHandler&&this.denoiser.removeEventListener(`start`,this._denoiserStartHandler),this._denoiserEndHandler&&this.denoiser.removeEventListener(`end`,this._denoiserEndHandler),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(),null),this._denoiserStartHandler=null,this._denoiserEndHandler=null,this._upscalerResChangedHandler=null,this._upscalerStartHandler=null,this._upscalerProgressHandler=null,this._upscalerEndHandler=null,this.denoiserCanvas?.parentNode&&(this.denoiserCanvas.parentNode.removeChild(this.denoiserCanvas),this.denoiserCanvas=null)}setOverlayManager(e){this._overlayManager=e}setResetCallback(e){this._onReset=e}setPostProcessRefreshCallback(e){this._onPostProcessRefresh=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)}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`].forEach(t=>e.removeTexture(t))}_applyNRDPreset(e){let t=Ge[e];if(!t)return;let n={};for(let e of We)n[e]=Ue[e];this._stages.nrd?.updateParameters({...n,...t})}_applyASVGFPreset(e){let t=He[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))}},Fp=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}},Ip=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 Lp(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 Rp(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 zp=4096,Bp=class{constructor(){this.canvas=Lp(!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=Rp(this._sizeSource,zp);!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(){Oe(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}},Vp=kt(`overlay`),Hp=(e,t)=>e.visible&&e.layer===t&&e.render,Up=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Lp(),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 Bp().init({device:e,sizeSource:t})}catch(e){Vp.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 Fp;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 Ip(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)&&(Vp.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())Hp(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Hp(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Hp(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?Rp(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())Hp(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)}},Wp=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._posBuffer=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}),this._skinnedCache.push(new Float32Array(a*3)),s+=i}this._posBuffer=new Float32Array(s*9);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:V.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:V.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:V.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:V.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._computePositions(),this._posBuffer}get currentTime(){return this.mixer?.time||0}update(){if(!this.isPlaying||!this.mixer)return null;this.timer.update();let e=this.timer.getDelta();return this.mixer.update(e),this._computePositions(),this._posBuffer}_computePositions(){let e=this._tempVec,t=this._posBuffer;this._mixerRoot.updateMatrixWorld(!0);for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n],{start:i,count:a,uniqueVerts:o,indices:s}=this._meshTriRanges[n],c=this._skinnedCache[n],l=r.matrixWorld;for(let t=0;t<o;t++)r.getVertexPosition(t,e),e.applyMatrix4(l),c[t*3]=e.x,c[t*3+1]=e.y,c[t*3+2]=e.z;if(s)for(let e=0;e<a;e++){let n=e*3,r=s[n]*3,a=s[n+1]*3,o=s[n+2]*3,l=(i+e)*9;t[l]=c[r],t[l+1]=c[r+1],t[l+2]=c[r+2],t[l+3]=c[a],t[l+4]=c[a+1],t[l+5]=c[a+2],t[l+6]=c[o],t[l+7]=c[o+1],t[l+8]=c[o+2]}else for(let e=0;e<a;e++){let n=e*3*3,r=(e*3+1)*3,a=(e*3+2)*3,o=(i+e)*9;t[o]=c[n],t[o+1]=c[n+1],t[o+2]=c[n+2],t[o+3]=c[r],t[o+4]=c[r+1],t[o+5]=c[r+2],t[o+6]=c[a],t[o+7]=c[a+1],t[o+8]=c[a+2]}}}get hasAnimations(){return this.actions.length>0}get clips(){return this._clipsCache||=this.actions.map((e,t)=>{let n=e.getClip();return{index:t,name:n.name||`Clip ${t}`,duration:n.duration}}),this._clipsCache}dispose(){this.mixer&&=(this.mixer.stopAllAction(),this.mixer.uncacheRoot(this._mixerRoot),null),this.actions=[],this.isPlaying=!1,this.timer.reset(),this._scene=null,this._mixerRoot=null,this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._skinnedCache=null,this._clipsCache=null}},Gp=new r.Vector3(0,0,-1),Kp=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._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._tempVec=new r.Vector3,this._normalMatrix=new r.Matrix3,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,this._meshTriRanges=[],this._skinnedCache=[],this._normalCache=[];let t=0;for(let n of e){let e=n.geometry,r=e.attributes.position,i=e.index?e.index.array:null,a=i?i.length/3:r.count/3,o=r.count;this._meshTriRanges.push({start:t,count:a,uniqueVerts:o,indices:i}),this._skinnedCache.push(new Float32Array(o*3)),this._normalCache.push(new Float32Array(o*3)),t+=a}this._posBuffer=new Float32Array(t*9),this._normalBuffer=new Float32Array(t*9),this._baselineComputed=!1}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(Gp,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:V.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:V.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:V.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._posBuffer||this._refitInFlight||!this._attached)return;this._attached.updateMatrixWorld(!0);let e=this._findAffectedMeshIndices(this._attached);if(e.length!==0){if(!this._baselineComputed)this._computeAllPositions(),this._baselineComputed=!0;else for(let t of e)this._computeMeshPositions(t);this._refitInFlight=!0;try{this._app.refitBLASes(e,this._posBuffer,this._normalBuffer)}catch(e){console.error(`Transform refit error:`,e)}finally{this._refitInFlight=!1}}}_findAffectedMeshIndices(e){let t=[];for(let n=0;n<this._meshes.length;n++){let r=this._meshes[n];(r===e||this._isDescendantOf(r,e))&&t.push(n)}return t}_isDescendantOf(e,t){let n=e.parent;for(;n;){if(n===t)return!0;n=n.parent}return!1}_computeAllPositions(){for(let e=0;e<this._meshes.length;e++)this._computeMeshPositions(e)}_computeMeshPositions(e){let t=this._meshes[e],{start:n,count:r,uniqueVerts:i,indices:a}=this._meshTriRanges[e],o=this._skinnedCache[e],s=this._normalCache[e],c=this._tempVec,l=this._posBuffer,u=this._normalBuffer;t.updateMatrixWorld(!0);let d=t.matrixWorld;this._normalMatrix.getNormalMatrix(d);let f=this._normalMatrix.elements,p=t.geometry.attributes.normal;for(let e=0;e<i;e++)if(t.getVertexPosition(e,c),c.applyMatrix4(d),o[e*3]=c.x,o[e*3+1]=c.y,o[e*3+2]=c.z,p){let t=p.getX(e),n=p.getY(e),r=p.getZ(e);s[e*3]=f[0]*t+f[3]*n+f[6]*r,s[e*3+1]=f[1]*t+f[4]*n+f[7]*r,s[e*3+2]=f[2]*t+f[5]*n+f[8]*r}if(a)for(let e=0;e<r;e++){let t=e*3,r=a[t]*3,i=a[t+1]*3,c=a[t+2]*3,d=(n+e)*9;l[d]=o[r],l[d+1]=o[r+1],l[d+2]=o[r+2],l[d+3]=o[i],l[d+4]=o[i+1],l[d+5]=o[i+2],l[d+6]=o[c],l[d+7]=o[c+1],l[d+8]=o[c+2],u[d]=s[r],u[d+1]=s[r+1],u[d+2]=s[r+2],u[d+3]=s[i],u[d+4]=s[i+1],u[d+5]=s[i+2],u[d+6]=s[c],u[d+7]=s[c+1],u[d+8]=s[c+2]}else for(let e=0;e<r;e++){let t=e*3*3,r=(e*3+1)*3,i=(e*3+2)*3,a=(n+e)*9;l[a]=o[t],l[a+1]=o[t+1],l[a+2]=o[t+2],l[a+3]=o[r],l[a+4]=o[r+1],l[a+5]=o[r+2],l[a+6]=o[i],l[a+7]=o[i+1],l[a+8]=o[i+2],u[a]=s[t],u[a+1]=s[t+1],u[a+2]=s[t+2],u[a+3]=s[r],u[a+4]=s[r+1],u[a+5]=s[r+2],u[a+6]=s[i],u[a+7]=s[i+1],u[a+8]=s[i+2]}}dispose(){this._controls.removeEventListener(`dragging-changed`,this._onDraggingChanged),this._controls.removeEventListener(`objectChange`,this._onObjectChange),this.detach(),this._gizmoScene.remove(this._controls.getHelper()),this._controls.dispose(),this._meshes=null,this._meshTriRanges=null,this._posBuffer=null,this._normalBuffer=null,this._skinnedCache=null,this._normalCache=null,this._baselineComputed=!1,this._tempForward=null,this._lightTargetDistance=null,this._lastLightPosition=null,this._app=null,this._orbitControls=null,this._camera=null,this._controls=null,this._gizmoScene=null}},qp=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}},Jp=new WeakMap,Yp=kt(`engine`);function Xp(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Zp=/swiftshader|llvmpipe|lavapipe|basic render|microsoft basic|warp/i;function Qp(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||Zp.test(n)}}var $p=class extends r.EventDispatcher{constructor(e,t={}){super();try{Jp.get(e)?.dispose()}catch(e){Yp.warn(`prior canvas owner dispose failed`,e)}Jp.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._container=t.container||null,this._applySceneMetadataEnabled=t.applySceneMetadata!==!1,this._applyingSceneMetadata=!1,this._profile=Fe(t.profile),this._issues=new po({strict:t.strict===!0,onIssue:e=>this.dispatchEvent({type:V.ISSUE,issue:e})}),this.settings=new Rd({...U,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=U.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 Wp,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 Nd,this._resizeDebounceTimer=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){Yp.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,Yp.debug(`WebGPU path tracer app initialized`),this}animate(){if(!this._deviceLost){if(this.animationManagerId=requestAnimationFrame(()=>this.animate()),this._loadingInProgress||this._sdf?.isProcessing){this.dispatchEvent({type:V.FRAME});return}if(this.cameraManager.controls&&this.cameraManager.controls.update(),this.animationManager?.isPlaying&&!this._animRefitInFlight){let e=this.animationManager.update();e&&(this._animRefitInFlight=!0,this.refitBVH(e).catch(e=>Yp.error(`animation refit error:`,e)).finally(()=>{this._animRefitInFlight=!1}))}if(this.needsReset&&=(this.reset(!0),!1),this.cameraManager.camera.updateMatrixWorld(),!this.pathTracerEnabled){this.renderer.render(this.meshScene,this.cameraManager.camera),this._renderHelperOverlay();return}if(!this.pauseRendering){if(this.cameraManager.updateAutoFocus(),this.stages.pathTracer?.isReady){if(this.stages.pathTracer.isComplete&&this.completion.renderCompleteDispatched){this._needsDisplayRefresh&&(this._needsDisplayRefresh=!1,this.stages.compositor.render(this.pipeline.context),this._renderHelperOverlay()),this.stopAnimation();return}this.pipeline.render(),this.stages.pathTracer.isComplete||(this.completion.updateTime(),this.denoisingManager?.tickContinuousDenoise(this.stages.pathTracer.frameCount)),this._ensureVRAMWiring();let e=this.stages.pathTracer?.vramTracker,t=this.stages.pathTracer?.frameCount??0;if(e&&(t<=1||t%30==0)&&e.measure(),Ce({timeElapsed:this.completion.timeElapsed,samples:we(this.stages.pathTracer),memoryUsed:e?.current??0,memoryPeak:e?.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:V.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:V.FRAME})}}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Yp.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:V.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(),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:V.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:V.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),xe(null),this._issues.detach(),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])ke(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){Yp.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&Jp.get(this.canvas)===this&&Jp.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),Oe(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.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 loadFile(e){let t=this.assetLoader?.getFileFormat(e?.name||``);if(!t)throw Error(`Unsupported file format: ${e?.name}`);if(t.type!==`environment`&&t.type!==`image`){await this._loadWithSceneRebuild(()=>this.assetLoader.loadAssetFromFile(e),{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?.triangleData&&!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.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}finally{this._loadingInProgress=!1}}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(lo.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:Id.SCENE_METADATA}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:V.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 Yo(``,{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(lo.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)`),H({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`),H({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&&(H({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()),Se(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.entries?.filter(Boolean).length??0,n=this._sdf?.geometryExtractor?.maps?.length??0;return[J.count(e.triangleCount,`tri`),t?J.count(t,`mesh`,`meshes`):null,J.count(e.materialData.materialCount,`material`),n?J.count(n,`map`):null,J.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.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset(),n}refitBLASes(e,t,n){let r=this._sdf.refitBLASes(e,t,n),{triRanges:i,bvhRanges:a}=this._sdf.computeBLASDirtyRanges(e);return this.stages.pathTracer.updateBufferRanges(i,a),this.reset(),this._sdf.scheduleBackgroundRebuild(e,()=>{this.stages.pathTracer.updateTriangleData(this._sdf.triangleData),this.stages.pathTracer.updateBVHData(this._sdf.bvhData),this.reset()}),r}setReservedRenderResolution(e,{allowLower:t=!1}={}){let n=t?e:Math.max(e,W);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(Be,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?Be:2048,a=Ve(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(lo.RENDER_RESERVE_CAPPED,`reserved render size ${J.n(e.requestedPx)}px was capped to ${J.n(t)}px by this device's limits — renders above ${J.n(t)}px will be declined`,{requested:e.requestedPx,applied:t}),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return W}_isRenderSizeSupported(e,t){return e>W||t>W?(this._issues.record(lo.RENDER_SIZE_DECLINED,`render resolution ${e}×${t} exceeds the ${W}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:W}),!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.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix();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(e,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.renderer.setSize(e,t,!1),this.cameraManager.camera.aspect=e/t,this.cameraManager.camera.updateProjectionMatrix(),clearTimeout(this._resizeDebounceTimer),this._applyRenderResize(e,t),{width:e,height:t})}configureForMode(e,t={}){let n=e===`production`,r=n?dt:ft;this.cameraManager.controls.enabled=!n,this.settings.setMany({maxSamples:r.maxSamples,maxBounces:r.bounces,transmissiveBounces:r.transmissiveBounces,maxSubsurfaceSteps:r.maxSubsurfaceSteps,enableAlphaShadows:r.enableAlphaShadows??!1,useAdaptiveSampling:r.useAdaptiveSampling??!1,noiseThreshold:r.noiseThreshold??U.noiseThreshold,adaptiveStopFraction:r.adaptiveStopFraction??U.adaptiveStopFraction,adaptiveMinSamples:r.adaptiveMinSamples??U.adaptiveMinSamples,usePixelFreeze:r.usePixelFreeze??!1,pixelFreezeThreshold:r.pixelFreezeThreshold??U.pixelFreezeThreshold,pixelFreezeStability:r.pixelFreezeStability??U.pixelFreezeStability},{silent:!0,source:Id.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(){if(this.denoisingManager?.abort(this.canvas),this.denoisingManager?.restoreBaseResolution()){let e=this.denoisingManager._lastRenderWidth,t=this.denoisingManager._lastRenderHeight;this.dispatchEvent({type:`resolution_changed`,width:e,height:t})}}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}={}){if(e!==`linear`&&e!==`srgb`)throw Error(`renderToBuffer: colorSpace must be 'linear' or 'srgb', got "${e}"`);let n=this.stages?.pathTracer,r=n?.storageTextures?.readTarget;if(!r)throw Error(`renderToBuffer: no render target — call init() and render at least one sample`);let{width:i,height:a}=n,o=await this.renderer.readRenderTargetPixelsAsync(r,0,0,i,a,0);return e===`linear`?{data:o,width:i,height:a,colorSpace:e}:{data:jo(o,{exposure:this.renderer.toneMappingExposure,toneMapping:this.renderer.toneMapping,saturation:this.settings.get(`saturation`)??1,preserveAlpha:t}),width:i,height:a,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;return(e?.denoiser?.enabled||e?.upscaler?.enabled)&&e?.denoiserCanvas&&this.stages.pathTracer?.isComplete?e.denoiserCanvas:(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=>Yp.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:{}}}_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)}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?.entries;if(!e)return;let t=new Set;for(let n of e)n&&n.visible===!1&&t.add(n.meshIndex);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 rebuildMaterials(e){await this.stages.pathTracer?.rebuildMaterials(e||this.meshScene),this.reset()}async _initRenderer(){if(xe(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=Qp(e),this.adapterInfo.isSoftware&&(this._issues.warn(lo.ADAPTER_SOFTWARE,`software GPU adapter "${this.adapterInfo.description||this.adapterInfo.vendor}" — renders are correct but orders of magnitude slower than hardware`,{...this.adapterInfo}),Yp.warn(`software GPU adapter — check app.adapterInfo.isSoftware. ${this.adapterInfo.description}`));let n=e.limits;if(this.renderer=new t.WebGPURenderer({canvas:this.canvas,alpha:!0,powerPreference:`high-performance`,requiredLimits:{maxBufferSize:n.maxBufferSize,maxStorageBufferBindingSize:n.maxStorageBufferBindingSize,maxColorAttachmentBytesPerSample:128,maxStorageBuffersPerShaderStage:Math.min(n.maxStorageBuffersPerShaderStage,10)}}),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 r=this.renderer.backend?.device;r?.lost&&(this._gpuDevice=r,this._deviceLostHolder={app:this},Xp(r,this._deviceLostHolder),r.onuncapturederror=e=>Yp.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)}_initCameraManager(){this.cameraManager=new Kf(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new k}_initAssetPipeline(){this._sdf=new es({issues:this._issues}),this.assetLoader=new Wf(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.wake()})}_initPipeline(){this._createStages();let{clientWidth:e,clientHeight:t}=this.canvas;this.pipeline=new jd(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.pipeline.setSize(n,r)}async _initManagers(){this.interactionManager=new Pd({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 qf(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new Jf(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new ap(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Kp({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new qp(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.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,V.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[V.DENOISING_START,V.DENOISING_END,V.UPSCALING_START,V.UPSCALING_PROGRESS,V.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[V.ANIMATION_STARTED,V.ANIMATION_PAUSED,V.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,V.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,V.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}),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),Se()}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:V.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new uu(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new du(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new fu(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new hu(this.renderer,{enabled:!1}),this.stages.nrd=new $u(this.renderer,{enabled:!1,pathTracer:this.stages.pathTracer}),this.stages.variance=new nd(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new id(this.renderer,{enabled:!1}),this.stages.edgeFilter=new ud(this.renderer,{enabled:!1}),this.stages.autoExposure=new _d(this.renderer,{enabled:U.autoExposure??!1}),this.stages.compositor=new vd(this.renderer,{saturation:this.settings.get(`saturation`)??U.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Pp({renderer:this.renderer,mainCanvas:this.canvas,scene:this.scene,camera:this.cameraManager.camera,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,getTransparentBg:()=>this.settings.get(`transparentBackground`)??!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:V.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:V.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Up(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 em(e){let t=await nm(e);try{return await tm(t,e)}finally{t.dispose()}}async function tm(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 nm({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 $p(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}}var rm=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=dt.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:V.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:V.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&&(Ce({samples:we(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(V.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(V.DENOISING_END,i),e.denoisingManager.onRenderComplete({isStillComplete:()=>!this._cancelled,context:e.pipeline?.context})})}_saveState(){let e=this._app;return{maxSamples:e.settings.get(`maxSamples`),maxBounces:e.settings.get(`maxBounces`),transmissiveBounces:e.settings.get(`transmissiveBounces`),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;t.settings.setMany({maxSamples:e.maxSamples,maxBounces:e.maxBounces,transmissiveBounces:e.transmissiveBounces},{silent:!0}),t.stages.pathTracer&&e.renderMode!==void 0&&t.stages.pathTracer?.setUniform(`renderMode`,parseInt(e.renderMode)),t.stages.pathTracer?.updateCompletionThreshold?.(),t.cameraManager.controls&&(t.cameraManager.controls.enabled=e.controlsEnabled??!0),t.denoisingManager?.denoiser&&(t.denoisingManager.applyOIDNEnabled(e.oidnEnabled??!1),e.oidnQuality&&t.denoisingManager.applyOIDNQuality(e.oidnQuality)),t.pauseRendering=e.pauseRendering??!1,t.animationManager?.stop(),t.reset(),t.wake()}};e.AF_DEFAULTS=Xe,e.ASVGF_QUALITY_PRESETS=He,e.AUTO_FOCUS_MODES=Ye,e.AnimationManager=Wp,e.BVH_LEAF_MARKERS=Qe,e.CAMERA_PRESETS=Je,e.CAMERA_RANGES=Ke,e.CameraManager=Kf,e.DEFAULT_TEXTURE_MATRIX=ut,e.DenoisingManager=Pp,e.ENGINE_DEFAULTS=U,e.EngineEvents=V,e.EngineIssueError=fo,e.GoboManager=Jf,e.IESManager=ap,e.INTERACTIVE_RENDER_CONFIG=ft,e.ISSUE_CODES=lo,e.ISSUE_SEVERITY=uo,e.InteractionManager=Pd,e.IssueLog=po,e.LOG_LEVELS=mt,e.LightManager=qf,e.Logger=Ot,e.MAX_RESERVABLE_RENDER_SIZE=Be,e.MEMORY_CONSTANTS=pt,e.NRD_DEFAULTS=Ue,e.NRD_HIT_DIST_A=Le,e.NRD_HIT_DIST_B=Re,e.NRD_PRESET_KEYS=We,e.NRD_QUALITY_PRESETS=Ge,e.OverlayManager=Up,e.PRODUCTION_RENDER_CONFIG=dt,e.PathTracerApp=$p,e.PipelineContext=yd,e.RENDER_PROFILES=Pe,e.RenderPipeline=jd,e.RenderSettings=Rd,e.RenderStage=_e,e.SETTING_SOURCE=Id,e.SKY_PRESETS=qe,e.StageExecutionMode=ge,e.TEXTURE_CONSTANTS=q,e.TRIANGLE_DATA_LAYOUT=G,e.TransformManager=Kp,e.VRAMTracker=mc,e.VideoRenderManager=rm,e.bufferBytes=fc,e.captureHeadless=tm,e.clearBindingAuditFindings=Ed,e.configureAssets=ls,e.createLogger=kt,e.deriveAlphaMode=Ho,e.describeAdapter=Qp,e.extractSceneMetadata=Lf,e.fmt=J,e.getAssetConfig=us,e.getBindingAuditFindings=Td,e.getRenderProfile=Fe,e.openHeadless=nm,e.parseSceneMetadata=If,e.renderHeadless=em,e.setBindingAudit=wd,e.textureBytes=pc});
|