@hology/core 0.0.274 → 0.0.275
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/rendering/node-material-webgpu-resolver.d.ts +4 -1
- package/dist/rendering/node-material-webgpu-resolver.js +1 -1
- package/dist/rendering/sdfgi-settings.d.ts +8 -0
- package/dist/rendering/sdfgi-settings.js +4 -0
- package/dist/rendering/sdfgi-surface-material.d.ts +8 -0
- package/dist/rendering/sdfgi-surface-material.js +4 -0
- package/dist/rendering/webgpu-experimental-backend.d.ts +10 -2
- package/dist/rendering/webgpu-experimental-backend.js +1 -1
- package/dist/rendering.d.ts +14 -2
- package/dist/rendering.js +1 -1
- package/dist/scene/materializer.d.ts +2 -0
- package/dist/scene/materializer.js +1 -1
- package/dist/scene/model.d.ts +2 -0
- package/dist/scene/scene-data-service.js +1 -1
- package/dist/shader-nodes/surface-reflection.d.ts +1 -0
- package/dist/shader-nodes/surface-reflection.js +1 -1
- package/dist/test/node-material-webgpu-resolver.test.js +1 -1
- package/dist/test/sdfgi-settings.test.d.ts +2 -0
- package/dist/test/sdfgi-settings.test.js +4 -0
- package/dist/test/shader-graph.test.js +1 -1
- package/dist/test/surface-reflection.test.js +1 -1
- package/package.json +2 -2
- package/tsconfig.tsbuildinfo +1 -1
package/dist/rendering.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e;import{__decorate as t,__metadata as s}from"tslib";import{skyPosition as i}from"./scene/sky.js";import*as a from"three";import{observeElementIntersection as n}from"./rendering/intersection-observer.js";import{Color as r,Material as o,Matrix4 as l,Mesh as h,PerspectiveCamera as c,ShaderChunk as p,ShaderMaterial as d,WebGLRenderTarget as u,Texture as m,Euler as g,MeshStandardMaterial as f}from"three";import{CopyShader as b,EffectComposer as w,FXAAShader as M,GammaCorrectionShader as v,LUTPass as x,RenderPass as P,ShaderPass as y}from"three-stdlib";import{CSMShader as S,CSMUtil as T}from"./csm.js";import{colorToNormal as G,float as R,NodeShaderMaterial as E,standardMaterial as C,uniformFloat as B,uniformVec3 as O,toonMaterial as W,lambertMaterial as U,normalize as D,rgb as A,rgba as k,transformed as I,varying as F,varyingAttributes as j,varyingTransformed as V,vec4 as L,BooleanExpression as _,select as z,ifDefApply as q,uniformSampler2d as H,RgbaNode as N,mix as $,attributes as Q,uniformVec2 as J,min as X}from"three-shader-graph";import{Reflector as Y}from"three-stdlib";import{BokehPass as K,OutputPass as Z}from"three/examples/jsm/Addons.js";import{CSM as ee}from"three/examples/jsm/csm/CSM.js";import te from"three/examples/jsm/libs/stats.module.js";import{FrameStats as se}from"./utils/three/frame-stats.js";import{GTAOPass as ie}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as ae}from"typedi";import{depthUniformName as ne,farUniformName as re,nearUniformName as oe,resolutionUniformName as le,sceneNormalUniformName as he,screenUV as ce,supportsDepthTextureExtension as pe}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as de}from"./shader-nodes/time.js";import{aoMapUniformName as ue,sceneMapUniformName as me,transmissionMapUniformName as ge}from"./shader-nodes/scene-sample.js";import{waterVolumeCameraPositionUniformName as fe,waterVolumeEnabledUniformName as be,waterVolumeInverseViewProjectionUniformName as we,waterVolumeWorldToLocalUniformName as Me}from"./shader-nodes/water-volume.js";import{DepthPass as ve}from"./utils/three/depth-pass.js";import{GPUStatsPanel as xe}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as Pe}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ye,traverseVisibleStop as Se}from"./utils/three/traverse.js";import{clamp as Te}from"./utils/math.js";import{ColorPass as Ge}from"./rendering/color-pass.js";import{PostProcessEffectPass as Re,PostProcessEffectRegistration as Ee,postProcessEffectStages as Ce,sanitizePostProcessEffectPriority as Be,sanitizePostProcessEffectStage as Oe}from"./rendering/post-process-effect.js";import{SSRPass as We}from"./rendering/ssr/SSRPass.js";import{SSRShader as Ue}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as De}from"./rendering/fog/volumetric-fog-pass.js";import{UnrealBloomPass as Ae}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as ke}from"./shader-nodes/depth.js";import{packDepthToRGBA as Ie}from"three-shader-graph";import{FogVolumeObject as Fe}from"./rendering/fog/fog-volume-object.js";import{ParallaxStandardMaterial as je}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Ve}from"./shader-nodes/pom.js";import{FullScreenQuad as Le}from"three-stdlib";import{edgeDepthEffect as _e}from"./shader-nodes/effects.js";import{decalDiscard as ze}from"./shader-nodes/decal.js";import{Pass as qe}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as He}from"./scene/batched-mesh-2.js";import{resolvePostProcessMaterial as Ne}from"./shader/post-process-shader.js";import{applyUvTiling as $e}from"./shader/uv-nodes.js";import{createPlaceholderTexture as Qe}from"./utils/three/placeholder-texture.js";import{getTemporalUpscalingJitter as Je,getUpscalingMethod as Xe,UpscaleOutputPass as Ye}from"./rendering/upscaling-pass.js";import{ExperimentalWebGpuBackend as Ke,formatWebGpuSceneCapabilitySummary as Ze}from"./rendering/webgpu-experimental-backend.js";import{WebGlBackend as et}from"./rendering/webgl-backend.js";import{defaultGraphicsRuntime as tt}from"./rendering/graphics-runtime.js";export{GraphicsRuntime}from"./rendering/graphics-runtime.js";function st(e){return{enabled:e?.enabled??!0,mapSize:Math.max(1,Math.floor(e?.mapSize??2048)),cascadeCount:Math.max(1,Math.min(4,Math.floor(e?.cascadeCount??4))),maxDistance:Math.max(1,e?.maxDistance??80)}}const it=new a.Vector3,at=new a.Matrix4,nt=(new a.Matrix4).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);T.patchSetupMaterial();const rt=document.createElement("div");rt.style.position="absolute",rt.style.left="50%",rt.style.top="50%",rt.style.color="black",rt.style.zIndex="999";(new a.Layers).set(9);new a.MeshBasicMaterial({color:"black"});const ot=new a.MeshDepthMaterial;var lt;ot.depthPacking=a.RGBADepthPacking,ot.blending=a.NoBlending,ot.side=a.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(lt||(lt={}));const ht=(()=>{const e=new Uint8Array([255,255,255,255]),t=new a.DataTexture(e,1,1,a.RGBAFormat);return t.needsUpdate=!0,t})(),ct=(()=>{const e=new Uint8Array([0,0,0,255]),t=new a.DataTexture(e,1,1,a.RGBAFormat);return t.needsUpdate=!0,t})(),pt=(()=>{const e=new Uint8Array([128,128,255,255]),t=new a.DataTexture(e,1,1,a.RGBAFormat);return t.needsUpdate=!0,t})(),dt=new E({color:R(0),position:L(R(0))});dt.visible=!1;const ut=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let mt=0;let gt=e=class{registerStaticSpatialObject(e){if("webgpu"!==this.requestedBackend)return()=>{};this.staticSpatialObjects.get(e)?.handle?.dispose();const t={handle:null,editing:!1};return this.staticSpatialObjects.set(e,t),null!=this.experimentalWebGpuBackend&&(t.handle=this.experimentalWebGpuBackend.registerStaticSpatialObject(e)),()=>{t.handle?.dispose(),this.staticSpatialObjects.get(e)===t&&this.staticSpatialObjects.delete(e)}}refreshStaticSpatialObjects(e,t){for(const[s,i]of this.staticSpatialObjects){let a=s;for(;a&&a!==e;)a=a.parent;a===e&&(void 0!==t?(i.editing=t,i.handle?.setEditing(t)):i.handle?.update())}}get activeBackend(){return this.backendHandle?.kind??null}get canvas(){return this.backendHandle?.canvas??null}get initialized(){return null!=this.backendHandle}get requestedBackend(){return"webgpu"===(e=this.options.backend)||"webgpu-experimental"===e?"webgpu":"webgl";var e}get vfxBackendPreference(){return this.options.webgpuVfx??"cpu"}get webgpuVfxInstancesPerTemplate(){return Math.max(1,Math.floor(this.options.webgpuVfxInstancesPerTemplate??128))}get webgpuVfxTemplateMemoryBudgetBytes(){return 1024*Math.max(1,this.options.webgpuVfxTemplateMemoryBudgetMiB??512)*1024}get webgpuVfxWorldMemoryBudgetBytes(){return 1024*Math.max(1,this.options.webgpuVfxWorldMemoryBudgetMiB??1024)*1024}get webgpuVfxColdTemplateSeconds(){return Math.max(0,this.options.webgpuVfxColdTemplateSeconds??30)}get webGpuDevice(){return this.experimentalWebGpuBackend?.getDevice()??null}get experimentalWebGpuDevice(){return this.webGpuDevice}registerExperimentalStaticDrawSet(e,t,s=!1,i="skip"){if("webgpu"!==this.requestedBackend)return()=>{};const a={root:e,label:t,allowUnsortedLateDraws:s,onUnsupported:i,sourceWasVisible:e.visible,staticDrawSet:null};return this.experimentalStaticDrawSetRegistrations.add(a),this.activateExperimentalStaticDrawSets(),()=>{this.experimentalStaticDrawSetRegistrations.delete(a)&&(a.staticDrawSet?.dispose(),null!=a.staticDrawSet&&(a.root.visible=a.sourceWasVisible),a.staticDrawSet=null)}}registerExperimentalWebGpuRenderGraphExtension(e){return"webgpu"!==this.requestedBackend?()=>{}:(this.experimentalWebGpuRenderGraphExtensions.add(e),()=>{this.experimentalWebGpuRenderGraphExtensions.delete(e)})}get webGlRenderer(){return"webgl"===this.activeBackend?this.renderer:null}registerWebGpuRenderGraphExtension(e){return this.registerExperimentalWebGpuRenderGraphExtension(e)}get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}createAoblendQuad(){const e=L(1),t=Qe(),s=H("tAlphaTest",t).sample(ce).a,i=H("tAO",t).sample(ce),n=z(s.lt(.05),i,X(L(1,1,1,1),i.addScalar(.4))),r=new E({outputs:[n,e,e],transparent:!0});r.depthWrite=!1,r.depthTest=!1,r.blending=a.MultiplyBlending;return new Le(r)}setPaused(e){this.paused=e}setResolutionScale(e){const t=Et(e,1);Rt(t,this.resolutionScale)||(this.resolutionScale=t,this.dynamicResolutionScale=t,this.dynamicResolutionLastAdjustmentAt=0,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}get currentResolutionScale(){return this.getEffectiveResolutionScale()}get currentRenderPixelRatio(){return this.getRenderPixelRatio()}get currentPresentationPixelRatio(){return this.getPresentationPixelRatio()}getRenderSize(e=new a.Vector2){return e.set(Math.max(1,this.container.clientWidth*this.getRenderPixelRatio()),Math.max(1,this.container.clientHeight*this.getRenderPixelRatio()))}getClientSize(e=new a.Vector2){return e.set(Math.max(1,this.previousClientWith??1),Math.max(1,this.previousClientHeight??1))}isUpscalingEnabled(){return!0===this.options.upscaling?.enabled&&!0!==this.options.enableXR}isTemporalUpscalingEnabled(){if(!this.isUpscalingEnabled())return!1;const e=Xe(this.options.upscaling);return"temporal"===e||"dlss"===e}resetUpscalingHistory(){this.hasPreviousTemporalViewProjection=!1,this.upscaleOutputPass?.resetHistory(),this.experimentalWebGpuBackend?.resetTemporalHistory()}prepareUpscalingFrame(){if(!this.isTemporalUpscalingEnabled()||null==this.upscaleOutputPass)return void this.upscaleOutputPass?.setFrameState(null);this.unjitteredProjectionMatrix.copy(this.camera.projectionMatrix),this.currentUnjitteredViewProjectionMatrix.multiplyMatrices(this.unjitteredProjectionMatrix,this.camera.matrixWorldInverse),this.hasPreviousTemporalViewProjection||(this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.upscaleOutputPass.resetHistory());const e=Et(this.options.upscaling?.temporal?.jitterScale,1);Je(this.temporalUpscalingFrameIndex++,this.temporalJitter,e),this.temporalJitterUv.set(this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),this.temporalJitter.y/Math.max(1,this.gRenderTarget.height));const t=2*this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),s=2*this.temporalJitter.y/Math.max(1,this.gRenderTarget.height);this.camera instanceof c?(this.camera.projectionMatrix.elements[8]+=t,this.camera.projectionMatrix.elements[9]+=s):(this.camera.projectionMatrix.elements[12]+=t,this.camera.projectionMatrix.elements[13]+=s),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.projectionJitterApplied=!0,this.currentViewProjectionMatrix.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),this.currentViewProjectionMatrixInverse.copy(this.currentViewProjectionMatrix).invert(),this.temporalUpscalingFrameState.depthTexture=this.gRenderTarget.depthTexture,this.upscaleOutputPass.setFrameState(this.temporalUpscalingFrameState)}finishUpscalingFrame(){this.projectionJitterApplied&&(this.camera.projectionMatrix.copy(this.unjitteredProjectionMatrix),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.hasPreviousTemporalViewProjection=!0,this.projectionJitterApplied=!1)}getBasePixelRatio(){const e=Et(this.maxPixelRatio,1),t=Et(window.devicePixelRatio,1);return Math.min(e,t)}getBaseResolutionScale(){return Et(this.resolutionScale,1)}getDynamicResolutionMinScale(){const e=this.getBaseResolutionScale(),t=Et(this.options.dynamicResolution?.minScale,.7);return Math.min(e,t)}getEffectiveResolutionScale(){const e=this.getBaseResolutionScale();return!0!==this.options.dynamicResolution?.enabled?e:Te(this.dynamicResolutionScale,this.getDynamicResolutionMinScale(),e)}getRenderPixelRatio(){return this.getBasePixelRatio()*this.getEffectiveResolutionScale()}getPresentationPixelRatio(){const e=this.getBasePixelRatio();return this.isUpscalingEnabled()?e:e*this.getEffectiveResolutionScale()}resetDynamicResolutionAverage(){this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0}updateDynamicResolution(e,t){const s=this.options.dynamicResolution;if(!0!==s?.enabled)return;if(!Number.isFinite(e)||e<=0||e>.25)return void this.resetDynamicResolutionAverage();const i=this.getBaseResolutionScale(),a=this.getDynamicResolutionMinScale(),n=Te(this.dynamicResolutionScale,a,i);Rt(n,this.dynamicResolutionScale)||(this.dynamicResolutionScale=n);const r=Et(s.targetFps,60),o=1e3/(null!=this.fpsCap?Math.min(r,this.fpsCap):r),l=1e3*e;this.dynamicResolutionFrameTimeAverage=null==this.dynamicResolutionFrameTimeAverage?l:.9*this.dynamicResolutionFrameTimeAverage+.1*l,this.dynamicResolutionFrameSamples++;const h=Math.max(1,Math.floor(Et(s.sampleFrames,20)));if(this.dynamicResolutionFrameSamples<h)return;const c=Et(s.decreaseCooldown,500),p=Et(s.increaseCooldown,2e3),d=Et(s.decreaseStep,.05),u=Et(s.increaseStep,.025),m=this.dynamicResolutionFrameTimeAverage;let g=n;m>1.12*o&&n>a&&t-this.dynamicResolutionLastAdjustmentAt>=c?g=Math.max(a,n-d):m<.85*o&&n<i&&t-this.dynamicResolutionLastAdjustmentAt>=p&&(g=Math.min(i,n+u)),Rt(g,n)||(this.dynamicResolutionScale=g,this.dynamicResolutionLastAdjustmentAt=t,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}resizeRender(e=!1){if(!this.running)return;const t=this.container.clientWidth,s=this.container.clientHeight,i=this.getRenderPixelRatio(),a=this.getPresentationPixelRatio();if(!e&&this.previousClientWith===t&&this.previousClientHeight===s&&this.previousRenderPixelRatio===i&&this.previousPresentationPixelRatio===a)return;if(0===t||0===s)return;if(this.previousClientWith=t,this.previousClientHeight=s,this.previousRenderPixelRatio=i,this.previousPresentationPixelRatio=a,this.camera instanceof c&&(this.camera.aspect=t/s,this.camera.updateProjectionMatrix()),!this.webGlInitialized)return this.experimentalWebGpuBackend?.setSize(t,s,this.getBasePixelRatio(),this.getEffectiveResolutionScale()),this.resetDynamicResolutionAverage(),void this.resetUpscalingHistory();this.renderer.setPixelRatio(a),this.renderer.setSize(t,s),this.composer.setPixelRatio(i),this.composer.setSize(t,s);const n=t*i,r=s*i;this.dofPass.setSize(n,r),this.fxaaPass.setSize(n,r),this.fxaaPass.uniforms.resolution.value.set(1/n,1/r),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.fquadBlendAO.material.uniforms.tAlphaTest.value=this.gRenderTarget.textures[1],this.sceneColorRenderTarget.dispose(),this.sceneDepthRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(),this.sceneDepthRenderTarget=this.createSceneDepthRenderTarget(),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0,this.experimentalWebGpuBackend?.setSize(t,s,this.getBasePixelRatio(),this.getEffectiveResolutionScale()),this.resetDynamicResolutionAverage(),this.resetUpscalingHistory()}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}addWaterPostProcessVolume(e){this.waterPostProcessVolumes.includes(e)||this.waterPostProcessVolumes.push(e)}removeWaterPostProcessVolume(e){const t=this.waterPostProcessVolumes.indexOf(e);t>=0&&this.waterPostProcessVolumes.splice(t,1)}updateUnderwaterPostProcessing(){if(null==this.camera)return;const e=this.camera.getWorldPosition(it),t=this.waterPostProcessVolumes.filter(e=>e.underwater.enabled&&bt(e.object)).sort((e,t)=>t.underwater.priority-e.underwater.priority),s=t.find(t=>t.containsWaterPoint(e))??null,i=s??t.find(t=>null!=t.getWaterPostProcessWorldToLocal&&!0===t.isWaterPostProcessRelevant?.(e,t.underwater.transitionDistance))??null;this.activeWaterPostProcessVolume=i;const a=i?.underwater.postProcessMaterial;let n=null;if(!0===a?.isShaderMaterial&&(n=this.underwaterPostProcessEffects.get(a)??null,null==n&&(n=this.addPostProcessEffect(a,{stage:"beforeFog",priority:-100,enabled:!1}),this.underwaterPostProcessEffects.set(a,n))),n!==this.activeUnderwaterPostProcessEffect&&(null!=this.activeUnderwaterPostProcessEffect&&(this.activeUnderwaterPostProcessEffect.enabled=!1),this.activeUnderwaterPostProcessEffect=n),null!=n){n.enabled=null!=i;const t=n.material,a=t.uniforms[Me],r=t.uniforms[fe],o=t.uniforms[be],l=t.uniforms[we];if(null!=l){const e="webgpu"===this.activeBackend?at.copy(nt).multiply(this.camera.projectionMatrix):this.camera.projectionMatrix;l.value.copy(e).multiply(this.camera.matrixWorldInverse).invert()}null!=i?.getWaterPostProcessWorldToLocal&&null!=a?(i.getWaterPostProcessWorldToLocal(a.value,e),r?.value.copy(e),null!=o&&(o.value=1)):null!=o&&(o.value=null!=s?-1:0)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}addPostProcessEffect(e,t={}){const s=Ne(e),i={id:++this.postProcessEffectId,material:s,pass:this.webGlInitialized?new Re(s):null,enabled:t.enabled??!0,priority:Be(t.priority),stage:Oe(t.stage)};return null!=i.pass&&(i.pass.enabled=i.enabled),this.postProcessEffects.push(i),this.refreshPostProcessEffectPassOrder(),new Ee(this,i)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),null!=t.pass&&(this.composer.removePass(t.pass),t.pass.dispose()),this.syncExperimentalWebGpuPostProcessEffects())}refreshPostProcessEffectPassOrder(){if(this.webGlInitialized){for(const e of this.postProcessEffects)e.pass??(e.pass=new Re(e.material)),e.pass.enabled=e.enabled,this.composer.removePass(e.pass);for(const e of Ce){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(wt);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}this.syncExperimentalWebGpuPostProcessEffects()}else this.syncExperimentalWebGpuPostProcessEffects()}syncExperimentalWebGpuPostProcessEffects(){this.experimentalWebGpuBackend?.setPostProcessEffects(this.postProcessEffects)}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.backendHandle=null,this.webGlBackend=null,this.experimentalWebGpuBackend=null,this.experimentalWebGpuBackendPoolKey=null,this.experimentalWebGpuFailed=!1,this.webGpuRuntimeErrorReported=!1,this.experimentalWebGpuCapabilityReported=!1,this.experimentalWebGpuTiledLightingEnabled=!0,this.experimentalWebGpuDynamicBatchingEnabled=!0,this.ambientOcclusionSettings={enabled:!1,blendIntensity:1,options:{}},this.experimentalWebGpuSelectedObjectInstances=[],this.outlinesEnabled=!1,this.selectedOutlineObjects=[],this.experimentalStaticDrawSetRegistrations=new Set,this.staticSpatialObjects=new Map,this.experimentalWebGpuRenderGraphExtensions=new Set,this.webGpuPresentationExtensions=new Set,this.worldEnvironment=null,this.isIntersecting=!1,this.stopIntersectionObservation=null,this.needsPausedRender=!1,this.wakePausedRenderer=null,this.resumeAnimationLoop=null,this.windowVisible=!0,this.queryScene=new a.Scene,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.waterPostProcessVolumes=[],this.underwaterPostProcessEffects=new Map,this.activeUnderwaterPostProcessEffect=null,this.activeWaterPostProcessVolume=null,this.postProcessSettings={},this.baseToneMapping=a.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this.webgpuDirectionalShadowUpdateOptions={},this.webgpuDirectionalShadowOptions={enabled:!0,mapSize:2048,cascadeCount:4,maxDistance:80},this._id=mt++,this.postProcessEffectId=0,this.postProcessEffects=[],this.occlusionClusters=[],this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.resolutionScale=1,this.maxPixelRatio=ut?1:window.devicePixelRatio,this.dynamicResolutionScale=1,this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0,this.dynamicResolutionLastAdjustmentAt=0,this.upscaleOutputPass=null,this.unjitteredProjectionMatrix=new l,this.temporalJitter=new a.Vector2,this.temporalJitterUv=new a.Vector2,this.currentUnjitteredViewProjectionMatrix=new l,this.currentViewProjectionMatrix=new l,this.currentViewProjectionMatrixInverse=new l,this.previousViewProjectionMatrix=new l,this.temporalUpscalingFrameState={depthTexture:null,currentJitterUv:this.temporalJitterUv,currentViewProjectionInverse:this.currentViewProjectionMatrixInverse,previousViewProjection:this.previousViewProjectionMatrix},this.temporalUpscalingFrameIndex=0,this.hasPreviousTemporalViewProjection=!1,this.projectionJitterApplied=!1,this.onResize=()=>{if(this.resizeRender(),this.paused)this.needsPausedRender=!0,this.wakePausedRenderer?.();else try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.webGlInitialized=!1,this.onLoopCallbacks=[],this.stats=new se,this.webGpuPassStatsDom=function(){const e=document.createElement("div");return e.dataset.hologyWebGpuPassStats="",e.setAttribute("aria-hidden","true"),e.style.cssText=["position:absolute","top:52px","left:12px","z-index:10000","width:min(520px,calc(100% - 24px))","pointer-events:none","color:white","font:12px/1.2 Arial,Helvetica,sans-serif","text-shadow:0 1px 2px black,0 0 3px black"].join(";"),e}(),this.webGpuResolutionStatsDom=document.createElement("div"),this.webGpuVisibilityStatsDom=function(){const e=document.createElement("div");return e.style.cssText=["margin-bottom:10px","padding-bottom:6px","border-bottom:1px solid rgba(255,255,255,.4)"].join(";"),e.textContent="GPU visibility: awaiting readback",e}(),this.webGpuPassStatsRows=[],this._showStats=!1,this._profilingEnabled=!1,this.gbufferMaterialCache=new Map,this.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.frameGBufferMeshes=[],this.frameGBufferPhaseMasks=[],this.frameUnsupportedGBufferObjects=[],this.frameGBufferExcludedObjects=new Set,this.appliedGBufferMeshes=[],this.originalGBufferMaterials=[],this.originalGBufferOnBeforeRender=[],this.hiddenGBufferObjects=[],this.gBufferPhaseMaskCache=new WeakMap,this.gBufferMaterialArrayCache=new WeakMap,this.gBufferShadowUpdaterCache=new WeakMap,this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.compileTail=Promise.resolve(),this.depthMaterialCachedMaterials=new Map,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new r,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,this.stats.style=s.statsStyle??"detailed",this.graphicsRuntime=s.graphicsRuntime??tt,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.dynamicResolutionScale=this.getBaseResolutionScale(),this.fpsCap=s.fpsCap,this.experimentalWebGpuDynamicBatchingEnabled=s.webgpuDynamicBatching??!0,this.experimentalWebGpuTiledLightingEnabled=s.webgpuTiledLighting??!0,this.outlinesEnabled=!0===s.enableOutlines,this.webgpuDirectionalShadowOptions=st(s.webgpuDirectionalShadows),"webgpu"===this.requestedBackend&&!0===s.enableXR&&(console.warn("[Hology WebGPU experiment] XR is not supported; using WebGL."),this.experimentalWebGpuFailed=!0),e.activeView=this,this.scene=new a.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}.bind(this.scene);const i=t.clientWidth||1,n=t.clientHeight||1,o=new a.PerspectiveCamera(45,i/n,.1,800);o.layers.enable(19),this.camera=o,T.renderingView=this,this.setCamera(o),this.setupEventListeners(),this.setupWebGlPipeline=()=>{if(!this.webGlInitialized)try{this.webGlBackend=et.initialize({container:this.container,pixelRatio:this.getPresentationPixelRatio(),enableXR:this.options.enableXR??!1,shadows:{enabled:this.options.shadows?.enabled??!0,autoUpdate:this.options.shadows?.autoUpdate??!1}}),this.renderer=this.webGlBackend.renderer,this.outlineEffect=this.webGlBackend.outlineEffect,this.createGRenderTarget(),this.composer=new w(this.renderer,function(e,t){const s=new a.WebGLRenderTarget(Math.max(1,e),Math.max(1,t),{minFilter:a.LinearFilter,magFilter:a.LinearFilter,format:a.RGBAFormat,type:a.HalfFloatType});return s.texture.name="EffectComposer.rt1",s.texture.generateMipmaps=!1,s}(t.clientWidth,t.clientHeight)),this.composer.setPixelRatio(this.getRenderPixelRatio()),this.composer.setSize(t.clientWidth,t.clientHeight),this.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.isDepthTextureExtensionSupported=pe(this.renderer),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container,this.getRenderPixelRatio()),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(),this.sceneDepthRenderTarget=this.createSceneDepthRenderTarget(),this.postProcessEffectResolution=new a.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:Qe(),normalTexture:Qe(128,128,255),resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopySceneColor=new Le(new d(b)),this.fquadCopySceneDepth=new Le(new E({color:L(H("tDepthTexture",Qe()).sample(j.uv).r)})),this.fquadBlendAO=this.createAoblendQuad();const i=new a.Vector2(t.clientWidth,t.clientHeight),n=(new P(this.scene,this.camera),new y(b,"prevtexture"));n.enabled=!0,n.needsSwap=!0,n.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=n;const r=new Ae(i,1.5,.4,.85);r.threshold=1,r.strength=.9,r.radius=.2,this.bloomPass=r;const o=new ie(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});o.normalRenderTarget?.dispose(),o.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),o.output=ie.OUTPUT.Off,o.enabled=!1,this.aoPass=o,o.enabled=this.ambientOcclusionSettings.enabled,o.blendIntensity=this.ambientOcclusionSettings.blendIntensity,o.updateGtaoMaterial(this.ambientOcclusionSettings.options),this.fquadBlendAO.material.uniforms.tAO.value=o.pdRenderTarget.texture,this.fquadBlendAO.material.uniforms.tAlphaTest.value=this.gRenderTarget.textures[1],Ue.fragmentShader=Ue.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const l=new We({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});l.output=We.OUTPUT.Default,l.blur=!0,l.fresnel=!1,l.distanceAttenuation=!0,l.maxDistance=50,l.selective=!0,l.bouncing=!1,l.opacity=.4,l.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(o);const c=new Lt((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(c);const p=new Lt((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(lt.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(p),this.composer.addPass(n),this.composer.addPass(l),this.phasedRenderPass=new Vt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(r),r.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new De(i),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new K(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const u=new Ge;this.composer.addPass(u),this.colorPass=u,u.vignetteEnabled=!1,this.outlinePass=new Pe(new a.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const m=new y(M);m.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(m),this.fxaaPass=m,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new y(v).clear=!1,this.fixStatsStyle(),this.lutPass=new x({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const g=new y(b,"prevtexture");g.enabled=!0,g.needsSwap=!1,g.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],g.renderToScreen=!0;const f=this.isUpscalingEnabled()?new Ye(this.options.upscaling):new Z;!function(e){const t=e.material;if(t.dithering=!0,t.fragmentShader.includes("<dithering_fragment>"))return;const s="#include <colorspace_pars_fragment>";if(!t.fragmentShader.includes(s))return;t.fragmentShader=t.fragmentShader.replace(s,`${s}\n #include <common>\n #include <dithering_pars_fragment>`);const i=t.fragmentShader.lastIndexOf("}");i<0||(t.fragmentShader=`${t.fragmentShader.slice(0,i)}\n #include <dithering_fragment>\n${t.fragmentShader.slice(i)}`,t.needsUpdate=!0)}(f),this.outputPass=f,this.upscaleOutputPass=f instanceof Ye?f:null,this.composer.addPass(f);const S=new a.MeshBasicMaterial({colorWrite:!1,depthWrite:!1,depthTest:!0,transparent:!1}),T=new h(new a.BoxGeometry(1,1,1),S);T.renderOrder=1/0,T.name="CLUSTER_BOUNDS_VOLUME",this.webGlInitialized=!0,this.backendHandle=this.webGlBackend,this.attachRendererDomElement(),this.refreshPostProcessEffectPassOrder()}catch(e){throw this.webGlInitialized=!1,this.webGlBackend?.dispose(),this.webGlBackend=null,this.backendHandle=null,e}},("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)&&this.setupWebGlPipeline()}addCluster(e){if(!1===this.options.occlusionCulling?.enabled)return;if(!this.webGlInitialized)return;if(!this.renderer.capabilities.isWebGL2)return;const t=this.renderer.getContext(),s=t.createQuery();if(null==s)return;const i={query:s,visible:!0,awaitingResult:!1,cluster:e,lastTested:-1/0,distance:0,update:()=>{if(i.awaitingResult&&t.getQueryParameter(s,t.QUERY_RESULT_AVAILABLE)){const e=t.getQueryParameter(s,t.QUERY_RESULT);i.visible=!!e,i.awaitingResult=!1}}};e.boundsMesh.onBeforeRender=()=>{i.awaitingResult||t.beginQuery(t.ANY_SAMPLES_PASSED,s)},e.boundsMesh.onAfterRender=()=>{i.awaitingResult||(t.endQuery(t.ANY_SAMPLES_PASSED),i.awaitingResult=!0)},this.occlusionClusters.push(i)}updateRenderedOcclusionClusters(){this.queryScene.clear();const e=performance.now(),t=[];for(const s of this.occlusionClusters){if(s.awaitingResult)continue;const i=s.cluster.bounds.distanceToPoint(this.camera.position);if(s.distance=i,i<10){s.visible=!0,s.lastTested=e;continue}if(i>1e3)continue;const a=e-s.lastTested;if(!(s.visible&&a<4e3)&&((s.visible||!(a<100))&&vt.intersectsBox(s.cluster.bounds)))if(s.visible)t.push(s);else{let e=0;for(;e<t.length&&t[e].distance<s.distance;)e++;t.splice(e,0,s)}}if(t.length<50)for(const s of t)s.lastTested=e,this.queryScene.add(s.cluster.boundsMesh);else{const s=Math.max(Math.floor(Math.random()*t.length-50),0);for(let i=0;i<50;i++){const a=t[s+i];if(null==a)break;a.lastTested=e,this.queryScene.add(a.cluster.boundsMesh)}if(t.length>0){const s=t[0];s.lastTested=e,this.queryScene.add(s.cluster.boundsMesh)}}}fixStatsStyle(){if("simple"===this.statsStyle)return;const e=this.stats.dom;e.style.position="absolute",e.style.display="flex",e.style.flexWrap="nowrap",e.style.width="max-content";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++){const s=t.item(e);s.style.flex="none",s.style.display="inline-block"}}setEnableOutlines(e){this.outlinesEnabled=e,null!=this.outlinePass&&(this.outlinePass.enabled=e),null!=this.fxaaPass&&(this.fxaaPass.enabled=e),this.syncWebGpuOutlineState()}registerWebGpuPresentationExtension(e){return"webgpu"!==this.requestedBackend?()=>{}:(this.webGpuPresentationExtensions.add(e),this.experimentalWebGpuBackend?.setPresentationExtensions(this.webGpuPresentationExtensions),this.wakePausedRenderer?.(),()=>{this.webGpuPresentationExtensions.delete(e),this.experimentalWebGpuBackend?.setPresentationExtensions(this.webGpuPresentationExtensions)})}get sharedGraphicsRuntime(){return this.graphicsRuntime}createSceneCapture(e,t,s){if(!this.experimentalWebGpuBackend||"webgpu"!==this.activeBackend)throw new Error("Scene capture requires an initialized WebGPU rendering backend.");return this.experimentalWebGpuBackend.createSceneCapture(e,t,s)}setCamera(e){if(this.camera=e,this.resetUpscalingHistory(),this.composer?.passes.forEach(t=>{t instanceof P?t.camera=e:t instanceof Pe?t.renderCamera=e:(t instanceof ve||t instanceof ie)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm){this.csm=new ee({maxFar:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.maxDistance:80,lightFar:250,lightMargin:20,shadowBias:-1e-4,cascades:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.cascadeCount:ut?2:3,shadowMapSize:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.mapSize:1024*(ut?.5:1),lightDirection:new a.Vector3(.5,-1,-.6).normalize(),lightIntensity:.25*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"});for(const e of this.csm.lights)e.shadow.normalBias=.01;if(null!=this.csmUpdateInvervals){this.csmCascadeLastUpdate=new Array(this.csm.lights.length).fill(0);for(const e of this.csm.lights)e.shadow.autoUpdate=!1}this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,p.lights_fragment_begin=S.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.selectedOutlineObjects=Array.from(t.values()),this.experimentalWebGpuSelectedObjectInstances=[],this.syncWebGpuOutlineState(),null!=this.outlinePass&&(this.outlinePass.selectedObjects=this.selectedOutlineObjects)}setExperimentalWebGpuTiledLightingEnabled(e){this.experimentalWebGpuTiledLightingEnabled=e,this.experimentalWebGpuBackend?.setTiledLightingEnabled(e)}setExperimentalWebGpuDynamicBatchingEnabled(e){this.experimentalWebGpuDynamicBatchingEnabled=e,this.experimentalWebGpuBackend?.setDynamicBatchingEnabled(e)}setMotionBlurOptions(e){this.experimentalWebGpuBackend?.setMotionBlurOptions(e)}setDirectionalShadowUpdateOptions(e){this.webgpuDirectionalShadowUpdateOptions={...e,cascadeUpdateHz:e.cascadeUpdateHz?.slice()},this.experimentalWebGpuBackend?.setDirectionalShadowUpdateOptions(this.webgpuDirectionalShadowUpdateOptions)}invalidateDirectionalShadows(){this.experimentalWebGpuBackend?.invalidateDirectionalShadows()}setDirectionalShadowOptions(e){if("webgpu"!==this.requestedBackend)return;const t=st(e),s=this.webgpuDirectionalShadowOptions,i=t.mapSize!==s.mapSize||t.cascadeCount!==s.cascadeCount||t.maxDistance!==s.maxDistance;if(i||t.enabled!==s.enabled){if(this.webgpuDirectionalShadowOptions=t,i&&null!=this.csm){const e=this.csm.lights[0],t={lightDirection:this.csm.lightDirection.clone(),lightIntensity:e?.intensity??this.csm.lightIntensity,lightColor:e?.color.clone()??new a.Color(16777215),castShadow:e?.castShadow??!0,userData:{...e?.userData??{}},shadowBias:e?.shadow.bias??this.csm.shadowBias,normalBias:e?.shadow.normalBias??.01,shadowRadius:e?.shadow.radius??1,shadowIntensity:e?.shadow.intensity??1};this.csm.remove(),this.csm.dispose(),this.csm=null,this.csmCascadeLastUpdate=void 0,this.setCamera(this.camera),this.csm.lightDirection.copy(t.lightDirection),this.csm.lightIntensity=t.lightIntensity,this.csm.shadowBias=t.shadowBias;for(const e of this.csm.lights)e.intensity=t.lightIntensity,e.color.copy(t.lightColor),e.castShadow=t.castShadow,e.userData={...t.userData},e.shadow.bias=t.shadowBias,e.shadow.normalBias=t.normalBias,e.shadow.radius=t.shadowRadius,e.shadow.intensity=t.shadowIntensity;this.csm.update()}this.experimentalWebGpuBackend?.setDirectionalShadowOptions(t.enabled,t.mapSize),this.syncExperimentalWebGpuCascades(),this.experimentalWebGpuBackend?.resetViewHistory()}}setGTAOOptions(e){this.experimentalWebGpuBackend?.setGTAOOptions(e)}configureAmbientOcclusion(e,t=1,s={}){this.ambientOcclusionSettings={enabled:e,blendIntensity:t,options:s},this.webGlInitialized&&(this.aoPass.enabled=e,this.aoPass.blendIntensity=t,this.aoPass.updateGtaoMaterial(s)),this.experimentalWebGpuBackend?.setGTAOOptions({...s,intensity:t,enabled:e})}invalidateShadows(){this.webGlInitialized&&(this.renderer.shadowMap.needsUpdate=!0)}initTexture(e){this._initTexture(e)}setBaseToneMapping(e,t){this.baseToneMapping=e,this.baseToneMappingExposure=t,this.webGlInitialized&&(this.renderer.toneMapping=e,this.renderer.toneMappingExposure=t)}get supportsWebGlDepthTexture(){return this.webGlInitialized&&this.isDepthTextureExtensionSupported}setAntiAliasingMode(e){this.experimentalWebGpuBackend?.setAntiAliasingMode(e)}setGTAOQuality(e){this.experimentalWebGpuBackend?.setGTAOQuality(e)}setVolumetricFogOptions(e){this.experimentalWebGpuBackend?.setVolumetricFogOptions(e)}setVolumetricFogQuality(e){this.experimentalWebGpuBackend?.setVolumetricFogQuality(e)}pushMotionBlurOverride(e){return this.experimentalWebGpuBackend?.pushMotionBlurOverride(e)??null}setObjectDetailCulling(e,t){e.userData.detailCulling=t}setObjectMotionBlur(e,t,s=1){e.traverse(e=>{e.userData.motionBlurMode=t,e.userData.motionBlurScale=Math.max(0,Math.min(s,8))})}invalidateObjectMotion(e){e.traverse(e=>{e.userData.motionBlurTeleported=!0,this.experimentalWebGpuBackend?.invalidateObjectMotion(e)})}setSelectedObjectInstances(e){this.experimentalWebGpuSelectedObjectInstances=[...e],this.syncWebGpuOutlineState()}static createDepthRenderTarget(e,t,s){const i=Math.max(1,Math.floor(t.clientWidth*s)),n=Math.max(1,Math.floor(t.clientHeight*s)),r=new a.WebGLRenderTarget(i,n);return r.texture.minFilter=a.NearestFilter,r.texture.magFilter=a.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new a.DepthTexture(i,n),r.depthTexture.type=a.UnsignedShortType,r.depthTexture.minFilter=a.NearestFilter,r.depthTexture.magFilter=a.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t,s=e.getPixelRatio()){const i=Math.max(1,t.clientWidth*s),n=Math.max(1,t.clientHeight*s),r=new a.DepthTexture(i,n);r.type=a.UnsignedInt248Type,r.minFilter=a.NearestFilter,r.magFilter=a.NearestFilter;const o=new a.WebGLRenderTarget(i,n,{type:a.HalfFloatType,depthTexture:r});return o.texture.minFilter=a.NearestFilter,o.texture.magFilter=a.NearestFilter,o.texture.generateMipmaps=!1,o.stencilBuffer=!1,o}createSceneColorRenderTarget(){const e=this.gRenderTarget.width,t=this.gRenderTarget.height,s=new a.WebGLRenderTarget(e,t,{type:a.HalfFloatType,format:a.RGBAFormat,colorSpace:a.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return s.texture.minFilter=a.LinearFilter,s.texture.magFilter=a.LinearFilter,s.texture.generateMipmaps=!1,s}createSceneDepthRenderTarget(){const e=new a.WebGLRenderTarget(this.gRenderTarget.width,this.gRenderTarget.height,{type:a.FloatType,format:a.RedFormat,minFilter:a.NearestFilter,magFilter:a.NearestFilter,depthBuffer:!1,stencilBuffer:!1});return e.texture.generateMipmaps=!1,e}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=this.getRenderPixelRatio(),s=Math.max(1,e.clientWidth*t),i=Math.max(1,e.clientHeight*t),n=new a.DepthTexture(s,i);n.type=a.UnsignedIntType,n.minFilter=a.NearestFilter,n.magFilter=a.NearestFilter,this.gRenderTarget=new u(s,i,{count:3,samples:this.options?.msaa??0,minFilter:a.NearestFilter,magFilter:a.NearestFilter,type:a.HalfFloatType,format:a.RGBAFormat,depthTexture:n}),this.gRenderTarget.textures[2].type=a.UnsignedByteType,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(t=!0){this.stopAnimationLoop(),this.stopIntersectionObservation?.(),this.stopIntersectionObservation=null,this.resumeAnimationLoop=null,this.onLoopCallbacks=[];for(const e of this.staticSpatialObjects.values())e.handle?.dispose();if(this.staticSpatialObjects.clear(),this.disposeExperimentalStaticDrawSets(),e.experimentalWebGpuPresentationView===this&&(e.experimentalWebGpuPresentationView=null),this.wakePausedRenderer=null,this.lightVolume?.shTexture.dispose(),window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),t&&this.webGlInitialized&&this.renderer.dispose(),this.webGlInitialized){this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.sceneDepthRenderTarget.dispose(),this.transmissionColorRenderTarget?.dispose(),this.transmissionCopyQuad?.material.dispose(),this.transmissionCopyQuad?.dispose();for(const e of this.postProcessEffects)null!=e.pass&&(this.composer.removePass(e.pass),e.pass.dispose());this.volumetricFogPass.dispose(),this.webGlBackend?.dispose(),this.webGlBackend=null}if(this.csm?.dispose(),this.postProcessEffects.length=0,this.detachOwnedDomElements(),this.releaseExperimentalWebGpuBackend(),this.experimentalWebGpuBackend=null,this.backendHandle=null,this.webGlInitialized&&this.occlusionClusters.length>0){const e=this.renderer.getContext();this.occlusionClusters.forEach(t=>{e.deleteQuery(t.query)})}T.clearSceneCache(this.scene)}stopAnimationLoop(){this.running=!1}suspendPresentation(){this.stopAnimationLoop(),this.detachOwnedDomElements()}activatePresentation(){if(e.activeView=this,null!=this.experimentalWebGpuBackend){const t=e.experimentalWebGpuPresentationView,s=t!==this;s&&t?.disposeExperimentalStaticDrawSets(),this.applyExperimentalWebGpuViewState(s),e.experimentalWebGpuPresentationView=this,this.activateExperimentalStaticDrawSets()}this.attachRendererDomElement(),this.resizeRender(!0)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){e&&!this._showStats&&this.stats.reset(),this._showStats=e,this.experimentalWebGpuBackend?.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),this._showStats&&this.stats.dom.parentElement!==this.container?(this.container.appendChild(this.stats.dom),this.fixStatsStyle()):this._showStats||this.stats.dom.parentElement!==this.container||this.container.removeChild(this.stats.dom),this.syncWebGpuPassStatsDom()}get showStats(){return this._showStats}set statsStyle(e){this.stats.style!==e&&(this.stats.style=e,this.fixStatsStyle(),this.experimentalWebGpuBackend?.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),this.syncWebGpuPassStatsDom())}get statsStyle(){return this.stats.style}get detailedStatsEnabled(){return this._showStats&&"detailed"===this.statsStyle}getLastFrameProfile(){return this.experimentalWebGpuBackend?.getLastFrameProfile()??null}setProfilingEnabled(e){this._profilingEnabled=e,this.experimentalWebGpuBackend?.setProfilingEnabled(e||this.detailedStatsEnabled)}attachRendererDomElement(){const t=this.getActiveRendererCanvas();if("webgpu"===this.activeBackend&&null!=this.experimentalWebGpuBackend&&e.experimentalWebGpuPresentationView!==this){const t=e.experimentalWebGpuPresentationView;t?.disposeExperimentalStaticDrawSets(),e.experimentalWebGpuPresentationView=this,this.applyExperimentalWebGpuViewState(!0),this.activateExperimentalStaticDrawSets()}const s=this.webGlInitialized?this.renderer.domElement:null,i=t===s?this.experimentalWebGpuBackend?.canvas:s;i?.parentElement===this.container&&this.container.removeChild(i),t.parentElement===this.container&&t===this.container.firstChild||this.container.insertBefore(t,this.container.firstChild),this._showStats&&this.stats.dom.parentElement!==this.container&&this.container.appendChild(this.stats.dom),this.syncWebGpuPassStatsDom()}detachOwnedDomElements(){this.webGlInitialized&&this.renderer.domElement.parentElement===this.container&&this.container.removeChild(this.renderer.domElement);const e=this.experimentalWebGpuBackend?.canvas;e?.parentElement===this.container&&this.container.removeChild(e),this.stats.dom.parentElement===this.container&&this.container.removeChild(this.stats.dom),this.webGpuPassStatsDom.parentElement===this.container&&this.container.removeChild(this.webGpuPassStatsDom)}syncWebGpuPassStatsDom(){const e=this.detailedStatsEnabled&&"webgpu"===this.requestedBackend;e&&this.webGpuPassStatsDom.parentElement!==this.container?this.container.appendChild(this.webGpuPassStatsDom):e||this.webGpuPassStatsDom.parentElement!==this.container||this.container.removeChild(this.webGpuPassStatsDom)}updateWebGpuPassStats(e){let t=this.webGpuPassStatsRows.length!==e.passes.length;for(let s=0;!t&&s<e.passes.length;s++)t=this.webGpuPassStatsRows[s].name!==e.passes[s].name;t&&(this.webGpuPassStatsDom.replaceChildren(this.webGpuResolutionStatsDom,this.webGpuVisibilityStatsDom),this.webGpuPassStatsRows=e.passes.map(e=>{const t=function(e){const t=document.createElement("div");t.style.cssText=["display:grid","grid-template-columns:minmax(0,1fr) 92px 92px","column-gap:12px","margin-bottom:7px"].join(";");const s=document.createElement("span");s.textContent=e,s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap";const i=document.createElement("span"),a=document.createElement("span"),n=document.createElement("div");return n.style.cssText=["grid-column:1","width:100%","height:4px","transform-origin:left center","transform:scaleX(0)","margin-top:4px","background:rgba(255,255,255,.78)","box-shadow:0 1px 2px rgba(0,0,0,.9)"].join(";"),t.append(s,i,a,n),{name:e,dom:t,gpu:i,cpu:a,bar:n}}(e.name);return this.webGpuPassStatsDom.appendChild(t.dom),t}));const s=null!=e.renderWidth&&null!=e.renderHeight&&null!=e.presentationWidth&&null!=e.presentationHeight?`Render: ${e.renderWidth} × ${e.renderHeight} | Output: ${e.presentationWidth} × ${e.presentationHeight}`:"";this.webGpuResolutionStatsDom.textContent!==s&&(this.webGpuResolutionStatsDom.textContent=s);const i=e.visibility;let a;if(null==i)a=e.hiZOcclusionCullingActive?"GPU visibility: awaiting readback":"GPU visibility: inactive";else{const e=i.totalInstances>0?i.visibleInstances/i.totalInstances*100:100;a=`GPU visibility: ${i.visibleInstances.toLocaleString()} / ${i.totalInstances.toLocaleString()} visible (${e.toFixed(1)}%), ${i.culledInstances.toLocaleString()} culled | dynamic ${i.dynamicVisibleInstances.toLocaleString()} / ${i.dynamicTotalInstances.toLocaleString()}, static ${i.staticVisibleInstances.toLocaleString()} / ${i.staticTotalInstances.toLocaleString()}`}this.webGpuVisibilityStatsDom.textContent!==a&&(this.webGpuVisibilityStatsDom.textContent=a);let n=.01;for(const t of e.passes)n=Math.max(n,t.gpuTimeMs??t.cpuTimeMs);for(let t=0;t<e.passes.length;t++){const s=e.passes[t],i=this.webGpuPassStatsRows[t],a=null==s.gpuTimeMs?"GPU --":`GPU ${s.gpuTimeMs.toFixed(2)} ms`,r=`CPU ${s.cpuTimeMs.toFixed(2)} ms`;i.gpu.textContent!==a&&(i.gpu.textContent=a),i.cpu.textContent!==r&&(i.cpu.textContent=r);const o=s.gpuTimeMs??s.cpuTimeMs,l=`scaleX(${Math.max(o>0?.02:0,o/n)})`;i.bar.style.transform!==l&&(i.bar.style.transform=l)}}getActiveRendererCanvas(){if(null==this.backendHandle)throw new Error("Rendering backend is not initialized. Await compileAsync() before rendering.");return this.backendHandle.canvas}requireInitializedBackend(e){const t=this.backendHandle;if(null==t)throw new Error(`Cannot ${e}: the rendering backend has not finished initializing.`);return t}activateExperimentalStaticDrawSets(){if("webgpu"!==this.activeBackend||null==this.experimentalWebGpuBackend)return;for(const[e,t]of this.staticSpatialObjects)null==t.handle&&(t.handle=this.experimentalWebGpuBackend.registerStaticSpatialObject(e),t.editing&&t.handle.setEditing(!0));let e=0,t=0,s=0,i=0;for(const a of this.experimentalStaticDrawSetRegistrations)if(null==a.staticDrawSet)try{const i=this.experimentalWebGpuBackend.createStaticDrawSet(a.root,a.label,a.allowUnsortedLateDraws,a.onUnsupported);if(null==i)continue;a.staticDrawSet=i,a.root.visible=!1,e++,t+=i.drawCount,s+=i.instanceCount}catch(e){i++,console.warn(`[Hology WebGPU experiment] Keeping static root "${a.label}" dynamic:`,e)}e>0&&console.info(`[Hology WebGPU experiment] Activated ${e} static draw set${1===e?"":"s"} (${t} draws, ${s} instances).`),i>0&&console.warn(`[Hology WebGPU experiment] ${i} static draw set${1===i?"":"s"} remain dynamic.`)}disposeExperimentalStaticDrawSets(){for(const e of this.experimentalStaticDrawSetRegistrations)e.staticDrawSet?.dispose(),null!=e.staticDrawSet&&(e.root.visible=e.sourceWasVisible),e.staticDrawSet=null}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof E&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:At(this.scene.environmentRotation,this.scene.environment,new a.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof E||e instanceof a.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setWorldEnvironment(e){const t=this.worldEnvironment?.source!==e?.source;this.worldEnvironment=e,null==e?(this.scene.environment=null,this.scene.environmentIntensity=1):("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)&&this.applyWorldEnvironmentToWebGl();const s=this.experimentalWebGpuBackend;if(null==s)return;const i=t&&"webgpu"===this.activeBackend;i&&this.disposeExperimentalStaticDrawSets(),s.setWorldEnvironment(e),i&&this.activateExperimentalStaticDrawSets()}applyWorldEnvironmentToWebGl(){const e=this.worldEnvironment;if(null==e)return this.scene.environment=null,void(this.scene.environmentIntensity=1);this.scene.environment=this.getEnvTexture(e.source),this.scene.environmentIntensity=e.intensity}hideOccluded(e){e.length=0;for(const t of this.occlusionClusters)if(!t.visible){let s=t.cluster.objects.length;for(;s--;){const i=t.cluster.objects[s];i.visible&&(i.visible=!1,e.push(i))}}}setupCsm(e){if(e instanceof a.Mesh||e instanceof a.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof a.MeshBasicMaterial||e instanceof f||e instanceof a.MeshLambertMaterial||e instanceof a.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof f||e instanceof a.MeshLambertMaterial||e instanceof a.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof f&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof a.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof je&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===_t.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||_t.includes(e)||zt.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of _t){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const n=t===lt.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=n.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==r){const s=this.usesShaderUniform(e,ne),l=this.usesSceneColorUniform(e),h=this.usesShaderUniform(e,ue),c=e.transparent&&e.alphaTest<=.01||e.blending===a.AdditiveBlending,p=t===lt.opaque?!(s||l||h||c):c||s||l||h;if(!p)return n.set(e,dt),dt;let u=j.uv;if(e instanceof je&&null!=e.heightMap){const t=B("heightScale",e.heightScale??1);u=Ve(u,H("heightMap",e.heightMap),t)}let m=V.normal;if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial){const t=e.normalMap??pt,s=B("useNormalMap",null!=e.normalMap?1:0),i=B("normalScale",e.normalScale?.x??1),a=G(H("normalMap",t).sample($e(u,e.normalMap)),i);m=$(V.normal,a,s)}else e instanceof E&&null!=e.outputNormal&&(m=e.outputNormal);!0!==e.userData.disableAO&&(m=q("DOUBLE_SIDED",m,e=>z(new _("gl_FrontFacing"),e,e.multiplyScalar(-1))));let g=e.userData?.reflective?R(0):R(1);if(e instanceof a.MeshStandardMaterial){const t=B("roughness",e.roughness??1),s=e.roughnessMap??ht,i=B("useRoughnessMap",null!=e.roughnessMap?1:0),a=H("roughnessMap",s).sample($e(u,e.roughnessMap)).g.multiply(t);g=$(t,a,i)}else e instanceof E&&null!=e.outputRoughness&&(g=e.outputRoughness);let b=null;if((e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial||e instanceof a.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,s=B("useLightMap",null!=e.lightMap?1:0),i=B("lightMapIntensity",e.lightMapIntensity??1),a=H("lightMap",t).sample(u).rgb.multiplyScalar(i);b=$(A(0),a,s)}let w=R(0);if(e instanceof a.MeshStandardMaterial){const t=B("metalness",e.metalness??0),s=e.metalnessMap??ct,i=B("useMetalnessMap",null!=e.metalnessMap?1:0),a=H("metalnessMap",s).sample($e(u,e.metalnessMap)).b.multiply(t);w=$(t,a,i)}else e instanceof E&&e.outputRoughness;let M=null,v=R(1);if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial||e instanceof a.MeshBasicMaterial){const t=e.aoMap??ht,s=B("useAoMap",null!=e.aoMap?1:0);v=B("aoMapIntensity",e.aoMapIntensity??1);const i=H("aoMap",t).sample($e(u,e.aoMap)).r;M=$(R(1),i,s)}else e instanceof E&&e.outputRoughness;const x=B("opacity",e.opacity??1);let P=R(1);if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;P=H("alphaMap",t).sample($e(u,e.alphaMap)).r}P=P.multiply(x)}else e instanceof E&&null!=e.outputOpacity&&(P=e.outputOpacity);let y=k(0,1);if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial||e instanceof a.MeshBasicMaterial){let t=O("color",(new a.Vector3).setFromColor(e.color));const s=e.map??ht,i=B("useAlbedoMap",null!=e.map?1:0),n=H("map",s).sample($e(u,e.map)),r=n.multiply(k(t,1)),o=k(t,1);y=$(o,r,i),e.vertexColors&&(y=y.multiply(L(F(Q.color.rgb),1)));const l=$(R(1),n.w,i);P=P.multiply(l)}const S=!0===e.userData.hasBloom;let T=A(0);if(e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial){const t=O("emissive",(new a.Vector3).setFromColor(e.emissive)),s=B("emissiveIntensity",e.emissiveIntensity),i=e.emissiveMap??ct,n=B("useEmissiveMap",null!=e.emissiveMap?1:0),r=H("emissiveMap",i).sample($e(u,e.emissiveMap)).rgb.multiply(t);T=$(t,r,n),T=T.multiplyScalar(s)}else e instanceof E&&null!=e.outputEmissive&&(T=e.outputEmissive);let I=null;if(e instanceof a.MeshPhysicalMaterial&&e.sheen>0&&(I=O("sheenColor",(new a.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=H("sheenColorMap",e.sheenColorMap).sample(u).rgb;I=I.multiply(t)}let N=null;if(e instanceof a.MeshPhysicalMaterial&&e.sheen>0&&(N=B("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=H("sheenRoughnessMap",e.sheenRoughnessMap).sample(u).r;N=N.multiply(t)}let X=null;if(e instanceof a.MeshPhysicalMaterial&&e.anisotropy>0&&(X=B("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=H("anisotropyMap",e.anisotropyMap).sample(u).r;X=X.multiply(t)}let Y=null;if(e instanceof a.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;Y=J("anisotropyDirection",new a.Vector2(Math.cos(t),Math.sin(t)))}const K=B("alphaTest",e.alphaTest);let Z,ee=e.alphaTest>0?P.lt(K):c&&t===lt.opaque?P.lt(.8):null;!0===e.userData.isDecal&&(ee=ee?ee.or(ze):ze),Z=c?L(0,0,0,0):(o=m,D(o).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?g:1);const te=e instanceof E?e.outputPosition:void 0,se=e instanceof E?e.outputTransform:void 0;let ie,ae=k("black",1);if(e instanceof E&&null!=e.outputColor)ae=e.outputColor;else if(e instanceof a.MeshStandardMaterial)ae=C({color:y,metalness:w,roughness:g,emissive:T.rgb,normal:m,ambientOcclusion:M,ambientOcclusionIntensity:v,bakedLight:b,sheenColor:I,sheenRoughness:N,anisotropy:X,anisotropyDirection:Y});else if(e instanceof a.MeshLambertMaterial||e instanceof a.MeshPhongMaterial)ae=U({color:y.rgb,ambientOcclusion:M,ambientOcclusionIntensity:v});else if(e instanceof a.MeshBasicMaterial){let e=y.rgb,t=b??A("black");null!=M&&(t=t.multiplyScalar(M.subtract(1).multiply(v).add(1))),e=e.add(t),ae=e.rgba(P)}else e instanceof a.MeshToonMaterial&&(ae=W({color:y,emissive:T.rgb,normal:m,ambientOcclusion:M,ambientOcclusionIntensity:v,bakedLight:b}));(e instanceof E||e instanceof a.MeshStandardMaterial)&&(ie=e.envMap);let re=!0;(e instanceof f||e instanceof a.MeshBasicMaterial||e instanceof a.ShaderMaterial)&&(re=e.fog);let oe=k(ae.rgb,P);re&&(oe=new FogNode(oe)),r=new E({transform:se,position:!0===e.userData.isSky?i:null==se?te:void 0,outputs:[oe,T.rgba(t===lt.opaque?K:S?1:0),Z],opacity:P,outputEncoding:!1,fog:re,transparent:e.transparent,lights:!0,envMap:ie,alphaTest:e.alphaTest,uniformNodes:e.uniformNodes??{},discard:ee}),e instanceof a.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(r.alphaMap=e.alphaMap),(e instanceof E||e instanceof a.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof E&&(Object.assign(r.defines,e.defines),null!=r.uniforms[ue]&&(r.uniforms[ue].value=this.aoPass.pdRenderTarget.texture,r.defines.USE_SSAO_MAP="")),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,c?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===lt.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,r.vertexColors=e.vertexColors,r.premultipliedAlpha=e.premultipliedAlpha,r.toneMapped=e.toneMapped,r.blendAlpha=e.blendAlpha,r.blendColor=e.blendColor,r.polygonOffset=e.polygonOffset,r.polygonOffsetFactor=e.polygonOffsetFactor,r.polygonOffsetUnits=e.polygonOffsetUnits,r.blending=e.blending,r.wireframe=e.wireframe??!1,r.userData.isGBufferMaterial=!0,r.visible=p,Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof d&&this.inheritCustomUniformBindings(e,r)),n.set(e,r)}var o;return r.visible&&(e instanceof d?this.updateUniformValues(e,r):this.updateMaterialProperties(e,r)),this.usesSceneColorUniform(r)&&this.initSceneColorUniform(r),this.initLightVolumeUniform(r),r}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof d&&(this.usesShaderUniform(e,ne)||this.usesSceneColorUniform(e)||this.usesShaderUniform(e,ue))}usesShaderUniform(e,t){return e instanceof d&&null!=e.uniforms[t]}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==a.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof E||e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshPhongMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof a.InstancedMesh||e instanceof He)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,i=R(1);e instanceof a.MeshStandardMaterial||e instanceof a.MeshLambertMaterial||e instanceof a.MeshBasicMaterial||e instanceof a.MeshToonMaterial||e instanceof a.MeshPhongMaterial?(i=B("opacity",e.opacity??1),null!=e.map&&(i=i.multiply(H("map",e.map).sample(j.uv).a)),null!=e.alphaMap&&(i=i.multiply(H("alphaMap",e.alphaMap).sample(j.uv).r))):e instanceof E&&(i=e.outputOpacity??R(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=i.lt(e.alphaTest));const n=e instanceof E?e.outputPosition:void 0,r=e instanceof E?e.outputTransform:void 0;t=new E({outputs:[k(0,0),k(0,0),k(0,0)],opacity:i,transform:r,position:null==r?n:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=a.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of _t)delete t.uniforms[e];for(const e of zt)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof E?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=a.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Se(this.scene,s=>{if(Ft(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof h))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.webGlInitialized&&this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}syncExperimentalWebGpuCascades(){const e=this.experimentalWebGpuBackend,t=this.camera,s=this.csm;if(null==e||!(t instanceof c)||null==s)return void e?.setCascadedShadowRanges([]);const i=[];s.getExtendedBreaks(i);const a=Math.max(t.far-t.near,1e-4),n=Math.max(Math.min(t.far,s.maxFar),0)/a;e.setCascadedShadowRanges(i.map(({x:e,y:t})=>({x:e*n,y:t*n})),s.lights)}loop(t,s=!1,i){if(this.requireInitializedBackend("start the render loop"),null!=this.resumeAnimationLoop)return this.running=!0,void this.resumeAnimationLoop();this.running=!0;const r=this.stats,o=r.addPanel(new te.Panel("Calls","#83f","#002")),c=r.addPanel(new te.Panel("Triangles","#c32","#002")),p="webgpu"===this.requestedBackend,d=p?r.addPanel(new te.Panel("WGPU CPU","#2cf","#013")):null,u=p?r.addPanel(new te.Panel("WGPU GPU","#fc2","#310")):null,m=p?r.addPanel(new te.Panel("Extract","#4f8","#021")):null,g=p?r.addPanel(new te.Panel("Upload","#f8c","#301")):null,f=p?r.addPanel(new te.Panel("Graph","#c8f","#201")):null;let b;s&&this.fixStatsStyle(),this.showStats=s;let w=10,M=1e3,v=16,x=16,P=4,y=4,S=16;let T=-1/0;const G=e=>!(e-T<.25)&&(T=e,!0),R=()=>{const e=this.renderer.info.render.calls;e>w&&(w=e,setTimeout(()=>w=10,5e3)),o.update(e,w);const t=this.renderer.info.render.triangles;t>M&&(M=t,setTimeout(()=>M=1e3,5e3)),c.update(t,M)},C=()=>{const e=this.experimentalWebGpuBackend?.getLastFrameProfile();null!=e&&(w=Math.max(w,e.drawCallCount),M=Math.max(M,e.triangleCount),v=Math.max(v,e.cpuTimeMs),P=Math.max(P,e.cpuPhases.extractSceneMs),y=Math.max(y,e.cpuPhases.uploadMs),S=Math.max(S,e.cpuPhases.renderGraphMs),o.update(e.drawCallCount,w),c.update(e.triangleCount,M),d?.update(e.cpuTimeMs,v),m?.update(e.cpuPhases.extractSceneMs,P),g?.update(e.cpuPhases.uploadMs,y),f?.update(e.cpuPhases.renderGraphMs,S),null!=e.gpuTimeMs&&(x=Math.max(x,e.gpuTimeMs),u?.update(e.gpuTimeMs,x)),this.updateWebGpuPassStats(e))};performance.now();a.Ray.prototype.intersectTriangle;this.resizeRender();const B=[],O=[],W=[],U=[];let D=0;const A=new l,k=new l;let I=0;let F=this.paused,j=!1,V=0,L=null,_=this.fpsCapRevision;const z=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(H)},q=()=>{this.running&&(e.activeView=this,j&&(j=!1,requestAnimationFrame(()=>H(V))))};this.wakePausedRenderer=q,this.stopIntersectionObservation?.(),this.isIntersecting=!1,this.stopIntersectionObservation=n(this.container,e=>{this.isIntersecting=e,e&&q()}),this.container.addEventListener("pointerdown",()=>{q()},{capture:!0});const H=s=>{if(j=!1,!this.running)return;const n=this.getActiveRendererCanvas(),o=this.needsPausedRender||this.webGpuPresentationExtensions.size>0;if(i?.(this.paused||!this.isIntersecting),!this.isIntersecting||this.paused&&!o&&n.height>1)return j=!0,V=s,setTimeout(()=>{this.running&&j&&H(s)},500),void(this.paused&&(F=!0));if(n.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return j=!0,void(V=s);this.attachRendererDomElement(),this.resizeRender()}if(!0!==this.options.enableXR){_!==this.fpsCapRevision&&(_=this.fpsCapRevision,L=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=L){const e=s-L;if(e<t)return void z();L=s-e%t}else L=s}else L=s}let l=(s*=.001)-D;D=s,F?(l=.016,F=!1,this.resetUpscalingHistory()):l>.25&&this.resetUpscalingHistory(),this.updateDynamicResolution(l,1e3*s);const c="webgpu"===this.activeBackend;c||(this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight)),this.showStats&&r.begin();const p=!c&&this.detailedStatsEnabled;if(p&&(!b&&navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(b=r.addPanel(new xe(this.renderer.getContext())),this.fixStatsStyle()),b?.startQuery()),c||(this.ssrPass.gpuPanel=p?b:void 0),A.copy(this.camera.matrixWorld),!this.paused){if(l>1){let e=l;for(;e>.05;)t(ft),e-=ft;t(e)}else t(l);this.onLoopCallbacks.forEach(e=>e(l))}this.paused||(this.simulationTime+=l*this.simulationTimeScale);const d=this.simulationTime;if(this.camera?.updateMatrixWorld(),this.updateUnderwaterPostProcessing(),this.applyPostProcessSettings(),k.copy(this.camera.matrixWorld),s-I>.08&&!k.equals(A)&&(this.webGlInitialized&&(this.renderer.shadowMap.needsUpdate=!0),I=s),this.updateCsm(),c){try{const e=this.experimentalWebGpuBackend;if(null==e||!Ke.supportsCamera(this.camera))throw new Error(`Unsupported camera type: ${this.camera?.type??"unknown"}`);this.syncExperimentalWebGpuCascades(),e.setRenderGraphExtensions(this.experimentalWebGpuRenderGraphExtensions),e.setPresentationExtensions(this.webGpuPresentationExtensions),e.render(this.scene,this.camera,d),this.webGpuRuntimeErrorReported=!1,this.detailedStatsEnabled&&G(s)&&C()}catch(e){if(!this.webGpuRuntimeErrorReported){const t=e instanceof Error?e.stack??e.message:String(e);console.error(`[Hology WebGPU] Frame rendering failed; the WebGPU backend remains active. ${t}`),this.webGpuRuntimeErrorReported=!0}}return this.showStats&&r.end(),void z()}let u=!1;B.length=0,O.length=0,W.length=0;for(const e of U)e.visible=!0;U.length=0;const m=vt;Pt.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),m.setFromProjectionMatrix(Pt);let g=!1,f=!1,w=!1,M=!1,v=!1;const x=this.frameGBufferMeshes,P=this.frameGBufferPhaseMasks,y=this.frameUnsupportedGBufferObjects,S=this.frameGBufferExcludedObjects;if(x.length=0,P.length=0,y.length=0,S.clear(),this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof Fe&&(g=!0),e instanceof h&&this.initCustomDepthMaterial(e),(e instanceof h||e instanceof a.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),this.initLightVolumeUniform(e.material),null!=this.scene.environment&&Mt(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(u=!0)),(e instanceof h||e instanceof a.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[ne])&&isObjectInFrustum(e,m)?(this.initDepthUniform(e.material),f=!0):e instanceof Y&&(e.visible=!1,O.push(e)),(e instanceof h||e instanceof a.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[ue]&&isObjectInFrustum(e,m)&&e.material instanceof E&&this.initAoUniform(e.material),e instanceof h||e instanceof a.Sprite){let t=!1;Mt(e,e=>{this.usesSceneColorUniform(e)&&(this.initSceneColorUniform(e),t=!0,M||(M=this.usesShaderUniform(e,me)),w||(w=this.usesShaderUniform(e,ge)))}),t&&(W.push(e),v=!0)}if(e instanceof h&&e.material?.uniforms&&null!=e.material?.uniforms[de])e.material.uniforms[de].value=d;else if(e instanceof h&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[de]&&(t.uniforms[de].value=d);if(S.has(e))for(let t=0;t<e.children.length;t++)S.add(e.children[t]);else if(Ft(e)){y.push(e);for(let t=0;t<e.children.length;t++)S.add(e.children[t])}else e instanceof h&&(x.push(e),P.push(this.getGBufferPhaseMask(e.material)))}),S.clear(),this.phasedRenderPass.enabled=y.length>0,this.bloomPass.enabled=u,!0===this.options.occlusionCulling?.enabled){for(const e of this.occlusionClusters)e.update();this.hideOccluded(U)}this.prepareUpscalingFrame(),this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene(lt.opaque),this.updateRenderedOcclusionClusters(),this.renderer.render(this.queryScene,this.camera),this.aoPass.output=ie.OUTPUT.Off;for(const e of this.postProcessEffects)if(e.pass?.enabled&&this.usesShaderUniform(e.pass.material,ne)){f=!0;break}w&&(this.transmissionCopyQuad.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.renderer.setRenderTarget(this.transmissionColorRenderTarget),this.transmissionCopyQuad.render(this.renderer)),M&&(this.fquadCopySceneColor.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.fquadCopySceneColor.render(this.renderer)),f&&(this.fquadCopySceneDepth.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.renderer.setRenderTarget(this.sceneDepthRenderTarget),this.fquadCopySceneDepth.render(this.renderer)),(f||v)&&this.renderer.setRenderTarget(this.gRenderTarget),W.length,B.forEach(e=>e.visible=!0),O.forEach(e=>e.visible=!0),W.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&g?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(d);try{this.paused&&!o||!this.running||(this.render(l),this.finishUpscalingFrame(),p&&b?.endQuery(),this.detailedStatsEnabled&&G(s)&&R(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}finally{this.finishUpscalingFrame(),o&&(this.needsPausedRender=!1)}this.showStats&&r.end(),this.csm?.update(),z()};this.resumeAnimationLoop=()=>{F=!0,j=!1,!0===this.options.enableXR?this.renderer.setAnimationLoop(H):requestAnimationFrame(H)},!0===this.options.enableXR?this.renderer.setAnimationLoop(H):requestAnimationFrame(H)}collectGBufferRenderables(e,t=this.frameGBufferMeshes,s=this.frameGBufferPhaseMasks,i=this.frameUnsupportedGBufferObjects){t.length=0,s.length=0,i.length=0,Se(e,e=>{if(Ft(e))return i.push(e),!1;e instanceof h&&(t.push(e),s.push(this.getGBufferPhaseMask(e.material)))})}getGBufferPhaseMask(e){if(Array.isArray(e)){let t=0;for(let s=0;s<e.length;s++)t|=this.getGBufferPhaseMask(e[s]);return t}if(null==e||!1===e.visible)return 0;let t=this.gBufferPhaseMaskCache.get(e);if(null!=t)return t;if(!0===e.userData.isGBufferMaterial)return t=1<<lt.opaque|1<<lt.transparent,this.gBufferPhaseMaskCache.set(e,t),t;const s=this.usesShaderUniform(e,ne),i=this.usesSceneColorUniform(e),n=this.usesShaderUniform(e,ue),r=e.transparent&&e.alphaTest<=.01||e.blending===a.AdditiveBlending,o=s||i||n;return t=0,o||r||(t|=1<<lt.opaque),(o||r)&&(t|=1<<lt.transparent),this.gBufferPhaseMaskCache.set(e,t),t}getGBufferMaterialArray(e,t){let s=this.gBufferMaterialArrayCache.get(e);null==s&&(s={opaque:[],transparent:[]},this.gBufferMaterialArrayCache.set(e,s));const i=t===lt.opaque?s.opaque:s.transparent;i.length=e.length;for(let s=0;s<e.length;s++)i[s]=this.createGBufferMaterial(e[s],t,!1);return i}applyGBufferMaterials(e,t=this.frameGBufferMeshes,s=this.frameGBufferPhaseMasks,i=this.frameUnsupportedGBufferObjects){const a=this.appliedGBufferMeshes,n=this.originalGBufferMaterials,r=this.originalGBufferOnBeforeRender,o=this.hiddenGBufferObjects;a.length=0,n.length=0,r.length=0,o.length=0;for(let e=0;e<i.length;e++){const t=i[e];t.visible&&(o.push(t),t.visible=!1)}const l=1<<e;for(let i=0;i<t.length;i++){const h=t[i];if(!h.visible)continue;const c=h.material;if(0!==(s[i]&l)||0!==h.children.length)if(a.push(h),n.push(c),r.push(h.onBeforeRender),0!==(s[i]&l)){if(Array.isArray(c)){const t=this.getGBufferMaterialArray(c,e);h.material=t;for(let e=0;e<t.length;e++)this.initShadowUniform(h,t[e])}else{const t=this.createGBufferMaterial(c,e,e===lt.opaque&&this.isDepthPrepassEligibleMesh(h));h.material=t,this.initShadowUniform(h,t)}this.applyGBufferShadowUniformUpdater(h)}else h.material=dt;else o.push(h),h.visible=!1}}unapplyGBufferMaterials(){const e=this.appliedGBufferMeshes;for(let t=0;t<e.length;t++){const s=e[t];s.material=this.originalGBufferMaterials[t],s.onBeforeRender=this.originalGBufferOnBeforeRender[t]}const t=this.hiddenGBufferObjects;for(let e=0;e<t.length;e++)t[e].visible=!0;e.length=0,this.originalGBufferMaterials.length=0,this.originalGBufferOnBeforeRender.length=0,t.length=0}applyGBufferShadowUniformUpdater(e){const t=e.onBeforeRender;let s=this.gBufferShadowUpdaterCache.get(e);if(null==s){const i=this,a={original:t,wrapper:null};a.wrapper=(t,s,n,r,o,l)=>{a.original.call(e,t,s,n,r,o,l),i.initShadowUniform(e,o)},s=a,this.gBufferShadowUpdaterCache.set(e,s)}s.original=t,e.onBeforeRender=s.wrapper}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof h)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}async initTexturesAsync(e=this.scene){if("webgpu"===this.activeBackend)return;const t=[];e.traverse(e=>{e instanceof h&&(Array.isArray(e.material)?t.push(...e.material):t.push(e.material))});let s=performance.now();for(const e of t)this._initiatedMaterialTextures.has(e)||(this._initMaterialTextures(e),performance.now()-s>=4&&(await new Promise(e=>setTimeout(e,0)),s=performance.now()))}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof d){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof m){if(this._initiatedTextures.has(s.value))continue;this._initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof m){if(this._initiatedTextures.has(s))continue;this._initTexture(s),this._initiatedTextures.add(s)}}_initTexture(e){const t=this.backendHandle??this.experimentalWebGpuBackend;if(null==t){if("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)throw new Error("Cannot initialize a texture before the rendering backend is available.")}else t.initTexture(e)}compileAsync(e=this.scene){const t=this.compileTail.catch(()=>{}).then(async()=>{try{await this.compileSceneAsync(e)}finally{this.compileInProgress=!1}});return this.compileTail=t,t}async compileSceneAsync(e){if("webgpu"===this.requestedBackend&&!this.experimentalWebGpuFailed&&e instanceof a.Scene){this.compileInProgress=!0;try{if(await this.compileExperimentalWebGpu(e))return}finally{this.compileInProgress=!1}}this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0;const t=[],s=[],i=[];this.collectGBufferRenderables(e,t,s,i),this.applyGBufferMaterials(lt.opaque,t,s,i),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(lt.transparent,t,s,i),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopySceneColor.mesh,this.fquadCopySceneColor.camera),this.transmissionColorRenderTarget&&this.transmissionCopyQuad&&(this.renderer.setRenderTarget(this.transmissionColorRenderTarget),await this.renderer.compileAsync(this.transmissionCopyQuad.mesh,this.transmissionCopyQuad.camera)),this.renderer.setRenderTarget(this.sceneDepthRenderTarget),this.renderer.compileAsync(this.fquadCopySceneDepth.mesh,this.fquadCopySceneDepth.camera));const n=this.csm.lights[0]?.shadow.camera;null!=n&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,n),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}createExperimentalWebGpuBackendOptions(){return{smaa:{quality:"high",edgeDetection:"color",threshold:.05,localContrastAdaptation:.35,cornerRounding:.15,sharpness:0},fxaa:!1,taa:!1,nativeUpscaling:!0===this.options.upscaling?.enabled&&"dlss"===Xe(this.options.upscaling)&&{method:"dlss",mode:this.options.upscaling?.dlss?.mode??"quality"},...this.options.webgpuPostProcessing}}async initializeBackend(){if("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed||null!=this.experimentalWebGpuBackend)return;const e=this.experimentalWebGpuBackendAcquisition??(this.experimentalWebGpuBackendAcquisition=(async()=>{const e=await this.acquireWebGpuBackend(this.createExperimentalWebGpuBackendOptions());if(null==e.backend)throw new Error(e.reason);this.experimentalWebGpuBackend=e.backend})());try{await e}finally{this.experimentalWebGpuBackendAcquisition===e&&(this.experimentalWebGpuBackendAcquisition=void 0)}}async compileExperimentalWebGpu(t){if(!(t instanceof a.Scene))throw new Error("Only THREE.Scene roots are supported by the WebGPU renderer.");if(!Ke.supportsCamera(this.camera))throw new Error(`Unsupported camera type: ${this.camera?.type??"unknown"}`);await this.initializeBackend();const s=this.experimentalWebGpuBackend;if(null==s)return!1;const i=e.experimentalWebGpuPresentationView,n=i!==this;n&&i?.disposeExperimentalStaticDrawSets(),this.applyExperimentalWebGpuViewState(n),e.experimentalWebGpuPresentationView=this,this.backendHandle=s,t===this.scene&&this.activateExperimentalStaticDrawSets();try{await s.compile(t,this.camera)}catch(e){throw t===this.scene&&this.disposeExperimentalStaticDrawSets(),e}return this.attachRendererDomElement(),t!==this.scene||this.experimentalWebGpuCapabilityReported||(console.info(Ze(s.inspect(t,this.camera))),this.experimentalWebGpuCapabilityReported=!0),!0}async acquireWebGpuBackend(e){const t=JSON.stringify(e),s=await Ke.probeAvailability();if(!1===s.available)return{backend:null,reason:s.reason};const i=await this.graphicsRuntime.acquire("webgpu-renderer",t,()=>Ke.create(e,s.adapter));return this.experimentalWebGpuBackendPoolKey=t,{backend:i}}releaseExperimentalWebGpuBackend(){const e=this.experimentalWebGpuBackendPoolKey;this.experimentalWebGpuBackendPoolKey=null,null!=e&&this.graphicsRuntime.release("webgpu-renderer",e,e=>e.destroy(),this.options.webGpuBackendIdleRetentionMs??0)}applyExperimentalWebGpuViewState(e){const t=this.experimentalWebGpuBackend;null!=t&&(e&&t.resetViewHistory(),t.setDynamicBatchingEnabled(this.experimentalWebGpuDynamicBatchingEnabled),t.setTiledLightingEnabled(this.experimentalWebGpuTiledLightingEnabled),t.setGTAOOptions({...this.ambientOcclusionSettings.options,intensity:this.ambientOcclusionSettings.blendIntensity,enabled:this.ambientOcclusionSettings.enabled}),t.setDirectionalShadowOptions(this.webgpuDirectionalShadowOptions.enabled,this.webgpuDirectionalShadowOptions.mapSize),t.setDirectionalShadowUpdateOptions(this.webgpuDirectionalShadowUpdateOptions),this.syncWebGpuOutlineState(t),this.syncExperimentalWebGpuPostProcessEffects(),t.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),t.setWorldEnvironment(this.worldEnvironment),t.setSize(this.container.clientWidth,this.container.clientHeight,this.getBasePixelRatio(),this.getEffectiveResolutionScale()))}syncWebGpuOutlineState(e=this.experimentalWebGpuBackend){null!=e&&(e.setEnableOutlines(this.outlinesEnabled),e.setSelectedObjects(this.selectedOutlineObjects),e.setSelectedObjectInstances(this.experimentalWebGpuSelectedObjectInstances))}applyDepthMaterial(){const e=this.depthMaterialCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Ht:t.material=null)})}unapplyDepthMaterial(){this.depthMaterialCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused&&!this.needsPausedRender)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==lt.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}if(e===lt.opaque){const e=this.appliedGBufferMeshes;for(let t=0;t<e.length;t++){const s=e[t],i=this.originalGBufferMaterials[t];!Array.isArray(i)&&!Array.isArray(s.material)&&i instanceof d&&this.updateLightUniformValues(s.material,i)}}this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){if(e.mapping===a.CubeUVReflectionMapping)return e;if(null!=this.backendHandle)return this.backendHandle.getEnvironmentTexture(e);if("webgpu"===this.requestedBackend&&!this.experimentalWebGpuFailed)return e;throw new Error("Cannot prepare an environment texture before the rendering backend is available.")}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.experimentalWebGpuBackend?.setPostProcessState(null),"webgpu"===this.activeBackend?void this.experimentalWebGpuBackend?.setWorldEnvironment(this.worldEnvironment):(this.applyWorldEnvironmentToWebGl(),this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure));!function(e,t=a.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new a.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=yt(e.globalSaturation,1,1,1),e.globalContrast=yt(e.globalContrast,1,1,1),e.globalGamma=yt(e.globalGamma,1,1,1),e.globalGain=yt(e.globalGain,1,1,1),e.globalOffset=yt(e.globalOffset,0,0,0),e.shadowsSaturation=yt(e.shadowsSaturation,1,1,1),e.shadowsContrast=yt(e.shadowsContrast,1,1,1),e.shadowsGamma=yt(e.shadowsGamma,1,1,1),e.shadowsGain=yt(e.shadowsGain,1,1,1),e.shadowsOffset=yt(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=yt(e.midtonesSaturation,1,1,1),e.midtonesContrast=yt(e.midtonesContrast,1,1,1),e.midtonesGamma=yt(e.midtonesGamma,1,1,1),e.midtonesGain=yt(e.midtonesGain,1,1,1),e.midtonesOffset=yt(e.midtonesOffset,0,0,0),e.highlightsSaturation=yt(e.highlightsSaturation,1,1,1),e.highlightsContrast=yt(e.highlightsContrast,1,1,1),e.highlightsGamma=yt(e.highlightsGamma,1,1,1),e.highlightsGain=yt(e.highlightsGain,1,1,1),e.highlightsOffset=yt(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;null!=this.worldEnvironment&&(e.envTexture=this.worldEnvironment.source,e.envIntensity=this.worldEnvironment.intensity);let t,s=!1;if(null==this.camera)return;const i=this.camera.getWorldPosition(Bt);let n=[];for(const r of this.postProcessVolumes){if(!bt(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(i);l>r.blendRadius||(r.blendRadius>0&&(o*=Te(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(n.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=a.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=a.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=a.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=a.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?a.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?a.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?a.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=a.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=a.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=a.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=a.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=a.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===n.length)return this.experimentalWebGpuBackend?.setPostProcessState(null),"webgpu"===this.activeBackend?void this.experimentalWebGpuBackend?.setWorldEnvironment(this.worldEnvironment):(this.applyWorldEnvironmentToWebGl(),this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure));if("webgpu"===this.activeBackend){const t=Gt(Ot,e.temperature,e.temperatureTint),i=e=>[e.x,e.y,e.z],a=n.some(e=>{return void 0!==(t=e.settings).tonemapMapping||void 0!==t.tonemapExposure||void 0!==t.vignetteIntensity||void 0!==t.colorTintIntensity||void 0!==t.temperature||void 0!==t.temperatureTint||void 0!==t.globalSaturation||void 0!==t.globalContrast||void 0!==t.globalGamma||void 0!==t.globalGain||void 0!==t.globalOffset||void 0!==t.shadowsSaturation||void 0!==t.shadowsContrast||void 0!==t.shadowsGamma||void 0!==t.shadowsGain||void 0!==t.shadowsOffset||void 0!==t.shadowsMax||void 0!==t.midtonesSaturation||void 0!==t.midtonesContrast||void 0!==t.midtonesGamma||void 0!==t.midtonesGain||void 0!==t.midtonesOffset||void 0!==t.highlightsSaturation||void 0!==t.highlightsContrast||void 0!==t.highlightsGamma||void 0!==t.highlightsGain||void 0!==t.highlightsOffset||void 0!==t.highlightsMin;var t}),r=n.some(e=>void 0!==e.settings.tonemapMapping||void 0!==e.settings.tonemapExposure);return this.experimentalWebGpuBackend?.setPostProcessState({enabled:a,exposure:r?e.tonemapExposure:1,toneMapping:r?St(e.tonemapMapping):"none",vignetteIntensity:e.vignetteIntensity,whiteBalance:i(t),tint:[e.colorTint.r,e.colorTint.g,e.colorTint.b],tintIntensity:e.colorTintIntensity,saturation:i(e.globalSaturation),contrast:i(e.globalContrast),gamma:i(e.globalGamma),gain:i(e.globalGain),offset:i(e.globalOffset),shadows:{saturation:i(e.shadowsSaturation),contrast:i(e.shadowsContrast),gamma:i(e.shadowsGamma),gain:i(e.shadowsGain),offset:i(e.shadowsOffset)},midtones:{saturation:i(e.midtonesSaturation),contrast:i(e.midtonesContrast),gamma:i(e.midtonesGamma),gain:i(e.midtonesGain),offset:i(e.midtonesOffset)},highlights:{saturation:i(e.highlightsSaturation),contrast:i(e.highlightsContrast),gamma:i(e.highlightsGamma),gain:i(e.highlightsGain),offset:i(e.highlightsOffset)},shadowsMax:e.shadowsMax,highlightsMin:e.highlightsMin,depthFocus:s?e.depthFocus:void 0,depthAperture:s?e.depthAperture:void 0,depthMaxBlur:s?e.depthMaxBlur:void 0}),void this.experimentalWebGpuBackend?.setWorldEnvironment(null!=e.envTexture?{source:e.envTexture,intensity:e.envIntensity}:this.worldEnvironment)}const r=e.vignetteIntensity>Ct,o=(l=e.temperature,h=e.temperatureTint,!Rt(l,6500)||!Rt(h,0));var l,h;const p=(d=e.colorTint,e.colorTintIntensity>Ct&&(!Rt(d.r,1)||!Rt(d.g,1)||!Rt(d.b,1)));var d;const u=!(Tt((m=e).globalSaturation,1,1,1)&&Tt(m.globalContrast,1,1,1)&&Tt(m.globalGamma,1,1,1)&&Tt(m.globalGain,1,1,1)&&Tt(m.globalOffset,0,0,0)&&Tt(m.shadowsSaturation,1,1,1)&&Tt(m.shadowsContrast,1,1,1)&&Tt(m.shadowsGamma,1,1,1)&&Tt(m.shadowsGain,1,1,1)&&Tt(m.shadowsOffset,0,0,0)&&Tt(m.midtonesSaturation,1,1,1)&&Tt(m.midtonesContrast,1,1,1)&&Tt(m.midtonesGamma,1,1,1)&&Tt(m.midtonesGain,1,1,1)&&Tt(m.midtonesOffset,0,0,0)&&Tt(m.highlightsSaturation,1,1,1)&&Tt(m.highlightsContrast,1,1,1)&&Tt(m.highlightsGamma,1,1,1)&&Tt(m.highlightsGain,1,1,1)&&Tt(m.highlightsOffset,0,0,0));var m;const g=o||p||u||r,f=g&&e.tonemapMapping!==a.NoToneMapping,b=null!=t&&e.lutIntensity>Ct;g?(this.renderer.toneMapping=a.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,g?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?Gt(Ot,e.temperature,e.temperatureTint):Ot.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=p,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=u,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=f,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof c?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=b,b&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(!this.webGlInitialized||0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof c?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneDepthRenderTarget.texture,t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass?.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(this.requireInitializedBackend("render"),"webgpu"===this.activeBackend){const e=this.experimentalWebGpuBackend;return void(null!=e&&Ke.supportsCamera(this.camera)&&(this.syncExperimentalWebGpuCascades(),e.setRenderGraphExtensions(this.experimentalWebGpuRenderGraphExtensions),e.setPresentationExtensions(this.webGpuPresentationExtensions),e.render(this.scene,this.camera,this.simulationTime)))}if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof h&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,vt)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ye(this.scene,e=>e instanceof h&&!0===e.material?.userData?.hasBloom)}usesSceneColorUniform(e){return this.usesShaderUniform(e,me)||this.usesShaderUniform(e,ge)}initSceneColorUniform(e){if(e instanceof d&&(null==e.uniforms[ge]||(this.transmissionColorRenderTarget||(this.transmissionColorRenderTarget=new a.WebGLRenderTarget(this.gRenderTarget.width,this.gRenderTarget.height,{type:a.HalfFloatType,colorSpace:a.LinearSRGBColorSpace,minFilter:a.LinearMipmapLinearFilter,magFilter:a.LinearFilter,generateMipmaps:!0,depthBuffer:!1,stencilBuffer:!1}),this.transmissionCopyQuad=new Le(new d({uniforms:{tDiffuse:{value:null}},vertexShader:b.vertexShader,fragmentShader:"uniform sampler2D tDiffuse; varying vec2 vUv; void main() { gl_FragColor = vec4(texture2D(tDiffuse, vUv).rgb, 1.0); }",toneMapped:!1}))),this.transmissionColorRenderTarget.setSize(this.gRenderTarget.width,this.gRenderTarget.height),e.uniforms[ge].value!==this.transmissionColorRenderTarget.texture&&(e.uniforms[ge].value=this.transmissionColorRenderTarget.texture,e.uniformsNeedUpdate=!0),null!=e.uniforms[me])))return null==e.uniforms[me]?(e.uniforms[me]={value:this.sceneColorRenderTarget.texture},void(e.uniformsNeedUpdate=!0)):void(e.uniforms[me].value!==this.sceneColorRenderTarget.texture&&(e.uniforms[me].value=this.sceneColorRenderTarget.texture,e.uniformsNeedUpdate=!0))}initDepthUniform(e){e instanceof d&&(e.uniforms[ne].value=this.sceneDepthRenderTarget.texture,this.camera instanceof c&&(null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.camera.near),null!=e.uniforms[re]&&(e.uniforms[re].value=this.camera.far)))}initNormalUniform(e){e instanceof d&&null!=e.uniforms[he]&&(e.uniforms[he].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof E&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof E&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof d&&null!=e.uniforms[le]&&e.uniforms[le].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[ue].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(!(t instanceof E&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Ie(ke);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new E({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};gt.activeView=null,gt.experimentalWebGpuPresentationView=null,gt=e=t([ae(),s("design:paramtypes",[HTMLElement,Object])],gt);export{gt as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const ft=.05;function bt(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function wt(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}function Mt(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}ie.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};new a.Box3;const vt=new a.Frustum,xt=new a.Box3,Pt=new a.Matrix4;export function isObjectInFrustum(e,t){const s=xt.setFromObject(e);return t.intersectsBox(s)}function yt(e,t,s,i){return null==e?new a.Vector3(t,s,i):e.set(t,s,i)}function St(e){switch(e){case a.LinearToneMapping:return"linear";case a.ReinhardToneMapping:return"reinhard";case a.CineonToneMapping:return"cineon";case a.ACESFilmicToneMapping:return"aces";case a.AgXToneMapping:return"agx";case a.NeutralToneMapping:return"neutral";default:return"none"}}function Tt(e,t,s,i){return null!=e&&Rt(e.x,t)&&Rt(e.y,s)&&Rt(e.z,i)}function Gt(e,t,s){const i=function(e){const t=Te(e,1e3,4e4)/100,s=t<=66?1:Te(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=Te(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:Te(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return Wt.set(s,i,a)}(t),a=1+.2*Te(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}function Rt(e,t,s=Ct){return Math.abs(e-t)<=s}function Et(e,t){return null!=e&&Number.isFinite(e)&&e>0?e:t}const Ct=1e-4,Bt=new a.Vector3,Ot=new a.Vector3(1,1,1),Wt=new a.Vector3(1,1,1);const Ut=new l,Dt=new g;function At(e,t,s=new a.Matrix3){return Dt.copy(e),Dt.x*=-1,Dt.y*=-1,Dt.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(Dt.y*=-1,Dt.z*=-1),s.setFromMatrix4(Ut.makeRotationFromEuler(Dt))}const kt=new E({outputs:[L(0,0,0,0),L(0,0,0,0),k(A("white"),_e(4))],transparent:!0}),It=new a.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});kt.depthWrite=!1;new h(new a.BoxGeometry(4,4,4),It);function Ft(e){return e instanceof a.Sprite||e.isPoints||e.isTransformControls||e.isTransformControlsGizmo||e instanceof h&&jt(e,e.material)}function jt(e,t){return null==t||(Array.isArray(t)?t.some(t=>jt(e,t)):t instanceof a.RawShaderMaterial||t instanceof a.ShaderMaterial&&!(t instanceof E))}class Vt extends qe{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,o=this.scene.matrixAutoUpdate,l=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const c=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let p=0,d=this.toRender;if(d.length=0,this.scene.traverseVisible(e=>{const t=Ft(e);e instanceof h&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(p++,d.push(e))}),p>0)for(const t of d)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=c,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=o,e.shadowMap.autoUpdate=l}}class Lt extends qe{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const _t=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],zt=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],qt=O("fogColor");export class FogNode extends N{constructor(e,t=qt){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(B("fogFar")),r=e.get(B("fogNear")),o=e.get(B("fogDensity")),l=e.get(F(I.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Ht=new a.MeshDepthMaterial({depthPacking:a.RGBADepthPacking});/*
|
|
1
|
+
var e;import{__decorate as t,__metadata as s}from"tslib";import{skyPosition as i}from"./scene/sky.js";import{resolveSDFGISettings as a}from"./rendering/sdfgi-settings.js";import*as n from"three";import{observeElementIntersection as r}from"./rendering/intersection-observer.js";import{Color as o,Material as l,Matrix4 as h,Mesh as c,PerspectiveCamera as p,ShaderChunk as d,ShaderMaterial as u,WebGLRenderTarget as m,Texture as g,Euler as f,MeshStandardMaterial as b}from"three";import{CopyShader as w,EffectComposer as M,FXAAShader as v,GammaCorrectionShader as x,LUTPass as P,RenderPass as S,ShaderPass as y}from"three-stdlib";import{CSMShader as T,CSMUtil as G}from"./csm.js";import{colorToNormal as R,float as E,NodeShaderMaterial as C,standardMaterial as B,uniformFloat as O,uniformVec3 as W,toonMaterial as D,lambertMaterial as U,normalize as A,rgb as k,rgba as I,transformed as F,varying as j,varyingAttributes as V,varyingTransformed as L,vec4 as _,BooleanExpression as z,select as q,ifDefApply as H,uniformSampler2d as N,RgbaNode as $,mix as Q,attributes as J,uniformVec2 as X,min as Y}from"three-shader-graph";import{Reflector as K}from"three-stdlib";import{BokehPass as Z,OutputPass as ee}from"three/examples/jsm/Addons.js";import{CSM as te}from"three/examples/jsm/csm/CSM.js";import se from"three/examples/jsm/libs/stats.module.js";import{FrameStats as ie}from"./utils/three/frame-stats.js";import{GTAOPass as ae}from"three/examples/jsm/postprocessing/GTAOPass.js";import{Service as ne}from"typedi";import{depthUniformName as re,farUniformName as oe,nearUniformName as le,resolutionUniformName as he,sceneNormalUniformName as ce,screenUV as pe,supportsDepthTextureExtension as de}from"./shader-nodes/depth.js";import{elapsedTimeUniformName as ue}from"./shader-nodes/time.js";import{aoMapUniformName as me,sceneMapUniformName as ge,transmissionMapUniformName as fe}from"./shader-nodes/scene-sample.js";import{waterVolumeCameraPositionUniformName as be,waterVolumeEnabledUniformName as we,waterVolumeInverseViewProjectionUniformName as Me,waterVolumeWorldToLocalUniformName as ve}from"./shader-nodes/water-volume.js";import{DepthPass as xe}from"./utils/three/depth-pass.js";import{GPUStatsPanel as Pe}from"./utils/three/gpu-stats-panel.js";import{OutlinePass as Se}from"./utils/three/outline-pass.js";import{findFirstVisibleObject as ye,traverseVisibleStop as Te}from"./utils/three/traverse.js";import{clamp as Ge}from"./utils/math.js";import{ColorPass as Re}from"./rendering/color-pass.js";import{PostProcessEffectPass as Ee,PostProcessEffectRegistration as Ce,postProcessEffectStages as Be,sanitizePostProcessEffectPriority as Oe,sanitizePostProcessEffectStage as We}from"./rendering/post-process-effect.js";import{SSRPass as De}from"./rendering/ssr/SSRPass.js";import{SSRShader as Ue}from"./rendering/ssr/SSRShader.js";import{VolumetricFogPass as Ae}from"./rendering/fog/volumetric-fog-pass.js";import{UnrealBloomPass as ke}from"./rendering/bloom/UnrealBloomPass.js";import{highPrecisionEyeDepth as Ie}from"./shader-nodes/depth.js";import{packDepthToRGBA as Fe}from"three-shader-graph";import{FogVolumeObject as je}from"./rendering/fog/fog-volume-object.js";import{ParallaxStandardMaterial as Ve}from"./shader/builtin/standard-shader.js";import{parallaxOcclusionMapping as Le}from"./shader-nodes/pom.js";import{FullScreenQuad as _e}from"three-stdlib";import{edgeDepthEffect as ze}from"./shader-nodes/effects.js";import{decalDiscard as qe}from"./shader-nodes/decal.js";import{Pass as He}from"three/examples/jsm/Addons.js";import{BatchedMesh2 as Ne}from"./scene/batched-mesh-2.js";import{resolvePostProcessMaterial as $e}from"./shader/post-process-shader.js";import{applyUvTiling as Qe}from"./shader/uv-nodes.js";import{createPlaceholderTexture as Je}from"./utils/three/placeholder-texture.js";import{getTemporalUpscalingJitter as Xe,getUpscalingMethod as Ye,UpscaleOutputPass as Ke}from"./rendering/upscaling-pass.js";import{ExperimentalWebGpuBackend as Ze,formatWebGpuSceneCapabilitySummary as et}from"./rendering/webgpu-experimental-backend.js";import{WebGlBackend as tt}from"./rendering/webgl-backend.js";import{defaultGraphicsRuntime as st}from"./rendering/graphics-runtime.js";export{GraphicsRuntime}from"./rendering/graphics-runtime.js";function it(e){return{enabled:e?.enabled??!0,mapSize:Math.max(1,Math.floor(e?.mapSize??2048)),cascadeCount:Math.max(1,Math.min(4,Math.floor(e?.cascadeCount??4))),maxDistance:Math.max(1,e?.maxDistance??80)}}const at=new n.Vector3,nt=new n.Matrix4,rt=(new n.Matrix4).set(1,0,0,0,0,1,0,0,0,0,.5,.5,0,0,0,1);G.patchSetupMaterial();const ot=document.createElement("div");ot.style.position="absolute",ot.style.left="50%",ot.style.top="50%",ot.style.color="black",ot.style.zIndex="999";(new n.Layers).set(9);new n.MeshBasicMaterial({color:"black"});const lt=new n.MeshDepthMaterial;var ht;lt.depthPacking=n.RGBADepthPacking,lt.blending=n.NoBlending,lt.side=n.DoubleSide,function(e){e[e.opaque=0]="opaque",e[e.transparent=1]="transparent"}(ht||(ht={}));const ct=(()=>{const e=new Uint8Array([255,255,255,255]),t=new n.DataTexture(e,1,1,n.RGBAFormat);return t.needsUpdate=!0,t})(),pt=(()=>{const e=new Uint8Array([0,0,0,255]),t=new n.DataTexture(e,1,1,n.RGBAFormat);return t.needsUpdate=!0,t})(),dt=(()=>{const e=new Uint8Array([128,128,255,255]),t=new n.DataTexture(e,1,1,n.RGBAFormat);return t.needsUpdate=!0,t})(),ut=new C({color:E(0),position:_(E(0))});ut.visible=!1;const mt=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);let gt=0;let ft=e=class{registerStaticSpatialObject(e){if("webgpu"!==this.requestedBackend)return()=>{};this.staticSpatialObjects.get(e)?.handle?.dispose();const t={handle:null,editing:!1};return this.staticSpatialObjects.set(e,t),null!=this.experimentalWebGpuBackend&&(t.handle=this.experimentalWebGpuBackend.registerStaticSpatialObject(e)),()=>{t.handle?.dispose(),this.staticSpatialObjects.get(e)===t&&this.staticSpatialObjects.delete(e)}}refreshStaticSpatialObjects(e,t){for(const[s,i]of this.staticSpatialObjects){let a=s;for(;a&&a!==e;)a=a.parent;a===e&&(void 0!==t?(i.editing=t,i.handle?.setEditing(t)):i.handle?.update())}}get activeBackend(){return this.backendHandle?.kind??null}get canvas(){return this.backendHandle?.canvas??null}get initialized(){return null!=this.backendHandle}get requestedBackend(){return"webgpu"===(e=this.options.backend)||"webgpu-experimental"===e?"webgpu":"webgl";var e}get vfxBackendPreference(){return this.options.webgpuVfx??"cpu"}get webgpuVfxInstancesPerTemplate(){return Math.max(1,Math.floor(this.options.webgpuVfxInstancesPerTemplate??128))}get webgpuVfxTemplateMemoryBudgetBytes(){return 1024*Math.max(1,this.options.webgpuVfxTemplateMemoryBudgetMiB??512)*1024}get webgpuVfxWorldMemoryBudgetBytes(){return 1024*Math.max(1,this.options.webgpuVfxWorldMemoryBudgetMiB??1024)*1024}get webgpuVfxColdTemplateSeconds(){return Math.max(0,this.options.webgpuVfxColdTemplateSeconds??30)}get webGpuDevice(){return this.experimentalWebGpuBackend?.getDevice()??null}get experimentalWebGpuDevice(){return this.webGpuDevice}registerExperimentalStaticDrawSet(e,t,s=!1,i="skip"){if("webgpu"!==this.requestedBackend)return()=>{};const a={root:e,label:t,allowUnsortedLateDraws:s,onUnsupported:i,sourceWasVisible:e.visible,staticDrawSet:null};return this.experimentalStaticDrawSetRegistrations.add(a),this.activateExperimentalStaticDrawSets(),()=>{this.experimentalStaticDrawSetRegistrations.delete(a)&&(a.staticDrawSet?.dispose(),null!=a.staticDrawSet&&(a.root.visible=a.sourceWasVisible),a.staticDrawSet=null)}}registerExperimentalWebGpuRenderGraphExtension(e){return"webgpu"!==this.requestedBackend?()=>{}:(this.experimentalWebGpuRenderGraphExtensions.add(e),()=>{this.experimentalWebGpuRenderGraphExtensions.delete(e)})}get webGlRenderer(){return"webgl"===this.activeBackend?this.renderer:null}registerWebGpuRenderGraphExtension(e){return this.registerExperimentalWebGpuRenderGraphExtension(e)}get fpsCap(){return this._fpsCap}set fpsCap(e){const t=null!=e&&Number.isFinite(e)&&e>0?e:null;t!==this._fpsCap&&(this._fpsCap=t,this.fpsCapRevision++)}createAoblendQuad(){const e=_(1),t=Je(),s=N("tAlphaTest",t).sample(pe).a,i=N("tAO",t).sample(pe),a=q(s.lt(.05),i,Y(_(1,1,1,1),i.addScalar(.4))),r=new C({outputs:[a,e,e],transparent:!0});r.depthWrite=!1,r.depthTest=!1,r.blending=n.MultiplyBlending;return new _e(r)}setPaused(e){this.paused=e}setResolutionScale(e){const t=Ct(e,1);Et(t,this.resolutionScale)||(this.resolutionScale=t,this.dynamicResolutionScale=t,this.dynamicResolutionLastAdjustmentAt=0,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}get currentResolutionScale(){return this.getEffectiveResolutionScale()}get currentRenderPixelRatio(){return this.getRenderPixelRatio()}get currentPresentationPixelRatio(){return this.getPresentationPixelRatio()}getRenderSize(e=new n.Vector2){return e.set(Math.max(1,this.container.clientWidth*this.getRenderPixelRatio()),Math.max(1,this.container.clientHeight*this.getRenderPixelRatio()))}getClientSize(e=new n.Vector2){return e.set(Math.max(1,this.previousClientWith??1),Math.max(1,this.previousClientHeight??1))}isUpscalingEnabled(){return!0===this.options.upscaling?.enabled&&!0!==this.options.enableXR}isTemporalUpscalingEnabled(){if(!this.isUpscalingEnabled())return!1;const e=Ye(this.options.upscaling);return"temporal"===e||"dlss"===e}resetUpscalingHistory(){this.hasPreviousTemporalViewProjection=!1,this.upscaleOutputPass?.resetHistory(),this.experimentalWebGpuBackend?.resetTemporalHistory()}prepareUpscalingFrame(){if(!this.isTemporalUpscalingEnabled()||null==this.upscaleOutputPass)return void this.upscaleOutputPass?.setFrameState(null);this.unjitteredProjectionMatrix.copy(this.camera.projectionMatrix),this.currentUnjitteredViewProjectionMatrix.multiplyMatrices(this.unjitteredProjectionMatrix,this.camera.matrixWorldInverse),this.hasPreviousTemporalViewProjection||(this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.upscaleOutputPass.resetHistory());const e=Ct(this.options.upscaling?.temporal?.jitterScale,1);Xe(this.temporalUpscalingFrameIndex++,this.temporalJitter,e),this.temporalJitterUv.set(this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),this.temporalJitter.y/Math.max(1,this.gRenderTarget.height));const t=2*this.temporalJitter.x/Math.max(1,this.gRenderTarget.width),s=2*this.temporalJitter.y/Math.max(1,this.gRenderTarget.height);this.camera instanceof p?(this.camera.projectionMatrix.elements[8]+=t,this.camera.projectionMatrix.elements[9]+=s):(this.camera.projectionMatrix.elements[12]+=t,this.camera.projectionMatrix.elements[13]+=s),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.projectionJitterApplied=!0,this.currentViewProjectionMatrix.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),this.currentViewProjectionMatrixInverse.copy(this.currentViewProjectionMatrix).invert(),this.temporalUpscalingFrameState.depthTexture=this.gRenderTarget.depthTexture,this.upscaleOutputPass.setFrameState(this.temporalUpscalingFrameState)}finishUpscalingFrame(){this.projectionJitterApplied&&(this.camera.projectionMatrix.copy(this.unjitteredProjectionMatrix),this.camera.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(),this.previousViewProjectionMatrix.copy(this.currentUnjitteredViewProjectionMatrix),this.hasPreviousTemporalViewProjection=!0,this.projectionJitterApplied=!1)}getBasePixelRatio(){const e=Ct(this.maxPixelRatio,1),t=Ct(window.devicePixelRatio,1);return Math.min(e,t)}getBaseResolutionScale(){return Ct(this.resolutionScale,1)}getDynamicResolutionMinScale(){const e=this.getBaseResolutionScale(),t=Ct(this.options.dynamicResolution?.minScale,.7);return Math.min(e,t)}getEffectiveResolutionScale(){const e=this.getBaseResolutionScale();return!0!==this.options.dynamicResolution?.enabled?e:Ge(this.dynamicResolutionScale,this.getDynamicResolutionMinScale(),e)}getRenderPixelRatio(){return this.getBasePixelRatio()*this.getEffectiveResolutionScale()}getPresentationPixelRatio(){const e=this.getBasePixelRatio();return this.isUpscalingEnabled()?e:e*this.getEffectiveResolutionScale()}resetDynamicResolutionAverage(){this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0}updateDynamicResolution(e,t){const s=this.options.dynamicResolution;if(!0!==s?.enabled)return;if(!Number.isFinite(e)||e<=0||e>.25)return void this.resetDynamicResolutionAverage();const i=this.getBaseResolutionScale(),a=this.getDynamicResolutionMinScale(),n=Ge(this.dynamicResolutionScale,a,i);Et(n,this.dynamicResolutionScale)||(this.dynamicResolutionScale=n);const r=Ct(s.targetFps,60),o=1e3/(null!=this.fpsCap?Math.min(r,this.fpsCap):r),l=1e3*e;this.dynamicResolutionFrameTimeAverage=null==this.dynamicResolutionFrameTimeAverage?l:.9*this.dynamicResolutionFrameTimeAverage+.1*l,this.dynamicResolutionFrameSamples++;const h=Math.max(1,Math.floor(Ct(s.sampleFrames,20)));if(this.dynamicResolutionFrameSamples<h)return;const c=Ct(s.decreaseCooldown,500),p=Ct(s.increaseCooldown,2e3),d=Ct(s.decreaseStep,.05),u=Ct(s.increaseStep,.025),m=this.dynamicResolutionFrameTimeAverage;let g=n;m>1.12*o&&n>a&&t-this.dynamicResolutionLastAdjustmentAt>=c?g=Math.max(a,n-d):m<.85*o&&n<i&&t-this.dynamicResolutionLastAdjustmentAt>=p&&(g=Math.min(i,n+u)),Et(g,n)||(this.dynamicResolutionScale=g,this.dynamicResolutionLastAdjustmentAt=t,this.resetDynamicResolutionAverage(),this.resizeRender(!0))}resizeRender(e=!1){if(!this.running)return;const t=this.container.clientWidth,s=this.container.clientHeight,i=this.getRenderPixelRatio(),a=this.getPresentationPixelRatio();if(!e&&this.previousClientWith===t&&this.previousClientHeight===s&&this.previousRenderPixelRatio===i&&this.previousPresentationPixelRatio===a)return;if(0===t||0===s)return;if(this.previousClientWith=t,this.previousClientHeight=s,this.previousRenderPixelRatio=i,this.previousPresentationPixelRatio=a,this.camera instanceof p&&(this.camera.aspect=t/s,this.camera.updateProjectionMatrix()),!this.webGlInitialized)return this.experimentalWebGpuBackend?.setSize(t,s,this.getBasePixelRatio(),this.getEffectiveResolutionScale()),this.resetDynamicResolutionAverage(),void this.resetUpscalingHistory();this.renderer.setPixelRatio(a),this.renderer.setSize(t,s),this.composer.setPixelRatio(i),this.composer.setSize(t,s);const n=t*i,r=s*i;this.dofPass.setSize(n,r),this.fxaaPass.setSize(n,r),this.fxaaPass.uniforms.resolution.value.set(1/n,1/r),this.createGRenderTarget(),this.phasedRenderPass.gRenderTarget=this.gRenderTarget,this.bloomPass.emissiveTexture=this.gRenderTarget.textures[1],this.ssrPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.ssrPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.aoPass.setSize(this.gRenderTarget.width,this.gRenderTarget.height),this.aoPass.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),this.fquadBlendAO.material.uniforms.tAlphaTest.value=this.gRenderTarget.textures[1],this.sceneColorRenderTarget.dispose(),this.sceneDepthRenderTarget.dispose(),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(),this.sceneDepthRenderTarget=this.createSceneDepthRenderTarget(),this.copyPass.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass.material.uniformsNeedUpdate=!0,this.experimentalWebGpuBackend?.setSize(t,s,this.getBasePixelRatio(),this.getEffectiveResolutionScale()),this.resetDynamicResolutionAverage(),this.resetUpscalingHistory()}addPostProcessVolume(e){if(0===this.postProcessVolumes.length)this.postProcessVolumes.push(e);else{let t=!1;for(let s=0;s<this.postProcessVolumes.length;s++)if(e.priority<this.postProcessVolumes[s].priority){this.postProcessVolumes.splice(s,0,e),t=!0;break}t||this.postProcessVolumes.push(e)}}addWaterPostProcessVolume(e){this.waterPostProcessVolumes.includes(e)||this.waterPostProcessVolumes.push(e)}removeWaterPostProcessVolume(e){const t=this.waterPostProcessVolumes.indexOf(e);t>=0&&this.waterPostProcessVolumes.splice(t,1)}updateUnderwaterPostProcessing(){if(null==this.camera)return;const e=this.camera.getWorldPosition(at),t=this.waterPostProcessVolumes.filter(e=>e.underwater.enabled&&wt(e.object)).sort((e,t)=>t.underwater.priority-e.underwater.priority),s=t.find(t=>t.containsWaterPoint(e))??null,i=s??t.find(t=>null!=t.getWaterPostProcessWorldToLocal&&!0===t.isWaterPostProcessRelevant?.(e,t.underwater.transitionDistance))??null;this.activeWaterPostProcessVolume=i;const a=i?.underwater.postProcessMaterial;let n=null;if(!0===a?.isShaderMaterial&&(n=this.underwaterPostProcessEffects.get(a)??null,null==n&&(n=this.addPostProcessEffect(a,{stage:"beforeFog",priority:-100,enabled:!1}),this.underwaterPostProcessEffects.set(a,n))),n!==this.activeUnderwaterPostProcessEffect&&(null!=this.activeUnderwaterPostProcessEffect&&(this.activeUnderwaterPostProcessEffect.enabled=!1),this.activeUnderwaterPostProcessEffect=n),null!=n){n.enabled=null!=i;const t=n.material,a=t.uniforms[ve],r=t.uniforms[be],o=t.uniforms[we],l=t.uniforms[Me];if(null!=l){const e="webgpu"===this.activeBackend?nt.copy(rt).multiply(this.camera.projectionMatrix):this.camera.projectionMatrix;l.value.copy(e).multiply(this.camera.matrixWorldInverse).invert()}null!=i?.getWaterPostProcessWorldToLocal&&null!=a?(i.getWaterPostProcessWorldToLocal(a.value,e),r?.value.copy(e),null!=o&&(o.value=1)):null!=o&&(o.value=null!=s?-1:0)}}removePostProcessVolume(e){const t=this.postProcessVolumes.indexOf(e);t>-1&&this.postProcessVolumes.splice(t,1)}addPostProcessEffect(e,t={}){const s=$e(e),i={id:++this.postProcessEffectId,material:s,pass:this.webGlInitialized?new Ee(s):null,enabled:t.enabled??!0,priority:Oe(t.priority),stage:We(t.stage)};return null!=i.pass&&(i.pass.enabled=i.enabled),this.postProcessEffects.push(i),this.refreshPostProcessEffectPassOrder(),new Ce(this,i)}removePostProcessEffectEntry(e){const t=e,s=this.postProcessEffects.indexOf(t);-1!==s&&(this.postProcessEffects.splice(s,1),null!=t.pass&&(this.composer.removePass(t.pass),t.pass.dispose()),this.syncExperimentalWebGpuPostProcessEffects())}refreshPostProcessEffectPassOrder(){if(this.webGlInitialized){for(const e of this.postProcessEffects)e.pass??(e.pass=new Ee(e.material)),e.pass.enabled=e.enabled,this.composer.removePass(e.pass);for(const e of Be){const t=this.getPostProcessEffectStageAnchorPass(e),s=null!=t?this.composer.passes.indexOf(t):this.composer.passes.length,i=this.postProcessEffects.filter(t=>t.stage===e).sort(Mt);for(let e=0;e<i.length;e++)this.composer.insertPass(i[e].pass,s+e)}this.syncExperimentalWebGpuPostProcessEffects()}else this.syncExperimentalWebGpuPostProcessEffects()}syncExperimentalWebGpuPostProcessEffects(){this.experimentalWebGpuBackend?.setPostProcessEffects(this.postProcessEffects)}getPostProcessEffectStageAnchorPass(e){switch(e){case"beforeFog":return this.volumetricFogPass;case"beforeDepthOfField":return this.dofPass;case"beforeColorAdjustment":return this.colorPass;case"beforeOutline":return this.outlinePass;case"beforeAntiAliasing":return this.fxaaPass;case"beforeLut":return this.lutPass;case"beforeOutput":return this.outputPass}}constructor(t,s={}){this.container=t,this.options=s,this.backendHandle=null,this.webGlBackend=null,this.experimentalWebGpuBackend=null,this.experimentalWebGpuBackendPoolKey=null,this.experimentalWebGpuFailed=!1,this.webGpuRuntimeErrorReported=!1,this.experimentalWebGpuCapabilityReported=!1,this.experimentalWebGpuTiledLightingEnabled=!0,this.experimentalWebGpuDynamicBatchingEnabled=!0,this.ambientOcclusionSettings={enabled:!1,blendIntensity:1,options:{}},this.experimentalWebGpuSelectedObjectInstances=[],this.outlinesEnabled=!1,this.selectedOutlineObjects=[],this.experimentalStaticDrawSetRegistrations=new Set,this.staticSpatialObjects=new Map,this.experimentalWebGpuRenderGraphExtensions=new Set,this.webGpuPresentationExtensions=new Set,this.worldEnvironment=null,this.isIntersecting=!1,this.stopIntersectionObservation=null,this.needsPausedRender=!1,this.wakePausedRenderer=null,this.resumeAnimationLoop=null,this.windowVisible=!0,this.queryScene=new n.Scene,this.running=!0,this.paused=!1,this._fpsCap=null,this.fpsCapRevision=0,this.postProcessVolumes=[],this.waterPostProcessVolumes=[],this.underwaterPostProcessEffects=new Map,this.activeUnderwaterPostProcessEffect=null,this.activeWaterPostProcessVolume=null,this.postProcessSettings={},this.baseToneMapping=n.NoToneMapping,this.baseToneMappingExposure=1,this.csmUpdateInvervals=this.options.shadows?.cascadeUpdateIntervals,this.webgpuDirectionalShadowUpdateOptions={},this.webgpuDirectionalShadowOptions={enabled:!0,mapSize:2048,cascadeCount:4,maxDistance:80},this._id=gt++,this.postProcessEffectId=0,this.postProcessEffects=[],this.occlusionClusters=[],this.simulationTime=0,this.simulationTimeScale=1,this.lightProbeIntensity=2,this.resolutionScale=1,this.maxPixelRatio=mt?1:window.devicePixelRatio,this.dynamicResolutionScale=1,this.dynamicResolutionFrameTimeAverage=null,this.dynamicResolutionFrameSamples=0,this.dynamicResolutionLastAdjustmentAt=0,this.upscaleOutputPass=null,this.unjitteredProjectionMatrix=new h,this.temporalJitter=new n.Vector2,this.temporalJitterUv=new n.Vector2,this.currentUnjitteredViewProjectionMatrix=new h,this.currentViewProjectionMatrix=new h,this.currentViewProjectionMatrixInverse=new h,this.previousViewProjectionMatrix=new h,this.temporalUpscalingFrameState={depthTexture:null,currentJitterUv:this.temporalJitterUv,currentViewProjectionInverse:this.currentViewProjectionMatrixInverse,previousViewProjection:this.previousViewProjectionMatrix},this.temporalUpscalingFrameIndex=0,this.hasPreviousTemporalViewProjection=!1,this.projectionJitterApplied=!1,this.onResize=()=>{if(this.resizeRender(),this.paused)this.needsPausedRender=!0,this.wakePausedRenderer?.();else try{this.render()}catch(e){}},this.onVisiblityChane=()=>{this.windowVisible=!document.hidden},this.isDepthTextureExtensionSupported=!0,this.webGlInitialized=!1,this.sdfgiRuntimeOptions={},this.sceneSDFGISettings=null,this.onLoopCallbacks=[],this.stats=new ie,this.webGpuPassStatsDom=function(){const e=document.createElement("div");return e.dataset.hologyWebGpuPassStats="",e.setAttribute("aria-hidden","true"),e.style.cssText=["position:absolute","top:52px","left:12px","z-index:10000","width:min(520px,calc(100% - 24px))","pointer-events:none","color:white","font:12px/1.2 Arial,Helvetica,sans-serif","text-shadow:0 1px 2px black,0 0 3px black"].join(";"),e}(),this.webGpuResolutionStatsDom=document.createElement("div"),this.webGpuVisibilityStatsDom=function(){const e=document.createElement("div");return e.style.cssText=["margin-bottom:10px","padding-bottom:6px","border-bottom:1px solid rgba(255,255,255,.4)"].join(";"),e.textContent="GPU visibility: awaiting readback",e}(),this.webGpuPassStatsRows=[],this._showStats=!1,this._profilingEnabled=!1,this.gbufferMaterialCache=new Map,this.gbufferDepthPrepassMaterialCache=new Map,this.tbufferMaterialCache=new Map,this.depthPrepassMaterialCache=new WeakMap,this.depthPrepassCachedMaterials=new Map,this.depthPrepassCachedVisibility=[],this.frameGBufferMeshes=[],this.frameGBufferPhaseMasks=[],this.frameUnsupportedGBufferObjects=[],this.frameGBufferExcludedObjects=new Set,this.appliedGBufferMeshes=[],this.originalGBufferMaterials=[],this.originalGBufferOnBeforeRender=[],this.hiddenGBufferObjects=[],this.gBufferPhaseMaskCache=new WeakMap,this.gBufferMaterialArrayCache=new WeakMap,this.gBufferShadowUpdaterCache=new WeakMap,this._initiatedMaterialTextures=new Set,this._initiatedTextures=new Set,this.compileInProgress=!1,this.compileTail=Promise.resolve(),this.depthMaterialCachedMaterials=new Map,this.insetHeight=200,this.insetWidth=this.insetHeight*(16/9),this.insetOffsetY=250,this.insetMargin=10,this.maxInsetCameras=4,this.overlayCameras=new Set,this.prevClearColor=new o,this.hadBloom=!1,this.bloomStoredMaterials={},this.bloomHidden=[],this._customDepthMaterialCache=new WeakMap,this.stats.style=s.statsStyle??"detailed",this.graphicsRuntime=s.graphicsRuntime??st,null!=s.maxPixelRatio&&(this.maxPixelRatio=s.maxPixelRatio),this.resolutionScale=s.resolutionScale??1,this.dynamicResolutionScale=this.getBaseResolutionScale(),this.fpsCap=s.fpsCap,this.experimentalWebGpuDynamicBatchingEnabled=s.webgpuDynamicBatching??!0,this.experimentalWebGpuTiledLightingEnabled=s.webgpuTiledLighting??!0,this.outlinesEnabled=!0===s.enableOutlines,this.webgpuDirectionalShadowOptions=it(s.webgpuDirectionalShadows),"webgpu"===this.requestedBackend&&!0===s.enableXR&&(console.warn("[Hology WebGPU experiment] XR is not supported; using WebGL."),this.experimentalWebGpuFailed=!0),e.activeView=this,this.scene=new n.Scene,this.scene.matrixWorldAutoUpdate=!0,this.scene.updateMatrixWorld=function(e){const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].updateMatrixWorld(e)}.bind(this.scene);const i=t.clientWidth||1,a=t.clientHeight||1,r=new n.PerspectiveCamera(45,i/a,.1,800);r.layers.enable(19),this.camera=r,G.renderingView=this,this.setCamera(r),this.setupEventListeners(),this.setupWebGlPipeline=()=>{if(!this.webGlInitialized)try{this.webGlBackend=tt.initialize({container:this.container,pixelRatio:this.getPresentationPixelRatio(),enableXR:this.options.enableXR??!1,shadows:{enabled:this.options.shadows?.enabled??!0,autoUpdate:this.options.shadows?.autoUpdate??!1}}),this.renderer=this.webGlBackend.renderer,this.outlineEffect=this.webGlBackend.outlineEffect,this.createGRenderTarget(),this.composer=new M(this.renderer,function(e,t){const s=new n.WebGLRenderTarget(Math.max(1,e),Math.max(1,t),{minFilter:n.LinearFilter,magFilter:n.LinearFilter,format:n.RGBAFormat,type:n.HalfFloatType});return s.texture.name="EffectComposer.rt1",s.texture.generateMipmaps=!1,s}(t.clientWidth,t.clientHeight)),this.composer.setPixelRatio(this.getRenderPixelRatio()),this.composer.setSize(t.clientWidth,t.clientHeight),this.baseToneMapping=this.renderer.toneMapping,this.baseToneMappingExposure=this.renderer.toneMappingExposure,this.isDepthTextureExtensionSupported=de(this.renderer),this.aoMaskDepthRenderTarget=e.createAOMaskDepthRenderTarget(this.renderer,this.container,this.getRenderPixelRatio()),this.sceneColorRenderTarget=this.createSceneColorRenderTarget(),this.sceneDepthRenderTarget=this.createSceneDepthRenderTarget(),this.postProcessEffectResolution=new n.Vector2(1,1),this.postProcessEffectUniformState={aoEnabled:!1,aoTexture:null,cameraFar:void 0,cameraNear:void 0,depthTexture:Je(),normalTexture:Je(128,128,255),resolution:this.postProcessEffectResolution,simulationTime:0},this.fquadCopySceneColor=new _e(new u(w)),this.fquadCopySceneDepth=new _e(new C({color:_(N("tDepthTexture",Je()).sample(V.uv).r)})),this.fquadBlendAO=this.createAoblendQuad();const i=new n.Vector2(t.clientWidth,t.clientHeight),a=(new S(this.scene,this.camera),new y(w,"prevtexture"));a.enabled=!0,a.needsSwap=!0,a.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.copyPass=a;const r=new ke(i,1.5,.4,.85);r.threshold=1,r.strength=.9,r.radius=.2,this.bloomPass=r;const o=new ae(this.scene,this.camera,this.gRenderTarget.width,this.gRenderTarget.height,{});o.normalRenderTarget?.dispose(),o.setGBuffer(this.gRenderTarget.depthTexture,this.gRenderTarget.textures[2]),o.output=ae.OUTPUT.Off,o.enabled=!1,this.aoPass=o,o.enabled=this.ambientOcclusionSettings.enabled,o.blendIntensity=this.ambientOcclusionSettings.blendIntensity,o.updateGtaoMaterial(this.ambientOcclusionSettings.options),this.fquadBlendAO.material.uniforms.tAO.value=o.pdRenderTarget.texture,this.fquadBlendAO.material.uniforms.tAlphaTest.value=this.gRenderTarget.textures[1],Ue.fragmentShader=Ue.fragmentShader.replace("if(metalness==0.) return;","if(metalness<0.1) return;");const l=new De({renderer:this.renderer,scene:this.scene,camera:this.camera,width:this.gRenderTarget.width,height:this.gRenderTarget.height,groundReflector:null,selects:[],normalTexture:this.gRenderTarget.textures[2],depthTexture:this.gRenderTarget.depthTexture});l.output=De.OUTPUT.Default,l.blur=!0,l.fresnel=!1,l.distanceAttenuation=!0,l.maxDistance=50,l.selective=!0,l.bouncing=!1,l.opacity=.4,l.enabled=!1!==this.options?.reflection?.enabled,this.ssrPass=l,!1!==this.options.ao?.enabled&&this.composer.addPass(o);const h=new _t((e,t,s,i,a)=>{this.aoPass.enabled&&(this.initResolutionUniform(this.fquadBlendAO.material),this.renderer.setRenderTarget(this.gRenderTarget),this.fquadBlendAO.render(this.renderer),this.renderer.setRenderTarget(null))});this.composer.addPass(h);const p=new _t((e,t,s,i,a)=>{this.renderer.setRenderTarget(this.gRenderTarget),this.renderScene(ht.transparent),this.renderer.setRenderTarget(null)});this.composer.addPass(p),this.composer.addPass(a),this.composer.addPass(l),this.phasedRenderPass=new Lt(this.scene,this.camera,this.gRenderTarget),this.composer.addPass(this.phasedRenderPass),this.composer.addPass(r),r.emissiveTexture=this.gRenderTarget.textures[1],this.renderer.info.autoReset=!1,this.volumetricFogPass=new Ae(i),this.composer.addPass(this.volumetricFogPass),this.volumetricFogPass.enabled=!0,this.dofPass=new Z(this.scene,this.camera,{focus:1,aperture:.025,maxblur:.01}),this.dofPass.enabled=!1,this.composer.addPass(this.dofPass);const d=new Re;this.composer.addPass(d),this.colorPass=d,d.vignetteEnabled=!1,this.outlinePass=new Se(new n.Vector2(t.clientWidth,t.clientHeight),this.scene,this.camera),this.outlinePass.edgeGlow=0,this.outlinePass.edgeThickness=1.5,this.outlinePass.edgeStrength=5,this.outlinePass.clear=!1,this.outlinePass.enabled=!1,this.composer.addPass(this.outlinePass);const m=new y(v);m.uniforms.resolution.value.set(1/t.clientWidth,1/t.clientHeight),this.composer.addPass(m),this.fxaaPass=m,this.fxaaPass.enabled=!1,!0===s.enableOutlines&&this.setEnableOutlines(!0),new y(x).clear=!1,this.fixStatsStyle(),this.lutPass=new P({}),this.lutPass.enabled=!1,this.composer.addPass(this.lutPass);const g=new y(w,"prevtexture");g.enabled=!0,g.needsSwap=!1,g.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[1],g.renderToScreen=!0;const f=this.isUpscalingEnabled()?new Ke(this.options.upscaling):new ee;!function(e){const t=e.material;if(t.dithering=!0,t.fragmentShader.includes("<dithering_fragment>"))return;const s="#include <colorspace_pars_fragment>";if(!t.fragmentShader.includes(s))return;t.fragmentShader=t.fragmentShader.replace(s,`${s}\n #include <common>\n #include <dithering_pars_fragment>`);const i=t.fragmentShader.lastIndexOf("}");i<0||(t.fragmentShader=`${t.fragmentShader.slice(0,i)}\n #include <dithering_fragment>\n${t.fragmentShader.slice(i)}`,t.needsUpdate=!0)}(f),this.outputPass=f,this.upscaleOutputPass=f instanceof Ke?f:null,this.composer.addPass(f);const b=new n.MeshBasicMaterial({colorWrite:!1,depthWrite:!1,depthTest:!0,transparent:!1}),T=new c(new n.BoxGeometry(1,1,1),b);T.renderOrder=1/0,T.name="CLUSTER_BOUNDS_VOLUME",this.webGlInitialized=!0,this.backendHandle=this.webGlBackend,this.attachRendererDomElement(),this.refreshPostProcessEffectPassOrder()}catch(e){throw this.webGlInitialized=!1,this.webGlBackend?.dispose(),this.webGlBackend=null,this.backendHandle=null,e}},("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)&&this.setupWebGlPipeline()}addCluster(e){if(!1===this.options.occlusionCulling?.enabled)return;if(!this.webGlInitialized)return;if(!this.renderer.capabilities.isWebGL2)return;const t=this.renderer.getContext(),s=t.createQuery();if(null==s)return;const i={query:s,visible:!0,awaitingResult:!1,cluster:e,lastTested:-1/0,distance:0,update:()=>{if(i.awaitingResult&&t.getQueryParameter(s,t.QUERY_RESULT_AVAILABLE)){const e=t.getQueryParameter(s,t.QUERY_RESULT);i.visible=!!e,i.awaitingResult=!1}}};e.boundsMesh.onBeforeRender=()=>{i.awaitingResult||t.beginQuery(t.ANY_SAMPLES_PASSED,s)},e.boundsMesh.onAfterRender=()=>{i.awaitingResult||(t.endQuery(t.ANY_SAMPLES_PASSED),i.awaitingResult=!0)},this.occlusionClusters.push(i)}updateRenderedOcclusionClusters(){this.queryScene.clear();const e=performance.now(),t=[];for(const s of this.occlusionClusters){if(s.awaitingResult)continue;const i=s.cluster.bounds.distanceToPoint(this.camera.position);if(s.distance=i,i<10){s.visible=!0,s.lastTested=e;continue}if(i>1e3)continue;const a=e-s.lastTested;if(!(s.visible&&a<4e3)&&((s.visible||!(a<100))&&xt.intersectsBox(s.cluster.bounds)))if(s.visible)t.push(s);else{let e=0;for(;e<t.length&&t[e].distance<s.distance;)e++;t.splice(e,0,s)}}if(t.length<50)for(const s of t)s.lastTested=e,this.queryScene.add(s.cluster.boundsMesh);else{const s=Math.max(Math.floor(Math.random()*t.length-50),0);for(let i=0;i<50;i++){const a=t[s+i];if(null==a)break;a.lastTested=e,this.queryScene.add(a.cluster.boundsMesh)}if(t.length>0){const s=t[0];s.lastTested=e,this.queryScene.add(s.cluster.boundsMesh)}}}fixStatsStyle(){if("simple"===this.statsStyle)return;const e=this.stats.dom;e.style.position="absolute",e.style.display="flex",e.style.flexWrap="nowrap",e.style.width="max-content";const t=e.getElementsByTagName("canvas");for(let e=0;e<t.length;e++){const s=t.item(e);s.style.flex="none",s.style.display="inline-block"}}setEnableOutlines(e){this.outlinesEnabled=e,null!=this.outlinePass&&(this.outlinePass.enabled=e),null!=this.fxaaPass&&(this.fxaaPass.enabled=e),this.syncWebGpuOutlineState()}registerWebGpuPresentationExtension(e){return"webgpu"!==this.requestedBackend?()=>{}:(this.webGpuPresentationExtensions.add(e),this.experimentalWebGpuBackend?.setPresentationExtensions(this.webGpuPresentationExtensions),this.wakePausedRenderer?.(),()=>{this.webGpuPresentationExtensions.delete(e),this.experimentalWebGpuBackend?.setPresentationExtensions(this.webGpuPresentationExtensions)})}get sharedGraphicsRuntime(){return this.graphicsRuntime}createSceneCapture(e,t,s){if(!this.experimentalWebGpuBackend||"webgpu"!==this.activeBackend)throw new Error("Scene capture requires an initialized WebGPU rendering backend.");return this.experimentalWebGpuBackend.createSceneCapture(e,t,s)}setCamera(e){if(this.camera=e,this.resetUpscalingHistory(),this.composer?.passes.forEach(t=>{t instanceof S?t.camera=e:t instanceof Se?t.renderCamera=e:(t instanceof xe||t instanceof ae)&&(t.camera=e)}),this.ssrPass&&(this.ssrPass.camera=e),this.aoPass&&(this.aoPass.camera=e),this.phasedRenderPass&&(this.phasedRenderPass.camera=e),null==this.csm){this.csm=new te({maxFar:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.maxDistance:80,lightFar:250,lightMargin:20,shadowBias:0,cascades:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.cascadeCount:mt?2:3,shadowMapSize:"webgpu"===this.requestedBackend?this.webgpuDirectionalShadowOptions.mapSize:1024*(mt?.5:1),lightDirection:new n.Vector3(.5,-1,-.6).normalize(),lightIntensity:.25*Math.PI,camera:this.camera,parent:this.scene,mode:"practical"});for(const e of this.csm.lights)e.shadow.normalBias="webgpu"===this.requestedBackend?.001:.01;if(null!=this.csmUpdateInvervals){this.csmCascadeLastUpdate=new Array(this.csm.lights.length).fill(0);for(const e of this.csm.lights)e.shadow.autoUpdate=!1}this.csm&&Array.isArray(this.csm.lights),this.csm.fade=!0,d.lights_fragment_begin=T.lights_fragment_begin}else this.csm.camera=this.camera,this.camera;this.csm.updateFrustums()}setSelectedObjects(e){const t=new Map;for(const s of e)t.set(s.uuid,s);for(const s of e)s.traverse(e=>{e.uuid!==s.uuid&&t.has(e.uuid)&&t.delete(e.uuid)});this.selectedOutlineObjects=Array.from(t.values()),this.experimentalWebGpuSelectedObjectInstances=[],this.syncWebGpuOutlineState(),null!=this.outlinePass&&(this.outlinePass.selectedObjects=this.selectedOutlineObjects)}setExperimentalWebGpuTiledLightingEnabled(e){this.experimentalWebGpuTiledLightingEnabled=e,this.experimentalWebGpuBackend?.setTiledLightingEnabled(e)}setExperimentalWebGpuDynamicBatchingEnabled(e){this.experimentalWebGpuDynamicBatchingEnabled=e,this.experimentalWebGpuBackend?.setDynamicBatchingEnabled(e)}setMotionBlurOptions(e){this.experimentalWebGpuBackend?.setMotionBlurOptions(e)}setDirectionalShadowUpdateOptions(e){this.webgpuDirectionalShadowUpdateOptions={...e,cascadeUpdateHz:e.cascadeUpdateHz?.slice()},this.experimentalWebGpuBackend?.setDirectionalShadowUpdateOptions(this.webgpuDirectionalShadowUpdateOptions)}invalidateDirectionalShadows(){this.experimentalWebGpuBackend?.invalidateDirectionalShadows()}setDirectionalShadowOptions(e){if("webgpu"!==this.requestedBackend)return;const t=it(e),s=this.webgpuDirectionalShadowOptions,i=t.mapSize!==s.mapSize||t.cascadeCount!==s.cascadeCount||t.maxDistance!==s.maxDistance;if(i||t.enabled!==s.enabled){if(this.webgpuDirectionalShadowOptions=t,i&&null!=this.csm){const e=this.csm.lights[0],t={lightDirection:this.csm.lightDirection.clone(),lightIntensity:e?.intensity??this.csm.lightIntensity,lightColor:e?.color.clone()??new n.Color(16777215),castShadow:e?.castShadow??!0,userData:{...e?.userData??{}},shadowBias:e?.shadow.bias??this.csm.shadowBias,normalBias:e?.shadow.normalBias??("webgpu"===this.requestedBackend?.001:.01),shadowRadius:e?.shadow.radius??1,shadowIntensity:e?.shadow.intensity??1};this.csm.remove(),this.csm.dispose(),this.csm=null,this.csmCascadeLastUpdate=void 0,this.setCamera(this.camera),this.csm.lightDirection.copy(t.lightDirection),this.csm.lightIntensity=t.lightIntensity,this.csm.shadowBias=t.shadowBias;for(const e of this.csm.lights)e.intensity=t.lightIntensity,e.color.copy(t.lightColor),e.castShadow=t.castShadow,e.userData={...t.userData},e.shadow.bias=t.shadowBias,e.shadow.normalBias=t.normalBias,e.shadow.radius=t.shadowRadius,e.shadow.intensity=t.shadowIntensity;this.csm.update()}this.experimentalWebGpuBackend?.setDirectionalShadowOptions(t.enabled,t.mapSize),this.syncExperimentalWebGpuCascades(),this.experimentalWebGpuBackend?.resetViewHistory()}}setSSROptions(e){this.experimentalWebGpuBackend?.setSSROptions(e)}setGTAOOptions(e){this.experimentalWebGpuBackend?.setGTAOOptions(e)}setSDFGIOptions(e){Object.assign(this.sdfgiRuntimeOptions,e),this.syncSDFGISettings()}setSceneSDFGISettings(e){this.sceneSDFGISettings=null==e?null:{...e},this.syncSDFGISettings(),this.paused&&(this.needsPausedRender=!0,this.wakePausedRenderer?.())}syncSDFGISettings(t=!1){const s=this.experimentalWebGpuBackend;if(null==s)return;const i=e.experimentalWebGpuPresentationView;if(!t&&null!=i&&i!==this&&i.experimentalWebGpuBackend===s)return;const n=null!=s.getSDFGIStats();s.setSDFGIOptions(a(this.options.webgpuPostProcessing?.sdfgi,this.sdfgiRuntimeOptions,this.sceneSDFGISettings)),n||null==s.getSDFGIStats()||(this.disposeExperimentalStaticDrawSets(),this.activateExperimentalStaticDrawSets(),this.syncExperimentalWebGpuCascades())}invalidateSDFGI(){this.experimentalWebGpuBackend?.invalidateSDFGI()}getSDFGIStats(){return this.experimentalWebGpuBackend?.getSDFGIStats()??null}configureAmbientOcclusion(e,t=1,s={}){this.ambientOcclusionSettings={enabled:e,blendIntensity:t,options:s},this.webGlInitialized&&(this.aoPass.enabled=e,this.aoPass.blendIntensity=t,this.aoPass.updateGtaoMaterial(s)),this.experimentalWebGpuBackend?.setGTAOOptions({...s,intensity:t,enabled:e})}invalidateShadows(){this.webGlInitialized&&(this.renderer.shadowMap.needsUpdate=!0)}initTexture(e){this._initTexture(e)}setBaseToneMapping(e,t){this.baseToneMapping=e,this.baseToneMappingExposure=t,this.webGlInitialized&&(this.renderer.toneMapping=e,this.renderer.toneMappingExposure=t)}get supportsWebGlDepthTexture(){return this.webGlInitialized&&this.isDepthTextureExtensionSupported}setAntiAliasingMode(e){this.experimentalWebGpuBackend?.setAntiAliasingMode(e)}setGTAOQuality(e){this.experimentalWebGpuBackend?.setGTAOQuality(e)}setVolumetricFogOptions(e){this.experimentalWebGpuBackend?.setVolumetricFogOptions(e)}setVolumetricFogQuality(e){this.experimentalWebGpuBackend?.setVolumetricFogQuality(e)}pushMotionBlurOverride(e){return this.experimentalWebGpuBackend?.pushMotionBlurOverride(e)??null}setObjectDetailCulling(e,t){e.userData.detailCulling=t}setObjectMotionBlur(e,t,s=1){e.traverse(e=>{e.userData.motionBlurMode=t,e.userData.motionBlurScale=Math.max(0,Math.min(s,8))})}invalidateObjectMotion(e){e.traverse(e=>{e.userData.motionBlurTeleported=!0,this.experimentalWebGpuBackend?.invalidateObjectMotion(e)})}setSelectedObjectInstances(e){this.experimentalWebGpuSelectedObjectInstances=[...e],this.syncWebGpuOutlineState()}static createDepthRenderTarget(e,t,s){const i=Math.max(1,Math.floor(t.clientWidth*s)),a=Math.max(1,Math.floor(t.clientHeight*s)),r=new n.WebGLRenderTarget(i,a);return r.texture.minFilter=n.NearestFilter,r.texture.magFilter=n.NearestFilter,r.texture.generateMipmaps=!1,r.stencilBuffer=!1,r.depthTexture=new n.DepthTexture(i,a),r.depthTexture.type=n.UnsignedShortType,r.depthTexture.minFilter=n.NearestFilter,r.depthTexture.magFilter=n.NearestFilter,r}static createAOMaskDepthRenderTarget(e,t,s=e.getPixelRatio()){const i=Math.max(1,t.clientWidth*s),a=Math.max(1,t.clientHeight*s),r=new n.DepthTexture(i,a);r.type=n.UnsignedInt248Type,r.minFilter=n.NearestFilter,r.magFilter=n.NearestFilter;const o=new n.WebGLRenderTarget(i,a,{type:n.HalfFloatType,depthTexture:r});return o.texture.minFilter=n.NearestFilter,o.texture.magFilter=n.NearestFilter,o.texture.generateMipmaps=!1,o.stencilBuffer=!1,o}createSceneColorRenderTarget(){const e=this.gRenderTarget.width,t=this.gRenderTarget.height,s=new n.WebGLRenderTarget(e,t,{type:n.HalfFloatType,format:n.RGBAFormat,colorSpace:n.SRGBColorSpace,depthBuffer:!1,stencilBuffer:!1});return s.texture.minFilter=n.LinearFilter,s.texture.magFilter=n.LinearFilter,s.texture.generateMipmaps=!1,s}createSceneDepthRenderTarget(){const e=new n.WebGLRenderTarget(this.gRenderTarget.width,this.gRenderTarget.height,{type:n.FloatType,format:n.RedFormat,minFilter:n.NearestFilter,magFilter:n.NearestFilter,depthBuffer:!1,stencilBuffer:!1});return e.texture.generateMipmaps=!1,e}createGRenderTarget(){const e=this.container;null!=this.gRenderTarget&&this.gRenderTarget.dispose();const t=this.getRenderPixelRatio(),s=Math.max(1,e.clientWidth*t),i=Math.max(1,e.clientHeight*t),a=new n.DepthTexture(s,i);a.type=n.UnsignedIntType,a.minFilter=n.NearestFilter,a.magFilter=n.NearestFilter,this.gRenderTarget=new m(s,i,{count:3,samples:this.options?.msaa??0,minFilter:n.NearestFilter,magFilter:n.NearestFilter,type:n.HalfFloatType,format:n.RGBAFormat,depthTexture:a}),this.gRenderTarget.textures[2].type=n.UnsignedByteType,this.gRenderTarget.texture.generateMipmaps=!1,this.gRenderTarget.stencilBuffer=!1}setupEventListeners(){window.addEventListener("resize",this.onResize),window.addEventListener("orientationchange",this.onResize),document.addEventListener("visibilitychange",this.onVisiblityChane)}stop(t=!0){this.stopAnimationLoop(),this.stopIntersectionObservation?.(),this.stopIntersectionObservation=null,this.resumeAnimationLoop=null,this.onLoopCallbacks=[];for(const e of this.staticSpatialObjects.values())e.handle?.dispose();if(this.staticSpatialObjects.clear(),this.disposeExperimentalStaticDrawSets(),e.experimentalWebGpuPresentationView===this&&(e.experimentalWebGpuPresentationView=null),this.wakePausedRenderer=null,this.lightVolume?.shTexture.dispose(),window.removeEventListener("resize",this.onResize),window.removeEventListener("orientationchange",this.onResize),document.removeEventListener("visibilitychange",this.onVisiblityChane),t&&this.webGlInitialized&&this.renderer.dispose(),this.webGlInitialized){this.gRenderTarget.dispose(),this.aoMaskDepthRenderTarget.dispose(),this.sceneColorRenderTarget.dispose(),this.sceneDepthRenderTarget.dispose(),this.transmissionColorRenderTarget?.dispose(),this.transmissionCopyQuad?.material.dispose(),this.transmissionCopyQuad?.dispose();for(const e of this.postProcessEffects)null!=e.pass&&(this.composer.removePass(e.pass),e.pass.dispose());this.volumetricFogPass.dispose(),this.webGlBackend?.dispose(),this.webGlBackend=null}if(this.csm?.dispose(),this.postProcessEffects.length=0,this.detachOwnedDomElements(),this.releaseExperimentalWebGpuBackend(),this.experimentalWebGpuBackend=null,this.backendHandle=null,this.webGlInitialized&&this.occlusionClusters.length>0){const e=this.renderer.getContext();this.occlusionClusters.forEach(t=>{e.deleteQuery(t.query)})}G.clearSceneCache(this.scene)}stopAnimationLoop(){this.running=!1}suspendPresentation(){this.stopAnimationLoop(),this.detachOwnedDomElements()}activatePresentation(){if(e.activeView=this,null!=this.experimentalWebGpuBackend){const t=e.experimentalWebGpuPresentationView,s=t!==this;s&&t?.disposeExperimentalStaticDrawSets(),this.applyExperimentalWebGpuViewState(s),e.experimentalWebGpuPresentationView=this,this.activateExperimentalStaticDrawSets()}this.attachRendererDomElement(),this.resizeRender(!0)}onLoop(e){this.onLoopCallbacks.push(e)}removeOnLoop(e){const t=this.onLoopCallbacks.findIndex(t=>t===e);t>=0&&this.onLoopCallbacks.splice(t,1)}set showStats(e){e&&!this._showStats&&this.stats.reset(),this._showStats=e,this.experimentalWebGpuBackend?.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),this._showStats&&this.stats.dom.parentElement!==this.container?(this.container.appendChild(this.stats.dom),this.fixStatsStyle()):this._showStats||this.stats.dom.parentElement!==this.container||this.container.removeChild(this.stats.dom),this.syncWebGpuPassStatsDom()}get showStats(){return this._showStats}set statsStyle(e){this.stats.style!==e&&(this.stats.style=e,this.fixStatsStyle(),this.experimentalWebGpuBackend?.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),this.syncWebGpuPassStatsDom())}get statsStyle(){return this.stats.style}get detailedStatsEnabled(){return this._showStats&&"detailed"===this.statsStyle}getLastFrameProfile(){return this.experimentalWebGpuBackend?.getLastFrameProfile()??null}setProfilingEnabled(e){this._profilingEnabled=e,this.experimentalWebGpuBackend?.setProfilingEnabled(e||this.detailedStatsEnabled)}attachRendererDomElement(){const t=this.getActiveRendererCanvas();if("webgpu"===this.activeBackend&&null!=this.experimentalWebGpuBackend&&e.experimentalWebGpuPresentationView!==this){const t=e.experimentalWebGpuPresentationView;t?.disposeExperimentalStaticDrawSets(),e.experimentalWebGpuPresentationView=this,this.applyExperimentalWebGpuViewState(!0),this.activateExperimentalStaticDrawSets()}const s=this.webGlInitialized?this.renderer.domElement:null,i=t===s?this.experimentalWebGpuBackend?.canvas:s;i?.parentElement===this.container&&this.container.removeChild(i),t.parentElement===this.container&&t===this.container.firstChild||this.container.insertBefore(t,this.container.firstChild),this._showStats&&this.stats.dom.parentElement!==this.container&&this.container.appendChild(this.stats.dom),this.syncWebGpuPassStatsDom()}detachOwnedDomElements(){this.webGlInitialized&&this.renderer.domElement.parentElement===this.container&&this.container.removeChild(this.renderer.domElement);const e=this.experimentalWebGpuBackend?.canvas;e?.parentElement===this.container&&this.container.removeChild(e),this.stats.dom.parentElement===this.container&&this.container.removeChild(this.stats.dom),this.webGpuPassStatsDom.parentElement===this.container&&this.container.removeChild(this.webGpuPassStatsDom)}syncWebGpuPassStatsDom(){const e=this.detailedStatsEnabled&&"webgpu"===this.requestedBackend;e&&this.webGpuPassStatsDom.parentElement!==this.container?this.container.appendChild(this.webGpuPassStatsDom):e||this.webGpuPassStatsDom.parentElement!==this.container||this.container.removeChild(this.webGpuPassStatsDom)}updateWebGpuPassStats(e){let t=this.webGpuPassStatsRows.length!==e.passes.length;for(let s=0;!t&&s<e.passes.length;s++)t=this.webGpuPassStatsRows[s].name!==e.passes[s].name;t&&(this.webGpuPassStatsDom.replaceChildren(this.webGpuResolutionStatsDom,this.webGpuVisibilityStatsDom),this.webGpuPassStatsRows=e.passes.map(e=>{const t=function(e){const t=document.createElement("div");t.style.cssText=["display:grid","grid-template-columns:minmax(0,1fr) 92px 92px","column-gap:12px","margin-bottom:7px"].join(";");const s=document.createElement("span");s.textContent=e,s.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap";const i=document.createElement("span"),a=document.createElement("span"),n=document.createElement("div");return n.style.cssText=["grid-column:1","width:100%","height:4px","transform-origin:left center","transform:scaleX(0)","margin-top:4px","background:rgba(255,255,255,.78)","box-shadow:0 1px 2px rgba(0,0,0,.9)"].join(";"),t.append(s,i,a,n),{name:e,dom:t,gpu:i,cpu:a,bar:n}}(e.name);return this.webGpuPassStatsDom.appendChild(t.dom),t}));const s=null!=e.renderWidth&&null!=e.renderHeight&&null!=e.presentationWidth&&null!=e.presentationHeight?`Render: ${e.renderWidth} × ${e.renderHeight} | Output: ${e.presentationWidth} × ${e.presentationHeight}`:"";this.webGpuResolutionStatsDom.textContent!==s&&(this.webGpuResolutionStatsDom.textContent=s);const i=e.visibility;let a;if(null==i)a=e.hiZOcclusionCullingActive?"GPU visibility: awaiting readback":"GPU visibility: inactive";else{const e=i.totalInstances>0?i.visibleInstances/i.totalInstances*100:100;a=`GPU visibility: ${i.visibleInstances.toLocaleString()} / ${i.totalInstances.toLocaleString()} visible (${e.toFixed(1)}%), ${i.culledInstances.toLocaleString()} culled | dynamic ${i.dynamicVisibleInstances.toLocaleString()} / ${i.dynamicTotalInstances.toLocaleString()}, static ${i.staticVisibleInstances.toLocaleString()} / ${i.staticTotalInstances.toLocaleString()}`}this.webGpuVisibilityStatsDom.textContent!==a&&(this.webGpuVisibilityStatsDom.textContent=a);let n=.01;for(const t of e.passes)n=Math.max(n,t.gpuTimeMs??t.cpuTimeMs);for(let t=0;t<e.passes.length;t++){const s=e.passes[t],i=this.webGpuPassStatsRows[t],a=null==s.gpuTimeMs?"GPU --":`GPU ${s.gpuTimeMs.toFixed(2)} ms`,r=`CPU ${s.cpuTimeMs.toFixed(2)} ms`;i.gpu.textContent!==a&&(i.gpu.textContent=a),i.cpu.textContent!==r&&(i.cpu.textContent=r);const o=s.gpuTimeMs??s.cpuTimeMs,l=`scaleX(${Math.max(o>0?.02:0,o/n)})`;i.bar.style.transform!==l&&(i.bar.style.transform=l)}}getActiveRendererCanvas(){if(null==this.backendHandle)throw new Error("Rendering backend is not initialized. Await compileAsync() before rendering.");return this.backendHandle.canvas}requireInitializedBackend(e){const t=this.backendHandle;if(null==t)throw new Error(`Cannot ${e}: the rendering backend has not finished initializing.`);return t}activateExperimentalStaticDrawSets(){if("webgpu"!==this.activeBackend||null==this.experimentalWebGpuBackend)return;for(const[e,t]of this.staticSpatialObjects)null==t.handle&&(t.handle=this.experimentalWebGpuBackend.registerStaticSpatialObject(e),t.editing&&t.handle.setEditing(!0));let e=0,t=0,s=0,i=0;for(const a of this.experimentalStaticDrawSetRegistrations)if(null==a.staticDrawSet)try{const i=this.experimentalWebGpuBackend.createStaticDrawSet(a.root,a.label,a.allowUnsortedLateDraws,a.onUnsupported);if(null==i)continue;a.staticDrawSet=i,a.root.visible=!1,e++,t+=i.drawCount,s+=i.instanceCount}catch(e){i++,console.warn(`[Hology WebGPU experiment] Keeping static root "${a.label}" dynamic:`,e)}e>0&&console.info(`[Hology WebGPU experiment] Activated ${e} static draw set${1===e?"":"s"} (${t} draws, ${s} instances).`),i>0&&console.warn(`[Hology WebGPU experiment] ${i} static draw set${1===i?"":"s"} remain dynamic.`)}disposeExperimentalStaticDrawSets(){for(const e of this.experimentalStaticDrawSetRegistrations)e.staticDrawSet?.dispose(),null!=e.staticDrawSet&&(e.root.visible=e.sourceWasVisible),e.staticDrawSet=null}applyEnvMap(e){if(null!=this.scene.environment&&(e instanceof C&&(null==e.envMap||e.userData.useSceneEnv)&&(e.userData.useSceneEnv=!0,null==e.uniforms.envMap&&(e.uniforms.envMap={value:this.scene.environment},e.uniformsNeedUpdate=!0,e.uniforms.envMapRotation={value:kt(this.scene.environmentRotation,this.scene.environment,new n.Matrix3)}),null==e.uniforms.envMapIntensity&&(e.uniforms.envMapIntensity={value:1},e.uniformsNeedUpdate=!0),e.uniforms.envMap.value=this.scene.environment,e.uniforms.envMapIntensity.value=this.scene.environmentIntensity,e.envMap=this.scene.environment),e instanceof C||e instanceof n.MeshStandardMaterial)){const t=this.gbufferMaterialCache.get(e);null==t||this.gbufferMaterialCache.has(t)||this.applyEnvMap(t)}}setWorldEnvironment(e){const t=this.worldEnvironment?.source!==e?.source;this.worldEnvironment=e,null==e?(this.scene.environment=null,this.scene.environmentIntensity=1):("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)&&this.applyWorldEnvironmentToWebGl();const s=this.experimentalWebGpuBackend;if(null==s)return;const i=t&&"webgpu"===this.activeBackend;i&&this.disposeExperimentalStaticDrawSets(),s.setWorldEnvironment(e),i&&this.activateExperimentalStaticDrawSets()}applyWorldEnvironmentToWebGl(){const e=this.worldEnvironment;if(null==e)return this.scene.environment=null,void(this.scene.environmentIntensity=1);this.scene.environment=this.getEnvTexture(e.source),this.scene.environmentIntensity=e.intensity}hideOccluded(e){e.length=0;for(const t of this.occlusionClusters)if(!t.visible){let s=t.cluster.objects.length;for(;s--;){const i=t.cluster.objects[s];i.visible&&(i.visible=!1,e.push(i))}}}setupCsm(e){if(e instanceof n.Mesh||e instanceof n.SkinnedMesh)if(e.material instanceof Array)for(const t of e.material)this.csm.setupMaterial(t);else this.csm.setupMaterial(e.material)}updateMaterialProperties(e,t){(e instanceof n.MeshBasicMaterial||e instanceof b||e instanceof n.MeshLambertMaterial||e instanceof n.MeshPhongMaterial)&&(null!=t.uniforms.color&&t.uniforms.color.value.setFromColor(e.color),null!=t.uniforms.opacity&&(t.uniforms.opacity.value=e.opacity),null!=t.uniforms.map&&(t.uniforms.map.value=e.map),null!=t.uniforms.alphaMap&&(t.uniforms.alphaMap.value=e.alphaMap),null!=t.uniforms.lightMap&&(t.uniforms.lightMap.value=e.lightMap,t.uniforms.lightMapIntensity.value=e.lightMapIntensity),null!=t.uniforms.aoMap&&(t.uniforms.aoMap.value=e.aoMap,t.uniforms.aoMapIntensity.value=e.aoMapIntensity),null!=t.uniforms.alphaTest&&(t.uniforms.alphaTest.value=e.alphaTest)),(e instanceof b||e instanceof n.MeshLambertMaterial||e instanceof n.MeshPhongMaterial)&&(t.uniforms.normalMap&&(t.uniforms.normalMap.value=e.normalMap,t.uniforms.normalScale.value=e.normalScale.x),t.uniforms.emissiveMap&&(t.uniforms.emissiveMap.value=e.emissiveMap,t.uniforms.emissive.value.setFromColor(e.emissive),t.uniforms.emissiveIntensity.value=e.emissiveIntensity)),e instanceof b&&(null!=t.uniforms.roughnessMap&&(t.uniforms.roughnessMap.value=e.roughnessMap),null!=t.uniforms.metalnessMap&&(t.uniforms.metalnessMap.value=e.metalnessMap),null!=t.uniforms.roughness&&(t.uniforms.roughness.value=e.roughness),null!=t.uniforms.metalness&&(t.uniforms.metalness.value=e.metalness)),e instanceof n.MeshPhysicalMaterial&&(t.uniforms.sheenColor&&t.uniforms.sheenColor.value.setFromColor(e.sheenColor).multiplyScalar(e.sheen),t.uniforms.sheenColorMap&&(t.uniforms.sheenColorMap.value=e.sheenColorMap),t.uniforms.sheenRoughness&&(t.uniforms.sheenRoughness.value=e.sheenRoughness),t.uniforms.sheenRoughnessMap&&(t.uniforms.sheenRoughnessMap.value=e.sheenRoughnessMap)),e instanceof Ve&&(t.uniforms.heightMap.value=e.heightMap,t.uniforms.heightScale.value=e.heightScale),this.updateMaterialCommonProperties(e,t)}updateUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s){const t=i[e],a=s[e].value;null!=t&&t.value!==a&&"receiveShadow"!==e&&!1===zt.includes(e)&&(t.value=a)}this.updateMaterialCommonProperties(e,t)}inheritCustomUniformBindings(e,t){const s=e.uniforms,i=t.uniforms;for(const e in s)null==i[e]&&("receiveShadow"===e||zt.includes(e)||qt.includes(e)||(i[e]={value:s[e].value}))}updateMaterialCommonProperties(e,t){t.alphaTest=e.alphaTest,t.side=e.side,t.depthTest=e.depthTest,t.blending=e.blending,t.colorWrite=e.colorWrite,t.premultipliedAlpha=e.premultipliedAlpha,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.visible=e.visible}updateLightUniformValues(e,t){const s=e.uniforms,i=t.uniforms;for(const e of zt){const t=i[e],a=s[e];null!=a&&null!=t&&(t.value=a.value)}}createGBufferMaterial(e,t,s=!1){const a=t===ht.opaque?this.gbufferMaterialCache:this.tbufferMaterialCache;let r=a.get(e);if(!0===e.userData.isGBufferMaterial)return e;if(null==r){const s=this.usesShaderUniform(e,re),l=this.usesSceneColorUniform(e),h=this.usesShaderUniform(e,me),c=e.transparent&&e.alphaTest<=.01||e.blending===n.AdditiveBlending,p=t===ht.opaque?!(s||l||h||c):c||s||l||h;if(!p)return a.set(e,ut),ut;let d=V.uv;if(e instanceof Ve&&null!=e.heightMap){const t=O("heightScale",e.heightScale??1);d=Le(d,N("heightMap",e.heightMap),t)}let m=L.normal;if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial){const t=e.normalMap??dt,s=O("useNormalMap",null!=e.normalMap?1:0),i=O("normalScale",e.normalScale?.x??1),a=R(N("normalMap",t).sample(Qe(d,e.normalMap)),i);m=Q(L.normal,a,s)}else e instanceof C&&null!=e.outputNormal&&(m=e.outputNormal);!0!==e.userData.disableAO&&(m=H("DOUBLE_SIDED",m,e=>q(new z("gl_FrontFacing"),e,e.multiplyScalar(-1))));let g=e.userData?.reflective?E(0):E(1);if(e instanceof n.MeshStandardMaterial){const t=O("roughness",e.roughness??1),s=e.roughnessMap??ct,i=O("useRoughnessMap",null!=e.roughnessMap?1:0),a=N("roughnessMap",s).sample(Qe(d,e.roughnessMap)).g.multiply(t);g=Q(t,a,i)}else e instanceof C&&null!=e.outputRoughness&&(g=e.outputRoughness);let f=null;if((e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial||e instanceof n.MeshBasicMaterial)&&null!=e.lightMap){const t=e.lightMap,s=O("useLightMap",null!=e.lightMap?1:0),i=O("lightMapIntensity",e.lightMapIntensity??1),a=N("lightMap",t).sample(d).rgb.multiplyScalar(i);f=Q(k(0),a,s)}let w=E(0);if(e instanceof n.MeshStandardMaterial){const t=O("metalness",e.metalness??0),s=e.metalnessMap??pt,i=O("useMetalnessMap",null!=e.metalnessMap?1:0),a=N("metalnessMap",s).sample(Qe(d,e.metalnessMap)).b.multiply(t);w=Q(t,a,i)}else e instanceof C&&e.outputRoughness;let M=null,v=E(1);if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial||e instanceof n.MeshBasicMaterial){const t=e.aoMap??ct,s=O("useAoMap",null!=e.aoMap?1:0);v=O("aoMapIntensity",e.aoMapIntensity??1);const i=N("aoMap",t).sample(Qe(d,e.aoMap)).r;M=Q(E(1),i,s)}else e instanceof C&&e.outputRoughness;const x=O("opacity",e.opacity??1);let P=E(1);if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshBasicMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial){if(null!=e.alphaMap){const t=e.alphaMap;P=N("alphaMap",t).sample(Qe(d,e.alphaMap)).r}P=P.multiply(x)}else e instanceof C&&null!=e.outputOpacity&&(P=e.outputOpacity);let S=I(0,1);if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial||e instanceof n.MeshBasicMaterial){let t=W("color",(new n.Vector3).setFromColor(e.color));const s=e.map??ct,i=O("useAlbedoMap",null!=e.map?1:0),a=N("map",s).sample(Qe(d,e.map)),r=a.multiply(I(t,1)),o=I(t,1);S=Q(o,r,i),e.vertexColors&&(S=S.multiply(_(j(J.color.rgb),1)));const l=Q(E(1),a.w,i);P=P.multiply(l)}const y=!0===e.userData.hasBloom;let T=k(0);if(e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial){const t=W("emissive",(new n.Vector3).setFromColor(e.emissive)),s=O("emissiveIntensity",e.emissiveIntensity),i=e.emissiveMap??pt,a=O("useEmissiveMap",null!=e.emissiveMap?1:0),r=N("emissiveMap",i).sample(Qe(d,e.emissiveMap)).rgb.multiply(t);T=Q(t,r,a),T=T.multiplyScalar(s)}else e instanceof C&&null!=e.outputEmissive&&(T=e.outputEmissive);let G=null;if(e instanceof n.MeshPhysicalMaterial&&e.sheen>0&&(G=W("sheenColor",(new n.Vector3).setFromColor(e.sheenColor).multiplyScalar(e.sheen)),e.sheen>0&&null!=e.sheenColorMap)){const t=N("sheenColorMap",e.sheenColorMap).sample(d).rgb;G=G.multiply(t)}let F=null;if(e instanceof n.MeshPhysicalMaterial&&e.sheen>0&&(F=O("sheenRoughness",e.sheenRoughness),e.sheen>0&&null!=e.sheenRoughnessMap)){const t=N("sheenRoughnessMap",e.sheenRoughnessMap).sample(d).r;F=F.multiply(t)}let $=null;if(e instanceof n.MeshPhysicalMaterial&&e.anisotropy>0&&($=O("anisotropy",e.anisotropy),e.anisotropy>0&&null!=e.anisotropyMap)){const t=N("anisotropyMap",e.anisotropyMap).sample(d).r;$=$.multiply(t)}let Y=null;if(e instanceof n.MeshPhysicalMaterial&&e.anisotropy>0){const t=e.anisotropyRotation??0;Y=X("anisotropyDirection",new n.Vector2(Math.cos(t),Math.sin(t)))}const K=O("alphaTest",e.alphaTest);let Z,ee=e.alphaTest>0?P.lt(K):c&&t===ht.opaque?P.lt(.8):null;!0===e.userData.isDecal&&(ee=ee?ee.or(qe):qe),Z=c?_(0,0,0,0):(o=m,A(o).multiplyScalar(.5).addScalar(.5)).rgba(e.userData?.reflective?g:1);const te=e instanceof C?e.outputPosition:void 0,se=e instanceof C?e.outputTransform:void 0;let ie,ae=I("black",1);if(e instanceof C&&null!=e.outputColor)ae=e.outputColor;else if(e instanceof n.MeshStandardMaterial)ae=B({color:S,metalness:w,roughness:g,emissive:T.rgb,normal:m,ambientOcclusion:M,ambientOcclusionIntensity:v,bakedLight:f,sheenColor:G,sheenRoughness:F,anisotropy:$,anisotropyDirection:Y});else if(e instanceof n.MeshLambertMaterial||e instanceof n.MeshPhongMaterial)ae=U({color:S.rgb,ambientOcclusion:M,ambientOcclusionIntensity:v});else if(e instanceof n.MeshBasicMaterial){let e=S.rgb,t=f??k("black");null!=M&&(t=t.multiplyScalar(M.subtract(1).multiply(v).add(1))),e=e.add(t),ae=e.rgba(P)}else e instanceof n.MeshToonMaterial&&(ae=D({color:S,emissive:T.rgb,normal:m,ambientOcclusion:M,ambientOcclusionIntensity:v,bakedLight:f}));(e instanceof C||e instanceof n.MeshStandardMaterial)&&(ie=e.envMap);let ne=!0;(e instanceof b||e instanceof n.MeshBasicMaterial||e instanceof n.ShaderMaterial)&&(ne=e.fog);let oe=I(ae.rgb,P);ne&&(oe=new FogNode(oe)),r=new C({transform:se,position:!0===e.userData.isSky?i:null==se?te:void 0,outputs:[oe,T.rgba(t===ht.opaque?K:y?1:0),Z],opacity:P,outputEncoding:!1,fog:ne,transparent:e.transparent,lights:!0,envMap:ie,alphaTest:e.alphaTest,uniformNodes:e.uniformNodes??{},discard:ee}),e instanceof n.MeshStandardMaterial&&null!=e.envMap&&null!=r.uniforms.envMapIntensity&&(r.uniforms.envMapIntensity.value=e.envMapIntensity),"alphaMap"in e&&null!=e.alphaMap&&(r.alphaMap=e.alphaMap),(e instanceof C||e instanceof n.MeshStandardMaterial)&&this.applyEnvMap(r),e instanceof C&&(Object.assign(r.defines,e.defines),null!=r.uniforms[me]&&(r.uniforms[me].value=this.aoPass.pdRenderTarget.texture,r.defines.USE_SSAO_MAP="")),r.userData.mrtOutputs=3,r.forceSinglePass=e.forceSinglePass,r.side=e.side,r.blending=e.blending,c?(r.depthWrite=!e.transparent,r.depthTest=e.depthTest,r.colorWrite=t===ht.transparent):(r.depthWrite=e.depthWrite,r.depthTest=e.depthTest),r.visible=e.visible,r.alphaTest=e.alphaTest,r.alphaHash=e.alphaHash,r.vertexColors=e.vertexColors,r.premultipliedAlpha=e.premultipliedAlpha,r.toneMapped=e.toneMapped,r.blendAlpha=e.blendAlpha,r.blendColor=e.blendColor,r.polygonOffset=e.polygonOffset,r.polygonOffsetFactor=e.polygonOffsetFactor,r.polygonOffsetUnits=e.polygonOffsetUnits,r.blending=e.blending,r.wireframe=e.wireframe??!1,r.userData.isGBufferMaterial=!0,r.visible=p,Object.assign(r.userData,e.userData),r.visible&&(this.csm.setupMaterial(r),e instanceof u&&this.inheritCustomUniformBindings(e,r)),a.set(e,r)}var o;return r.visible&&(e instanceof u?this.updateUniformValues(e,r):this.updateMaterialProperties(e,r)),this.usesSceneColorUniform(r)&&this.initSceneColorUniform(r),this.initLightVolumeUniform(r),r}isDepthPrepassEnabled(){return!0===this.options.depthPrepass?.enabled}usesSceneFeedbackUniforms(e){return e instanceof u&&(this.usesShaderUniform(e,re)||this.usesSceneColorUniform(e)||this.usesShaderUniform(e,me))}usesShaderUniform(e,t){return e instanceof u&&null!=e.uniforms[t]}isDepthPrepassEligibleMaterial(e){return null!=e&&(!1!==e.visible&&!1!==e.depthTest&&!1!==e.depthWrite&&(!e.transparent&&e.blending!==n.AdditiveBlending&&(!this.usesSceneFeedbackUniforms(e)&&(e instanceof C||e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshPhongMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshBasicMaterial))))}isDepthPrepassEligibleMesh(e){return!!this.isDepthPrepassEnabled()&&((e instanceof n.InstancedMesh||e instanceof Ne)&&(!Array.isArray(e.material)&&this.isDepthPrepassEligibleMaterial(e.material)))}createDepthPrepassMaterial(e){if(!this.isDepthPrepassEligibleMaterial(e))return null;let t=this.depthPrepassMaterialCache.get(e);if(null==t){let s,i=E(1);e instanceof n.MeshStandardMaterial||e instanceof n.MeshLambertMaterial||e instanceof n.MeshBasicMaterial||e instanceof n.MeshToonMaterial||e instanceof n.MeshPhongMaterial?(i=O("opacity",e.opacity??1),null!=e.map&&(i=i.multiply(N("map",e.map).sample(V.uv).a)),null!=e.alphaMap&&(i=i.multiply(N("alphaMap",e.alphaMap).sample(V.uv).r))):e instanceof C&&(i=e.outputOpacity??E(1)),null!=e.alphaTest&&e.alphaTest>0&&(s=i.lt(e.alphaTest));const a=e instanceof C?e.outputPosition:void 0,r=e instanceof C?e.outputTransform:void 0;t=new C({outputs:[I(0,0),I(0,0),I(0,0)],opacity:i,transform:r,position:null==r?a:void 0,discard:s,lights:!1,fog:!1,outputEncoding:!1,transparent:!1,alphaTest:e.alphaTest}),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=n.NoBlending,t.lights=!1,t.fog=!1,t.toneMapped=!1,t.side=e.side,t.alphaTest=e.alphaTest,t.visible=e.visible,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t.onBeforeCompile=()=>{},t.customProgramCacheKey=()=>`depth-prepass:${e.id}:${e.version}:${e.alphaTest}:${e.side}`;for(const e of zt)delete t.uniforms[e];for(const e of qt)delete t.uniforms[e];delete t.uniforms.receiveShadow,this.depthPrepassMaterialCache.set(e,t)}return e instanceof C?this.updateUniformValues(e,t):this.updateMaterialProperties(e,t),t.depthWrite=!0,t.depthTest=e.depthTest,t.colorWrite=!1,t.transparent=!1,t.blending=n.NoBlending,t.visible=e.visible,t.alphaTest=e.alphaTest,t.side=e.side,t.polygonOffset=e.polygonOffset,t.polygonOffsetFactor=e.polygonOffsetFactor,t.polygonOffsetUnits=e.polygonOffsetUnits,t}applyDepthPrepassMaterials(){const e=this.depthPrepassCachedMaterials,t=this.depthPrepassCachedVisibility;e.clear(),t.length=0,Te(this.scene,s=>{if(jt(s))return t.push(s),s.visible=!1,!1;if(!(s instanceof c))return;if(e.set(s,s.material),!this.isDepthPrepassEligibleMesh(s))return t.push(s),void(s.visible=!1);const i=this.createDepthPrepassMaterial(s.material);if(null==i)return t.push(s),void(s.visible=!1);s.material=i,s.visible=!0})}unapplyDepthPrepassMaterials(){this.depthPrepassCachedMaterials.forEach((e,t)=>{t.material=e}),this.depthPrepassCachedVisibility.forEach(e=>{e.visible=!0})}renderDepthPrepass(){if(!this.isDepthPrepassEnabled())return;this.applyDepthPrepassMaterials();const e=this.scene.matrixWorldAutoUpdate,t=this.scene.matrixAutoUpdate,s=this.renderer.shadowMap.autoUpdate;this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1,this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clearDepth();try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Depth prepass render failed",e)}this.unapplyDepthPrepassMaterials(),this.renderer.shadowMap.autoUpdate=s,this.scene.matrixWorldAutoUpdate=e,this.scene.matrixAutoUpdate=t}updateCsm(){const e=this.csmUpdateInvervals;if(this.webGlInitialized&&this.renderer.shadowMap.autoUpdate&&null!=this.csmCascadeLastUpdate&&Array.isArray(e)){const t=performance.now();for(let s=0;s<this.csm.lights.length;++s){const i=e[s]??e[e.length-1]??16;(t-this.csmCascadeLastUpdate[s]>=i||0===s)&&this.csm.lights[s].shadow&&(this.csm.lights[s].shadow.needsUpdate=!0,this.csmCascadeLastUpdate[s]=t)}}this.csm.update()}syncExperimentalWebGpuCascades(){const e=this.experimentalWebGpuBackend,t=this.camera,s=this.csm;if(null==e||!(t instanceof p)||null==s)return void e?.setCascadedShadowRanges([]);const i=[];s.getExtendedBreaks(i);const a=Math.max(t.far-t.near,1e-4),n=Math.max(Math.min(t.far,s.maxFar),0)/a;e.setCascadedShadowRanges(i.map(({x:e,y:t})=>({x:e*n,y:t*n})),s.lights)}loop(t,s=!1,i){if(this.requireInitializedBackend("start the render loop"),null!=this.resumeAnimationLoop)return this.running=!0,void this.resumeAnimationLoop();this.running=!0;const a=this.stats,o=a.addPanel(new se.Panel("Calls","#83f","#002")),l=a.addPanel(new se.Panel("Triangles","#c32","#002")),p="webgpu"===this.requestedBackend,d=p?a.addPanel(new se.Panel("WGPU CPU","#2cf","#013")):null,u=p?a.addPanel(new se.Panel("WGPU GPU","#fc2","#310")):null,m=p?a.addPanel(new se.Panel("Extract","#4f8","#021")):null,g=p?a.addPanel(new se.Panel("Upload","#f8c","#301")):null,f=p?a.addPanel(new se.Panel("Graph","#c8f","#201")):null;let b;s&&this.fixStatsStyle(),this.showStats=s;let w=10,M=1e3,v=16,x=16,P=4,S=4,y=16;let T=-1/0;const G=e=>!(e-T<.25)&&(T=e,!0),R=()=>{const e=this.renderer.info.render.calls;e>w&&(w=e,setTimeout(()=>w=10,5e3)),o.update(e,w);const t=this.renderer.info.render.triangles;t>M&&(M=t,setTimeout(()=>M=1e3,5e3)),l.update(t,M)},E=()=>{const e=this.experimentalWebGpuBackend?.getLastFrameProfile();null!=e&&(w=Math.max(w,e.drawCallCount),M=Math.max(M,e.triangleCount),v=Math.max(v,e.cpuTimeMs),P=Math.max(P,e.cpuPhases.extractSceneMs),S=Math.max(S,e.cpuPhases.uploadMs),y=Math.max(y,e.cpuPhases.renderGraphMs),o.update(e.drawCallCount,w),l.update(e.triangleCount,M),d?.update(e.cpuTimeMs,v),m?.update(e.cpuPhases.extractSceneMs,P),g?.update(e.cpuPhases.uploadMs,S),f?.update(e.cpuPhases.renderGraphMs,y),null!=e.gpuTimeMs&&(x=Math.max(x,e.gpuTimeMs),u?.update(e.gpuTimeMs,x)),this.updateWebGpuPassStats(e))};performance.now();n.Ray.prototype.intersectTriangle;this.resizeRender();const B=[],O=[],W=[],D=[];let U=0;const A=new h,k=new h;let I=0;let F=this.paused,j=!1,V=0,L=null,_=this.fpsCapRevision;const z=()=>{this.running&&!0!==this.options.enableXR&&requestAnimationFrame(H)},q=()=>{this.running&&(e.activeView=this,j&&(j=!1,requestAnimationFrame(()=>H(V))))};this.wakePausedRenderer=q,this.stopIntersectionObservation?.(),this.isIntersecting=!1,this.stopIntersectionObservation=r(this.container,e=>{this.isIntersecting=e,e&&q()}),this.container.addEventListener("pointerdown",()=>{q()},{capture:!0});const H=s=>{if(j=!1,!this.running)return;const r=this.getActiveRendererCanvas(),o=this.needsPausedRender||this.webGpuPresentationExtensions.size>0;if(i?.(this.paused||!this.isIntersecting),!this.isIntersecting||this.paused&&!o&&r.height>1)return j=!0,V=s,setTimeout(()=>{this.running&&j&&H(s)},500),void(this.paused&&(F=!0));if(r.parentElement!==this.container){if(e.activeView!==this&&null!==e.activeView)return j=!0,void(V=s);this.attachRendererDomElement(),this.resizeRender()}if(!0!==this.options.enableXR){_!==this.fpsCapRevision&&(_=this.fpsCapRevision,L=null);const e=this.fpsCap;if(null!=e){const t=1e3/e;if(null!=L){const e=s-L;if(e<t)return void z();L=s-e%t}else L=s}else L=s}let l=(s*=.001)-U;U=s,F?(l=.016,F=!1,this.resetUpscalingHistory()):l>.25&&this.resetUpscalingHistory(),this.updateDynamicResolution(l,1e3*s);const h="webgpu"===this.activeBackend;h||(this.renderer.autoClear=!1,this.renderer.setViewport(0,0,this.container.clientWidth,this.container.clientHeight)),this.showStats&&a.begin();const p=!h&&this.detailedStatsEnabled;if(p&&(!b&&navigator.userAgent.includes("Chrome")&&navigator.userAgent.includes("HologyEngine")&&(b=a.addPanel(new Pe(this.renderer.getContext())),this.fixStatsStyle()),b?.startQuery()),h||(this.ssrPass.gpuPanel=p?b:void 0),A.copy(this.camera.matrixWorld),!this.paused){if(l>1){let e=l;for(;e>.05;)t(bt),e-=bt;t(e)}else t(l);this.onLoopCallbacks.forEach(e=>e(l))}this.paused||(this.simulationTime+=l*this.simulationTimeScale);const d=this.simulationTime;if(this.camera?.updateMatrixWorld(),this.updateUnderwaterPostProcessing(),this.applyPostProcessSettings(),k.copy(this.camera.matrixWorld),s-I>.08&&!k.equals(A)&&(this.webGlInitialized&&(this.renderer.shadowMap.needsUpdate=!0),I=s),this.updateCsm(),h){try{const e=this.experimentalWebGpuBackend;if(null==e||!Ze.supportsCamera(this.camera))throw new Error(`Unsupported camera type: ${this.camera?.type??"unknown"}`);this.syncExperimentalWebGpuCascades(),e.setRenderGraphExtensions(this.experimentalWebGpuRenderGraphExtensions),e.setPresentationExtensions(this.webGpuPresentationExtensions),e.render(this.scene,this.camera,d),this.webGpuRuntimeErrorReported=!1,this.detailedStatsEnabled&&G(s)&&E()}catch(e){if(!this.webGpuRuntimeErrorReported){const t=e instanceof Error?e.stack??e.message:String(e);console.error(`[Hology WebGPU] Frame rendering failed; the WebGPU backend remains active. ${t}`),this.webGpuRuntimeErrorReported=!0}}return this.showStats&&a.end(),void z()}let u=!1;B.length=0,O.length=0,W.length=0;for(const e of D)e.visible=!0;D.length=0;const m=xt;St.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),m.setFromProjectionMatrix(St);let g=!1,f=!1,w=!1,M=!1,v=!1;const x=this.frameGBufferMeshes,P=this.frameGBufferPhaseMasks,S=this.frameUnsupportedGBufferObjects,y=this.frameGBufferExcludedObjects;if(x.length=0,P.length=0,S.length=0,y.clear(),this.scene.traverseVisible(e=>{if(this.setupCsm(e),this.outlineEffect.apply(e),e instanceof je&&(g=!0),e instanceof c&&this.initCustomDepthMaterial(e),(e instanceof c||e instanceof n.Sprite)&&(this.initResolutionUniform(e.material),this.initNormalUniform(e.material),this.initShadowUniform(e,e.material),this.initLightVolumeUniform(e.material),null!=this.scene.environment&&vt(e,e=>this.applyEnvMap(e)),!0===e.material?.userData?.hasBloom&&(u=!0)),(e instanceof c||e instanceof n.Sprite)&&e.visible&&(e.material?.userData?.water||e.material?.uniforms&&null!=e.material?.uniforms[re])&&isObjectInFrustum(e,m)?(this.initDepthUniform(e.material),f=!0):e instanceof K&&(e.visible=!1,O.push(e)),(e instanceof c||e instanceof n.Sprite)&&e.material?.uniforms&&null!=e.material?.uniforms[me]&&isObjectInFrustum(e,m)&&e.material instanceof C&&this.initAoUniform(e.material),e instanceof c||e instanceof n.Sprite){let t=!1;vt(e,e=>{this.usesSceneColorUniform(e)&&(this.initSceneColorUniform(e),t=!0,M||(M=this.usesShaderUniform(e,ge)),w||(w=this.usesShaderUniform(e,fe)))}),t&&(W.push(e),v=!0)}if(e instanceof c&&e.material?.uniforms&&null!=e.material?.uniforms[ue])e.material.uniforms[ue].value=d;else if(e instanceof c&&Array.isArray(e.material))for(const t of e.material)t.uniforms&&null!=t.uniforms[ue]&&(t.uniforms[ue].value=d);if(y.has(e))for(let t=0;t<e.children.length;t++)y.add(e.children[t]);else if(jt(e)){S.push(e);for(let t=0;t<e.children.length;t++)y.add(e.children[t])}else e instanceof c&&(x.push(e),P.push(this.getGBufferPhaseMask(e.material)))}),y.clear(),this.phasedRenderPass.enabled=S.length>0,this.bloomPass.enabled=u,!0===this.options.occlusionCulling?.enabled){for(const e of this.occlusionClusters)e.update();this.hideOccluded(D)}this.prepareUpscalingFrame(),this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.clear(),this.renderDepthPrepass(),this.renderScene(ht.opaque),this.updateRenderedOcclusionClusters(),this.renderer.render(this.queryScene,this.camera),this.aoPass.output=ae.OUTPUT.Off;for(const e of this.postProcessEffects)if(e.pass?.enabled&&this.usesShaderUniform(e.pass.material,re)){f=!0;break}w&&(this.transmissionCopyQuad.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.renderer.setRenderTarget(this.transmissionColorRenderTarget),this.transmissionCopyQuad.render(this.renderer)),M&&(this.fquadCopySceneColor.material.uniforms.tDiffuse.value=this.gRenderTarget.textures[0],this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.fquadCopySceneColor.render(this.renderer)),f&&(this.fquadCopySceneDepth.material.uniforms.tDepthTexture.value=this.gRenderTarget.depthTexture,this.renderer.setRenderTarget(this.sceneDepthRenderTarget),this.fquadCopySceneDepth.render(this.renderer)),(f||v)&&this.renderer.setRenderTarget(this.gRenderTarget),W.length,B.forEach(e=>e.visible=!0),O.forEach(e=>e.visible=!0),W.forEach(e=>e.visible=!0),this.aoPass.enabled,this.ssrPass&&(this.ssrPass.elapsedTime=s),this.volumetricFogPass&&g?(this.volumetricFogPass.update(this.camera,this.gRenderTarget,this.csm,this.scene),this.volumetricFogPass.enabled=!0):this.volumetricFogPass&&(this.volumetricFogPass.enabled=!1),this.updatePostProcessEffectUniforms(d);try{this.paused&&!o||!this.running||(this.render(l),this.finishUpscalingFrame(),p&&b?.endQuery(),this.detailedStatsEnabled&&G(s)&&R(),this.renderer.info.reset(),this.renderOverlay())}catch(e){console.warn(e)}finally{this.finishUpscalingFrame(),o&&(this.needsPausedRender=!1)}this.showStats&&a.end(),this.csm?.update(),z()};this.resumeAnimationLoop=()=>{F=!0,j=!1,!0===this.options.enableXR?this.renderer.setAnimationLoop(H):requestAnimationFrame(H)},!0===this.options.enableXR?this.renderer.setAnimationLoop(H):requestAnimationFrame(H)}collectGBufferRenderables(e,t=this.frameGBufferMeshes,s=this.frameGBufferPhaseMasks,i=this.frameUnsupportedGBufferObjects){t.length=0,s.length=0,i.length=0,Te(e,e=>{if(jt(e))return i.push(e),!1;e instanceof c&&(t.push(e),s.push(this.getGBufferPhaseMask(e.material)))})}getGBufferPhaseMask(e){if(Array.isArray(e)){let t=0;for(let s=0;s<e.length;s++)t|=this.getGBufferPhaseMask(e[s]);return t}if(null==e||!1===e.visible)return 0;let t=this.gBufferPhaseMaskCache.get(e);if(null!=t)return t;if(!0===e.userData.isGBufferMaterial)return t=1<<ht.opaque|1<<ht.transparent,this.gBufferPhaseMaskCache.set(e,t),t;const s=this.usesShaderUniform(e,re),i=this.usesSceneColorUniform(e),a=this.usesShaderUniform(e,me),r=e.transparent&&e.alphaTest<=.01||e.blending===n.AdditiveBlending,o=s||i||a;return t=0,o||r||(t|=1<<ht.opaque),(o||r)&&(t|=1<<ht.transparent),this.gBufferPhaseMaskCache.set(e,t),t}getGBufferMaterialArray(e,t){let s=this.gBufferMaterialArrayCache.get(e);null==s&&(s={opaque:[],transparent:[]},this.gBufferMaterialArrayCache.set(e,s));const i=t===ht.opaque?s.opaque:s.transparent;i.length=e.length;for(let s=0;s<e.length;s++)i[s]=this.createGBufferMaterial(e[s],t,!1);return i}applyGBufferMaterials(e,t=this.frameGBufferMeshes,s=this.frameGBufferPhaseMasks,i=this.frameUnsupportedGBufferObjects){const a=this.appliedGBufferMeshes,n=this.originalGBufferMaterials,r=this.originalGBufferOnBeforeRender,o=this.hiddenGBufferObjects;a.length=0,n.length=0,r.length=0,o.length=0;for(let e=0;e<i.length;e++){const t=i[e];t.visible&&(o.push(t),t.visible=!1)}const l=1<<e;for(let i=0;i<t.length;i++){const h=t[i];if(!h.visible)continue;const c=h.material;if(0!==(s[i]&l)||0!==h.children.length)if(a.push(h),n.push(c),r.push(h.onBeforeRender),0!==(s[i]&l)){if(Array.isArray(c)){const t=this.getGBufferMaterialArray(c,e);h.material=t;for(let e=0;e<t.length;e++)this.initShadowUniform(h,t[e])}else{const t=this.createGBufferMaterial(c,e,e===ht.opaque&&this.isDepthPrepassEligibleMesh(h));h.material=t,this.initShadowUniform(h,t)}this.applyGBufferShadowUniformUpdater(h)}else h.material=ut;else o.push(h),h.visible=!1}}unapplyGBufferMaterials(){const e=this.appliedGBufferMeshes;for(let t=0;t<e.length;t++){const s=e[t];s.material=this.originalGBufferMaterials[t],s.onBeforeRender=this.originalGBufferOnBeforeRender[t]}const t=this.hiddenGBufferObjects;for(let e=0;e<t.length;e++)t[e].visible=!0;e.length=0,this.originalGBufferMaterials.length=0,this.originalGBufferOnBeforeRender.length=0,t.length=0}applyGBufferShadowUniformUpdater(e){const t=e.onBeforeRender;let s=this.gBufferShadowUpdaterCache.get(e);if(null==s){const i=this,a={original:t,wrapper:null};a.wrapper=(t,s,n,r,o,l)=>{a.original.call(e,t,s,n,r,o,l),i.initShadowUniform(e,o)},s=a,this.gBufferShadowUpdaterCache.set(e,s)}s.original=t,e.onBeforeRender=s.wrapper}initTextures(e=this.scene){e.traverse(e=>{if(e instanceof c)if(Array.isArray(e.material))for(let t=0;t<e.material.length;t++)this._initMaterialTextures(e.material[t]);else this._initMaterialTextures(e.material)})}async initTexturesAsync(e=this.scene){if("webgpu"===this.activeBackend)return;const t=[];e.traverse(e=>{e instanceof c&&(Array.isArray(e.material)?t.push(...e.material):t.push(e.material))});let s=performance.now();for(const e of t)this._initiatedMaterialTextures.has(e)||(this._initMaterialTextures(e),performance.now()-s>=4&&(await new Promise(e=>setTimeout(e,0)),s=performance.now()))}_initMaterialTextures(e){if(!this._initiatedMaterialTextures.has(e))if(this._initiatedMaterialTextures.add(e),e instanceof u){for(const[t,s]of Object.entries(e.uniforms))if(s.value instanceof g){if(this._initiatedTextures.has(s.value))continue;this._initTexture(s.value),this._initiatedTextures.add(s.value)}}else for(const[t,s]of Object.entries(e))if(s instanceof g){if(this._initiatedTextures.has(s))continue;this._initTexture(s),this._initiatedTextures.add(s)}}_initTexture(e){const t=this.backendHandle??this.experimentalWebGpuBackend;if(null==t){if("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed)throw new Error("Cannot initialize a texture before the rendering backend is available.")}else t.initTexture(e)}compileAsync(e=this.scene){const t=this.compileTail.catch(()=>{}).then(async()=>{try{await this.compileSceneAsync(e)}finally{this.compileInProgress=!1}});return this.compileTail=t,t}async compileSceneAsync(e){if("webgpu"===this.requestedBackend&&!this.experimentalWebGpuFailed&&e instanceof n.Scene){this.compileInProgress=!0;try{if(await this.compileExperimentalWebGpu(e))return}finally{this.compileInProgress=!1}}this.renderer.setRenderTarget(this.gRenderTarget),this.compileInProgress=!0;const t=[],s=[],i=[];this.collectGBufferRenderables(e,t,s,i),this.applyGBufferMaterials(ht.opaque,t,s,i),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.applyGBufferMaterials(ht.transparent,t,s,i),await this.renderer.compileAsync(e,this.camera),this.unapplyGBufferMaterials(),this.isDepthPrepassEnabled()&&(this.renderer.setRenderTarget(this.gRenderTarget),this.applyDepthPrepassMaterials(),await this.renderer.compileAsync(e,this.camera),this.unapplyDepthPrepassMaterials()),e===this.scene&&(this.renderer.setRenderTarget(this.gRenderTarget),this.renderer.compileAsync(this.fquadBlendAO.mesh,this.fquadBlendAO.camera),this.renderer.setRenderTarget(this.sceneColorRenderTarget),this.renderer.compileAsync(this.fquadCopySceneColor.mesh,this.fquadCopySceneColor.camera),this.transmissionColorRenderTarget&&this.transmissionCopyQuad&&(this.renderer.setRenderTarget(this.transmissionColorRenderTarget),await this.renderer.compileAsync(this.transmissionCopyQuad.mesh,this.transmissionCopyQuad.camera)),this.renderer.setRenderTarget(this.sceneDepthRenderTarget),this.renderer.compileAsync(this.fquadCopySceneDepth.mesh,this.fquadCopySceneDepth.camera));const a=this.csm.lights[0]?.shadow.camera;null!=a&&(this.applyDepthMaterial(),await this.renderer.compileAsync(e,a),this.unapplyDepthMaterial()),this.compileInProgress=!1,this.renderer.setRenderTarget(null)}createExperimentalWebGpuBackendOptions(){return{smaa:{quality:"high",edgeDetection:"color",threshold:.05,localContrastAdaptation:.35,cornerRounding:.15,sharpness:0},fxaa:!1,taa:!1,nativeUpscaling:!0===this.options.upscaling?.enabled&&"dlss"===Ye(this.options.upscaling)&&{method:"dlss",mode:this.options.upscaling?.dlss?.mode??"quality"},...this.options.webgpuPostProcessing}}async initializeBackend(){if("webgpu"!==this.requestedBackend||this.experimentalWebGpuFailed||null!=this.experimentalWebGpuBackend)return;const e=this.experimentalWebGpuBackendAcquisition??(this.experimentalWebGpuBackendAcquisition=(async()=>{const e=await this.acquireWebGpuBackend(this.createExperimentalWebGpuBackendOptions());if(null==e.backend)throw new Error(e.reason);this.experimentalWebGpuBackend=e.backend,this.syncSDFGISettings()})());try{await e}finally{this.experimentalWebGpuBackendAcquisition===e&&(this.experimentalWebGpuBackendAcquisition=void 0)}}async compileExperimentalWebGpu(t){if(!(t instanceof n.Scene))throw new Error("Only THREE.Scene roots are supported by the WebGPU renderer.");if(!Ze.supportsCamera(this.camera))throw new Error(`Unsupported camera type: ${this.camera?.type??"unknown"}`);await this.initializeBackend();const s=this.experimentalWebGpuBackend;if(null==s)return!1;const i=e.experimentalWebGpuPresentationView,a=i!==this;a&&i?.disposeExperimentalStaticDrawSets(),this.applyExperimentalWebGpuViewState(a),e.experimentalWebGpuPresentationView=this,this.backendHandle=s,t===this.scene&&this.activateExperimentalStaticDrawSets();try{await s.compile(t,this.camera)}catch(e){throw t===this.scene&&this.disposeExperimentalStaticDrawSets(),e}return this.attachRendererDomElement(),t!==this.scene||this.experimentalWebGpuCapabilityReported||(console.info(et(s.inspect(t,this.camera))),this.experimentalWebGpuCapabilityReported=!0),!0}async acquireWebGpuBackend(e){const t=JSON.stringify(e),s=await Ze.probeAvailability();if(!1===s.available)return{backend:null,reason:s.reason};const i=await this.graphicsRuntime.acquire("webgpu-renderer",t,()=>Ze.create(e,s.adapter));return this.experimentalWebGpuBackendPoolKey=t,{backend:i}}releaseExperimentalWebGpuBackend(){const e=this.experimentalWebGpuBackendPoolKey;this.experimentalWebGpuBackendPoolKey=null,null!=e&&this.graphicsRuntime.release("webgpu-renderer",e,e=>e.destroy(),this.options.webGpuBackendIdleRetentionMs??0)}applyExperimentalWebGpuViewState(e){const t=this.experimentalWebGpuBackend;null!=t&&(e&&t.resetViewHistory(),this.syncSDFGISettings(!0),t.setDynamicBatchingEnabled(this.experimentalWebGpuDynamicBatchingEnabled),t.setTiledLightingEnabled(this.experimentalWebGpuTiledLightingEnabled),t.setGTAOOptions({...this.ambientOcclusionSettings.options,intensity:this.ambientOcclusionSettings.blendIntensity,enabled:this.ambientOcclusionSettings.enabled}),t.setDirectionalShadowOptions(this.webgpuDirectionalShadowOptions.enabled,this.webgpuDirectionalShadowOptions.mapSize),t.setDirectionalShadowUpdateOptions(this.webgpuDirectionalShadowUpdateOptions),this.syncWebGpuOutlineState(t),this.syncExperimentalWebGpuPostProcessEffects(),t.setProfilingEnabled(this.detailedStatsEnabled||this._profilingEnabled),t.setWorldEnvironment(this.worldEnvironment),t.setSize(this.container.clientWidth,this.container.clientHeight,this.getBasePixelRatio(),this.getEffectiveResolutionScale()))}syncWebGpuOutlineState(e=this.experimentalWebGpuBackend){null!=e&&(e.setEnableOutlines(this.outlinesEnabled),e.setSelectedObjects(this.selectedOutlineObjects),e.setSelectedObjectInstances(this.experimentalWebGpuSelectedObjectInstances))}applyDepthMaterial(){const e=this.depthMaterialCachedMaterials;e.clear(),this.scene.traverse(t=>{(t.isMesh||t.isPoints||t.isLine||t.isSprite)&&(this.initCustomDepthMaterial(t),e.set(t,t.material),t.castShadow?null!=t.customDepthMaterial?t.material=t.customDepthMaterial:t.material=Nt:t.material=null)})}unapplyDepthMaterial(){this.depthMaterialCachedMaterials.forEach((e,t)=>{t.material=e})}renderScene(e){if(!this.running||this.paused&&!this.needsPausedRender)return;if(this.compileInProgress)return void console.error("Compile in progress, skipping render");this.applyGBufferMaterials(e);const t=this.scene.matrixWorldAutoUpdate,s=this.scene.matrixAutoUpdate,i=this.renderer.shadowMap.autoUpdate;e!==ht.opaque&&(this.renderer.shadowMap.autoUpdate=!1,this.scene.matrixWorldAutoUpdate=!1,this.scene.matrixAutoUpdate=!1);try{this.renderer.render(this.scene,this.camera)}catch(e){console.warn("Render failed",e)}if(e===ht.opaque){const e=this.appliedGBufferMeshes;for(let t=0;t<e.length;t++){const s=e[t],i=this.originalGBufferMaterials[t];!Array.isArray(i)&&!Array.isArray(s.material)&&i instanceof u&&this.updateLightUniformValues(s.material,i)}}this.unapplyGBufferMaterials(),this.renderer.shadowMap.autoUpdate=i,this.scene.matrixWorldAutoUpdate=t,this.scene.matrixAutoUpdate=s}getEnvTexture(e){if(e.mapping===n.CubeUVReflectionMapping)return e;if(null!=this.backendHandle)return this.backendHandle.getEnvironmentTexture(e);if("webgpu"===this.requestedBackend&&!this.experimentalWebGpuFailed)return e;throw new Error("Cannot prepare an environment texture before the rendering backend is available.")}applyPostProcessSettings(){if(0==this.postProcessVolumes.length)return this.experimentalWebGpuBackend?.setPostProcessState(null),"webgpu"===this.activeBackend?void this.experimentalWebGpuBackend?.setWorldEnvironment(this.worldEnvironment):(this.applyWorldEnvironmentToWebGl(),this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure));!function(e,t=n.NoToneMapping,s=1){e.tonemapMapping=t,e.tonemapExposure=s,e.envIntensity=1,e.envTexture=void 0,e.vignetteIntensity=0,e.colorTint=e.colorTint??new n.Color("white"),e.colorTint.set("white"),e.colorTintIntensity=0,e.depthFocus=void 0,e.depthAperture=void 0,e.depthMaxBlur=void 0,e.temperature=6500,e.temperatureTint=0,e.globalSaturation=yt(e.globalSaturation,1,1,1),e.globalContrast=yt(e.globalContrast,1,1,1),e.globalGamma=yt(e.globalGamma,1,1,1),e.globalGain=yt(e.globalGain,1,1,1),e.globalOffset=yt(e.globalOffset,0,0,0),e.shadowsSaturation=yt(e.shadowsSaturation,1,1,1),e.shadowsContrast=yt(e.shadowsContrast,1,1,1),e.shadowsGamma=yt(e.shadowsGamma,1,1,1),e.shadowsGain=yt(e.shadowsGain,1,1,1),e.shadowsOffset=yt(e.shadowsOffset,0,0,0),e.shadowsMax=.09,e.midtonesSaturation=yt(e.midtonesSaturation,1,1,1),e.midtonesContrast=yt(e.midtonesContrast,1,1,1),e.midtonesGamma=yt(e.midtonesGamma,1,1,1),e.midtonesGain=yt(e.midtonesGain,1,1,1),e.midtonesOffset=yt(e.midtonesOffset,0,0,0),e.highlightsSaturation=yt(e.highlightsSaturation,1,1,1),e.highlightsContrast=yt(e.highlightsContrast,1,1,1),e.highlightsGamma=yt(e.highlightsGamma,1,1,1),e.highlightsGain=yt(e.highlightsGain,1,1,1),e.highlightsOffset=yt(e.highlightsOffset,0,0,0),e.highlightsMin=.5,e.lut=void 0,e.lutIntensity=0}(this.postProcessSettings,this.baseToneMapping,this.baseToneMappingExposure);const e=this.postProcessSettings;null!=this.worldEnvironment&&(e.envTexture=this.worldEnvironment.source,e.envIntensity=this.worldEnvironment.intensity);let t,s=!1;if(null==this.camera)return;const i=this.camera.getWorldPosition(Ot);let a=[];for(const r of this.postProcessVolumes){if(!wt(r.object))continue;let o=r.blendWeight??1;const l=r.distanceToPoint(i);l>r.blendRadius||(r.blendRadius>0&&(o*=Ge(1-l/r.blendRadius,0,1)),o>1&&(o=1),o>0&&(a.push(r),void 0!==r.settings.tonemapMapping&&(e.tonemapMapping=r.settings.tonemapMapping),void 0!==r.settings.tonemapExposure&&(e.tonemapExposure=n.MathUtils.lerp(e.tonemapExposure,r.settings.tonemapExposure,o)),void 0!==r.settings.envTexture&&(e.envTexture=r.settings.envTexture),void 0!==r.settings.envIntensity&&(e.envIntensity=n.MathUtils.lerp(e.envIntensity,r.settings.envIntensity,o)),void 0!==r.settings.vignetteIntensity&&(e.vignetteIntensity=n.MathUtils.lerp(e.vignetteIntensity,r.settings.vignetteIntensity,o)),void 0!==r.settings.colorTint&&void 0!==r.settings.colorTintIntensity&&r.settings.colorTintIntensity>0&&(e.colorTint=e.colorTint.lerp(r.settings.colorTint,o)),void 0!==r.settings.colorTintIntensity&&(e.colorTintIntensity=n.MathUtils.lerp(e.colorTintIntensity,r.settings.colorTintIntensity,o)),void 0!==r.settings.depthFocus&&(s=!0,e.depthFocus=void 0!==e.depthFocus?n.MathUtils.lerp(e.depthFocus,r.settings.depthFocus,o):r.settings.depthFocus),void 0!==r.settings.depthAperture&&(s=!0,e.depthAperture=void 0!==e.depthAperture?n.MathUtils.lerp(e.depthAperture,r.settings.depthAperture,o):r.settings.depthAperture),void 0!==r.settings.depthMaxBlur&&(s=!0,e.depthMaxBlur=void 0!==e.depthMaxBlur?n.MathUtils.lerp(e.depthMaxBlur,r.settings.depthMaxBlur,o):r.settings.depthMaxBlur),void 0!==r.settings.temperature&&(e.temperature=n.MathUtils.lerp(e.temperature,r.settings.temperature,o)),void 0!==r.settings.temperatureTint&&(e.temperatureTint=n.MathUtils.lerp(e.temperatureTint,r.settings.temperatureTint,o)),void 0!==r.settings.globalSaturation&&e.globalSaturation.lerp(r.settings.globalSaturation,o),void 0!==r.settings.globalContrast&&e.globalContrast.lerp(r.settings.globalContrast,o),void 0!==r.settings.globalGamma&&e.globalGamma.lerp(r.settings.globalGamma,o),void 0!==r.settings.globalGain&&e.globalGain.lerp(r.settings.globalGain,o),void 0!==r.settings.globalOffset&&e.globalOffset.lerp(r.settings.globalOffset,o),void 0!==r.settings.shadowsSaturation&&e.shadowsSaturation.lerp(r.settings.shadowsSaturation,o),void 0!==r.settings.shadowsContrast&&e.shadowsContrast.lerp(r.settings.shadowsContrast,o),void 0!==r.settings.shadowsGamma&&e.shadowsGamma.lerp(r.settings.shadowsGamma,o),void 0!==r.settings.shadowsGain&&e.shadowsGain.lerp(r.settings.shadowsGain,o),void 0!==r.settings.shadowsOffset&&e.shadowsOffset.lerp(r.settings.shadowsOffset,o),void 0!==r.settings.shadowsMax&&(e.shadowsMax=n.MathUtils.lerp(e.shadowsMax,r.settings.shadowsMax,o)),void 0!==r.settings.midtonesSaturation&&e.midtonesSaturation.lerp(r.settings.midtonesSaturation,o),void 0!==r.settings.midtonesContrast&&e.midtonesContrast.lerp(r.settings.midtonesContrast,o),void 0!==r.settings.midtonesGamma&&e.midtonesGamma.lerp(r.settings.midtonesGamma,o),void 0!==r.settings.midtonesGain&&e.midtonesGain.lerp(r.settings.midtonesGain,o),void 0!==r.settings.midtonesOffset&&e.midtonesOffset.lerp(r.settings.midtonesOffset,o),void 0!==r.settings.highlightsSaturation&&e.highlightsSaturation.lerp(r.settings.highlightsSaturation,o),void 0!==r.settings.highlightsContrast&&e.highlightsContrast.lerp(r.settings.highlightsContrast,o),void 0!==r.settings.highlightsGamma&&e.highlightsGamma.lerp(r.settings.highlightsGamma,o),void 0!==r.settings.highlightsGain&&e.highlightsGain.lerp(r.settings.highlightsGain,o),void 0!==r.settings.highlightsOffset&&e.highlightsOffset.lerp(r.settings.highlightsOffset,o),void 0!==r.settings.highlightsMin&&(e.highlightsMin=n.MathUtils.lerp(e.highlightsMin,r.settings.highlightsMin,o)),void 0!==r.settings.lut&&(t=r.settings.lut),void 0!==r.settings.lutIntensity&&(e.lutIntensity=n.MathUtils.lerp(e.lutIntensity,r.settings.lutIntensity,o))))}if(0===a.length)return this.experimentalWebGpuBackend?.setPostProcessState(null),"webgpu"===this.activeBackend?void this.experimentalWebGpuBackend?.setWorldEnvironment(this.worldEnvironment):(this.applyWorldEnvironmentToWebGl(),this.lutPass.enabled=!1,this.colorPass.enabled=!1,this.dofPass.enabled=!1,this.renderer.toneMapping=this.baseToneMapping,void(this.renderer.toneMappingExposure=this.baseToneMappingExposure));if("webgpu"===this.activeBackend){const t=Rt(Wt,e.temperature,e.temperatureTint),i=e=>[e.x,e.y,e.z],n=a.some(e=>{return void 0!==(t=e.settings).tonemapMapping||void 0!==t.tonemapExposure||void 0!==t.vignetteIntensity||void 0!==t.colorTintIntensity||void 0!==t.temperature||void 0!==t.temperatureTint||void 0!==t.globalSaturation||void 0!==t.globalContrast||void 0!==t.globalGamma||void 0!==t.globalGain||void 0!==t.globalOffset||void 0!==t.shadowsSaturation||void 0!==t.shadowsContrast||void 0!==t.shadowsGamma||void 0!==t.shadowsGain||void 0!==t.shadowsOffset||void 0!==t.shadowsMax||void 0!==t.midtonesSaturation||void 0!==t.midtonesContrast||void 0!==t.midtonesGamma||void 0!==t.midtonesGain||void 0!==t.midtonesOffset||void 0!==t.highlightsSaturation||void 0!==t.highlightsContrast||void 0!==t.highlightsGamma||void 0!==t.highlightsGain||void 0!==t.highlightsOffset||void 0!==t.highlightsMin;var t}),r=a.some(e=>void 0!==e.settings.tonemapMapping||void 0!==e.settings.tonemapExposure);return this.experimentalWebGpuBackend?.setPostProcessState({enabled:n,exposure:r?e.tonemapExposure:1,toneMapping:r?Tt(e.tonemapMapping):"none",vignetteIntensity:e.vignetteIntensity,whiteBalance:i(t),tint:[e.colorTint.r,e.colorTint.g,e.colorTint.b],tintIntensity:e.colorTintIntensity,saturation:i(e.globalSaturation),contrast:i(e.globalContrast),gamma:i(e.globalGamma),gain:i(e.globalGain),offset:i(e.globalOffset),shadows:{saturation:i(e.shadowsSaturation),contrast:i(e.shadowsContrast),gamma:i(e.shadowsGamma),gain:i(e.shadowsGain),offset:i(e.shadowsOffset)},midtones:{saturation:i(e.midtonesSaturation),contrast:i(e.midtonesContrast),gamma:i(e.midtonesGamma),gain:i(e.midtonesGain),offset:i(e.midtonesOffset)},highlights:{saturation:i(e.highlightsSaturation),contrast:i(e.highlightsContrast),gamma:i(e.highlightsGamma),gain:i(e.highlightsGain),offset:i(e.highlightsOffset)},shadowsMax:e.shadowsMax,highlightsMin:e.highlightsMin,depthFocus:s?e.depthFocus:void 0,depthAperture:s?e.depthAperture:void 0,depthMaxBlur:s?e.depthMaxBlur:void 0}),void this.experimentalWebGpuBackend?.setWorldEnvironment(null!=e.envTexture?{source:e.envTexture,intensity:e.envIntensity}:this.worldEnvironment)}const r=e.vignetteIntensity>Bt,o=(l=e.temperature,h=e.temperatureTint,!Et(l,6500)||!Et(h,0));var l,h;const c=(d=e.colorTint,e.colorTintIntensity>Bt&&(!Et(d.r,1)||!Et(d.g,1)||!Et(d.b,1)));var d;const u=!(Gt((m=e).globalSaturation,1,1,1)&&Gt(m.globalContrast,1,1,1)&&Gt(m.globalGamma,1,1,1)&&Gt(m.globalGain,1,1,1)&&Gt(m.globalOffset,0,0,0)&&Gt(m.shadowsSaturation,1,1,1)&&Gt(m.shadowsContrast,1,1,1)&&Gt(m.shadowsGamma,1,1,1)&&Gt(m.shadowsGain,1,1,1)&&Gt(m.shadowsOffset,0,0,0)&&Gt(m.midtonesSaturation,1,1,1)&&Gt(m.midtonesContrast,1,1,1)&&Gt(m.midtonesGamma,1,1,1)&&Gt(m.midtonesGain,1,1,1)&&Gt(m.midtonesOffset,0,0,0)&&Gt(m.highlightsSaturation,1,1,1)&&Gt(m.highlightsContrast,1,1,1)&&Gt(m.highlightsGamma,1,1,1)&&Gt(m.highlightsGain,1,1,1)&&Gt(m.highlightsOffset,0,0,0));var m;const g=o||c||u||r,f=g&&e.tonemapMapping!==n.NoToneMapping,b=null!=t&&e.lutIntensity>Bt;g?(this.renderer.toneMapping=n.NoToneMapping,this.renderer.toneMappingExposure=1):(this.renderer.toneMapping=e.tonemapMapping,this.renderer.toneMappingExposure=e.tonemapExposure),null!=e.envTexture&&(this.scene.environment=this.getEnvTexture(e.envTexture)),this.scene.environmentIntensity=e.envIntensity,g?(this.colorPass.whiteBalanceEnabled=o,this.colorPass.whiteBalanceScale=o?Rt(Wt,e.temperature,e.temperatureTint):Wt.set(1,1,1),this.colorPass.vignetteIntensity=e.vignetteIntensity,this.colorPass.vignetteEnabled=r,this.colorPass.colorTintEnabled=c,this.colorPass.colorTint=e.colorTint,this.colorPass.colorTintIntensity=e.colorTintIntensity,this.colorPass.colorGradingEnabled=u,this.colorPass.toneMapping=e.tonemapMapping,this.colorPass.toneMappingEnabled=f,this.colorPass.toneMappingExposure=e.tonemapExposure,this.colorPass.globalSaturation=e.globalSaturation,this.colorPass.globalContrast=e.globalContrast,this.colorPass.globalGamma=e.globalGamma,this.colorPass.globalGain=e.globalGain,this.colorPass.globalOffset=e.globalOffset,this.colorPass.shadowsSaturation=e.shadowsSaturation,this.colorPass.shadowsContrast=e.shadowsContrast,this.colorPass.shadowsGamma=e.shadowsGamma,this.colorPass.shadowsGain=e.shadowsGain,this.colorPass.shadowsOffset=e.shadowsOffset,this.colorPass.shadowsMax=e.shadowsMax,this.colorPass.midtonesSaturation=e.midtonesSaturation,this.colorPass.midtonesContrast=e.midtonesContrast,this.colorPass.midtonesGamma=e.midtonesGamma,this.colorPass.midtonesGain=e.midtonesGain,this.colorPass.midtonesOffset=e.midtonesOffset,this.colorPass.highlightsSaturation=e.highlightsSaturation,this.colorPass.highlightsContrast=e.highlightsContrast,this.colorPass.highlightsGamma=e.highlightsGamma,this.colorPass.highlightsGain=e.highlightsGain,this.colorPass.highlightsOffset=e.highlightsOffset,this.colorPass.highlightsMin=e.highlightsMin,this.colorPass.enabled=!0):this.colorPass.enabled=!1,s&&this.camera instanceof p?(this.dofPass.enabled=!0,void 0!==e.depthFocus&&(this.dofPass.uniforms.focus.value=e.depthFocus),void 0!==e.depthAperture&&(this.dofPass.uniforms.aperture.value=e.depthAperture),void 0!==e.depthMaxBlur&&(this.dofPass.uniforms.maxblur.value=e.depthMaxBlur)):this.dofPass.enabled=!1,this.lutPass.enabled=b,b&&(null!=t&&(t.flipY=!0,t.generateMipmaps=!1),this.lutPass.lut=t,this.lutPass.intensity=e.lutIntensity)}updatePostProcessEffectUniforms(e){if(!this.webGlInitialized||0===this.postProcessEffects.length)return;const t=this.postProcessEffectUniformState;t.aoEnabled=this.aoPass.enabled,t.aoTexture=this.aoPass.enabled?this.aoPass.pdRenderTarget.texture:null,this.camera instanceof p?(t.cameraNear=this.camera.near,t.cameraFar=this.camera.far):(t.cameraNear=void 0,t.cameraFar=void 0),t.depthTexture=this.sceneDepthRenderTarget.texture,t.normalTexture=this.gRenderTarget.textures[2],t.resolution.set(this.gRenderTarget.width,this.gRenderTarget.height),t.simulationTime=e;for(const e of this.postProcessEffects)e.pass?.updateUniformState(t)}renderOverlay(){if(!this.running)return;if(0===this.overlayCameras.size)return;const e=Array.from(this.overlayCameras.values()).slice(0,this.maxInsetCameras),t=this.previousClientWith/2,s=e.length*this.insetWidth+(e.length-1)*this.insetMargin;for(let i=0;i<e.length;i++)this.renderer.clearDepth(),this.renderer.setViewport(t-s/2+this.insetWidth*i+this.insetMargin*i,this.insetOffsetY,this.insetWidth,this.insetHeight),this.renderer.render(this.scene,e[i])}addOverlayCamera(e){this.overlayCameras.add(e)}clearOverlayCameras(){this.overlayCameras.clear()}removeOverlayCamera(e){this.overlayCameras.delete(e)}render(e){if(this.requireInitializedBackend("render"),"webgpu"===this.activeBackend){const e=this.experimentalWebGpuBackend;return void(null!=e&&Ze.supportsCamera(this.camera)&&(this.syncExperimentalWebGpuCascades(),e.setRenderGraphExtensions(this.experimentalWebGpuRenderGraphExtensions),e.setPresentationExtensions(this.webGpuPresentationExtensions),e.render(this.scene,this.camera,this.simulationTime)))}if(0===this.composer.renderTarget1.width||0===this.composer.renderTarget1.height)return;if(0===this.composer.renderTarget2.width||0===this.composer.renderTarget2.height)return;let t=!1;if(this.ssrPass.enabled&&!1!==this.options?.reflection?.enabled){const e=this.ssrPass.selects??[];e.length=0,this.scene.traverseVisible(t=>{t instanceof c&&!0===t.material.userData?.reflective&&isObjectInFrustum(t,xt)&&e.push(t)}),this.ssrPass.selects=e,0==e.length&&(this.ssrPass.enabled=!1),t=!0}this.composer.render(e),this.scene.matrixWorldAutoUpdate=!0,this.scene.matrixAutoUpdate=!0,t&&(this.ssrPass.enabled=!0)}hasBloom(){return null!=ye(this.scene,e=>e instanceof c&&!0===e.material?.userData?.hasBloom)}usesSceneColorUniform(e){return this.usesShaderUniform(e,ge)||this.usesShaderUniform(e,fe)}initSceneColorUniform(e){if(e instanceof u&&(null==e.uniforms[fe]||(this.transmissionColorRenderTarget||(this.transmissionColorRenderTarget=new n.WebGLRenderTarget(this.gRenderTarget.width,this.gRenderTarget.height,{type:n.HalfFloatType,colorSpace:n.LinearSRGBColorSpace,minFilter:n.LinearMipmapLinearFilter,magFilter:n.LinearFilter,generateMipmaps:!0,depthBuffer:!1,stencilBuffer:!1}),this.transmissionCopyQuad=new _e(new u({uniforms:{tDiffuse:{value:null}},vertexShader:w.vertexShader,fragmentShader:"uniform sampler2D tDiffuse; varying vec2 vUv; void main() { gl_FragColor = vec4(texture2D(tDiffuse, vUv).rgb, 1.0); }",toneMapped:!1}))),this.transmissionColorRenderTarget.setSize(this.gRenderTarget.width,this.gRenderTarget.height),e.uniforms[fe].value!==this.transmissionColorRenderTarget.texture&&(e.uniforms[fe].value=this.transmissionColorRenderTarget.texture,e.uniformsNeedUpdate=!0),null!=e.uniforms[ge])))return null==e.uniforms[ge]?(e.uniforms[ge]={value:this.sceneColorRenderTarget.texture},void(e.uniformsNeedUpdate=!0)):void(e.uniforms[ge].value!==this.sceneColorRenderTarget.texture&&(e.uniforms[ge].value=this.sceneColorRenderTarget.texture,e.uniformsNeedUpdate=!0))}initDepthUniform(e){e instanceof u&&(e.uniforms[re].value=this.sceneDepthRenderTarget.texture,this.camera instanceof p&&(null!=e.uniforms[le]&&(e.uniforms[le].value=this.camera.near),null!=e.uniforms[oe]&&(e.uniforms[oe].value=this.camera.far)))}initNormalUniform(e){e instanceof u&&null!=e.uniforms[ce]&&(e.uniforms[ce].value=this.gRenderTarget.textures[2])}initShadowUniform(e,t){t instanceof C&&(t.uniforms.receiveShadow?t.uniforms.receiveShadow.value=e.receiveShadow:t.uniforms.receiveShadow={value:e.receiveShadow})}initLightVolumeUniform(e){e instanceof C&&(null!=this.lightVolume?null==e.uniforms.uSH?(e.defines.USE_LIGHT_PROBE_VOLUME="",e.uniforms.gridOrigin={value:this.lightVolume.gridOrigin},e.uniforms.gridSize={value:this.lightVolume.gridSize},e.uniforms.gridRes={value:this.lightVolume.gridResolution},e.uniforms.giIntensity={value:this.lightProbeIntensity},e.uniforms.uSH={value:this.lightVolume.shTexture},e.uniformsNeedUpdate=!0,e.needsUpdate=!0):e.uniforms.giIntensity.value=this.lightProbeIntensity:null!=e.uniforms.uSH&&(delete e.defines.USE_LIGHT_PROBE_VOLUME,delete e.uniforms.gridOrigin,delete e.uniforms.gridSize,delete e.uniforms.gridRes,delete e.uniforms.giIntensity,delete e.uniforms.uSH,e.uniformsNeedUpdate=!0,e.needsUpdate=!0))}initResolutionUniform(e){e instanceof u&&null!=e.uniforms[he]&&e.uniforms[he].value.set(this.gRenderTarget.width,this.gRenderTarget.height)}initAoUniform(e){if(this.aoPass.enabled){e.uniforms[me].value=this.aoPass.pdRenderTarget.texture,null==e.defines.USE_SSAO_MAP&&(e.defines.USE_SSAO_MAP="",e.needsUpdate=!0),e.defines.USE_SSAO_MAP="";const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}else if(null!=e.defines.USE_SSAO_MAP){delete e.defines.USE_SSAO_MAP,e.needsUpdate=!0;const t=this.tbufferMaterialCache.get(e);null!=t&&this.initAoUniform(t)}}initCustomDepthMaterial(e){if(null!=e.customDepthMaterial||!e.castShadow)return;const t=e.material;if(!(t instanceof C&&t.depthWrite&&t.alphaTest>0))return;let s=this._customDepthMaterialCache.get(t);if(null==s){const e=Fe(Ie);let i;null!=t.alphaTest&&t.alphaTest>0&&null!=t.outputOpacity&&(i=t.outputOpacity.lt(t.alphaTest)),s=new C({color:e,discard:i}),this._customDepthMaterialCache.set(t,s)}e.customDepthMaterial=s}};ft.activeView=null,ft.experimentalWebGpuPresentationView=null,ft=e=t([ne(),s("design:paramtypes",[HTMLElement,Object])],ft);export{ft as RenderingView};export function setRenderingPaused(e){null!=window.editor?.viewer?.renderingView&&(window.editor.viewer.renderingView.paused=e)}const bt=.05;function wt(e){let t=e;for(;t;){if(!1===t.visible)return!1;t=t.parent}return!0}function Mt(e,t){return e.priority!==t.priority?e.priority-t.priority:e.id-t.id}function vt(e,t){if(Array.isArray(e.material))for(const s of e.material)t(s);else null!=e.material&&t(e.material)}ae.prototype.overrideVisibility=function(){const e=this.scene,t=this._visibilityCache;e.traverse(function(e){if(t.set(e,e.visible),(e.isPoints||e.isLine||e.isTransformControls||e.isSprite)&&(e.visible=!1),null!=e.material){let t=!1,s=!1;if(Array.isArray(e.material)){for(const s of e.material)if(null!=s.alphaTest&&s.alphaTest>0){t=!0;break}}else null!=e.material.alphaTest&&e.material.alphaTest>0?t=!0:!0===e.material.userData.isDecal&&(s=!0);s&&(e.visible=!1)}})};new n.Box3;const xt=new n.Frustum,Pt=new n.Box3,St=new n.Matrix4;export function isObjectInFrustum(e,t){const s=Pt.setFromObject(e);return t.intersectsBox(s)}function yt(e,t,s,i){return null==e?new n.Vector3(t,s,i):e.set(t,s,i)}function Tt(e){switch(e){case n.LinearToneMapping:return"linear";case n.ReinhardToneMapping:return"reinhard";case n.CineonToneMapping:return"cineon";case n.ACESFilmicToneMapping:return"aces";case n.AgXToneMapping:return"agx";case n.NeutralToneMapping:return"neutral";default:return"none"}}function Gt(e,t,s,i){return null!=e&&Et(e.x,t)&&Et(e.y,s)&&Et(e.z,i)}function Rt(e,t,s){const i=function(e){const t=Ge(e,1e3,4e4)/100,s=t<=66?1:Ge(1.292936186062745*Math.pow(t-60,-.1332047592),0,1),i=Ge(t<=66?.3900815787690196*Math.log(t)-.6318414437886275:1.129890860895294*Math.pow(t-60,-.0755148492),0,1),a=t>=66?1:t<=19?0:Ge(.5432067891101962*Math.log(t-10)-1.19625408914,0,1);return Dt.set(s,i,a)}(t),a=1+.2*Ge(s,-1,1),n=i.x,r=i.y*a,o=i.z,l=Math.max(r,1e-4);return e.set(1/Math.max(n/l,1e-4),1/Math.max(r/l,1e-4),1/Math.max(o/l,1e-4)),e}function Et(e,t,s=Bt){return Math.abs(e-t)<=s}function Ct(e,t){return null!=e&&Number.isFinite(e)&&e>0?e:t}const Bt=1e-4,Ot=new n.Vector3,Wt=new n.Vector3(1,1,1),Dt=new n.Vector3(1,1,1);const Ut=new h,At=new f;function kt(e,t,s=new n.Matrix3){return At.copy(e),At.x*=-1,At.y*=-1,At.z*=-1,t.isCubeTexture&&!1===t.isRenderTargetTexture&&(At.y*=-1,At.z*=-1),s.setFromMatrix4(Ut.makeRotationFromEuler(At))}const It=new C({outputs:[_(0,0,0,0),_(0,0,0,0),I(k("white"),ze(4))],transparent:!0}),Ft=new n.MeshBasicMaterial({color:"blue",transparent:!0,opacity:.5});It.depthWrite=!1;new c(new n.BoxGeometry(4,4,4),Ft);function jt(e){return e instanceof n.Sprite||e.isPoints||e.isTransformControls||e.isTransformControlsGizmo||e instanceof c&&Vt(e,e.material)}function Vt(e,t){return null==t||(Array.isArray(t)?t.some(t=>Vt(e,t)):t instanceof n.RawShaderMaterial||t instanceof n.ShaderMaterial&&!(t instanceof C))}class Lt extends He{constructor(e,t,s){super(),this.scene=e,this.camera=t,this.gRenderTarget=s,this.cachedVisibility=[],this.toRender=[],this.needsSwap=!1}render(e,t,s,i,a){const n=e.autoClear;e.autoClear=!1;const r=this.scene.matrixWorldAutoUpdate,o=this.scene.matrixAutoUpdate,l=e.shadowMap.autoUpdate;this.scene.matrixAutoUpdate=!1,e.shadowMap.autoUpdate=!1;const h=s.depthTexture;s.depthTexture=this.gRenderTarget.depthTexture,e.setRenderTarget(s),this.cachedVisibility.length=0;let p=0,d=this.toRender;if(d.length=0,this.scene.traverseVisible(e=>{const t=jt(e);e instanceof c&&!t?(this.cachedVisibility.push(e),e.visible=!1):t&&(p++,d.push(e))}),p>0)for(const t of d)e.render(t,this.camera);this.cachedVisibility.forEach((e,t)=>{e.visible=!0}),e.setRenderTarget(null),e.autoClear=n,s.depthTexture=h,this.scene.matrixWorldAutoUpdate=r,this.scene.matrixAutoUpdate=o,e.shadowMap.autoUpdate=l}}class _t extends He{constructor(e){super(),this.fn=e}render(e,t,s,i,a){this.fn(e,t,s,i,a)}}const zt=["ambientLightColor","cameraNear","directionalLightShadows","directionalLights","directionalShadowMap","directionalShadowMatrix","fogColor","fogDensity","fogFar","fogNear","hemisphereLights","lightProbe","ltc_1","ltc_2","pointLightShadows","pointLights","pointShadowMap","pointShadowMatrix","rectAreaLights","shadowFar","spotLightMap","spotLightMatrix","spotLightShadows","spotLights","spotShadowMap"],qt=["directionalShadowMap","directionalShadowMatrix","pointLightShadows","pointShadowMap","pointShadowMatrix","spotLightShadows","spotShadowMap"],Ht=W("fogColor");export class FogNode extends ${constructor(e,t=Ht){super(),this.source=e,this.fogColor=t}compile(e){const t=e.variable(),s=e.get(this.source.rgb),i=e.get(this.source.a),a=e.get(this.fogColor),n=e.get(O("fogFar")),r=e.get(O("fogNear")),o=e.get(O("fogDensity")),l=e.get(j(F.mvPosition.z));return{pars:"\n ",chunk:`\n #ifdef FOG_EXP2\n float fogFactor_${t} = 1.0 - exp( - ${o} * ${o} * ${l} * ${l} );\n #else\n float fogFactor_${t} = smoothstep( ${r}, ${n}, ${l} );\n #endif\n vec4 color_vec4_${t} = vec4(mix(${s}, ${a}, fogFactor_${t}), ${i});\n `,out:`color_vec4_${t}`}}}const Nt=new n.MeshDepthMaterial({depthPacking:n.RGBADepthPacking});/*
|
|
2
2
|
* Copyright (©) 2026 Hology Interactive AB. All rights reserved.
|
|
3
3
|
* See the LICENSE.md file for details.
|
|
4
4
|
*/
|
|
@@ -175,6 +175,8 @@ export type SceneObjectShape = {
|
|
|
175
175
|
physics?: SceneObjectPhysicsSettings;
|
|
176
176
|
} & SceneObject;
|
|
177
177
|
export type SceneWorldEnvironmentSettings = {
|
|
178
|
+
/** Omitted in legacy scenes to inherit the project's GI behavior. */
|
|
179
|
+
globalIllumination?: import('../rendering/sdfgi-settings.js').SceneSDFGISettings;
|
|
178
180
|
ao: {
|
|
179
181
|
enabled: boolean;
|
|
180
182
|
blendIntensity: number;
|