rayzee 7.25.0 → 7.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/rayzee.es.js +319 -205
- package/dist/rayzee.umd.js +4 -4
- package/package.json +1 -1
- package/src/PathTracerApp.js +193 -15
- package/src/Processor/AssetLoader.js +11 -1
- package/src/Processor/SceneMetadata.js +123 -0
- package/src/index.js +3 -0
- package/src/managers/EnvironmentManager.js +34 -2
package/dist/rayzee.umd.js
CHANGED
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
return seed;
|
|
114
114
|
|
|
115
115
|
}
|
|
116
|
-
`,[te,I]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},be=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},xe=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}},L={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`},R=new t.QuadMesh(null).geometry,Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:L.LOADING_RESET}),z=e=>{Se?.({type:L.LOADING_UPDATE,...e})},B=e=>{Se?.({type:L.STATS_UPDATE,...e})};function Te(e){return e.frameCount||0}function Ee(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(De(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;De(e),e.dispose()}}function De(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 Oe({material:e,geometry:t,children:n}){if(e&&Ee(e),t&&t.dispose(),n.length>0)for(let e of n)Oe(e)}function ke(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize),e.dispose(),e._canvasTarget=null;let t=R._listeners?.dispose;t&&(t.length=0)}function Ae(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Ee(e);return}for(;e.children.length>0;)for(let t of e.children)Ae(t);Oe(e),e.removeFromParent(),e.clear()}}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 V={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:270,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,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Pe=.01,Fe=4096,H=2048;function Ie(e){return H=Math.max(256,Math.min(Fe,Math.floor(e)||256)),H}var Le={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}},Re={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},ze={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}},Be={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}},Ve={MANUAL:`manual`,AUTO:`auto`},He={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},U={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},W={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}},Ue=e=>Number.isFinite(e)&&e>0?e:0,We={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},G={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:128,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256};function K(e,t=G.MATERIAL_BUCKET_COUNT){let n=[];for(let r=t-1;r>=0;r--)n.push(Math.max(G.MIN_TEXTURE_WIDTH,Math.round(e/2**r)));return n}function Ge(e,t,n,r=G.MATERIAL_BUCKET_COUNT){let i=2**Math.ceil(Math.log2(Math.max(e||1,t||1))),a=K(n,r);for(let e=0;e<a.length;e++)if(i<=a[e])return e;return a.length-1}function Ke(e,t){return e*G.BUCKET_LAYER_STRIDE+t}var qe=[0,0,1,1,0,0,0,1],Je={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},Ye={maxSamples:V.maxSamples,bounces:V.bounces,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:V.transmissiveBounces,maxSubsurfaceSteps:V.maxSubsurfaceSteps,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0},Xe={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},Ze={silent:0,error:1,warn:2,info:3,debug:4},q=`info`,Qe=`rayzeeLogLevel`,$e=`rayzeeLogNamespaces`,et=`color:#7c8494`,tt=`color:inherit`,nt=null,rt=null;function it(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function at(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function ot(){if(nt!==null)return nt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Ze?(nt=Ze[e],nt):(nt=Ze[it(Qe)]??Ze[q],nt)}function st(){if(rt!==null)return rt;let e=globalThis.__RAYZEE_LOG_NS__??it($e);return rt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],rt}function ct(e,t){if(t<Ze.debug)return!0;let n=st();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function lt(e,t,n){if(e>ot()||!ct(t,e))return;let r=e===Ze.error?console.error:e===Ze.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,et,tt,...n.slice(1)):r(`%c${i}`,et,...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(` · `)},ut={levels:Ze,setLevel(e){return e in Ze?(globalThis.__RAYZEE_LOG_LEVEL__=e,nt=Ze[e],at(Qe,e===q?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Ze).join(`, `)}`),this.getLevel())},getLevel(){let e=ot();return Object.keys(Ze).find(t=>Ze[t]===e)},isEnabled(e){return(Ze[e]??Ze.debug)<=ot()},only(...e){let t=e.flat().filter(Boolean);return rt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),at($e,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return nt=null,rt=null,this.getLevel()}};function dt(e){return{namespace:e,error:(...t)=>lt(Ze.error,e,t),warn:(...t)=>lt(Ze.warn,e,t),info:(...t)=>lt(Ze.info,e,t),debug:(...t)=>lt(Ze.debug,e,t),isEnabled:e=>ut.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){lt(Ze.info,e,[t]),r.forEach(t=>lt(Ze.debug,e,[t]));return}Ze.info>ot()||((ot()>=Ze.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,et,tt),r.forEach(e=>console.log(e)),console.groupEnd())}}}var ft=new Set;function pt(e,t,...n){ft.has(t)||(ft.add(t),e.warn(...n))}function mt(){return ut.getLevel()}var ht=dt(`gpu`);function gt(){let e=new t.StorageTexture(H,H);return e.type=r.FloatType,e.format=r.RGBAFormat,e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e}var _t=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=gt(),this.writeNormalDepth=gt(),this.writeAlbedo=gt(),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`,ht.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}},vt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},yt=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,V.bounces,`int`),i(`maxSamples`,V.maxSamples,`int`),i(`transmissiveBounces`,V.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,V.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,V.maxTransparentBounces,`int`),i(`visMode`,V.debugMode,`int`),i(`debugVisScale`,V.debugVisScale,`float`),a(`useAdaptiveSampling`,V.useAdaptiveSampling),i(`noiseThreshold`,V.noiseThreshold,`float`),i(`adaptiveMinSamples`,V.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,V.adaptiveStopFraction,`float`),a(`usePixelFreeze`,V.usePixelFreeze),i(`pixelFreezeThreshold`,V.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,V.pixelFreezeStability,`int`),a(`convergenceOverlay`,V.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,V.environmentIntensity,`float`),i(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,V.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,V.backgroundBlurSamples,`int`),a(`showBackground`,V.showBackground),a(`transparentBackground`,V.transparentBackground),a(`enableEnvironment`,V.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`,V.groundProjectionEnabled),i(`groundProjectionRadius`,V.groundProjectionRadius,`float`),i(`groundProjectionHeight`,V.groundProjectionHeight,`float`),i(`groundProjectionLevel`,V.groundProjectionLevel,`float`),a(`enableGroundCatcher`,V.enableGroundCatcher),i(`groundCatcherHeight`,V.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),i(`exposure`,V.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`,+(V.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(V.panoramaLonRange),`vec2`),i(`panoLatRange`,o(V.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,V.panoramaLevelHorizon),a(`enableDOF`,V.enableDOF),i(`focusDistance`,V.focusDistance,`float`),i(`focalLength`,V.focalLength,`float`),i(`aperture`,V.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,V.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,k),k.value=V.samplingTechnique,i(`fireflyThreshold`,V.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),i(`emissiveBoost`,V.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,V.renderMode,`int`),a(`enableAlphaShadows`,V.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=vt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._lightBuffers={})}},bt=dt(`material`),xt=W.SLOTS_PER_MATERIAL,St=U.UV_C_MAT_OFFSET+2,Ct=U.NORMAL_C_OFFSET+3,wt=U.NORMAL_A_OFFSET+3,Tt=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Et={ior:W.IOR,transmission:W.TRANSMISSION,thickness:W.THICKNESS,emissiveIntensity:W.EMISSIVE_INTENSITY,attenuationDistance:W.ATTENUATION_DISTANCE,opacity:W.OPACITY,alphaTest:W.ALPHA_TEST,metalness:W.METALNESS,roughness:W.ROUGHNESS,clearcoat:W.CLEARCOAT,clearcoatRoughness:W.CLEARCOAT_ROUGHNESS,dispersion:W.DISPERSION,sheen:W.SHEEN,sheenRoughness:W.SHEEN_ROUGHNESS,specularIntensity:W.SPECULAR_INTENSITY,iridescence:W.IRIDESCENCE,iridescenceIOR:W.IRIDESCENCE_IOR,subsurface:W.SUBSURFACE,subsurfaceRadiusScale:W.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:W.SUBSURFACE_ANISOTROPY,anisotropy:W.ANISOTROPY,anisotropyRotation:W.ANISOTROPY_ROTATION},Dt=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.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/xt),bt.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=Et[t];if(r===void 0)return;let i=e*W.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){bt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*W.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+W.COLOR]=n[0],r[i+W.COLOR+1]=n[1],r[i+W.COLOR+2]=n[2]):(r[i+W.COLOR]=n.r,r[i+W.COLOR+1]=n.g,r[i+W.COLOR+2]=n.b);break;case`metalness`:r[i+W.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+W.EMISSIVE]=n[0],r[i+W.EMISSIVE+1]=n[1],r[i+W.EMISSIVE+2]=n[2]):(r[i+W.EMISSIVE]=n.r,r[i+W.EMISSIVE+1]=n.g,r[i+W.EMISSIVE+2]=n.b);break;case`roughness`:r[i+W.ROUGHNESS]=n;break;case`ior`:r[i+W.IOR]=n;break;case`transmission`:r[i+W.TRANSMISSION]=n;break;case`thickness`:r[i+W.THICKNESS]=n;break;case`emissiveIntensity`:r[i+W.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.ATTENUATION_COLOR]=n[0],r[i+W.ATTENUATION_COLOR+1]=n[1],r[i+W.ATTENUATION_COLOR+2]=n[2]):(r[i+W.ATTENUATION_COLOR]=n.r,r[i+W.ATTENUATION_COLOR+1]=n.g,r[i+W.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+W.ATTENUATION_DISTANCE]=Ue(n);break;case`dispersion`:r[i+W.DISPERSION]=n;break;case`sheen`:r[i+W.SHEEN]=n;break;case`sheenRoughness`:r[i+W.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SHEEN_COLOR]=n[0],r[i+W.SHEEN_COLOR+1]=n[1],r[i+W.SHEEN_COLOR+2]=n[2]):(r[i+W.SHEEN_COLOR]=n.r,r[i+W.SHEEN_COLOR+1]=n.g,r[i+W.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+W.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SPECULAR_COLOR]=n[0],r[i+W.SPECULAR_COLOR+1]=n[1],r[i+W.SPECULAR_COLOR+2]=n[2]):(r[i+W.SPECULAR_COLOR]=n.r,r[i+W.SPECULAR_COLOR+1]=n.g,r[i+W.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+W.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+W.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+W.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+W.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+W.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+W.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+W.OPACITY]=n;break;case`side`:r[i+W.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+W.TRANSPARENT]=n;break;case`alphaTest`:r[i+W.ALPHA_TEST]=n;break;case`alphaMode`:r[i+W.ALPHA_MODE]=n;break;case`depthWrite`:r[i+W.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+W.NORMAL_SCALE]=n,r[i+W.NORMAL_SCALE+1]=n):(r[i+W.NORMAL_SCALE]=n.x,r[i+W.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+W.BUMP_SCALE]=n;break;case`displacementScale`:r[i+W.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+W.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+W.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+W.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+W.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+W.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SUBSURFACE_COLOR]=n[0],r[i+W.SUBSURFACE_COLOR+1]=n[1],r[i+W.SUBSURFACE_COLOR+2]=n[2]):(r[i+W.SUBSURFACE_COLOR]=n.r,r[i+W.SUBSURFACE_COLOR+1]=n.g,r[i+W.SUBSURFACE_COLOR+2]=n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+W.SUBSURFACE_RADIUS]=n[0],r[i+W.SUBSURFACE_RADIUS+1]=n[1],r[i+W.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+W.SUBSURFACE_RADIUS]=n.x,r[i+W.SUBSURFACE_RADIUS+1]=n.y,r[i+W.SUBSURFACE_RADIUS+2]=n.z);break;default:bt.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Tt.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`,`subsurface`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){bt.warn(`material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*W.FLOATS_PER_MATERIAL;t.color&&(n[r+W.COLOR]=t.color.r??t.color[0]??1,n[r+W.COLOR+1]=t.color.g??t.color[1]??1,n[r+W.COLOR+2]=t.color.b??t.color[2]??1),n[r+W.METALNESS]=t.metalness??0,t.emissive&&(n[r+W.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+W.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+W.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+W.ROUGHNESS]=t.roughness??1,n[r+W.IOR]=t.ior??1.5,n[r+W.TRANSMISSION]=t.transmission??0,n[r+W.THICKNESS]=t.thickness??.1,n[r+W.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+W.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+W.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+W.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+W.ATTENUATION_DISTANCE]=Ue(t.attenuationDistance),n[r+W.DISPERSION]=t.dispersion??0,n[r+W.VISIBLE]=1,n[r+W.SHEEN]=t.sheen??0,n[r+W.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+W.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+W.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+W.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+W.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+W.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+W.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+W.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+W.IRIDESCENCE]=t.iridescence??0,n[r+W.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+W.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+W.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+W.ALBEDO_MAP_INDEX]=t.map??-1,n[r+W.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+W.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+W.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+W.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+W.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+W.CLEARCOAT]=t.clearcoat??0,n[r+W.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+W.OPACITY]=t.opacity??1,n[r+W.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+W.TRANSPARENT]=t.transparent??0,n[r+W.ALPHA_TEST]=t.alphaTest??0,n[r+W.ALPHA_MODE]=t.alphaMode??0,n[r+W.DEPTH_WRITE]=t.depthWrite??1,n[r+W.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+W.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+W.BUMP_SCALE]=t.bumpScale??1,n[r+W.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+W.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1,n[r+W.SUBSURFACE]=t.subsurface??0,t.subsurfaceColor&&(n[r+W.SUBSURFACE_COLOR]=t.subsurfaceColor.r??t.subsurfaceColor[0]??1,n[r+W.SUBSURFACE_COLOR+1]=t.subsurfaceColor.g??t.subsurfaceColor[1]??1,n[r+W.SUBSURFACE_COLOR+2]=t.subsurfaceColor.b??t.subsurfaceColor[2]??1),t.subsurfaceRadius&&(n[r+W.SUBSURFACE_RADIUS]=t.subsurfaceRadius[0]??1,n[r+W.SUBSURFACE_RADIUS+1]=t.subsurfaceRadius[1]??.2,n[r+W.SUBSURFACE_RADIUS+2]=t.subsurfaceRadius[2]??.1),n[r+W.SUBSURFACE_RADIUS_SCALE]=t.subsurfaceRadiusScale??1,n[r+W.SUBSURFACE_ANISOTROPY]=t.subsurfaceAnisotropy??0,n[r+W.ANISOTROPY]=t.anisotropy??0,n[r+W.ANISOTROPY_ROTATION]=t.anisotropyRotation??0,n[r+W.ANISOTROPY_MAP_INDEX]=t.anisotropyMap??-1,n[r+W.TRANSMISSION_MAP_INDEX]=t.transmissionMap??-1,n[r+W.CLEARCOAT_MAP_INDEX]=t.clearcoatMap??-1,n[r+W.CLEARCOAT_ROUGHNESS_MAP_INDEX]=t.clearcoatRoughnessMap??-1,n[r+W.SHEEN_COLOR_MAP_INDEX]=t.sheenColorMap??-1,n[r+W.SHEEN_ROUGHNESS_MAP_INDEX]=t.sheenRoughnessMap??-1,n[r+W.IRIDESCENCE_MAP_INDEX]=t.iridescenceMap??-1,n[r+W.IRIDESCENCE_THICKNESS_MAP_INDEX]=t.iridescenceThicknessMap??-1,n[r+W.SPECULAR_INTENSITY_MAP_INDEX]=t.specularIntensityMap??-1,n[r+W.SPECULAR_COLOR_MAP_INDEX]=t.specularColorMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:W.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:W.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:W.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:W.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:W.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:W.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:W.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.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),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){bt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*W.FLOATS_PER_MATERIAL,a={map:W.ALBEDO_TRANSFORM,normalMap:W.NORMAL_TRANSFORM,roughnessMap:W.ROUGHNESS_TRANSFORM,metalnessMap:W.METALNESS_TRANSFORM,emissiveMap:W.EMISSIVE_TRANSFORM,bumpMap:W.BUMP_TRANSFORM,displacementMap:W.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){bt.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()}rescanMaterialFeatures(){if(!this.materialStorageAttr?.array)return bt.warn(`material storage buffer not available for feature scanning`),!1;let e=this.materialStorageAttr.array,t=this.sdfs.materialCount||1,n={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasSubsurface:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let r=0;r<t;r++){let t=r*W.FLOATS_PER_MATERIAL,i=e[t+W.TRANSMISSION],a=e[t+W.DISPERSION],o=e[t+W.SHEEN],s=e[t+W.IRIDESCENCE],c=e[t+W.CLEARCOAT],l=e[t+W.OPACITY],u=e[t+W.TRANSPARENT],d=e[t+W.ALPHA_TEST],f=e[t+W.SUBSURFACE];c>0&&(n.hasClearcoat=!0),i>0&&(n.hasTransmission=!0),a>0&&(n.hasDispersion=!0),s>0&&(n.hasIridescence=!0),o>0&&(n.hasSheen=!0),(u>0||l<1||d>0)&&(n.hasTransparency=!0),f>0&&(n.hasSubsurface=!0),[c>0,i>0,s>0,o>0].filter(Boolean).length>=2&&(n.hasMultiLobeMaterials=!0)}let r=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(n);return r&&(this.sdfs.sceneFeatures=n),r}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){bt.warn(`no sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(bt.debug(`material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*W.FLOATS_PER_MATERIAL,r=t[n+W.ALPHA_MODE]|0,i=t[n+W.TRANSPARENT]|0,a=t[n+W.TRANSMISSION]||0,o=t[n+W.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,wt,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=U.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+St]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ct,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.compiledFeatures=null}},Ot=`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})}};`,kt=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ot],{type:`text/javascript;charset=utf-8`});function At(e){let t;try{if(t=kt&&(self.URL||self.webkitURL).createObjectURL(kt),!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(Ot),{type:`module`,name:e?.name})}}function jt(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 Mt(e,t,n){return .2126*e+.7152*t+.0722*n}function Nt(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function Pt(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]=Nt(o[e]),o[e+1]=Nt(o[e+1]),o[e+2]=Nt(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 Ft=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}=Pt(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}=Pt(e);this._worker=new At;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=Mt(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]=Mt(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]=(jt(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]=(jt(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},It=Math.PI,Lt=Math.PI*2,Rt=Math.E,zt=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],Bt=[183999185144339.78,277980239196605.28,407904795438610.94],Vt=1.6110731556870734,Ht=1.5,Ut=1e3,Wt=8400,Gt=1250,Kt=.9999566769464484,qt=.05968310365946075,Jt=.07957747154594767;function Yt(e){return Ut*Math.max(0,1-Rt**+(-(Vt-Math.acos(Math.max(-1,Math.min(1,e))))/Ht))}function Xt(e){let t=.2*e*1e-17;return[.434*t*Bt[0],.434*t*Bt[1],.434*t*Bt[2]]}function Zt(e){return qt*(1+e**2)}function Qt(e,t){let n=t*t;return Jt*((1-n)/(1-2*t*e+n)**1.5)}function $t(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function en(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 tn(e,t,n,r,i,a,o,s){let c=(1-t)*It,l=(e-.5)*Lt,u=Math.sin(c),d=en([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=en(n),p=Yt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[zt[0]*m,zt[1]*m,zt[2]*m],g=Xt(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/It*v)**-1.253,b=Wt/y,x=Gt/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=$t(d,f),w=Zt(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=Qt(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]],ee=nn(Kt,Kt+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*ee;let F=65504;return[Math.min((A[0]+P[0])*.04,F),Math.min((A[1]+P[1])*.04+3e-4,F),Math.min((A[2]+P[2])*.04+75e-5,F),1]}function nn(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var rn=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=tn((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()}},an=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()}},on=dt(`env`),sn=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Ft,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(V.gradientZenithColor),gradientHorizonColor:new r.Color(V.gradientHorizonColor),gradientGroundColor:new r.Color(V.gradientGroundColor),solidSkyColor:new r.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_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),on.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${e?``:` (main thread)`}`]))}catch(e){on.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){let t=this.environmentTexture;e&&t&&t!==e&&t!==this._envPlaceholder&&t!==this._previousHDRI&&t.dispose?.(),this.scene.environment=e,this.setEnvironmentTexture(e),e?await this.buildEnvironmentCDF():(this._updateCDFTexture(),this.uniforms.set(`envTotalSum`,0),this.uniforms.set(`envCompensationDelta`,0));let n=this.callbacks.getSceneTextureNodes?.();n&&e&&n.envTex&&(n.envTex.value=e),e&&!e._isGeneratedProcedural&&this.uniforms.set(`hasSun`,0),this._notifyReset()}async generateGradientTexture(){this.simpleSkyRenderer||=new an(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){on.error(`gradient sky generation failed:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new an(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){on.error(`solid color sky generation failed:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new rn(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),on.debug(`sun synced · dir ${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){on.error(`procedural sky generation failed:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.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}},cn=S({origin:`vec3`,direction:`vec3`}),ln=S({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`}),un=S({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`}),dn=S({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),fn=S({shadowed:`vec3`,unoccluded:`vec3`});S({position:`vec3`,radius:`float`,material:ln});var pn=S({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});S({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:ln,materialIndex:`int`,meshIndex:`int`}),S({color:`vec4`,samples:`int`});var mn=S({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`}),hn=S({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),gn=S({Ta:`vec3`,Ba:`vec3`}),_n=S({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),vn=S({compensation:`vec3`,E_total:`vec3`}),yn=S({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),bn=S({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),xn=S({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Sn=S({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});S({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`});var Cn=3.14159,wn=1/Cn,Tn=2*Cn,En=1e-6,Dn=.05,On=.089,kn=.001,An=(0,n.vec3)(.2126,.7152,.0722),Y=W.SLOTS_PER_MATERIAL,jn=W.SLOT,X=jn,Mn=(0,n.mat3)(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252);(0,n.wgslFn)(`
|
|
116
|
+
`,[te,I]),ye={ALWAYS:`always`,PER_CYCLE:`per_cycle`,PER_TILE:`per_tile`,CONDITIONAL:`conditional`},be=class{constructor(e,t={}){this.name=e,this.enabled=t.enabled!==!1,this.executionMode=t.executionMode||ye.ALWAYS,this.context=null,this.eventBus=null}initialize(e,t){this.context=e,this.eventBus=t,this.setupEventListeners()}setupEventListeners(){}shouldExecuteThisFrame(e){if(!this.enabled)return!1;let t=e.getState(`renderMode`)||0,n=e.getState(`tileRenderingComplete`);switch(this.executionMode){case ye.ALWAYS:return!0;case ye.PER_CYCLE:return t===0?!0:n===!0;case ye.PER_TILE:return!0;case ye.CONDITIONAL:return this.shouldExecute(e);default:return this.warn(`Unknown execution mode: ${this.executionMode}`),!0}}shouldExecute(e){return!0}render(e,t){throw Error(`render() must be implemented in ${this.name}`)}reset(){}setSize(e,t){}dispose(){}emit(e,t){this.eventBus&&this.eventBus.emit(e,t)}on(e,t){this.eventBus&&this.eventBus.on(e,t)}once(e,t){this.eventBus&&this.eventBus.once(e,t)}off(e,t){this.eventBus&&this.eventBus.off(e,t)}enable(){this.enabled||(this.enabled=!0,this.emit(`stage:enabled`,{stage:this.name}))}disable(){this.enabled&&(this.enabled=!1,this.emit(`stage:disabled`,{stage:this.name}))}toggle(){this.enabled?this.disable():this.enable()}isEnabled(){return this.enabled}log(...e){console.log(`[${this.name}]`,...e)}warn(...e){console.warn(`[${this.name}]`,...e)}error(...e){console.error(`[${this.name}]`,...e)}},xe=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}},L={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`},R=new t.QuadMesh(null).geometry,Se=null;function Ce(e){Se=e}var we=()=>Se?.({type:L.LOADING_RESET}),z=e=>{Se?.({type:L.LOADING_UPDATE,...e})},B=e=>{Se?.({type:L.STATS_UPDATE,...e})};function Te(e){return e.frameCount||0}function Ee(e){if(Array.isArray(e))e.forEach(e=>{e.userData&&e.userData.isFallback||(De(e),e.dispose())});else{if(e.userData&&e.userData.isFallback)return;De(e),e.dispose()}}function De(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 Oe({material:e,geometry:t,children:n}){if(e&&Ee(e),t&&t.dispose(),n.length>0)for(let e of n)Oe(e)}function ke(e){if(!e)return;e._canvasTarget&&e._onCanvasTargetResize&&e._canvasTarget.removeEventListener(`resize`,e._onCanvasTargetResize),e.dispose(),e._canvasTarget=null;let t=R._listeners?.dispose;t&&(t.length=0)}function Ae(e,t=[]){if(e&&!(t.includes(e.name)||e.isScene)){if(e.isMaterial){Ee(e);return}for(;e.children.length>0;)for(let t of e.children)Ae(t);Oe(e),e.removeFromParent(),e.clear()}}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 V={resolution:512,canvasWidth:512,canvasHeight:512,maxTextureSize:4096,toneMapping:4,exposure:1,saturation:1.2,enableEnvironment:!0,showBackground:!0,transparentBackground:!1,environmentIntensity:1,backgroundIntensity:1,backgroundColor:`#000000`,backgroundBlurriness:0,backgroundBlurSamples:8,environmentRotation:270,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,autoExposure:!1,autoExposureKeyValue:.18,autoExposureMinExposure:.1,autoExposureMaxExposure:20,autoExposureAdaptSpeedBright:3,autoExposureAdaptSpeedDark:.5},Pe=.01,Fe=4096,H=2048;function Ie(e){return H=Math.max(256,Math.min(Fe,Math.floor(e)||256)),H}var Le={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}},Re={fov:{min:10,max:90,default:V.fov},focusDistance:{min:.3,max:100,default:V.focusDistance},aperture:{options:[1.4,2,2.8,4,5.6,8,11,16],default:V.aperture},focalLength:{min:0,max:200,default:V.focalLength}},ze={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}},Be={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}},Ve={MANUAL:`manual`,AUTO:`auto`},He={SMOOTHING_FACTOR:.15,RESET_THRESHOLD:.05,FALLBACK_DISTANCE:10,SNAP_THRESHOLD:.5},U={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},W={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}},Ue=e=>Number.isFinite(e)&&e>0?e:0,We={TRIANGLE_LEAF:-1,BLAS_POINTER_LEAF:-2},G={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:128,MATERIAL_BUCKET_COUNT:4,BUCKET_LAYER_STRIDE:256};function K(e,t=G.MATERIAL_BUCKET_COUNT){let n=[];for(let r=t-1;r>=0;r--)n.push(Math.max(G.MIN_TEXTURE_WIDTH,Math.round(e/2**r)));return n}function Ge(e,t,n,r=G.MATERIAL_BUCKET_COUNT){let i=2**Math.ceil(Math.log2(Math.max(e||1,t||1))),a=K(n,r);for(let e=0;e<a.length;e++)if(i<=a[e])return e;return a.length-1}function Ke(e,t){return e*G.BUCKET_LAYER_STRIDE+t}var qe=[0,0,1,1,0,0,0,1],Je={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},Ye={maxSamples:V.maxSamples,bounces:V.bounces,renderMode:V.renderMode,enableAlphaShadows:V.enableAlphaShadows,transmissiveBounces:V.transmissiveBounces,maxSubsurfaceSteps:V.maxSubsurfaceSteps,enableOIDN:!1,oidnQuality:`fast`,interactionModeEnabled:!0,useAdaptiveSampling:!0,noiseThreshold:.1,usePixelFreeze:!0},Xe={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},Ze={silent:0,error:1,warn:2,info:3,debug:4},q=`info`,Qe=`rayzeeLogLevel`,$e=`rayzeeLogNamespaces`,et=`color:#7c8494`,tt=`color:inherit`,nt=null,rt=null;function it(e){try{return globalThis.localStorage?.getItem(e)??null}catch{return null}}function at(e,t){try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}function ot(){if(nt!==null)return nt;let e=globalThis.__RAYZEE_LOG_LEVEL__;return e!==void 0&&e in Ze?(nt=Ze[e],nt):(nt=Ze[it(Qe)]??Ze[q],nt)}function st(){if(rt!==null)return rt;let e=globalThis.__RAYZEE_LOG_NS__??it($e);return rt=e?String(e).split(`,`).map(e=>e.trim()).filter(Boolean):[],rt}function ct(e,t){if(t<Ze.debug)return!0;let n=st();return n.length===0||n.some(t=>e===t||e.startsWith(`${t}:`))}function lt(e,t,n){if(e>ot()||!ct(t,e))return;let r=e===Ze.error?console.error:e===Ze.warn?console.warn:console.log,i=`[${t}]`;typeof n[0]==`string`?r(`%c${i}%c ${n[0]}`,et,tt,...n.slice(1)):r(`%c${i}`,et,...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(` · `)},ut={levels:Ze,setLevel(e){return e in Ze?(globalThis.__RAYZEE_LOG_LEVEL__=e,nt=Ze[e],at(Qe,e===q?null:e),e):(console.warn(`[log] unknown level '${e}' — expected one of ${Object.keys(Ze).join(`, `)}`),this.getLevel())},getLevel(){let e=ot();return Object.keys(Ze).find(t=>Ze[t]===e)},isEnabled(e){return(Ze[e]??Ze.debug)<=ot()},only(...e){let t=e.flat().filter(Boolean);return rt=t,globalThis.__RAYZEE_LOG_NS__=t.join(`,`),at($e,t.length?t.join(`,`):null),t.length&&this.setLevel(`debug`),t},refresh(){return nt=null,rt=null,this.getLevel()}};function dt(e){return{namespace:e,error:(...t)=>lt(Ze.error,e,t),warn:(...t)=>lt(Ze.warn,e,t),info:(...t)=>lt(Ze.info,e,t),debug:(...t)=>lt(Ze.debug,e,t),isEnabled:e=>ut.isEnabled(e),summary(t,n=[]){let r=n.filter(Boolean);if(r.length===0||!console.groupCollapsed){lt(Ze.info,e,[t]),r.forEach(t=>lt(Ze.debug,e,[t]));return}Ze.info>ot()||((ot()>=Ze.debug&&console.group?console.group:console.groupCollapsed)(`%c[${e}]%c ${t}`,et,tt),r.forEach(e=>console.log(e)),console.groupEnd())}}}var ft=new Set;function pt(e,t,...n){ft.has(t)||(ft.add(t),e.warn(...n))}function mt(){return ut.getLevel()}var ht=dt(`gpu`);function gt(){let e=new t.StorageTexture(H,H);return e.type=r.FloatType,e.format=r.RGBAFormat,e.minFilter=r.LinearFilter,e.magFilter=r.LinearFilter,e}var _t=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=gt(),this.writeNormalDepth=gt(),this.writeAlbedo=gt(),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`,ht.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}},vt={cameraViewMatrix:`ptCameraViewMatrix`,cameraProjectionMatrix:`ptCameraProjectionMatrix`},yt=class{constructor(e=1920,t=1080){this._uniforms=new Map,this._booleans=new Set,this._lightBuffers={},this._initUniforms(e,t),this._nameAll()}get(e){return this._uniforms.get(e)}set(e,t){let n=this._uniforms.get(e);if(!n){console.warn(`UniformManager: Unknown uniform "${e}"`);return}this._booleans.has(e)?n.value=+!!t:typeof t==`object`&&t&&typeof n.value?.copy==`function`?n.value.copy(t):n.value=t}has(e){return this._uniforms.has(e)}keys(){return this._uniforms.keys()}getLightBufferNodes(){return this._lightBuffers}updateMany(e){let t=!1;for(let[n,r]of Object.entries(e)){let e=this._uniforms.get(n);e&&e.value!==r&&(e.value=r,t=!0)}return t}_initUniforms(e,t){let i=(e,t,r)=>{let i=(0,n.uniform)(t,r);return this._uniforms.set(e,i),i},a=(e,t)=>(this._booleans.add(e),i(e,+!!t,`int`));i(`frame`,0,`uint`),i(`seedFrame`,0,`uint`),i(`maxBounces`,V.bounces,`int`),i(`maxSamples`,V.maxSamples,`int`),i(`transmissiveBounces`,V.transmissiveBounces,`int`),i(`maxSubsurfaceSteps`,V.maxSubsurfaceSteps,`int`),i(`maxTransparentBounces`,V.maxTransparentBounces,`int`),i(`visMode`,V.debugMode,`int`),i(`debugVisScale`,V.debugVisScale,`float`),a(`useAdaptiveSampling`,V.useAdaptiveSampling),i(`noiseThreshold`,V.noiseThreshold,`float`),i(`adaptiveMinSamples`,V.adaptiveMinSamples,`int`),i(`adaptiveStopFraction`,V.adaptiveStopFraction,`float`),a(`usePixelFreeze`,V.usePixelFreeze),i(`pixelFreezeThreshold`,V.pixelFreezeThreshold,`float`),i(`pixelFreezeStability`,V.pixelFreezeStability,`int`),a(`convergenceOverlay`,V.convergenceOverlay),a(`enableAccumulation`,!0),i(`accumulationAlpha`,0,`float`),a(`cameraIsMoving`,!1),a(`hasPreviousAccumulated`,!1),i(`auxAccumulationAlpha`,1,`float`),a(`hasPreviousAux`,!1),i(`environmentIntensity`,V.environmentIntensity,`float`),i(`backgroundIntensity`,V.backgroundIntensity,`float`),i(`backgroundColor`,new r.Color(0,0,0),`color`),i(`backgroundBlurriness`,V.backgroundBlurriness,`float`),i(`backgroundBlurSamples`,V.backgroundBlurSamples,`int`),a(`showBackground`,V.showBackground),a(`transparentBackground`,V.transparentBackground),a(`enableEnvironment`,V.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`,V.groundProjectionEnabled),i(`groundProjectionRadius`,V.groundProjectionRadius,`float`),i(`groundProjectionHeight`,V.groundProjectionHeight,`float`),i(`groundProjectionLevel`,V.groundProjectionLevel,`float`),a(`enableGroundCatcher`,V.enableGroundCatcher),i(`groundCatcherHeight`,V.groundCatcherHeight,`float`),i(`sunDirection`,new r.Vector3(0,1,0),`vec3`),i(`sunAngularSize`,.0087,`float`),a(`hasSun`,!1),i(`globalIlluminationIntensity`,V.globalIlluminationIntensity,`float`),i(`exposure`,V.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`,+(V.cameraProjection===`equirectangular`),`int`),i(`panoLonRange`,o(V.panoramaLonRange),`vec2`),i(`panoLatRange`,o(V.panoramaLatRange),`vec2`),a(`panoLevelHorizon`,V.panoramaLevelHorizon),a(`enableDOF`,V.enableDOF),i(`focusDistance`,V.focusDistance,`float`),i(`focalLength`,V.focalLength,`float`),i(`aperture`,V.aperture,`float`),i(`apertureScale`,1,`float`),i(`anamorphicRatio`,V.anamorphicRatio??1,`float`),i(`sceneScale`,1,`float`),this._uniforms.set(`samplingTechnique`,k),k.value=V.samplingTechnique,i(`fireflyThreshold`,V.fireflyThreshold,`float`),a(`enableEmissiveTriangleSampling`,V.enableEmissiveTriangleSampling),i(`emissiveBoost`,V.emissiveBoost,`float`),i(`emissiveTriangleCount`,0,`int`),i(`emissiveTotalPower`,0,`float`),i(`lightBVHNodeCount`,0,`int`),i(`emissiveVec4Offset`,0,`int`),i(`reverseMapVec4Offset`,0,`int`),i(`renderMode`,V.renderMode,`int`),a(`enableAlphaShadows`,V.enableAlphaShadows),i(`resolution`,new r.Vector2(e,t),`vec2`)}_nameAll(){for(let[e,t]of this._uniforms)t.name=vt[e]||e}dispose(){this._disposed||(this._disposed=!0,this._uniforms.clear(),this._booleans.clear(),this._lightBuffers={})}},bt=dt(`material`),xt=W.SLOTS_PER_MATERIAL,St=U.UV_C_MAT_OFFSET+2,Ct=U.NORMAL_C_OFFSET+3,wt=U.NORMAL_A_OFFSET+3,Tt=new Set([`transmission`,`transparent`,`opacity`,`alphaMode`]),Et={ior:W.IOR,transmission:W.TRANSMISSION,thickness:W.THICKNESS,emissiveIntensity:W.EMISSIVE_INTENSITY,attenuationDistance:W.ATTENUATION_DISTANCE,opacity:W.OPACITY,alphaTest:W.ALPHA_TEST,metalness:W.METALNESS,roughness:W.ROUGHNESS,clearcoat:W.CLEARCOAT,clearcoatRoughness:W.CLEARCOAT_ROUGHNESS,dispersion:W.DISPERSION,sheen:W.SHEEN,sheenRoughness:W.SHEEN_ROUGHNESS,specularIntensity:W.SPECULAR_INTENSITY,iridescence:W.IRIDESCENCE,iridescenceIOR:W.IRIDESCENCE_IOR,subsurface:W.SUBSURFACE,subsurfaceRadiusScale:W.SUBSURFACE_RADIUS_SCALE,subsurfaceAnisotropy:W.SUBSURFACE_ANISOTROPY,anisotropy:W.ANISOTROPY,anisotropyRotation:W.ANISOTROPY_ROTATION},Dt=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.compiledFeatures=null,this.callbacks={}}setMaterialData(e){if(!e)return;let r=e.length/4;this.materialStorageNode?(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode.value=this.materialStorageAttr,this.materialStorageNode.bufferCount=r):(this.materialStorageAttr=new t.StorageInstancedBufferAttribute(e,4),this.materialStorageNode=(0,n.storage)(this.materialStorageAttr,`vec4`,r).toReadOnly()),this.materialCount=Math.floor(r/xt),bt.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=Et[t];if(r===void 0)return;let i=e*W.FLOATS_PER_MATERIAL+r;return i<n.length?n[i]:void 0}updateMaterialProperty(e,t,n){if(!this.materialStorageAttr){bt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*W.FLOATS_PER_MATERIAL;switch(t){case`color`:n.r===void 0?Array.isArray(n)&&(r[i+W.COLOR]=n[0],r[i+W.COLOR+1]=n[1],r[i+W.COLOR+2]=n[2]):(r[i+W.COLOR]=n.r,r[i+W.COLOR+1]=n.g,r[i+W.COLOR+2]=n.b);break;case`metalness`:r[i+W.METALNESS]=n;break;case`emissive`:n.r===void 0?Array.isArray(n)&&(r[i+W.EMISSIVE]=n[0],r[i+W.EMISSIVE+1]=n[1],r[i+W.EMISSIVE+2]=n[2]):(r[i+W.EMISSIVE]=n.r,r[i+W.EMISSIVE+1]=n.g,r[i+W.EMISSIVE+2]=n.b);break;case`roughness`:r[i+W.ROUGHNESS]=n;break;case`ior`:r[i+W.IOR]=n;break;case`transmission`:r[i+W.TRANSMISSION]=n;break;case`thickness`:r[i+W.THICKNESS]=n;break;case`emissiveIntensity`:r[i+W.EMISSIVE_INTENSITY]=n;break;case`attenuationColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.ATTENUATION_COLOR]=n[0],r[i+W.ATTENUATION_COLOR+1]=n[1],r[i+W.ATTENUATION_COLOR+2]=n[2]):(r[i+W.ATTENUATION_COLOR]=n.r,r[i+W.ATTENUATION_COLOR+1]=n.g,r[i+W.ATTENUATION_COLOR+2]=n.b);break;case`attenuationDistance`:r[i+W.ATTENUATION_DISTANCE]=Ue(n);break;case`dispersion`:r[i+W.DISPERSION]=n;break;case`sheen`:r[i+W.SHEEN]=n;break;case`sheenRoughness`:r[i+W.SHEEN_ROUGHNESS]=n;break;case`sheenColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SHEEN_COLOR]=n[0],r[i+W.SHEEN_COLOR+1]=n[1],r[i+W.SHEEN_COLOR+2]=n[2]):(r[i+W.SHEEN_COLOR]=n.r,r[i+W.SHEEN_COLOR+1]=n.g,r[i+W.SHEEN_COLOR+2]=n.b);break;case`specularIntensity`:r[i+W.SPECULAR_INTENSITY]=n;break;case`specularColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SPECULAR_COLOR]=n[0],r[i+W.SPECULAR_COLOR+1]=n[1],r[i+W.SPECULAR_COLOR+2]=n[2]):(r[i+W.SPECULAR_COLOR]=n.r,r[i+W.SPECULAR_COLOR+1]=n.g,r[i+W.SPECULAR_COLOR+2]=n.b);break;case`iridescence`:r[i+W.IRIDESCENCE]=n;break;case`iridescenceIOR`:r[i+W.IRIDESCENCE_IOR]=n;break;case`iridescenceThicknessRange`:Array.isArray(n)&&(r[i+W.IRIDESCENCE_THICKNESS_RANGE]=n[0],r[i+W.IRIDESCENCE_THICKNESS_RANGE+1]=n[1]);break;case`clearcoat`:r[i+W.CLEARCOAT]=n;break;case`clearcoatRoughness`:r[i+W.CLEARCOAT_ROUGHNESS]=n;break;case`opacity`:r[i+W.OPACITY]=n;break;case`side`:r[i+W.SIDE]=n,this._patchTriangleSideForMaterial(e,n);break;case`transparent`:r[i+W.TRANSPARENT]=n;break;case`alphaTest`:r[i+W.ALPHA_TEST]=n;break;case`alphaMode`:r[i+W.ALPHA_MODE]=n;break;case`depthWrite`:r[i+W.DEPTH_WRITE]=n;break;case`normalScale`:n.x===void 0?typeof n==`number`&&(r[i+W.NORMAL_SCALE]=n,r[i+W.NORMAL_SCALE+1]=n):(r[i+W.NORMAL_SCALE]=n.x,r[i+W.NORMAL_SCALE+1]=n.y);break;case`bumpScale`:r[i+W.BUMP_SCALE]=n;break;case`displacementScale`:r[i+W.DISPLACEMENT_SCALE]=n;break;case`subsurface`:r[i+W.SUBSURFACE]=n;break;case`subsurfaceRadiusScale`:r[i+W.SUBSURFACE_RADIUS_SCALE]=n;break;case`subsurfaceAnisotropy`:r[i+W.SUBSURFACE_ANISOTROPY]=n;break;case`anisotropy`:r[i+W.ANISOTROPY]=n;break;case`anisotropyRotation`:r[i+W.ANISOTROPY_ROTATION]=n;break;case`subsurfaceColor`:n.r===void 0?Array.isArray(n)&&(r[i+W.SUBSURFACE_COLOR]=n[0],r[i+W.SUBSURFACE_COLOR+1]=n[1],r[i+W.SUBSURFACE_COLOR+2]=n[2]):(r[i+W.SUBSURFACE_COLOR]=n.r,r[i+W.SUBSURFACE_COLOR+1]=n.g,r[i+W.SUBSURFACE_COLOR+2]=n.b);break;case`subsurfaceRadius`:Array.isArray(n)?(r[i+W.SUBSURFACE_RADIUS]=n[0],r[i+W.SUBSURFACE_RADIUS+1]=n[1],r[i+W.SUBSURFACE_RADIUS+2]=n[2]):n.x!==void 0&&(r[i+W.SUBSURFACE_RADIUS]=n.x,r[i+W.SUBSURFACE_RADIUS+1]=n.y,r[i+W.SUBSURFACE_RADIUS+2]=n.z);break;default:bt.warn(`unknown material property: ${t}`);return}this.materialStorageAttr.needsUpdate=!0,Tt.has(t)&&this._recomputeOpaqueBlockerForMaterial(e),[`transmission`,`clearcoat`,`sheen`,`iridescence`,`dispersion`,`transparent`,`opacity`,`alphaTest`,`subsurface`].includes(t)&&this.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),this._notifyReset()}updateMaterialDataFromObject(e,t){if(!this.materialStorageAttr){bt.warn(`material storage buffer not available`);return}let n=this.materialStorageAttr.array,r=e*W.FLOATS_PER_MATERIAL;t.color&&(n[r+W.COLOR]=t.color.r??t.color[0]??1,n[r+W.COLOR+1]=t.color.g??t.color[1]??1,n[r+W.COLOR+2]=t.color.b??t.color[2]??1),n[r+W.METALNESS]=t.metalness??0,t.emissive&&(n[r+W.EMISSIVE]=t.emissive.r??t.emissive[0]??0,n[r+W.EMISSIVE+1]=t.emissive.g??t.emissive[1]??0,n[r+W.EMISSIVE+2]=t.emissive.b??t.emissive[2]??0),n[r+W.ROUGHNESS]=t.roughness??1,n[r+W.IOR]=t.ior??1.5,n[r+W.TRANSMISSION]=t.transmission??0,n[r+W.THICKNESS]=t.thickness??.1,n[r+W.EMISSIVE_INTENSITY]=t.emissiveIntensity??1,t.attenuationColor&&(n[r+W.ATTENUATION_COLOR]=t.attenuationColor.r??t.attenuationColor[0]??1,n[r+W.ATTENUATION_COLOR+1]=t.attenuationColor.g??t.attenuationColor[1]??1,n[r+W.ATTENUATION_COLOR+2]=t.attenuationColor.b??t.attenuationColor[2]??1),n[r+W.ATTENUATION_DISTANCE]=Ue(t.attenuationDistance),n[r+W.DISPERSION]=t.dispersion??0,n[r+W.VISIBLE]=1,n[r+W.SHEEN]=t.sheen??0,n[r+W.SHEEN_ROUGHNESS]=t.sheenRoughness??1,t.sheenColor&&(n[r+W.SHEEN_COLOR]=t.sheenColor.r??t.sheenColor[0]??0,n[r+W.SHEEN_COLOR+1]=t.sheenColor.g??t.sheenColor[1]??0,n[r+W.SHEEN_COLOR+2]=t.sheenColor.b??t.sheenColor[2]??0),n[r+W.SPECULAR_INTENSITY]=t.specularIntensity??1,t.specularColor&&(n[r+W.SPECULAR_COLOR]=t.specularColor.r??t.specularColor[0]??1,n[r+W.SPECULAR_COLOR+1]=t.specularColor.g??t.specularColor[1]??1,n[r+W.SPECULAR_COLOR+2]=t.specularColor.b??t.specularColor[2]??1),n[r+W.IRIDESCENCE]=t.iridescence??0,n[r+W.IRIDESCENCE_IOR]=t.iridescenceIOR??1.3,t.iridescenceThicknessRange&&(n[r+W.IRIDESCENCE_THICKNESS_RANGE]=t.iridescenceThicknessRange[0]??100,n[r+W.IRIDESCENCE_THICKNESS_RANGE+1]=t.iridescenceThicknessRange[1]??400),n[r+W.ALBEDO_MAP_INDEX]=t.map??-1,n[r+W.NORMAL_MAP_INDEX]=t.normalMap??-1,n[r+W.ROUGHNESS_MAP_INDEX]=t.roughnessMap??-1,n[r+W.METALNESS_MAP_INDEX]=t.metalnessMap??-1,n[r+W.EMISSIVE_MAP_INDEX]=t.emissiveMap??-1,n[r+W.BUMP_MAP_INDEX]=t.bumpMap??-1,n[r+W.CLEARCOAT]=t.clearcoat??0,n[r+W.CLEARCOAT_ROUGHNESS]=t.clearcoatRoughness??0,n[r+W.OPACITY]=t.opacity??1,n[r+W.SIDE]=t.side??0,this._patchTriangleSideForMaterial(e,t.side??0),this._recomputeOpaqueBlockerForMaterial(e),n[r+W.TRANSPARENT]=t.transparent??0,n[r+W.ALPHA_TEST]=t.alphaTest??0,n[r+W.ALPHA_MODE]=t.alphaMode??0,n[r+W.DEPTH_WRITE]=t.depthWrite??1,n[r+W.NORMAL_SCALE]=t.normalScale?.x??(typeof t.normalScale==`number`?t.normalScale:1),n[r+W.NORMAL_SCALE+1]=t.normalScale?.y??(typeof t.normalScale==`number`?t.normalScale:1),n[r+W.BUMP_SCALE]=t.bumpScale??1,n[r+W.DISPLACEMENT_SCALE]=t.displacementScale??1,n[r+W.DISPLACEMENT_MAP_INDEX]=t.displacementMap??-1,n[r+W.SUBSURFACE]=t.subsurface??0,t.subsurfaceColor&&(n[r+W.SUBSURFACE_COLOR]=t.subsurfaceColor.r??t.subsurfaceColor[0]??1,n[r+W.SUBSURFACE_COLOR+1]=t.subsurfaceColor.g??t.subsurfaceColor[1]??1,n[r+W.SUBSURFACE_COLOR+2]=t.subsurfaceColor.b??t.subsurfaceColor[2]??1),t.subsurfaceRadius&&(n[r+W.SUBSURFACE_RADIUS]=t.subsurfaceRadius[0]??1,n[r+W.SUBSURFACE_RADIUS+1]=t.subsurfaceRadius[1]??.2,n[r+W.SUBSURFACE_RADIUS+2]=t.subsurfaceRadius[2]??.1),n[r+W.SUBSURFACE_RADIUS_SCALE]=t.subsurfaceRadiusScale??1,n[r+W.SUBSURFACE_ANISOTROPY]=t.subsurfaceAnisotropy??0,n[r+W.ANISOTROPY]=t.anisotropy??0,n[r+W.ANISOTROPY_ROTATION]=t.anisotropyRotation??0,n[r+W.ANISOTROPY_MAP_INDEX]=t.anisotropyMap??-1,n[r+W.TRANSMISSION_MAP_INDEX]=t.transmissionMap??-1,n[r+W.CLEARCOAT_MAP_INDEX]=t.clearcoatMap??-1,n[r+W.CLEARCOAT_ROUGHNESS_MAP_INDEX]=t.clearcoatRoughnessMap??-1,n[r+W.SHEEN_COLOR_MAP_INDEX]=t.sheenColorMap??-1,n[r+W.SHEEN_ROUGHNESS_MAP_INDEX]=t.sheenRoughnessMap??-1,n[r+W.IRIDESCENCE_MAP_INDEX]=t.iridescenceMap??-1,n[r+W.IRIDESCENCE_THICKNESS_MAP_INDEX]=t.iridescenceThicknessMap??-1,n[r+W.SPECULAR_INTENSITY_MAP_INDEX]=t.specularIntensityMap??-1,n[r+W.SPECULAR_COLOR_MAP_INDEX]=t.specularColorMap??-1;let i=[1,0,0,0,1,0,0,0,1],a=[{key:`mapMatrix`,offset:W.ALBEDO_TRANSFORM},{key:`normalMapMatrices`,offset:W.NORMAL_TRANSFORM},{key:`roughnessMapMatrices`,offset:W.ROUGHNESS_TRANSFORM},{key:`metalnessMapMatrices`,offset:W.METALNESS_TRANSFORM},{key:`emissiveMapMatrices`,offset:W.EMISSIVE_TRANSFORM},{key:`bumpMapMatrices`,offset:W.BUMP_TRANSFORM},{key:`displacementMapMatrices`,offset:W.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.rescanMaterialFeatures()&&this._notifyFeaturesChanged(),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){bt.warn(`material storage buffer not available`);return}let r=this.materialStorageAttr.array,i=e*W.FLOATS_PER_MATERIAL,a={map:W.ALBEDO_TRANSFORM,normalMap:W.NORMAL_TRANSFORM,roughnessMap:W.ROUGHNESS_TRANSFORM,metalnessMap:W.METALNESS_TRANSFORM,emissiveMap:W.EMISSIVE_TRANSFORM,bumpMap:W.BUMP_TRANSFORM,displacementMap:W.DISPLACEMENT_TRANSFORM}[t];if(a===void 0){bt.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()}rescanMaterialFeatures(){if(!this.materialStorageAttr?.array)return bt.warn(`material storage buffer not available for feature scanning`),!1;let e=this.materialStorageAttr.array,t=this.sdfs.materialCount||1,n={hasClearcoat:!1,hasTransmission:!1,hasDispersion:!1,hasIridescence:!1,hasSheen:!1,hasTransparency:!1,hasSubsurface:!1,hasMultiLobeMaterials:!1,hasMRTOutputs:!0};for(let r=0;r<t;r++){let t=r*W.FLOATS_PER_MATERIAL,i=e[t+W.TRANSMISSION],a=e[t+W.DISPERSION],o=e[t+W.SHEEN],s=e[t+W.IRIDESCENCE],c=e[t+W.CLEARCOAT],l=e[t+W.OPACITY],u=e[t+W.TRANSPARENT],d=e[t+W.ALPHA_TEST],f=e[t+W.SUBSURFACE];c>0&&(n.hasClearcoat=!0),i>0&&(n.hasTransmission=!0),a>0&&(n.hasDispersion=!0),s>0&&(n.hasIridescence=!0),o>0&&(n.hasSheen=!0),(u>0||l<1||d>0)&&(n.hasTransparency=!0),f>0&&(n.hasSubsurface=!0),[c>0,i>0,s>0,o>0].filter(Boolean).length>=2&&(n.hasMultiLobeMaterials=!0)}let r=JSON.stringify(this.sdfs.sceneFeatures)!==JSON.stringify(n);return r&&(this.sdfs.sceneFeatures=n),r}injectMaterialFeatureDefines(){let e=this.sdfs.sceneFeatures;if(!e){bt.warn(`no sceneFeatures detected, skipping define injection`);return}let t=JSON.stringify(e);(!this.compiledFeatures||this.compiledFeatures!==t)&&(bt.debug(`material features:`,e),this.compiledFeatures=t)}_notifyReset(){this.callbacks.onReset&&this.callbacks.onReset()}_notifyFeaturesChanged(){this.injectMaterialFeatureDefines()}_recomputeOpaqueBlockerForMaterial(e){let t=this.materialStorageAttr?.array;if(!t)return;let n=e*W.FLOATS_PER_MATERIAL,r=t[n+W.ALPHA_MODE]|0,i=t[n+W.TRANSPARENT]|0,a=t[n+W.TRANSMISSION]||0,o=t[n+W.OPACITY]??1,s=+(r===0&&i===0&&a===0&&o>=1);this._patchTriangleFlagForMaterial(e,wt,s)}_patchTriangleFlagForMaterial(e,t,n){let r=this.callbacks.getTriangleData?.(),i=r?.array,a=r?.count|0;if(!i||a===0)return;let o=U.FLOATS_PER_TRIANGLE,s=0;for(let r=0;r<a;r++){let a=r*o;i[a+St]===e&&(i[a+t]=n,s++)}s>0&&this.callbacks.onTriangleDataChanged&&this.callbacks.onTriangleDataChanged()}_patchTriangleSideForMaterial(e,t){this._patchTriangleFlagForMaterial(e,Ct,t)}dispose(){this.materialStorageAttr=null,this.materialStorageNode=null,this.materialCount=0,this.srgbBuckets=null,this.linearBuckets=null,this._srgbTexPacked=null,this._linearTexPacked=null,this.compiledFeatures=null}},Ot=`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})}};`,kt=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ot],{type:`text/javascript;charset=utf-8`});function At(e){let t;try{if(t=kt&&(self.URL||self.webkitURL).createObjectURL(kt),!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(Ot),{type:`module`,name:e?.name})}}function jt(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 Mt(e,t,n){return .2126*e+.7152*t+.0722*n}function Nt(e){return e<=.04045?e/12.92:((e+.055)/1.055)**2.4}function Pt(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]=Nt(o[e]),o[e+1]=Nt(o[e+1]),o[e+2]=Nt(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 Ft=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}=Pt(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}=Pt(e);this._worker=new At;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=Mt(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]=Mt(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]=(jt(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]=(jt(d,(n+1)/t,e*t,t)+.5)/t}return{marginalData:m,conditionalData:h,totalSum:l,compensationDelta:u}}},It=Math.PI,Lt=Math.PI*2,Rt=Math.E,zt=[5804542996261093e-21,13562911419845635e-21,30265902468824876e-21],Bt=[183999185144339.78,277980239196605.28,407904795438610.94],Vt=1.6110731556870734,Ht=1.5,Ut=1e3,Wt=8400,Gt=1250,Kt=.9999566769464484,qt=.05968310365946075,Jt=.07957747154594767;function Yt(e){return Ut*Math.max(0,1-Rt**+(-(Vt-Math.acos(Math.max(-1,Math.min(1,e))))/Ht))}function Xt(e){let t=.2*e*1e-17;return[.434*t*Bt[0],.434*t*Bt[1],.434*t*Bt[2]]}function Zt(e){return qt*(1+e**2)}function Qt(e,t){let n=t*t;return Jt*((1-n)/(1-2*t*e+n)**1.5)}function $t(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function en(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 tn(e,t,n,r,i,a,o,s){let c=(1-t)*It,l=(e-.5)*Lt,u=Math.sin(c),d=en([u*Math.sin(l),Math.cos(c),u*Math.cos(l)]),f=en(n),p=Yt(f[1])*r,m=i-1*(1-(1-Math.max(0,Math.min(1,1-Math.exp(f[1]/45e4))))),h=[zt[0]*m,zt[1]*m,zt[2]*m],g=Xt(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/It*v)**-1.253,b=Wt/y,x=Gt/y,S=[Math.exp(-(h[0]*b+_[0]*x)),Math.exp(-(h[1]*b+_[1]*x)),Math.exp(-(h[2]*b+_[2]*x))],C=$t(d,f),w=Zt(C*.5+.5),T=[h[0]*w,h[1]*w,h[2]*w],E=Qt(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]],ee=nn(Kt,Kt+2e-5,C);for(let e=0;e<3;e++)P[e]+=p*19e3*S[e]*ee;let F=65504;return[Math.min((A[0]+P[0])*.04,F),Math.min((A[1]+P[1])*.04+3e-4,F),Math.min((A[2]+P[2])*.04+75e-5,F),1]}function nn(e,t,n){let r=Math.max(0,Math.min(1,(n-e)/(t-e)));return r*r*(3-2*r)}var rn=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=tn((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()}},an=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()}},on=dt(`env`),sn=class{constructor(e,t){this.scene=e,this.uniforms=t,this.equirectHdrInfo=new Ft,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(V.gradientZenithColor),gradientHorizonColor:new r.Color(V.gradientHorizonColor),gradientGroundColor:new r.Color(V.gradientGroundColor),solidSkyColor:new r.Color(V.solidSkyColor),skySunDirection:this._calculateInitialSunDirection(),skySunIntensity:V.skySunIntensity,skyRayleighDensity:V.skyRayleighDensity,skyTurbidity:V.skyTurbidity,skyMieAnisotropy:V.skyMieAnisotropy},this.callbacks={},this._previousHDRI=null}async setMode(e){let t=this.envParams.mode;this.envParams.mode=e,e!==`hdri`&&t===`hdri`&&(this._previousHDRI=this.environmentTexture),e===`gradient`?await this.generateGradientTexture():e===`color`?await this.generateSolidColorTexture():e===`procedural`?await this.generateProceduralSkyTexture():e===`hdri`&&this._previousHDRI&&(await this.setEnvironmentMap(this._previousHDRI),this._previousHDRI=null),this.markDirty(),this.callbacks.onAutoExposureReset?.(),this._notifyReset()}markDirty(){this.environmentTexture&&(this.environmentTexture.needsUpdate=!0)}get params(){return this.envParams}get texture(){return this.environmentTexture}generateGradient(){return this.generateGradientTexture()}generateSolid(){return this.generateSolidColorTexture()}generateProcedural(){return this.generateProceduralSkyTexture()}_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),on.info(J.list([J.px(this.envTexSize.x,this.envTexSize.y),`CDF ${J.ms(this.cdfBuildTime)}${e?``:` (main thread)`}`]))}catch(e){on.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 an(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){on.error(`gradient sky generation failed:`,e)}}async generateSolidColorTexture(){this.simpleSkyRenderer||=new an(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){on.error(`solid color sky generation failed:`,e)}}async generateProceduralSkyTexture(){this.proceduralSkyRenderer||=new rn(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),on.debug(`sun synced · dir ${this.envParams.skySunDirection.toArray().map(e=>e.toFixed(2)).join(`,`)}`)}catch(e){on.error(`procedural sky generation failed:`,e)}}_calculateInitialSunDirection(){let e=V.skySunAzimuth*(Math.PI/180),t=V.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}},cn=S({origin:`vec3`,direction:`vec3`}),ln=S({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`}),un=S({transmission:`float`,clearcoat:`float`,clearcoatRoughness:`float`,sheenColor:`vec3`,sheenRoughness:`float`,iridescence:`float`,iridescenceThickness:`float`,specularIntensity:`float`,specularColor:`vec3`}),dn=S({color:`vec4`,ior:`float`,transmission:`float`,attenuationColor:`vec3`,attenuationDistance:`float`,albedoMapIndex:`int`,opacity:`float`,transparent:`bool`,alphaTest:`float`,alphaMode:`int`,albedoTransform:`mat3`}),fn=S({shadowed:`vec3`,unoccluded:`vec3`});S({position:`vec3`,radius:`float`,material:ln});var pn=S({didHit:`bool`,dst:`float`,hitPoint:`vec3`,normal:`vec3`,uv:`vec2`,materialIndex:`int`,meshIndex:`int`,triangleIndex:`int`,boxTests:`int`,triTests:`int`});S({posA:`vec3`,posB:`vec3`,posC:`vec3`,uvA:`vec2`,uvB:`vec2`,uvC:`vec2`,normalA:`vec3`,normalB:`vec3`,normalC:`vec3`,material:ln,materialIndex:`int`,meshIndex:`int`}),S({color:`vec4`,samples:`int`});var mn=S({direction:`vec3`,value:`vec3`,pdf:`float`,isTransmission:`bool`,colorWeight:`vec3`}),hn=S({specular:`float`,diffuse:`float`,sheen:`float`,clearcoat:`float`,transmission:`float`,iridescence:`float`}),gn=S({Ta:`vec3`,Ba:`vec3`}),_n=S({NoL:`float`,NoV:`float`,NoH:`float`,VoH:`float`,LoH:`float`,ToH:`float`,BoH:`float`,ToV:`float`,BoV:`float`,ToL:`float`,BoL:`float`}),vn=S({compensation:`vec3`,E_total:`vec3`}),yn=S({albedo:`vec4`,emissive:`vec3`,metalness:`float`,roughness:`float`,normal:`vec3`,hasTextures:`bool`}),bn=S({isMetallic:`bool`,isRough:`bool`,isSmooth:`bool`,isTransmissive:`bool`,hasClearcoat:`bool`,isEmissive:`bool`,complexityScore:`float`}),xn=S({albedoUV:`vec2`,normalUV:`vec2`,metalnessUV:`vec2`,emissiveUV:`vec2`,bumpUV:`vec2`,roughnessUV:`vec2`,normalBumpSameUV:`bool`,metalRoughSameUV:`bool`,albedoEmissiveSameUV:`bool`,allSameUV:`bool`}),Sn=S({invRoughness:`float`,metalFactor:`float`,iorFactor:`float`,maxSheenColor:`float`});S({traversals:`int`,transmissiveTraversals:`int`,rayType:`int`,isPrimaryRay:`bool`,actualBounceDepth:`int`});var Cn=3.14159,wn=1/Cn,Tn=2*Cn,En=1e-6,Dn=.05,On=.089,kn=.001,An=(0,n.vec3)(.2126,.7152,.0722),Y=W.SLOTS_PER_MATERIAL,jn=W.SLOT,X=jn,Mn=(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 ) );
|
|
@@ -727,8 +727,8 @@
|
|
|
727
727
|
}
|
|
728
728
|
`),Nl=class extends be{constructor(e,r={}){super(`AutoExposure`,{...r,executionMode:ye.ALWAYS}),this.renderer=e,this.REDUCTION_SIZE=64,this.keyValueU=(0,n.uniform)(r.keyValue??.18),this.minExposureU=(0,n.uniform)(r.minExposure??.1),this.maxExposureU=(0,n.uniform)(r.maxExposure??20),this.adaptSpeedBrightU=(0,n.uniform)(r.adaptSpeedBright??3),this.adaptSpeedDarkU=(0,n.uniform)(r.adaptSpeedDark??.5),this.epsilonU=(0,n.uniform)(r.epsilon??1e-4),this.deltaTimeU=(0,n.uniform)(1/60),this.isFirstFrameU=(0,n.uniform)(1),this.previousExposureU=(0,n.uniform)(r.initialExposure??1),this.lowPercentileU=(0,n.uniform)(r.lowPercentile??.1),this.highPercentileU=(0,n.uniform)(r.highPercentile??.9),this.centerWeightU=(0,n.uniform)(r.centerWeight??8),this.inputResW=(0,n.uniform)(1),this.inputResH=(0,n.uniform)(1),this._inputTexNode=new t.TextureNode,this._reductionReadTexNode=new t.TextureNode,this.currentExposure=r.initialExposure??1,this.currentLuminance=.18,this.targetExposure=1,this.lastTime=performance.now(),this.isFirstFrame=!0,this._pendingReadback=!1,this._readbackGeneration=0,this._initRenderTargets(),this._buildCompute()}_initRenderTargets(){let e={type:r.FloatType,format:r.RGBAFormat,minFilter:r.NearestFilter,magFilter:r.NearestFilter,depthBuffer:!1,stencilBuffer:!1};this._downsampleTarget=new t.RenderTarget(this.REDUCTION_SIZE,this.REDUCTION_SIZE,e),this._downsampleStorageTex=new t.StorageTexture(this.REDUCTION_SIZE,this.REDUCTION_SIZE),this._downsampleStorageTex.type=r.FloatType,this._downsampleStorageTex.format=r.RGBAFormat,this._downsampleStorageTex.minFilter=r.NearestFilter,this._downsampleStorageTex.magFilter=r.NearestFilter,this._reductionStorageTex=new t.StorageTexture(1,1),this._reductionStorageTex.type=r.FloatType,this._reductionStorageTex.format=r.RGBAFormat,this._reductionStorageTex.minFilter=r.NearestFilter,this._reductionStorageTex.magFilter=r.NearestFilter,this._reductionReadTarget=new t.RenderTarget(1,1,e),this._adaptationResult=(0,n.attributeArray)(1,`vec4`),this._readbackBuffer=new t.ReadbackBuffer(16),this._readbackBuffer.name=`AutoExposureAdaptation`,this._histogramBuffer=(0,n.attributeArray)(Dl,`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=Pn((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)(Ol)).div((0,n.float)(kl)).mul((0,n.float)(Dl)).floor().clamp(0,(0,n.float)(Dl-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)(jl)));(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)(Dl,({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)(Dl,({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)(Ol).add((0,n.float)(t).add(.5).mul((0,n.float)(Al)));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=Ml(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()}},Pl=class extends be{constructor(e,i={}){super(`Compositor`,{...i,executionMode:ye.ALWAYS}),this.renderer=e,this.saturation=(0,n.uniform)(i.saturation??1),this._transparentBackground=(0,n.uniform)(0,`int`),this._pathTracer=i.pathTracer??null,this._convergenceOverlay=!1,this._debugMaterial=null,this._debugQuad=null,this._debugTexNode=null,this._debugM2Attr=null,this._debugMaskAttr=null,this._debugExposureComp=(0,n.uniform)(1),this._sourceTexNode=new t.TextureNode;let a=this._sourceTexNode.sample((0,n.uv)()),o=(0,n.mix)((0,n.vec3)((0,n.dot)(a.xyz,An)),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(`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,An).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}},Fl=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={}}},Il=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):[]}},Ll=!1,Rl=[],zl=new WeakMap;function Bl(e){Ll=!!e}function Vl(){return Rl.slice()}function Hl(){Rl.length=0}function Ul(e){let t=[];for(let n of Object.keys(e))e[n]?.isTextureNode===!0&&t.push(n);return t}var Wl=e=>!e||!e.image||!(e.image.width>0);function Gl(e,t,n){if(!Ll){n();return}let r=zl.get(e);if(r||(r={phase:`pending`,unboundAtCompile:[]},zl.set(e,r)),r.phase!==`pending`){n(),r.phase===`watch`&&Kl(e,r);return}let i=Object.prototype.hasOwnProperty.call(t,`compute`),a=t.compute;t.compute=function(...t){return r.phase===`pending`&&(r.unboundAtCompile=Ul(e).filter(t=>Wl(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 Kl(e,t){let n=[];for(let r of t.unboundAtCompile){let t=e[r]?.value;if(Wl(t))return;t.isStorageTexture!==!0&&n.push(r)}t.phase=`done`,n.length!==0&&Rl.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 ql=class{constructor(e,t,n){this.renderer=e,this.width=t,this.height=n,this.stages=[],this.context=new Fl,this.eventBus=new Il,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(Gl(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){console.error(`[Pipeline] Error in stage '${t.name}':`,e)}}if(this.context.incrementFrame(),this.eventBus.emit(`frame:complete`,{frame:this.context.getState(`frame`),accumulatedFrames:this.context.getState(`accumulatedFrames`)}),this.stats.enabled){let e=performance.now()-t;this.stats.timings.has(`_total`)||this.stats.timings.set(`_total`,[]);let n=this.stats.timings.get(`_total`);n.push(e),n.length>60&&n.shift(),this.stats.frameCount++}}reset(){this.eventBus.emit(`pipeline:reset`);for(let e of this.stages)if(e.reset)try{e.reset()}catch(t){console.error(`[Pipeline] Error resetting stage '${e.name}':`,t)}this.context.reset(),this.stats.enabled&&(this.stats.timings.clear(),this.stats.frameCount=0)}setSize(e,t){this.width=e,this.height=t,this.context.setState(`width`,e),this.context.setState(`height`,t),this.eventBus.emit(`pipeline:resize`,{width:e,height:t});for(let n of this.stages)if(n.setSize)try{n.setSize(e,t)}catch(e){console.error(`[Pipeline] Error resizing stage '${n.name}':`,e)}}dispose(){for(let e of this.stages)if(e.dispose)try{e.dispose()}catch(t){console.error(`[Pipeline] Error disposing stage '${e.name}':`,t)}this.stages=[],this.context.dispose(),this.eventBus.clear(),this.stats.timings.clear()}setStatsEnabled(e){this.stats.enabled=e,e||(this.stats.timings.clear(),this.stats.frameCount=0)}getStats(){if(!this.stats.enabled)return null;let e={frameCount:this.stats.frameCount,stages:{},total:0};for(let[t,n]of this.stats.timings.entries()){if(n.length===0)continue;let r=n.reduce((e,t)=>e+t,0)/n.length,i=Math.min(...n),a=Math.max(...n);t===`_total`?(e.total=r,e.totalMin=i,e.totalMax=a):e.stages[t]={avg:r,min:i,max:a}}return e}logStats(){let e=this.getStats();if(!e){console.log(`[Pipeline] Stats not enabled`);return}console.group(`[Pipeline] Performance Stats`),console.log(`Frames: ${e.frameCount}`),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()}},Jl=dt(`engine`),Yl=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,Jl.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:e.frameCount>=e.completionThreshold||(e._isConvergedComplete?.()??!1):!1}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}},Xl=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:L.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:L.OBJECT_SELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`objectDeselected`,t=>{this.select(null),e.refreshFrame(),e.dispatchEvent({type:L.OBJECT_DESELECTED,object:t.object,uuid:t.uuid})}),this.addEventListener(`selectModeChanged`,t=>{e.dispatchEvent({type:L.SELECT_MODE_CHANGED,enabled:t.enabled})}),this.addEventListener(`objectDoubleClicked`,t=>{this.select(t.object),e.refreshFrame(),e.dispatchEvent({type:L.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:L.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}},Zl={STRING:`string`,NUMBER:`number`,WORD:`word`,LBRACKET:`[`,RBRACKET:`]`},Ql=e=>e===` `||e===` `||e===`
|
|
729
729
|
`||e===`\r`||e===`\f`,$l=e=>e>=`0`&&e<=`9`,eu=(e,t,n)=>!!($l(e)||e===`.`&&$l(t)||(e===`-`||e===`+`)&&($l(t)||t===`.`&&$l(n)));function tu(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e[r];if(Ql(i)){r++;continue}if(i===`#`){for(;r<n&&e[r]!==`
|
|
730
|
-
`;)r++;continue}if(i===`[`){t.push({type:Zl.LBRACKET}),r++;continue}if(i===`]`){t.push({type:Zl.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:Zl.STRING,value:e.slice(i,r)}),r++;continue}if(eu(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:Zl.NUMBER,value:o});continue}{let i=r;for(;r<n&&!Ql(e[r])&&e[r]!==`"`&&e[r]!==`[`&&e[r]!==`]`&&e[r]!==`#`;)r++;t.push({type:Zl.WORD,value:e.slice(i,r)})}}return t}function nu(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function ru(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 iu(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function au(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function ou(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 su(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function cu(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 lu(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function uu(e,t,n){let r=lu(su(t,e)),i=lu(cu(lu(n),r)),a=cu(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 du(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 nu();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 fu=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=nu(),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(tu(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!==Zl.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!==Zl.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===Zl.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==Zl.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===Zl.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===Zl.LBRACKET){for(this._next();this._peek()&&this._peek().type!==Zl.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===Zl.NUMBER||e.type===Zl.STRING)return e.value;if(e.type===Zl.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!==Zl.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=nu();break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this.ctm=ru(this.ctm,iu(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this.ctm=ru(this.ctm,au(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this.ctm=ru(this.ctm,ou(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=uu([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this.ctm=ru(this.ctm,du(t));break}case`Transform`:this.ctm=this._readBracketedOrBareNumbers(16);break;case`ConcatTransform`:{let e=this._readBracketedOrBareNumbers(16);this.ctm=ru(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:du(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=nu(),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===Zl.STRING&&this._next(),this._peek()&&this._peek().type===Zl.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=ru(du(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(tu(t)),this.dirStack.pop()}_skipTypeAndParams(){this._peek()&&this._peek().type===Zl.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===Zl.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}`))}},pu={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]},mu=[.92,.92,.92];function hu(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 gu(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function _u(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function vu(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:hu(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=yu(i.value[0]);return e&&pu[e]?{rgb:pu[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 yu(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(pu))if(e.toLowerCase().includes(t))return t;return null}function bu(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=gu(e,`uroughness`,null),r=gu(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function xu(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 vu(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await vu(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 vu(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await vu(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 vu(i,`eta`,t,mu)).rgb||mu:pu.cu);a.metalness=1,a.roughness=bu(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=gu(i,`eta`,1.5),a.roughness=bu(i,0),a.thickness=n===`thindielectric`?0:gu(i,`thickness`,0);break;case`coateddiffuse`:s(await vu(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=bu(i,0);break;case`diffusetransmission`:{let e=await vu(i,`transmittance`,t,[.25,.25,.25]);s(await vu(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,gu(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([xu(o,t),xu(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 vu(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 Su=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],Cu=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=ru(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?ru(Su,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=_u(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(gu(e,`radius`,1),48,32)}_disk(e){let t=gu(e,`radius`,1),n=gu(e,`innerradius`,0),i=gu(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 xu(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 vu(t.params,`L`,n,[1,1,1]),i=gu(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=_u(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=gu(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=gu(t.params,`scale`,1),i=_u(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 vu(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)`)}},wu=new TextDecoder;function Tu(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 Eu(e,t){return!e||t.startsWith(`/`)?Tu(t):Tu(`${e}/${t}`)}var Du=class{constructor(e){this.byPath=new Map,this.byBase=new Map;for(let t in e){let n=Tu(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=Tu(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 Ou(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 ku(e){let{vfs:t,plyParser:n,imageFromBytes:r,envFromBytes:i,convertHandedness:a}=e,o=new Du(t),s=e.entryPath||Ou(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 fu({resolveInclude:(e,t)=>{let n=o.find(Eu(t,e))||o.find(e);return n?wu.decode(n):null}}).parse(wu.decode(c),l),d=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{...await new Cu({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 Au={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`}},ju=/\.(usd|usda|usdc)$/i,Mu=/\.(png|jpg|jpeg|avif)$/i,Nu=class e extends r.EventDispatcher{constructor(e,t,n){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this._externalModel=null,this.floorPlane=null,this.sceneScale=1,this.loaderCache={},this.uploadedFileInfo=null,this.animations=[],this.renderer=null,this._loadingManager=new r.LoadingManager,this._loadCancelled=!1}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;z({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){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}releaseTargetModel(){this.targetModel&&(this.targetModel===this._externalModel?this.targetModel.parent?.remove(this.targetModel):Ae(this.targetModel),this.targetModel=null,this._externalModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return Au[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);z({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`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}),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,p.unzipSync)(new Uint8Array(n));return Ou(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(z({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 ku({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,z({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(Au[n]&&Au[n].type===`model`)return ju.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=>ju.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&&(ju.test(e)||Mu.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,p.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(ju,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,p.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,p.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.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,p.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,p.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 m=new o(c);m.setMaterials(f);let h=(0,p.strFromU8)(e.content),g=m.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,p.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}=go(),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(f.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{z({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||[],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{z({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`){return e.name=e.name||t,this._processAndParent(e),{root:e}}removeModelRoot(e,{external:t=!1}={}){e&&(t?e.parent?.remove(e):Ae(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({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||[],z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let 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,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(z({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,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){return e.name=e.name||t,this.releaseTargetModel(),this.targetModel=e,this._externalModel=e,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e,filename:t}),e}async onModelLoad(e){let t=new eo(`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&&!t.includes(e.uuid)&&t.push(e.uuid),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI,n.__candelaConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let i=new r.RectAreaLight(new r.Color(...n.color),n.intensity*.1,n.width,n.height);i.userData.normalize=n.normalize??!0,i.userData.spread=Number.isFinite(n.spread)?n.spread:Math.PI,i.userData.shape=n.shape??`rectangle`,i.position.z=-2,i.name=n.name,e.add(i),t.push(i.uuid)}if(e.isMesh&&Array.isArray(e.material)){console.log(`Found multi-material mesh:`,e.name);let t=(0,d.createMeshesFromMultiMaterialMesh)(e);e.parent&&(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(Au))r.type===e&&(t[n]=r);return t}return Au}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.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},Pu={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`}},Fu={bounces:`maxBounces`,debugMode:`visMode`},Iu=class extends r.EventDispatcher{constructor(e=V){super(),this._values=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?.denoiserStrategy===`asvgf`&&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}={}){let i=this._values.get(e);if(i===t)return;this._values.set(e,t);let a=Pu[e];a&&(this._applyRoute(a,t,i),(n===void 0?a.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:L.SETTING_CHANGED,key:e,value:t,prev:i}))}setMany(e,{silent:t,reset:n}={}){let r=!1;for(let[n,i]of Object.entries(e)){let e=this._values.get(n);if(e===i)continue;this._values.set(n,i);let a=Pu[n];a&&(this._applyRoute(a,i,e),(a.reset??!0)&&(r=!0),t||this.dispatchEvent({type:L.SETTING_CHANGED,key:n,value:i,prev:e}))}(n===void 0?r:n)&&this._resetCallback?.()}get(e){return this._values.get(e)}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=Pu[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(Pu))t in e&&this._values.set(t,e[t]);for(let[t,n]of Object.entries(Fu))t in e&&this._values.set(n,e[t])}},Lu=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 m.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=He.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=He.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=He.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>He.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:L.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>He.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()}},Ru=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));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}},zu=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=>Bu(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:Vu(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 Bu(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 Vu(e){return Math.max(0,Math.min(1,e))}function Hu(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:Zl.LBRACKET}),r++;continue}if(i===`]`){t.push({type:Zl.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:Zl.STRING,value:e.slice(i,r)}),r++;continue}if(eu(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:Zl.NUMBER,value:o});continue}{let i=r;for(;r<n&&!Ql(e[r])&&e[r]!==`"`&&e[r]!==`[`&&e[r]!==`]`&&e[r]!==`#`;)r++;t.push({type:Zl.WORD,value:e.slice(i,r)})}}return t}function nu(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function ru(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 iu(e,t,n){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,n,1]}function au(e,t,n){return[e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1]}function ou(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 su(e,t){return[e[0]-t[0],e[1]-t[1],e[2]-t[2]]}function cu(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 lu(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function uu(e,t,n){let r=lu(su(t,e)),i=lu(cu(lu(n),r)),a=cu(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 du(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 nu();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 fu=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=nu(),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(tu(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!==Zl.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!==Zl.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===Zl.LBRACKET){this._next();let e=[];for(;this._peek()&&this._peek().type!==Zl.RBRACKET;)e.push(this._expectNumber(`transform element`));return this._next(),e}return this._readNumbers(e)}_parseParams(){let e={};for(;this._peek()&&this._peek().type===Zl.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===Zl.LBRACKET){for(this._next();this._peek()&&this._peek().type!==Zl.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===Zl.NUMBER||e.type===Zl.STRING)return e.value;if(e.type===Zl.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!==Zl.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=nu();break;case`Translate`:{let[e,t,n]=this._readNumbers(3);this.ctm=ru(this.ctm,iu(e,t,n));break}case`Scale`:{let[e,t,n]=this._readNumbers(3);this.ctm=ru(this.ctm,au(e,t,n));break}case`Rotate`:{let[e,t,n,r]=this._readNumbers(4);this.ctm=ru(this.ctm,ou(e,t,n,r));break}case`LookAt`:{let e=this._readNumbers(9),t=uu([e[0],e[1],e[2]],[e[3],e[4],e[5]],[e[6],e[7],e[8]]);this.ctm=ru(this.ctm,du(t));break}case`Transform`:this.ctm=this._readBracketedOrBareNumbers(16);break;case`ConcatTransform`:{let e=this._readBracketedOrBareNumbers(16);this.ctm=ru(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:du(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=nu(),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===Zl.STRING&&this._next(),this._peek()&&this._peek().type===Zl.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=ru(du(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(tu(t)),this.dirStack.pop()}_skipTypeAndParams(){this._peek()&&this._peek().type===Zl.STRING&&this._next(),this._parseParams()}_skipNamedAndParams(){this._peek()&&this._peek().type===Zl.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}`))}},pu={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]},mu=[.92,.92,.92];function hu(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 gu(e,t,n){let r=e[t];return r&&typeof r.value[0]==`number`?r.value[0]:n}function _u(e,t,n){let r=e[t];return r&&typeof r.value[0]==`string`?r.value[0]:n}async function vu(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:hu(i.value[0]),texture:null};if(i.type===`spectrum`){if(typeof i.value[0]==`string`){let e=yu(i.value[0]);return e&&pu[e]?{rgb:pu[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 yu(e){let t=e.toLowerCase().match(/metal-([a-z]+)/);if(t)return t[1];for(let t of Object.keys(pu))if(e.toLowerCase().includes(t))return t;return null}function bu(e,t){if(e.roughness&&typeof e.roughness.value[0]==`number`)return e.roughness.value[0];let n=gu(e,`uroughness`,null),r=gu(e,`vroughness`,null);return n!==null&&r!==null?(n+r)/2:n===null?t:n}async function xu(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 vu(i,`reflectance`,t,[.5,.5,.5])),a.roughness=1,a.metalness=0;break;case`conductor`:case`metal`:{let e=await vu(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 vu(i,`eta`,t,[.2,.92,1.1])).rgb,n=(await vu(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 vu(i,`eta`,t,mu)).rgb||mu:pu.cu);a.metalness=1,a.roughness=bu(i,.1);break}case`dielectric`:case`thindielectric`:a.transmission=1,a.metalness=0,a.color.setRGB(1,1,1),a.ior=gu(i,`eta`,1.5),a.roughness=bu(i,0),a.thickness=n===`thindielectric`?0:gu(i,`thickness`,0);break;case`coateddiffuse`:s(await vu(i,`reflectance`,t,[.5,.5,.5])),a.roughness=.6,a.metalness=0,a.clearcoat=1,a.clearcoatRoughness=bu(i,0);break;case`diffusetransmission`:{let e=await vu(i,`transmittance`,t,[.25,.25,.25]);s(await vu(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,gu(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([xu(o,t),xu(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 vu(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 Su=[1,0,0,0,0,1,0,0,0,0,-1,0,0,0,0,1],Cu=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=ru(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?ru(Su,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=_u(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(gu(e,`radius`,1),48,32)}_disk(e){let t=gu(e,`radius`,1),n=gu(e,`innerradius`,0),i=gu(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 xu(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 vu(t.params,`L`,n,[1,1,1]),i=gu(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=_u(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=gu(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=gu(t.params,`scale`,1),i=_u(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 vu(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)`)}},wu=new TextDecoder;function Tu(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 Eu(e,t){return!e||t.startsWith(`/`)?Tu(t):Tu(`${e}/${t}`)}var Du=class{constructor(e){this.byPath=new Map,this.byBase=new Map;for(let t in e){let n=Tu(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=Tu(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 Ou(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 ku(e){let{vfs:t,plyParser:n,imageFromBytes:r,envFromBytes:i,convertHandedness:a}=e,o=new Du(t),s=e.entryPath||Ou(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 fu({resolveInclude:(e,t)=>{let n=o.find(Eu(t,e))||o.find(e);return n?wu.decode(n):null}}).parse(wu.decode(c),l),d=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{...await new Cu({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 Au=[`sourceFile`,`url`,`file`];function ju(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 Mu(e){let t=typeof e==`string`?parseFloat(e):e;return Number.isFinite(t)?t:void 0}function Nu(e){let t=ju(e);if(!t)return null;let n=ju(t.rayzee);return n&&n.environment!==void 0?n:t.environment===void 0?null:t}function Pu(e){let t=ju(e);if(!t)return null;let n=Au.map(e=>t[e]).find(e=>typeof e==`string`&&e.trim());if(!n)return null;let r=Mu(t.rotation),i=Mu(t.intensity),a={sourceFile:n.trim()};return r!==void 0&&(a.rotation=r),i!==void 0&&(a.intensity=Math.max(0,i)),a}function Fu(e){let t=Nu(e);if(!t)return null;let n=Pu(t.environment);return n?{environment:n}:null}function Iu(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=Fu(e);if(t)return t}return null}var Lu={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`}},Ru=/\.(usd|usda|usdc)$/i,zu=/\.(png|jpg|jpeg|avif)$/i,Bu=class e extends r.EventDispatcher{constructor(e,t,n){super(),this.scene=e,this.camera=t,this.controls=n,this.targetModel=null,this._externalModel=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}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;z({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){z({status:e,progress:t,canCancel:!1,loadedBytes:null,totalBytes:null})}static _isNetworkUrl(e){return typeof e==`string`&&/^https?:/i.test(e)}releaseTargetModel(){this.sceneMetadata=null,this.targetModel&&(this.targetModel===this._externalModel?this.targetModel.parent?.remove(this.targetModel):Ae(this.targetModel),this.targetModel=null,this._externalModel=null,this.animations=[])}setRenderer(e){this.renderer=e}getFileFormat(e){return Lu[e.split(`.`).pop().toLowerCase()]||null}readFileAsArrayBuffer(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsArrayBuffer(e)})}readFileAsText(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=e=>t(e.target.result),r.onerror=e=>n(e),r.readAsText(e)})}async loadAssetFromFile(e){let t=e.name,n=this.getFileFormat(t);if(!n)throw Error(`Unsupported file format: ${t}`);z({isLoading:!0,status:`Loading ${n.name}...`,progress:2});try{let r;switch(n.type){case`model`:r=await this.loadModelFromFile(e,t);break;case`environment`:case`image`:r=await this.loadEnvironmentFromFile(e,t);break;case`archive`:r=await this.loadArchiveFromFile(e,t);break;default:throw Error(`Unknown asset type: ${n.type}`)}return r}catch(e){throw this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadModelFromFile(e,t){let n=t.split(`.`).pop().toLowerCase(),r=await this.readFileAsArrayBuffer(e);switch(n){case`glb`:case`gltf`:return await this.loadGLBFromArrayBuffer(r,t);case`fbx`:return await this.loadFBXFromArrayBuffer(r,t);case`obj`:return await this.loadOBJFromFile(e,t);case`stl`:return await this.loadSTLFromArrayBuffer(r,t);case`ply`:return await this.loadPLYFromArrayBuffer(r,t);case`dae`:return await this.loadColladaFromFile(e,t);case`3mf`:return await this.load3MFFromArrayBuffer(r,t);case`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,p.unzipSync)(new Uint8Array(n));return Ou(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(z({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 ku({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,z({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(Lu[n]&&Lu[n].type===`model`)return Ru.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=>Ru.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&&(Ru.test(e)||zu.test(e))&&(i[e]=[t[e],{level:0}]);return await this.loadUSDFromArrayBuffer((0,p.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(Ru,``)===t[t.length-2]})||r[0]}async loadModelFromZipEntry(e,t,n,r){try{z({isLoading:!0,status:`Processing ${n.toUpperCase()} from ZIP...`,progress:5});let i=new Blob([e.buffer],{type:`application/octet-stream`}),a=URL.createObjectURL(i),o;switch(n){case`glb`:case`gltf`:o=await this.handleGltfFromZip(n,e,t,r);break;case`fbx`:o=await this.loadFBXFromArrayBuffer(e.buffer,t);break;case`obj`:o=await this.handleObjFromZip(e,t,r);break;case`stl`:o=await this.loadSTLFromArrayBuffer(e.buffer,t);break;case`ply`:o=await this.loadPLYFromArrayBuffer(e.buffer,t);break;case`dae`:{let n=(0,p.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,p.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=Iu(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,p.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,p.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 m=new o(c);m.setMaterials(f);let h=(0,p.strFromU8)(e.content),g=m.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,p.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}=go(),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(f.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{z({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=Iu(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{z({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`){return e.name=e.name||t,this._processAndParent(e),{root:e}}removeModelRoot(e,{external:t=!1}={}){e&&(t?e.parent?.remove(e):Ae(e))}async loadGLBFromArrayBuffer(e,t=`model.glb`){let n=await this.createGLTFLoader();try{z({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=Iu(r),z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading GLB:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}finally{this._disposeGLTFLoader(n)}}async loadFBXFromArrayBuffer(e,t=`model.fbx`){try{if(z({isLoading:!0,status:`Processing FBX Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.fbx){let{FBXLoader:e}=await import(`three/examples/jsm/loaders/FBXLoader.js`);this.loaderCache.fbx=new e}let n=this.loaderCache.fbx.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading FBX:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadOBJFromFile(e,t=`model.obj`){try{if(z({isLoading:!0,status:`Processing OBJ Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.obj){let{OBJLoader:e}=await import(`three/examples/jsm/loaders/OBJLoader.js`);this.loaderCache.obj=new e}let n=await this.readFileAsText(e),r=this.loaderCache.obj.parse(n);return r.name=t,this.releaseTargetModel(),this.targetModel=r,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r,filename:t}),r}catch(e){throw console.error(`Error loading OBJ:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadSTLFromArrayBuffer(e,t=`model.stl`){try{if(z({isLoading:!0,status:`Processing STL Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.stl){let{STLLoader:e}=await import(`three/examples/jsm/loaders/STLLoader.js`);this.loaderCache.stl=new e}let n=new r.Mesh(this.loaderCache.stl.parse(e),new r.MeshStandardMaterial);return n.name=t,this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading STL:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadPLYFromArrayBuffer(e,t=`model.ply`){try{if(z({isLoading:!0,status:`Processing PLY Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.ply){let{PLYLoader:e}=await import(`three/examples/jsm/loaders/PLYLoader.js`);this.loaderCache.ply=new e}let 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,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:i,filename:t}),i}catch(e){throw console.error(`Error loading PLY:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadColladaFromFile(e,t=`model.dae`){try{if(z({isLoading:!0,status:`Processing Collada Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.collada){let{ColladaLoader:e}=await import(`three/examples/jsm/loaders/ColladaLoader.js`);this.loaderCache.collada=new e}let n=await this.readFileAsText(e),r=this.loaderCache.collada.parse(n);return r.scene.name=t,this.releaseTargetModel(),this.targetModel=r.scene,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:r.scene,filename:t}),r}catch(e){throw console.error(`Error loading Collada:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async load3MFFromArrayBuffer(e,t=`model.3mf`){try{if(z({isLoading:!0,status:`Processing 3MF Data...`,progress:5}),await new Promise(e=>setTimeout(e,0)),!this.loaderCache.threemf){let{ThreeMFLoader:e}=await import(`three/examples/jsm/loaders/3MFLoader.js`);this.loaderCache.threemf=new e}let n=this.loaderCache.threemf.parse(e);return this.releaseTargetModel(),this.targetModel=n,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading 3MF:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadUSDFromArrayBuffer(e,t=`model.usd`){try{if(z({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,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:n,filename:t}),n}catch(e){throw console.error(`Error loading USD:`,e),this.dispatchEvent({type:`error`,message:e.message,filename:t}),e}}async loadObject3D(e,t=`object3d`){return e.name=e.name||t,this.releaseTargetModel(),this.targetModel=e,this._externalModel=e,z({isLoading:!0,status:`Processing Data...`,progress:10}),await this.onModelLoad(this.targetModel),this.dispatchEvent({type:`load`,model:e,filename:t}),e}async onModelLoad(e){let t=new eo(`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&&!t.includes(e.uuid)&&t.push(e.uuid),(e.isPointLight||e.isSpotLight)&&!n.__candelaConverted&&(e.intensity*=4*Math.PI,n.__candelaConverted=!0),e.name.startsWith(`RectAreaLightPlaceholder`)&&n.name&&n.type===`RectAreaLight`){let i=new r.RectAreaLight(new r.Color(...n.color),n.intensity*.1,n.width,n.height);i.userData.normalize=n.normalize??!0,i.userData.spread=Number.isFinite(n.spread)?n.spread:Math.PI,i.userData.shape=n.shape??`rectangle`,i.position.z=-2,i.name=n.name,e.add(i),t.push(i.uuid)}if(e.isMesh&&Array.isArray(e.material)){console.log(`Found multi-material mesh:`,e.name);let t=(0,d.createMeshesFromMultiMaterialMesh)(e);e.parent&&(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(Lu))r.type===e&&(t[n]=r);return t}return Lu}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.releaseTargetModel()}removeAllEventListeners(){this._listeners=void 0}},Vu={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`}},Hu={bounces:`maxBounces`,debugMode:`visMode`},Uu=class extends r.EventDispatcher{constructor(e=V){super(),this._values=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?.denoiserStrategy===`asvgf`&&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}={}){let i=this._values.get(e);if(i===t)return;this._values.set(e,t);let a=Vu[e];a&&(this._applyRoute(a,t,i),(n===void 0?a.reset??!0:n)&&this._resetCallback?.(),r||this.dispatchEvent({type:L.SETTING_CHANGED,key:e,value:t,prev:i}))}setMany(e,{silent:t,reset:n}={}){let r=!1;for(let[n,i]of Object.entries(e)){let e=this._values.get(n);if(e===i)continue;this._values.set(n,i);let a=Vu[n];a&&(this._applyRoute(a,i,e),(a.reset??!0)&&(r=!0),t||this.dispatchEvent({type:L.SETTING_CHANGED,key:n,value:i,prev:e}))}(n===void 0?r:n)&&this._resetCallback?.()}get(e){return this._values.get(e)}getAll(){return Object.fromEntries(this._values)}applyAll(){for(let[e,t]of this._values){let n=Vu[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(Vu))t in e&&this._values.set(t,e[t]);for(let[t,n]of Object.entries(Hu))t in e&&this._values.set(n,e[t])}},Wu=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 m.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=He.SMOOTHING_FACTOR?`auto`:`manual`,this.afScreenPoint={x:.5,y:.5},this.afSmoothingFactor=He.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=He.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>He.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:L.AUTO_FOCUS_UPDATED,distance:_/e});let t=Math.abs(_-g)/Math.max(g,.001);h?c?.():t>He.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()}},Gu=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));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}},Ku=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=>qu(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:Ju(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 qu(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 Ju(e){return Math.max(0,Math.min(1,e))}function Yu(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=$u(o),t=2+2*Number(e[1]);o=ed(o,t)}let s=$u(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 Xu(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=td(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=nd(o[p][0],o[m][0],g);else{let e=u+(n+.5)/t*(l-u),r=td(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=nd(nd(f,h,d),nd(_,v,d),g)}let c=Math.min(1,Math.max(0,i/s));r[e*t+n]=Math.round(c*255)}}return r}function Zu(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 Qu(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 $u(e){return e.split(/\s+/).filter(e=>e.length>0)}function ed(e,t){let n=/\S+/g,r=0;for(;n.exec(e)!==null;)if(r++,r===t)return e.slice(n.lastIndex);return``}function td(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 nd(e,t,n){return e+(t-e)*n}var rd=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=Yu(await r.text(),e.name);return{it:e,profile:i,grid:Xu(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=Zu(r);c.push({name:i[e].it.name,index:e,maxCandela:r.maxCandela,photometricType:r.photometricType,suggestedAngle:a,suggestedPenumbra:Qu(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:id(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 id(e){return Math.max(0,Math.min(1,e))}var ad=e=>Math.min(Math.max(e,0),1);function od(e,t,n,r,i){i[0]=ad(e),i[1]=ad(t),i[2]=ad(n)}function sd(e,t,n,r,i){i[0]=ad(e*r),i[1]=ad(t*r),i[2]=ad(n*r)}function cd(e,t,n,r,i){e*=r,t*=r,n*=r,i[0]=ad(e/(e+1)),i[1]=ad(t/(t+1)),i[2]=ad(n/(n+1))}function ld(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 ud(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]=ad(1.60475*a-.53108*o-.07367*s),i[1]=ad(-.10208*a+1.10813*o-.00605*s),i[2]=ad(-.00327*a-.07276*o+1.07602*s)}function dd(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=ad((Math.log2(Math.max(c,1e-10))-d)/f),l=ad((Math.log2(Math.max(l,1e-10))-d)/f),u=ad((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]=ad(1.6605*m-.5876*h-.0728*g),i[1]=ad(-.1246*m+1.1329*h-.0083*g),i[2]=ad(-.0182*m-.1006*h+1.1187*g)}function fd(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 pd=e=>(t,n,r,i,a)=>e(t>0?t:0,n>0?n:0,r>0?r:0,i,a),md=new Map([[r.NoToneMapping,pd(od)],[r.LinearToneMapping,pd(sd)],[r.ReinhardToneMapping,pd(cd)],[r.CineonToneMapping,pd(ld)],[r.ACESFilmicToneMapping,pd(ud)],[r.AgXToneMapping,pd(dd)],[r.NeutralToneMapping,pd(fd)]]),hd=1/2.2;function gd(e){return e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055}function _d(e,t){return t===r.NoToneMapping?1:e}var vd=.2126,yd=.7152,bd=.0722;function xd(e,t){if(t===1)return;let n=e[0]*vd+e[1]*yd+e[2]*bd;e[0]=n+(e[0]-n)*t,e[1]=n+(e[1]-n)*t,e[2]=n+(e[2]-n)*t}var Sd=dt(`oidn`),Cd=null;async function wd(){return Cd||=(await import(`oidn-web`)).initUNetFromURL,Cd}var Td=new Float32Array(3),Ed={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`,debugGbufferMaps:!0,tileSize:1024}},Dd=`
|
|
732
732
|
@group(0) @binding(0) var<storage, read_write> col: array<vec4<f32>>;
|
|
733
733
|
@group(0) @binding(1) var<uniform> scale: f32;
|
|
734
734
|
|
|
@@ -740,4 +740,4 @@ fn main( @builtin(global_invocation_id) gid: vec3<u32>,
|
|
|
740
740
|
let c = col[ i ];
|
|
741
741
|
col[ i ] = vec4<f32>( c.xyz * scale, c.w );
|
|
742
742
|
}
|
|
743
|
-
`,xd=64,Sd=32768,Cd=.18;function wd(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=Cd/2**(n/t);return Number.isFinite(r)&&r>0?r:1}var Td=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={...yd.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=>{hd.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}=yd;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 _d())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),hd.debug(`UNet weights loaded:`,e)}catch(e){hd.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}=go(),{QUALITY_MODELS:t}=yd;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(yd.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(yd.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;hd.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`?hd.debug(`denoise aborted`):hd.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 hd.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let n=this.getGPUTextures();if(!n?.color)return hd.warn(`GPU textures not ready yet`),!1;let r=this.gpuDevice;if(!r)return hd.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=wd(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 ud(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/xd),i=Math.min(r,Sd),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:bd}),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=sd.get(this.getToneMapping())||sd.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&&(vd[0]=a,vd[1]=o,vd[2]=c,md(vd,l),a=vd[0],o=vd[1],c=vd[2]),u(a,o,c,1,vd),t.data[r]=ld(vd[0])*255+.5|0,t.data[r+1]=ld(vd[1])*255+.5|0,t.data[r+2]=ld(vd[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){hd.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=sd.get(this.getToneMapping())||sd.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&&(vd[0]=t,vd[1]=n,vd[2]=r,md(vd,d),t=vd[0],n=vd[1],r=vd[2]),f(t,n,r,1,vd),l.data[e]=ld(vd[0])*255+.5|0,l.data[e+1]=ld(vd[1])*255+.5|0,l.data[e+2]=ld(vd[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`}),hd.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=>{hd.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?.(),hd.debug(`disposed`)}},Ed='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})}};',Dd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Ed],{type:`text/javascript;charset=utf-8`});function Od(e){let t;try{if(t=Dd&&(self.URL||self.webkitURL).createObjectURL(Dd),!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(Ed),{type:`module`,name:e?.name})}}var kd={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 Ad(){let{upscalerModelBaseUrl:e}=go(),t={};for(let n in kd){t[n]={};for(let r in kd[n])t[n][r]=e+kd[n][r]}return t}var jd={get QUALITY_PRESETS(){return Ad()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},Md=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||jd.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=jd.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 Od,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}=go();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:jd.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=sd.get(this.getToneMapping())||sd.get(r.ACESFilmicToneMapping),this._hdrExposure=ud(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=jd.TILE_OVERLAP,c=this.tileSize,l=c-s*2,u=Math.ceil(n/l),d=Math.ceil(i/l),f=u*d,p=0;for(let r=0;r<d;r++)for(let s=0;s<u;s++){if(e.aborted)throw new DOMException(`Aborted`,`AbortError`);let u=Math.min(s*l,Math.max(0,n-c)),d=Math.min(r*l,Math.max(0,i-c)),m=Math.min(c,n-u),h=Math.min(c,i-d),g=this._extractTile(t,u,d,m,h),_=await this._inferTile(g,m,h),v=u*a,y=d*a,b=m*a,x=h*a,S=this._tensorToImageData(_,b,x,v,y);o.putImageData(S,v,y),p++,this.dispatchEvent({type:`progress`,progress:p/f,tile:{x:s,y:r,total:f,completed:p}}),this.dispatchEvent({type:`tileProgress`,tile:{x:v,y,width:b,height:x},imageWidth:n*a,imageHeight:i*a})}}_captureSource(){let e=this.getSourceCanvas?this.getSourceCanvas():null;if(e&&e!==this.output){this.refreshInput?.();let t=document.createElement(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);return n.drawImage(e,0,0),n.getImageData(0,0,t.width,t.height)}return this.output.getContext(`2d`,{willReadFrequently:!0}).getImageData(0,0,this.output.width,this.output.height)}async _captureSourceHDR(){let e=this.getGPUTextures();if(!e?.color)throw Error(`No GPU color texture available for HDR capture`);let t=this.renderer.backend.device,n=e.color,r=n.width,i=n.height,a=Math.ceil(r*16/256)*256,o=a*i;(this._hdrStagingWidth!==r||this._hdrStagingHeight!==i)&&(this._hdrStagingBuffer?.destroy(),this._hdrStagingBuffer=t.createBuffer({label:`aiupscaler-hdr-readback`,size:o,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this._hdrStagingWidth=r,this._hdrStagingHeight=i);let s=this._hdrStagingBuffer,c=t.createCommandEncoder();c.copyTextureToBuffer({texture:n},{buffer:s,bytesPerRow:a,rowsPerImage:i},{width:r,height:i,depthOrArrayLayers:1}),t.queue.submit([c.finish()]),await s.mapAsync(GPUMapMode.READ);let l=new Float32Array(s.getMappedRange()),u=r*4,d=a/4,f=new Float32Array(r*i*4);for(let e=0;e<i;e++){let t=e*d,n=e*u;f.set(l.subarray(t,t+u),n)}return s.unmap(),{data:f,width:r,height:i,isHDR:!0}}_extractTile(e,t,n,r,i){let{data:a,width:o}=e,s=e.isHDR,c=r*i,l=new Float32Array(3*c);for(let e=0;e<i;e++)for(let i=0;i<r;i++){let u=((n+e)*o+(t+i))*4,d=e*r+i;if(s){let e=this._hdrToneMapFn,t=this._hdrExposure,n=this._hdrSaturation,r=a[u]*t,i=a[u+1]*t,o=a[u+2]*t;n!==1&&(this._tmOut[0]=r,this._tmOut[1]=i,this._tmOut[2]=o,md(this._tmOut,n),r=this._tmOut[0],i=this._tmOut[1],o=this._tmOut[2]),e(r,i,o,1,this._tmOut),l[d]=this._tmOut[0]**+cd,l[c+d]=this._tmOut[1]**+cd,l[2*c+d]=this._tmOut[2]**+cd}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=sd.get(this.getToneMapping())||sd.get(r.ACESFilmicToneMapping),l=ud(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,md(d,u),r=d[0],i=d[1],a=d[2]),c(r,i,a,1,d),s[t]=d[0]**+cd*255+.5|0,s[t+1]=d[1]**+cd*255+.5|0,s[t+2]=d[2]**+cd*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(!jd.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`)}},Nd=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 Td(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...V,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=V.enableOIDN,this._denoiserStartHandler=()=>this.dispatchEvent({type:L.DENOISING_START}),this._denoiserEndHandler=()=>this.dispatchEvent({type:L.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 Md(this.denoiserCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.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=V.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:L.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:L.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:L.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.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.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`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.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))}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=!!e.asvgf?.enabled,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.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?.()}_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`].forEach(t=>e.removeTexture(t))}_applyASVGFPreset(e){let t=Le[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))}},Pd=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}},Fd=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,h.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 Id(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 Ld(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 Rd=4096,zd=class{constructor(){this.canvas=Id(!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=Ld(this._sizeSource,Rd);!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(){ke(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}},Bd=dt(`overlay`),Vd=(e,t)=>e.visible&&e.layer===t&&e.render,Hd=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Id(),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 zd().init({device:e,sizeSource:t})}catch(e){Bd.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 Pd;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 Fd(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)&&(Bd.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())Vd(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Vd(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Vd(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?Ld(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())Vd(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)}},Ud=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:L.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:L.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:L.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:L.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}},Wd=new r.Vector3(0,0,-1),Gd=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new g.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(Wd,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:L.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:L.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:L.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}},Kd=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}},qd=new WeakMap,Jd=dt(`engine`);function Yd(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var Xd=class extends r.EventDispatcher{constructor(e,t={}){super();try{qd.get(e)?.dispose()}catch(e){Jd.warn(`prior canvas owner dispose failed`,e)}qd.set(e,this),this.canvas=e,this._autoResize=t.autoResize!==!1,this._container=t.container||null,this.settings=new Iu(V),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._maxTextureSize=V.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 Ud,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 Yl,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}_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){Jd.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,Jd.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:L.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=>Jd.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(),B({timeElapsed:this.completion.timeElapsed,samples:Te(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};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:L.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:L.FRAME})}}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,Jd.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:L.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._abortPostProcess(),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:L.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:L.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])Ae(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){Jd.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&qd.get(this.canvas)===this&&qd.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),ke(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})}async loadEnvironment(e){if(this._loadingInProgress)throw Error(`PathTracerApp.loadEnvironment: another load is already in progress`);this._loadingInProgress=!0;try{await this.assetLoader.loadEnvironment(e);let t=this.meshScene.environment;t&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(t),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.dispatchEvent({type:`EnvironmentLoaded`,url:e})}finally{this._loadingInProgress=!1}}async loadExampleModels(e,t){await this._loadWithSceneRebuild(()=>this.assetLoader.loadExampleModels(e,t),{type:`ModelLoaded`,index:e})}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 Error(`PathTracerApp: another load is already in progress`);this._loadingInProgress=!0;try{await e(),this._emissiveSamplingUserSet=!1,this._clearAppendedModels(),this._syncControlsAfterLoad(),await this.loadSceneData(),this.pipeline?.eventBus.emit(`autoexposure:resetHistory`),this.reset(),this.cameraManager.currentCameraIndex=0,this.dispatchEvent(t),this._dispatchCamerasUpdated()}finally{this._loadingInProgress=!1}}async loadSceneData(){this._preserveSelectionOnRebuild||this.interactionManager?.deselect(),this.animationManager.dispose(),this._animRefitInFlight=!1,this._tagPrimarySceneObject();let e=new eo(``,{namespace:`scene`,level:`info`}),t=this.meshScene.environment,n=null;if(t?.image?.data&&(e.start(`Environment CDF build (worker)`),this.stages.pathTracer.scene.environment=t,n=this.stages.pathTracer.environment.buildEnvironmentCDF().then(()=>e.end(`Environment CDF build (worker)`))),e.start(`BVH build (SceneProcessor)`),this._sdf.setMaxTextureSize(this._maxTextureSize),await this._sdf.buildBVH(this.meshScene),e.end(`BVH build (SceneProcessor)`),z({status:`Transferring data to GPU...`,progress:86}),await new Promise(e=>setTimeout(e,0)),e.start(`GPU data transfer`),!this._sdf.uploadToPathTracer(this.stages.pathTracer,this.lightManager,this.meshScene,t))return!1;this.stages.pathTracer._meshRefs=this.stages.pathTracer._collectMeshRefs(this.meshScene),this.stages.pathTracer.setMeshVisibilityData(this.stages.pathTracer._meshRefs),this._refreshEmissiveForVisibility(),e.end(`GPU data transfer`),z({status:`Compiling shaders...`,progress:90}),await new Promise(e=>setTimeout(e,0)),e.start(`Material setup (TSL compile)`),this.stages.pathTracer.setupMaterial(),e.end(`Material setup (TSL compile)`),this._rasterPrecompile=null,this._pathTracerEnabled||(e.start(`Pipeline precompile`),await this.precompileRaster(),e.end(`Pipeline precompile`)),n&&(z({status:`Finalizing environment map...`,progress:95}),await n,this.stages.pathTracer.environment.applyCDFResults());let r=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,r,{reset:!1}),this.settings.set(`groundCatcherHeight`,r,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return e.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),e.end(`Apply settings`),e.print(this._sceneSummaryParts()),we(),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.assetLoader?.targetModel;e&&(e.userData.__rayzeeSceneObject=!0,e.userData.__rayzeeExternal=e===this.assetLoader._externalModel)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.assetLoader?.targetModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r,{external:!!r.userData.__rayzeeExternal})}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,n.userData.__rayzeeExternal=!1,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,n.userData.__rayzeeExternal=!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){let t=this.meshScene;if(!t)return!1;let n=this.assetLoader?.floorPlane;if(n&&n.uuid===e)return!1;let r=t.children.find(t=>t.uuid===e&&t.userData?.__rayzeeSceneObject);if(!r)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?.(),r===this.assetLoader.targetModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(r,{external:!!r.userData.__rayzeeExternal}),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??[]}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,H);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(Fe,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?Fe:2048,a=Ie(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&&Jd.warn(`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.`),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return H}_isRenderSizeSupported(e,t){return e>H||t>H?(Jd.warn(`render resolution ${e}×${t} exceeds the ${H}px reserve (compute storage textures are pre-allocated at ${H}px). Ignoring resize — raise the reserve with setReservedRenderResolution( ${Math.max(e,t)} ) first, or use a resolution ≤ ${H}.`),!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?Je:Ye;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??V.noiseThreshold,adaptiveStopFraction:r.adaptiveStopFraction??V.adaptiveStopFraction,adaptiveMinSamples:r.adaptiveMinSamples??V.adaptiveMinSamples,usePixelFreeze:r.usePixelFreeze??!1,pixelFreezeThreshold:r.pixelFreezeThreshold??V.pixelFreezeThreshold,pixelFreezeStability:r.pixelFreezeStability??V.pixelFreezeStability},{silent:!0}),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 isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r}={}){let i=this.stages.pathTracer;if(!i)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await i.blueNoiseReady;let a=(t?0:i.frameCount)+e;this.settings.get(`maxSamples`)<a&&this.settings.set(`maxSamples`,a,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let o=e+64,s=0;for(;i.frameCount<a&&s<o;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!i.isReady)throw Error(`renderFrames: path tracer stage is not ready`);this.pipeline.render(),s++,r?.(i.frameCount),n>0&&s%n===0&&await new Promise(e=>setTimeout(e,0))}if(i.frameCount<a)throw Error(`renderFrames: stalled at ${i.frameCount}/${a} samples after ${s} passes — something retired the render (maxSamples, a stray reset, or a canvas resize)`);return i.frameCount}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=>Jd.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(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);let n=e.limits;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();let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},Yd(a,this._deviceLostHolder),a.onuncapturederror=e=>Jd.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=r.ACESFilmicToneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1)}_initCameraManager(){this.cameraManager=new Lu(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new O}_initAssetPipeline(){this._sdf=new ao,this.assetLoader=new Nu(this.meshScene,this.cameraManager.camera,this.cameraManager.controls),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 ql(this.renderer,e||1,t||1),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.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 Xl({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 Ru(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new zu(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new Xu(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Gd({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new Kd(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,L.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[L.DENOISING_START,L.DENOISING_END,L.UPSCALING_START,L.UPSCALING_PROGRESS,L.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[L.ANIMATION_STARTED,L.ANIMATION_PAUSED,L.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,L.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,L.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){if(e.model)this._clearAppendedModels(),await this.loadSceneData();else if(e.texture){let e=this.meshScene.environment;e&&this.stages.pathTracer&&await this.stages.pathTracer.environment.setEnvironmentMap(e),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.assetLoader?.targetModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:L.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new ul(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new dl(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new fl(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new hl(this.renderer,{enabled:!1}),this.stages.variance=new vl(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new bl(this.renderer,{enabled:!1}),this.stages.edgeFilter=new El(this.renderer,{enabled:!1}),this.stages.autoExposure=new Nl(this.renderer,{enabled:V.autoExposure??!1}),this.stages.compositor=new Pl(this.renderer,{saturation:this.settings.get(`saturation`)??V.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Nd({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,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:L.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:L.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Hd(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))}},Zd=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=Je.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:L.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:L.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&&(B({samples:Te(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(L.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(L.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=He,e.ASVGF_QUALITY_PRESETS=Le,e.AUTO_FOCUS_MODES=Ve,e.AnimationManager=Ud,e.BVH_LEAF_MARKERS=We,e.CAMERA_PRESETS=Be,e.CAMERA_RANGES=Re,e.CameraManager=Lu,e.DEFAULT_TEXTURE_MATRIX=qe,e.DenoisingManager=Nd,e.ENGINE_DEFAULTS=V,e.EngineEvents=L,e.GoboManager=zu,e.IESManager=Xu,e.INTERACTIVE_RENDER_CONFIG=Ye,e.InteractionManager=Xl,e.LOG_LEVELS=Ze,e.LightManager=Ru,e.Logger=ut,e.MAX_RESERVABLE_RENDER_SIZE=Fe,e.MEMORY_CONSTANTS=Xe,e.OverlayManager=Hd,e.PRODUCTION_RENDER_CONFIG=Je,e.PathTracerApp=Xd,e.PipelineContext=Fl,e.RenderPipeline=ql,e.RenderSettings=Iu,e.RenderStage=be,e.SKY_PRESETS=ze,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=G,e.TRIANGLE_DATA_LAYOUT=U,e.TransformManager=Gd,e.VRAMTracker=_s,e.VideoRenderManager=Zd,e.bufferBytes=hs,e.clearBindingAuditFindings=Hl,e.configureAssets=ho,e.createLogger=dt,e.fmt=J,e.getAssetConfig=go,e.getBindingAuditFindings=Vl,e.setBindingAudit=Bl,e.textureBytes=gs});
|
|
743
|
+
`,Od=64,kd=32768,Ad=.18;function jd(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=Ad/2**(n/t);return Number.isFinite(r)&&r>0?r:1}var Md=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={...Ed.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=>{Sd.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}=Ed;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 wd())(e,n,{aux:!0,hdr:!0,maxTileSize:t,dynamicTile:!1}),this.currentTZAUrl=e,this._activeTileSize=t,this.dispatchEvent({type:`loaded`}),Sd.debug(`UNet weights loaded:`,e)}catch(e){Sd.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}=go(),{QUALITY_MODELS:t}=Ed;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(Ed.QUALITY_MODELS,e))throw Error(`Invalid quality setting: ${e}. Must be one of: ${Object.keys(Ed.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;Sd.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`?Sd.debug(`denoise aborted`):Sd.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 Sd.warn(`GPU mode enabled but getGPUTextures not provided`),!1;let n=this.getGPUTextures();if(!n?.color)return Sd.warn(`GPU textures not ready yet`),!1;let r=this.gpuDevice;if(!r)return Sd.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=jd(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 _d(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/Od),i=Math.min(r,kd),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:Dd}),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=md.get(this.getToneMapping())||md.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&&(Td[0]=a,Td[1]=o,Td[2]=c,xd(Td,l),a=Td[0],o=Td[1],c=Td[2]),u(a,o,c,1,Td),t.data[r]=gd(Td[0])*255+.5|0,t.data[r+1]=gd(Td[1])*255+.5|0,t.data[r+2]=gd(Td[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){Sd.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=md.get(this.getToneMapping())||md.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&&(Td[0]=t,Td[1]=n,Td[2]=r,xd(Td,d),t=Td[0],n=Td[1],r=Td[2]),f(t,n,r,1,Td),l.data[e]=gd(Td[0])*255+.5|0,l.data[e+1]=gd(Td[1])*255+.5|0,l.data[e+2]=gd(Td[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`}),Sd.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=>{Sd.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?.(),Sd.debug(`disposed`)}},Nd='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})}};',Pd=typeof self<`u`&&self.Blob&&new Blob([`URL.revokeObjectURL(import.meta.url);`,Nd],{type:`text/javascript;charset=utf-8`});function Fd(e){let t;try{if(t=Pd&&(self.URL||self.webkitURL).createObjectURL(Pd),!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(Nd),{type:`module`,name:e?.name})}}var Id={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 Ld(){let{upscalerModelBaseUrl:e}=go(),t={};for(let n in Id){t[n]={};for(let r in Id[n])t[n][r]=e+Id[n][r]}return t}var Rd={get QUALITY_PRESETS(){return Ld()},TILE_SIZE:512,TILE_OVERLAP:16,SESSION_OPTIONS:{executionProviders:[{name:`webgpu`,preferredLayout:`NCHW`}],graphOptimizationLevel:`all`}},zd=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||Rd.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=Rd.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 Fd,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}=go();this._worker.addEventListener(`message`,r),this._worker.postMessage({type:`load`,url:t,sessionOptions:Rd.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=md.get(this.getToneMapping())||md.get(r.ACESFilmicToneMapping),this._hdrExposure=_d(this.getExposure(),this.getToneMapping()),this._hdrSaturation=this.getSaturation(),this._tmOut=new Float32Array(3));let s=Rd.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,xd(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]**+hd,l[c+d]=this._tmOut[1]**+hd,l[2*c+d]=this._tmOut[2]**+hd}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=md.get(this.getToneMapping())||md.get(r.ACESFilmicToneMapping),l=_d(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,xd(d,u),r=d[0],i=d[1],a=d[2]),c(r,i,a,1,d),s[t]=d[0]**+hd*255+.5|0,s[t+1]=d[1]**+hd*255+.5|0,s[t+2]=d[2]**+hd*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(!Rd.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`)}},Bd=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 Md(this.denoiserCanvas,this.renderer,this.scene,this.camera,{...V,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=V.enableOIDN,this._denoiserStartHandler=()=>this.dispatchEvent({type:L.DENOISING_START}),this._denoiserEndHandler=()=>this.dispatchEvent({type:L.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 zd(this.denoiserCanvas,this.renderer,{scaleFactor:V.upscalerScale||2,quality:V.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=V.enableUpscaler||!1,this._upscalerResChangedHandler=e=>this.dispatchEvent({type:`resolution_changed`,width:e.width,height:e.height}),this._upscalerStartHandler=()=>this.dispatchEvent({type:L.UPSCALING_START}),this._upscalerProgressHandler=e=>this.dispatchEvent({type:L.UPSCALING_PROGRESS,progress:e.progress}),this._upscalerEndHandler=()=>this.dispatchEvent({type:L.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.edgeFilter?.enabled?`edgeaware`:`none`}setDenoiserStrategy(e,t){let n=this._stages;switch(n.asvgf&&(n.asvgf.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`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.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))}_syncGBufferStages(){let e=this._stages,t=e.normalDepth,n=e.motionVector,r=!!e.asvgf?.enabled,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.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?.()}_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`].forEach(t=>e.removeTexture(t))}_applyASVGFPreset(e){let t=Le[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))}},Vd=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}},Hd=class{constructor(e,i){this.layer=`scene`,this._enabled=!0,this._outlineNode=(0,h.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 Ud(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 Wd(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 Gd=4096,Kd=class{constructor(){this.canvas=Ud(!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=Wd(this._sizeSource,Gd);!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(){ke(this.renderer),this.renderer=null,this.canvas.parentElement?.removeChild(this.canvas)}},qd=dt(`overlay`),Jd=(e,t)=>e.visible&&e.layer===t&&e.render,Yd=class{constructor(e){this.camera=e,this._helpers=new Map,this._hudCanvas=Ud(),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 Kd().init({device:e,sizeSource:t})}catch(e){qd.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 Vd;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 Hd(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)&&(qd.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())Jd(t,`scene`)&&t.render(e,this.camera)}_hasVisibleSceneOverlay(){if(this._helperScene?.isDrawing)return!0;for(let e of this._helpers.values())if(Jd(e,`scene`))return!0;return!1}refreshHUD(){let e=this._hudCanvas,t=this._hudCtx,n=!1;for(let e of this._helpers.values())if(Jd(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?Wd(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())Jd(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)}},Xd=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:L.ANIMATION_STARTED})}}pause(){this.mixer&&(this.mixer.timeScale=0,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:L.ANIMATION_PAUSED}))}resume(){this.mixer&&(this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!0,this.wakeCallback?.(),this.dispatchEvent({type:L.ANIMATION_STARTED}))}stop(){this.mixer&&(this.mixer.stopAllAction(),this.mixer.timeScale=this._savedTimeScale||1,this.timer.reset(),this.isPlaying=!1,this.dispatchEvent({type:L.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}},Zd=new r.Vector3(0,0,-1),Qd=class{constructor({camera:e,canvas:t,orbitControls:n,app:i}){this._app=i,this._orbitControls=n,this._camera=e,this._controls=new g.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(Zd,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:L.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:L.OBJECT_TRANSFORM_START}):(this._attached?.isLight?this._finalizeLightTransform():this._recomputeAndRefit(),this._app.dispatchEvent({type:L.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}},$d=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}},ef=new WeakMap,tf=dt(`engine`);function nf(e,t){e.lost.then(e=>{t.app&&t.app._handleDeviceLost(e)})}var rf=class extends r.EventDispatcher{constructor(e,t={}){super();try{ef.get(e)?.dispose()}catch(e){tf.warn(`prior canvas owner dispose failed`,e)}ef.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.settings=new Uu(V),this.renderer=null,this.scene=null,this.meshScene=null,this._sceneHelpers=null,this.assetLoader=null,this._sdf=null,this._animRefitInFlight=!1,this._maxTextureSize=V.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 Xd,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 Yl,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}_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){tf.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,tf.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:L.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=>tf.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(),B({timeElapsed:this.completion.timeElapsed,samples:Te(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};this.dispatchEvent({type:`RenderComplete`,...e}),this.dispatchEvent({type:L.RENDER_COMPLETE,...e})}}this._renderHelperOverlay(),this.dispatchEvent({type:L.FRAME})}}}stopAnimation(){this.animationManagerId&&=(cancelAnimationFrame(this.animationManagerId),null)}_handleDeviceLost(e){this._deviceLost||(this._deviceLost=!0,tf.error(`WebGPU device lost (${e?.reason||`unknown`}): ${e?.message||``}`),this.stopAnimation(),this.dispatchEvent({type:L.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._abortPostProcess(),this.completion.reset(),this.wake(),this.dispatchEvent({type:`RenderReset`}),this.dispatchEvent({type:L.RENDER_RESET})}dispose(){if(!this._disposed){if(this._disposed=!0,this.dispatchEvent({type:L.DISPOSE}),this.stopAnimation(),clearTimeout(this._resizeDebounceTimer),this._resizeDebounceTimer=null,this._removeTrackedListeners(),Ce(null),this.interactionManager?.deselect?.(),this.transformManager?.detach?.(),this.animationManager?.dispose(),this.transformManager?.dispose(),this.overlayManager?.dispose(),this.lightManager?.dispose(),this.goboManager?.dispose(),this.iesManager?.dispose(),this.denoisingManager?.dispose(),this.interactionManager?.dispose(),this.cameraManager?.dispose(),this.pipeline?.dispose(),this._sdf?.dispose(),this._sdf=null,this.assetLoader?.dispose(),this.assetLoader=null,this.meshScene){this.meshScene.environment?.dispose(),this.meshScene.environment=null;for(let e of[...this.meshScene.children])Ae(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){tf.warn(`failed to clear TSL texture singleton listeners`,e)}this.canvas&&ef.get(this.canvas)===this&&ef.delete(this.canvas),this._gpuDevice&&=(this._gpuDevice.onuncapturederror=null,null),this._deviceLostHolder&&=(this._deviceLostHolder.app=null,null),ke(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=>(tf.warn(`scene metadata: environment "${e.sourceFile}" failed to load`,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}),this.scene&&(this.scene.background=e),this.dispatchEvent({type:`SceneMetadataApplied`,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 eo(``,{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=>tf.warn(`scene metadata: environment install failed`,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)`),z({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`),z({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&&(z({status:`Finalizing environment map...`,progress:95}),await r,this.stages.pathTracer.environment.applyCDFResults());let i=this.getSceneMinY();if(this.settings.set(`groundProjectionLevel`,i,{reset:!1}),this.settings.set(`groundCatcherHeight`,i,{reset:!1}),!this._emissiveSamplingUserSet){let e=(this._sdf?.emissiveTriangleBuilder?.emissiveTriangles?.length??this._sdf?.emissiveTriangleCount??0)>0;this.settings.set(`enableEmissiveTriangleSampling`,e,{reset:!1})}return t.start(`Apply settings`),this.settings.applyAll(),this.stages.compositor.setTransparentBackground(this.settings.get(`transparentBackground`)),t.end(`Apply settings`),t.print(this._sceneSummaryParts()),we(),this._initAnimationAndTransforms(),this.dispatchEvent({type:`SceneRebuild`}),!0}_sceneSummaryParts(){let e=this.stages.pathTracer,t=this._sdf?.instanceTable?.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.assetLoader?.targetModel;e&&(e.userData.__rayzeeSceneObject=!0,e.userData.__rayzeeExternal=e===this.assetLoader._externalModel)}_clearAppendedModels(){let e=this.meshScene;if(!e)return;let t=this.assetLoader?.floorPlane,n=this.assetLoader?.targetModel;for(let r of[...e.children])r===t||r===n||r.userData?.__rayzeeSceneObject&&this.assetLoader.removeModelRoot(r,{external:!!r.userData.__rayzeeExternal})}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,n.userData.__rayzeeExternal=!1,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,n.userData.__rayzeeExternal=!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){let t=this.meshScene;if(!t)return!1;let n=this.assetLoader?.floorPlane;if(n&&n.uuid===e)return!1;let r=t.children.find(t=>t.uuid===e&&t.userData?.__rayzeeSceneObject);if(!r)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?.(),r===this.assetLoader.targetModel?this.assetLoader.releaseTargetModel():this.assetLoader.removeModelRoot(r,{external:!!r.userData.__rayzeeExternal}),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??[]}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,H);if(!this.renderer)return this._pendingReservedRenderSize={requestedPx:e,allowLower:t},Math.max(256,Math.min(Fe,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?Fe:2048,a=Ie(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&&tf.warn(`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.`),this.dispatchEvent({type:`reserved_render_size_changed`,size:t})}getReservedRenderResolution(){return H}_isRenderSizeSupported(e,t){return e>H||t>H?(tf.warn(`render resolution ${e}×${t} exceeds the ${H}px reserve (compute storage textures are pre-allocated at ${H}px). Ignoring resize — raise the reserve with setReservedRenderResolution( ${Math.max(e,t)} ) first, or use a resolution ≤ ${H}.`),!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?Je:Ye;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??V.noiseThreshold,adaptiveStopFraction:r.adaptiveStopFraction??V.adaptiveStopFraction,adaptiveMinSamples:r.adaptiveMinSamples??V.adaptiveMinSamples,usePixelFreeze:r.usePixelFreeze??!1,pixelFreezeThreshold:r.pixelFreezeThreshold??V.pixelFreezeThreshold,pixelFreezeStability:r.pixelFreezeStability??V.pixelFreezeStability},{silent:!0}),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 isDeterministic(){return this._deterministic&&this._dispatchPinned}async renderFrames(e,{reset:t=!0,yieldEvery:n=8,onProgress:r}={}){let i=this.stages.pathTracer;if(!i)throw Error(`renderFrames: app is not initialized`);if(!(e>0))throw Error(`renderFrames: count must be positive, got ${e}`);await i.blueNoiseReady;let a=(t?0:i.frameCount)+e;this.settings.get(`maxSamples`)<a&&this.settings.set(`maxSamples`,a,{silent:!0,reset:!1}),t&&this.reset(),this.stopAnimation();let o=e+64,s=0;for(;i.frameCount<a&&s<o;){if(this._deviceLost)throw Error(`renderFrames: WebGPU device lost`);if(!i.isReady)throw Error(`renderFrames: path tracer stage is not ready`);this.pipeline.render(),s++,r?.(i.frameCount),n>0&&s%n===0&&await new Promise(e=>setTimeout(e,0))}if(i.frameCount<a)throw Error(`renderFrames: stalled at ${i.frameCount}/${a} samples after ${s} passes — something retired the render (maxSamples, a stray reset, or a canvas resize)`);return i.frameCount}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=>tf.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(Ce(e=>this.dispatchEvent(e)),!navigator.gpu)throw Error(`WebGPU is not supported in this browser`);let e=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(!e)throw Error(`Failed to get WebGPU adapter`);let n=e.limits;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();let a=this.renderer.backend?.device;a?.lost&&(this._gpuDevice=a,this._deviceLostHolder={app:this},nf(a,this._deviceLostHolder),a.onuncapturederror=e=>tf.error(`WebGPU uncaptured error:`,e.error)),t.RectAreaLightNode.setLTC(i.RectAreaLightTexturesLib.init()),this.renderer.outputColorSpace=t.SRGBColorSpace,this.renderer.toneMapping=r.ACESFilmicToneMapping,this.renderer.toneMappingExposure=1,this.renderer.setPixelRatio(1)}_initCameraManager(){this.cameraManager=new Wu(this.canvas)}_initScenes(){this.scene=new r.Scene,this.meshScene=new r.Scene,this._sceneHelpers=new O}_initAssetPipeline(){this._sdf=new ao,this.assetLoader=new Bu(this.meshScene,this.cameraManager.camera,this.cameraManager.controls),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 ql(this.renderer,e||1,t||1),this.pipeline.addStage(this.stages.pathTracer),this.pipeline.addStage(this.stages.normalDepth),this.pipeline.addStage(this.stages.motionVector),this.pipeline.addStage(this.stages.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 Xl({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 Gu(this.scene,this._sceneHelpers,this.stages.pathTracer,{onReset:()=>this.reset()}),this.goboManager=new Ku(this.stages.pathTracer,{onReset:()=>this.reset()}),this.iesManager=new rd(this.stages.pathTracer,{onReset:()=>this.reset()}),this._setupDenoisingManager(),await this._setupOverlayManager(),this.transformManager=new Qd({camera:this.cameraManager.camera,canvas:this.canvas,orbitControls:this.cameraManager.controls,app:this}),this.overlayManager.register(`transform`,new $d(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,L.AUTO_FOCUS_UPDATED,e=>this.dispatchEvent(e)),this._forwardEvents(this.denoisingManager,[L.DENOISING_START,L.DENOISING_END,L.UPSCALING_START,L.UPSCALING_PROGRESS,L.UPSCALING_END,`resolution_changed`]),this._setupAutoExposureListener(),this.animationManager.wakeCallback=()=>this.wake(),this._forwardEvents(this.animationManager,[L.ANIMATION_STARTED,L.ANIMATION_PAUSED,L.ANIMATION_STOPPED]),this._addTrackedListener(this.animationManager,L.ANIMATION_PAUSED,()=>{this._animRefitInFlight=!1}),this._addTrackedListener(this.animationManager,L.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),we()}this.pauseRendering=!1,this.reset()}},this._addTrackedListener(this.assetLoader,`load`,this._onAssetLoaded),this._addTrackedListener(this.assetLoader,`modelProcessed`,e=>{let t=[this.cameraManager.camera,...e.cameras||[]];this.cameraManager.setCameras(t),this.interactionManager&&(this.interactionManager.floorPlane=this.assetLoader.floorPlane)})}_initAnimationAndTransforms(){let e=this.assetLoader?.animations||[];if(e.length>0){let t=this.assetLoader?.targetModel||this.meshScene;this.animationManager.init(this.meshScene,t,this._sdf.meshes,e),this.animationManager.onFinished=()=>{this._animRefitInFlight=!1,this.dispatchEvent({type:L.ANIMATION_FINISHED})}}this.transformManager?.setMeshData(this._sdf.meshes)}_createStages(){this.stages.pathTracer=new ul(this.renderer,this.scene,this.cameraManager.camera),this.stages.normalDepth=new dl(this.renderer,{pathTracer:this.stages.pathTracer}),this.stages.motionVector=new fl(this.renderer,this.cameraManager.camera,{pathTracer:this.stages.pathTracer}),this.stages.asvgf=new hl(this.renderer,{enabled:!1}),this.stages.variance=new vl(this.renderer,{enabled:!1}),this.stages.bilateralFilter=new bl(this.renderer,{enabled:!1}),this.stages.edgeFilter=new El(this.renderer,{enabled:!1}),this.stages.autoExposure=new Nl(this.renderer,{enabled:V.autoExposure??!1}),this.stages.compositor=new Pl(this.renderer,{saturation:this.settings.get(`saturation`)??V.saturation,pathTracer:this.stages.pathTracer})}_setupDenoisingManager(){this.denoisingManager=new Bd({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,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:L.RENDER_RESET}),this.wake())}_setupAutoExposureListener(){this.stages.autoExposure&&this.stages.autoExposure.on(`autoexposure:updated`,e=>{this.dispatchEvent({type:L.AUTO_EXPOSURE_UPDATED,exposure:e.exposure,luminance:e.luminance})})}_renderHelperOverlay(){this.scene.updateMatrixWorld(),this.overlayManager?.render()}async _setupOverlayManager(){this.overlayManager=new Yd(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))}},af=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=Je.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:L.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:L.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&&(B({samples:Te(t)}),await new Promise(e=>setTimeout(e,0)))}_waitForDenoise(e){return new Promise(t=>{let n,r=()=>{e.removeEventListener(L.DENOISING_END,i),clearTimeout(n)},i=()=>{r(),t()};n=setTimeout(()=>{console.warn(`VideoRenderManager: Denoise timed out, skipping`),r(),t()},3e4),e.addEventListener(L.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=He,e.ASVGF_QUALITY_PRESETS=Le,e.AUTO_FOCUS_MODES=Ve,e.AnimationManager=Xd,e.BVH_LEAF_MARKERS=We,e.CAMERA_PRESETS=Be,e.CAMERA_RANGES=Re,e.CameraManager=Wu,e.DEFAULT_TEXTURE_MATRIX=qe,e.DenoisingManager=Bd,e.ENGINE_DEFAULTS=V,e.EngineEvents=L,e.GoboManager=Ku,e.IESManager=rd,e.INTERACTIVE_RENDER_CONFIG=Ye,e.InteractionManager=Xl,e.LOG_LEVELS=Ze,e.LightManager=Gu,e.Logger=ut,e.MAX_RESERVABLE_RENDER_SIZE=Fe,e.MEMORY_CONSTANTS=Xe,e.OverlayManager=Yd,e.PRODUCTION_RENDER_CONFIG=Je,e.PathTracerApp=rf,e.PipelineContext=Fl,e.RenderPipeline=ql,e.RenderSettings=Uu,e.RenderStage=be,e.SKY_PRESETS=ze,e.StageExecutionMode=ye,e.TEXTURE_CONSTANTS=G,e.TRIANGLE_DATA_LAYOUT=U,e.TransformManager=Qd,e.VRAMTracker=_s,e.VideoRenderManager=af,e.bufferBytes=hs,e.clearBindingAuditFindings=Hl,e.configureAssets=ho,e.createLogger=dt,e.extractSceneMetadata=Iu,e.fmt=J,e.getAssetConfig=go,e.getBindingAuditFindings=Vl,e.parseSceneMetadata=Fu,e.setBindingAudit=Bl,e.textureBytes=gs});
|