@threepipe/webgi-plugins 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{RenderManager as e,PipelinePassPlugin as t,ProgressivePlugin as r,GBufferPlugin as i,generateUiConfig as a,uiToggle as n,uiConfig as s,ExtendedShaderPass as o,Vector2 as l,Matrix4 as c,CopyShader as u,getOrCall as d,serialize as h,uniform as p,uiVector as f,matDefineBool as m,LinearSRGBColorSpace as g,GBufferRenderPass as v,Color as _,UnsignedByteType as y,shaderReplaceString as x,ShaderMaterial as S,NoBlending as b,Matrix3 as w,DoubleSide as T,uiImage as D,uiFolderContainer as P,uiConfigMaterialExtension as M,updateBit as E,Vector4 as C,HalfFloatType as R,AdditiveBlending as A,uiSlider as U,onChange as L,onChange2 as B,Vector3 as N,now as O,FrameFadePlugin as F,PickingPlugin as k,ExtendedShaderMaterial as I,shaderUtils as z,RGBAFormat as V,NearestFilter as j,bindToValue as G,AViewerPluginSync as H,updateMaterialDefines as W,glsl as Y,BaseGroundPlugin as X,matDefine as K,SSAAPlugin as q,getTexelDecoding as Z,AScreenPassExtensionPlugin as J,animateTarget as $,RenderPass as Q,uiColor as ee,makeSamplerUi as te,SRGBColorSpace as re,Mesh2 as ie,MathUtils as ae,Plane as ne,PerspectiveCamera as se,DirectionalLight2 as oe,copyObject3DUserData as le,Serialization as ce,ThreeSerialization as ue,ShadowMaterial as de,SimpleEventDispatcher as he,ShaderMaterial2 as pe,BasicShadowMap as fe,NoColorSpace as me,Layers as ge,LinearFilter as ve,LinearMipmapLinearFilter as _e,PCFShadowMap as ye,PCFSoftShadowMap as xe,VSMShadowMap as Se,uiDropdown as be,uiInput as we,uiButton as Te}from"threepipe";const De={computeScreenSpaceVelocity:"uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;vec2 computeScreenSpaceVelocity(const in vec3 worldPosition){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(worldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(worldPosition,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}",getWorldPositionFromViewZ:"uniform mat4 inverseViewMatrix;vec3 getWorldPositionFromViewZ(const in vec2 uv,const in float viewDepth){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewDepth/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewDepth/projection[1][1];return(inverseViewMatrix*vec4(xe,ye,viewDepth,1.)).xyz;}",temporalAA:"#include <common>\n#include <gbuffer_unpack>\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#include <cameraHelpers>\nvarying vec2 vUv;uniform vec2 previousRTSize;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;vec3 find_closest_fragment_3x3(const in vec2 uv){const vec3 offset=vec3(-1.0,1.0,0.0);vec2 texelSize=1.0/previousRTSize;vec3 dtr=vec3(1,1,getDepth(uv+offset.yy*texelSize));vec3 dtc=vec3(0,1,getDepth(uv+offset.zy*texelSize));vec3 dtl=vec3(-1,1,getDepth(uv+offset.xy*texelSize));vec3 dml=vec3(-1,0,getDepth(uv+offset.xz*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dmr=vec3(1,0,getDepth(uv+offset.yz*texelSize));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.xx*texelSize));vec3 dbc=vec3(0,-1,getDepth(uv+offset.zx*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.yx*texelSize));vec3 dmin=dtl;if(dmin.z>dtc.z)dmin=dtc;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dml.z)dmin=dml;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dmr.z)dmin=dmr;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbc.z)dmin=dbc;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+texelSize.xy*dmin.xy,dmin.z);}vec3 find_closest_fragment_5tap(const in vec2 uv){vec2 texelSize=1.0/previousRTSize;vec2 offset=vec2(1.0,-1.0);vec3 dtl=vec3(-1,1,getDepth(uv+offset.yx*texelSize));vec3 dtr=vec3(1,1,getDepth(uv+offset.xx*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.yy*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.xy*texelSize));vec3 dmin=dtl;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+dmin.xy*texelSize,dmin.z);}vec4 clip_aabb(const in vec4 aabb_min,const in vec4 aabb_max,vec4 p){const float FLT_EPS=1e-8;vec4 p_clip=0.5*(aabb_max+aabb_min);vec4 e_clip=0.5*(aabb_max-aabb_min)+FLT_EPS;vec4 v_clip=p-p_clip;vec4 v_unit=abs(v_clip/e_clip);float ma_unit=max(v_unit.x,max(v_unit.y,v_unit.z));if(ma_unit>1.0)return p_clip+v_clip/ma_unit;else return p;}\n#if HAS_VELOCITY_BUFFER == 0 || defined(DEBUG_VELOCITY)\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec4 currentRTTexelToLinear1(vec4 a){if(isinf(a.x)||isinf(a.y)||isinf(a.z)||isinf(a.w)){return vec4(1.);}return currentRTTexelToLinear(a);}vec4 computeTAA(const in vec2 uv,const in vec2 screenSpaceVelocity,const in float feedbackScale){vec2 uvUnJitter=uv;vec4 currentColor=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter));vec4 previousColor=previousRTTexelToLinear(texture2D(previousRT,uv-screenSpaceVelocity));const vec3 offset=vec3(1.,-1.,0.);vec2 texelSize=1./previousRTSize;float texelSpeed=length(screenSpaceVelocity);vec4 tl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yx*texelSize));vec4 tc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zx*texelSize));vec4 tr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xx*texelSize));vec4 ml=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yz*texelSize));vec4 mc=currentColor;vec4 mr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xz*texelSize));vec4 bl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yy*texelSize));vec4 bc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zy*texelSize));vec4 br=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xy*texelSize));vec4 corners=2.0*(tr+bl+br+tl)-2.0*mc;mc+=(mc-(corners*0.166667))*2.718282*0.3;mc=max(vec4(0.0),mc);vec4 min5=min(tc,min(ml,min(mc,min(mr,bc))));vec4 max5=max(tc,max(ml,max(mc,max(mr,bc))));vec4 cmin=min(min5,min(tl,min(tr,min(bl,br))));vec4 cmax=max(min5,max(tl,max(tr,max(bl,br))));;cmin=0.5*(cmin+min5);cmax=0.5*(cmax+max5);previousColor=clip_aabb(cmin,cmax,previousColor);float lum0=luminance(currentColor.rgb);float lum1=luminance(previousColor.rgb);float unbiased_diff=abs(lum0-lum1)/max(lum0,max(lum1,0.2));float unbiased_weight=1.0-unbiased_diff;float unbiased_weight_sqr=unbiased_weight*unbiased_weight;float k_feedback=mix(feedBack.x,feedBack.y,unbiased_weight_sqr);return mix(currentColor,previousColor,clamp(k_feedback*feedbackScale,0.,1.));}void main(){\n#if HAS_VELOCITY_BUFFER == 0\n#if QUALITY == 1\nvec3 c_frag=find_closest_fragment_3x3(vUv);\n#else\nvec3 c_frag=find_closest_fragment_5tap(vUv);\n#endif\n#else\nvec3 c_frag=vec3(vUv,0.);\n#endif\nbool bg=firstFrame;\n#if BACKGROUND_TAA\nfloat d=c_frag.z;float edgef=min(1.,max(0.,1.-(d*100.-99.)));\n#else\nbg=bg||c_frag.z>0.999;\n#endif\nif(bg){gl_FragColor=currentRTTexelToLinear1(texture2D(currentRT,vUv));}else{\n#if HAS_VELOCITY_BUFFER == 0\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(c_frag.xy);\n#endif\n#if BACKGROUND_TAA\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity*edgef,edgef);\n#else\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity,1.);\n#endif\n}\n#include <colorspace_fragment>\n#ifdef DEBUG_VELOCITY\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);gl_FragColor=vec4(10.*length(screenSpaceVelocity),0.,0.,1.);\n#endif\n}",ssReflection:"uniform float currentFrameCount;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nuniform float objectRadius;uniform float radius;uniform float tolerance;uniform float ssrRoughnessFactor;uniform bool autoRadius;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#if SSREFL_ENABLED == 2\nuniform float ssrSplitX;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeReflectionL(vec3 N,vec2 E,vec3 V,float rough){float rough4=rough*rough*rough*rough;float phi=2.0*PI*E.x;float cos_theta=pow(max(E.y,0.000001),rough4/(2.0-rough4));float sin_theta=sqrt(max(0.,1.0-cos_theta*cos_theta));vec3 half_vec=vec3(sin_theta*cos(phi),sin_theta*sin(phi),cos_theta);vec3 tangentX=normalize(cross(abs(N.z)<0.999 ? vec3(0.0,0.0,1.0): vec3(1.0,0.0,0.0),N));vec3 tangentY=cross(N,tangentX);half_vec=half_vec.x*tangentX+half_vec.y*tangentY+half_vec.z*N;vec3 ray_dir=(2.0*dot(V,half_vec))*half_vec-V;return ray_dir;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=interleavedGradientNoise(gl_FragCoord.xy,frameCount*34.+seed);rand_e.y=fract(rand_e.x*38.65435);rand_e.y=mix(rand_e.y,1.0,0.7);return rand_e;}vec4 calculateSSR(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor,in float roughness){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeReflectionL(normal,E,-normalize(viewPos),roughness*ssrRoughnessFactor);L=normalize(L);float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,frameCount+seed);rayLen=max(rayLen,0.001);int steps=SSR_STEP_COUNT/(currentFrameCount<float(SSR_LOW_QUALITY_FRAMES)? 2 : 1);vec3 state=vec3(0.,(r+0.5)/float(steps),2.);viewPos+=normal*max(-0.0001*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,steps);if(state.z<0.99){if(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}",calculateGI:"uniform float currentFrameCount;uniform float intensity;uniform float objectRadius;uniform float rayCount;uniform float power;uniform float bias;uniform float falloff;uniform float tolerance;uniform bool autoRadius;uniform vec2 screenSize;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeUniformL(vec3 N,vec2 E){vec3 L;L.xy=E;L.z=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*5.);L=L*2.-1.;return L;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=random3(vec3(gl_FragCoord.xy,currentFrameCount+seed));rand_e.y=random3(vec3(gl_FragCoord.yx,rand_e.x+(currentFrameCount)*7.));return rand_e;}float saturate2(float v,float mx){return max(0.,min(mx,v));}vec4 calculateGI(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeUniformL(normal,E);L=normalize(L);L*=sign(dot(L,normal));float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*14.+seed)+0.05;rayLen=max(rayLen,0.001);vec3 state=vec3(1.,(r+0.5)/float(RTAO_STEP_COUNT),2.);viewPos+=normal*max(-0.01*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,RTAO_STEP_COUNT);vec3 viewHitP=screenToView3(screenHitP.xy,screenHitP.z);vec3 LRes=viewHitP-viewPos;if(state.z>1.)LRes=vec3(9999999.);float dist=length(LRes)*falloff;float EPS=0.01;float zBias=(viewPos.z)*bias;float ao=(max(dot(normal,L)+zBias,0.))/(dist*dist+EPS);\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nif(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy)).rgb;vec3 hitNormal=getViewNormal(screenHitP.xy);float giWeight=1.;giWeight=saturate2(giWeight/(dist+EPS),1.);giWeight*=saturate2((dot(normal,L)),1.0);giWeight*=saturate2((dot(hitNormal,-L)),1.0);return vec4(hitColor*giWeight,ao);\n#endif\nreturn vec4(0,0,0,ao);}float normpdf(in float x,in float sigma){return exp(-0.5*x*x/(sigma*sigma));}vec4 getLastThis(sampler2D tex,float depth,vec3 normal){vec2 direction=vec2(1,1);vec4 color=clamp(tLastThisTexelToLinear(texture2D(tex,vUv.xy)),0.,5.);return color;}void main(){float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>0.99){discard;gl_FragColor=getLastThis(tLastThis,depth,normal);return;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec4 gi=vec4(0.);gi+=calculateGI(8.,screenPos,normal,1.);if(rayCount>1.5)gi=max(gi,calculateGI(2.,screenPos,normal,0.4));if(rayCount>2.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.5));if(rayCount>3.5)gi=max(gi,calculateGI(1.,screenPos,normal,0.6));if(rayCount>4.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.));gi.a=min(1.,gi.a);gi.a=max(0.,gi.a);gi.rgb=min(vec3(3.),gi.rgb);gi.rgb=max(vec3(0.),gi.rgb);if(currentFrameCount<3.){gl_FragColor=gi;return;}gl_FragColor=(texture2D(tLastThis,vUv));gl_FragColor=((gi+(gl_FragColor)*currentFrameCount)/(currentFrameCount+1.));}",__inited:!1};function Pe(){return De.__inited||(De.__inited=!0,Object.assign(e.ShaderChunk,De)),De}var Me=Object.defineProperty,Ee=Object.getOwnPropertyDescriptor,Ce=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?Ee(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&Me(t,r,n),n};class Re extends t{static PluginType="TAA";static OldPluginType="TemporalAAPlugin";passId="taa";constructor(e=!0){super(),this.enabled=e,this.setDirty=this.setDirty.bind(this)}_stableNoise=!0;get stableNoise(){return this._viewer?.renderManager.stableNoise??this._stableNoise}set stableNoise(e){this._viewer&&(this._viewer.renderManager.stableNoise=e),this._stableNoise=e}_gbufferUnpackExtension=void 0;_gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("TemporalAAPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed"))};_createPass(){if(!this._viewer)throw new Error("TemporalAAPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");const e=!!this._viewer.renderManager.msaa;return new Ae(this.passId,()=>this._viewer?.getPlugin(r)?.target,e)}dependencies=[i,r];onAdded(e){super.onAdded(e),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.addEventListener("resize",this._pass.onSizeUpdate)}onRemove(e){e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.removeEventListener("resize",this._pass.onSizeUpdate),super.onRemove(e)}uiConfig={type:"folder",label:"TemporalAA Plugin",onChange:this.setDirty.bind(this),children:[...a(this)||[]]};_beforeRender(e,t,i){if(!super._beforeRender(e,t,i))return!1;const a=this.pass,n=this._viewer;if(!a||!n)return!1;const s=i.frameCount;if(a.taaEnabled=s<=1&&e.renderCamera===e.mainCamera,!a.taaEnabled)return!1;const o=t;return!!o&&(o.updateMatrixWorld(!0),o.updateShaderProperties(a.material),a.updateCameraProperties(o),a.target=n.getPlugin(r).target,!0)}}Ce([n("Stable Noise (Total frame count)")],Re.prototype,"stableNoise",1),Ce([s(void 0,{unwrapContents:!0})],Re.prototype,"_pass",2);class Ae extends o{before=["progressive"];after=[];required=["render","progressive"];target;passId;constructor(e,t,r=!1){super({vertexShader:u.vertexShader,fragmentShader:Pe().temporalAA,uniforms:{currentRT:{value:null},previousRT:{value:null},previousRTSize:{value:new l},cameraNearFar:{value:new l},lastProjectionViewMatrix:{value:new c},currentProjectionViewMatrix:{value:new c},projection:{value:new c},inverseViewMatrix:{value:new c},jitterSample:{value:new l},firstFrame:{value:!0}},defines:{QUALITY:1,UNJITTER:0,BACKGROUND_TAA:r?1:0}},"currentRT","previousRT"),this.passId=e,this.onSizeUpdate=this.onSizeUpdate.bind(this),this.target=t,this.clear=!1,this.needsSwap=!0}taaEnabled=!0;render(e,t,r,i,a){this.taaEnabled&&this.enabled?(this.needsSwap=!0,this.uniforms.previousRT.value=d(this.target)?.texture??null,super.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value),this.uniforms.firstFrame.value=!1):this.needsSwap=!1}updateCameraProperties(e){e&&(this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(e.matrixWorld))}onSizeUpdate(){this.uniforms.firstFrame.value=!0,this.setDirty()}setSize(e,t){super.setSize(e,t),this.onSizeUpdate()}feedBack=new l(.88,.97);debugVelocity=!1;uiConfig={type:"folder",label:"Temporal AA Pass",onChange:this.setDirty,children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"],onChange:()=>this.onSizeUpdate()},...a(this)?.filter(e=>e&&"Enabled"!==e.label)||[]]}}Ce([h(),p(),f("Feedback",void 0,1e-4)],Ae.prototype,"feedBack",2),Ce([n(),m("DEBUG_VELOCITY",void 0,!1,void 0,!0)],Ae.prototype,"debugVelocity",2);var Ue=Object.defineProperty,Le=Object.getOwnPropertyDescriptor,Be=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?Le(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&Ue(t,r,n),n},Ne=(e,t,r)=>((e,t,r)=>t in e?Ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let Oe=class extends t{passId="velocityBuffer";target;texture;material=new Fe;bufferType;_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:0,type:this.bufferType,generateMipmaps:!1,colorSpace:g})),this.texture=this.target.texture,this.texture.name="velocityBuffer",this._pass&&(this._pass.target=this.target))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("VelocityBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=this._viewer,t=new class extends v{_firstCall=!0;render(t,r,i,a,n){if(e.renderManager.frameCount>0)return;if(!this.enabled||!this.camera)return;const s=this.overrideMaterial;s.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse),this._firstCall&&(s.uniforms.lastProjectionViewMatrix.value.copy(s.uniforms.currentProjectionViewMatrix.value),this._firstCall=!1),super.render(t,r,i,a,n),s.uniforms.lastProjectionViewMatrix.value.copy(s.uniforms.currentProjectionViewMatrix.value)}}(this.passId,this.target,this.material,new _(.5,.5,.5),1),r=t.preprocessMaterial;return t.preprocessMaterial=e=>r(e,e.userData[Oe.PluginType]?.disabled),t.before=["render"],t.after=[],t.required=["render"],t}_attachToTaa;constructor(e=y,t=!0,r=!0){super(),this.enabled=t,this.bufferType=e,this._attachToTaa=r}onAdded(e){super.onAdded(e),e.forPlugin(Re,e=>{this._attachToTaa&&e.pass?.material.registerMaterialExtensions([this.unpackExtension])},e=>{e.pass?.material?.unregisterMaterialExtensions([this.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}unpackExtension={shaderExtender:e=>{this.isDisabled()||(e.fragmentShader=x(e.fragmentShader,"#pragma <velocity_unpack>","\n#if defined(HAS_VELOCITY_BUFFER)\nuniform sampler2D tVelocity;vec2 getVelocity(const in vec2 uv){vec2 screenSpaceVelocity=texture2D(tVelocity,uv).xy*2.0-1.0;return sign(screenSpaceVelocity)*pow(abs(screenSpaceVelocity),vec2(4.));}\n#endif\n\n"))},computeCacheKey:()=>this.isDisabled()?"":"vb",extraUniforms:{tVelocity:()=>({value:this.isDisabled()?null:this.target?.texture})},extraDefines:{HAS_VELOCITY_BUFFER:()=>!this.isDisabled()&&this.target?.texture?1:void 0},priority:100,isCompatible:()=>!0};setDirty(){super.setDirty(),this.unpackExtension.setDirty?.()}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;return!!i&&(!(r.frameCount>0)&&(i.scene=e,i.camera=t,t.updateShaderProperties(i.overrideMaterial),!0))}};Ne(Oe,"PluginType","VelocityBuffer"),Ne(Oe,"OldPluginType","VelocityBufferPlugin"),Be([D("Velocity Buffer",{readOnly:!0})],Oe.prototype,"texture",2),Oe=Be([P("Velocity Buffer Plugin (for TAA)")],Oe);class Fe extends S{constructor(){super({vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <uv_pars_vertex>\n#include <batching_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 modelMatrixPrevious;void main(){\n#include <uv_vertex>\n#include <batching_vertex>\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\nvec4 mvPosition=vec4(transformed,1.0);\n#ifdef USE_INSTANCING\nmvPosition=instanceMatrix*mvPosition;\n#endif\nvWorldPosition=(modelMatrix*mvPosition).xyz;vWorldPositionPrevious=(modelMatrixPrevious*mvPosition).xyz;mvPosition=modelViewMatrix*mvPosition;gl_Position=projectionMatrix*mvPosition;\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 currentProjectionViewMatrix;uniform mat4 lastProjectionViewMatrix;vec2 computeScreenSpaceVelocity2(){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(vWorldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(vWorldPositionPrevious,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}void main(){vec2 velocity=clamp(computeScreenSpaceVelocity2(),-1.0,1.0);velocity=sign(velocity)*pow(abs(velocity),vec2(1./4.));velocity=velocity*0.5+0.5;gl_FragColor=vec4(velocity.x,velocity.y,1.,1.);}",uniforms:{cameraNearFar:{value:new l(.1,1e3)},alphaMap:{value:null},alphaTest:{value:null},alphaMapTransform:{value:/* @__PURE__ */new w},currentProjectionViewMatrix:{value:new c},lastProjectionViewMatrix:{value:new c}},blending:b})}extraUniformsToUpload={modelMatrixPrevious:{value:(new c).identity()}};_previousWorldMatrices={};onBeforeRender(e,t,r,i,a,n){super.onBeforeRender(e,t,r,i,a,n);const s=this._previousWorldMatrices[a.uuid];this.extraUniformsToUpload.modelMatrixPrevious.value.copy(s??a.matrixWorld),s?s.copy(a.matrixWorld):this._previousWorldMatrices[a.uuid]=a.matrixWorld.clone();let o=a.material;Array.isArray(o)&&(o=o[0]),this.uniforms.alphaMap.value=o?.alphaMap??null,this.uniforms.alphaTest.value=!o||!o.alphaTest||o.alphaTest<1e-7?.001:o.alphaTest;let l=this.uniforms.alphaMap.value?1:void 0;l!==this.defines.USE_ALPHAMAP&&(void 0===l?delete this.defines.USE_ALPHAMAP:this.defines.USE_ALPHAMAP=l,this.needsUpdate=!0),l=o?.userData.ALPHA_I_RGBA_PACKING?1:void 0,l!==this.defines.ALPHA_I_RGBA_PACKING&&(void 0===l?delete this.defines.ALPHA_I_RGBA_PACKING:this.defines.ALPHA_I_RGBA_PACKING=l,this.needsUpdate=!0),this.side=o?.side??T}}var ke=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,ze=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?Ie(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&ke(t,r,n),n};const Ve=class e extends t{static PluginType="Bloom";static OldPluginType="BloomPlugin";passId="bloom";materialExtension=M(this._getUiConfig.bind(this),e.PluginType);_createPass(){return new Ge(this.passId,Math.min(8,this._viewer?.renderManager.maxHDRIntensity||8))}constructor(e=!0){super(),this.enabled=e}dependencies=[i];onAdded(e){super.onAdded(e);const t=e.getPlugin(i);t?(t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass.material.registerMaterialExtensions([t.unpackExtension])):e.addEventListener("addPlugin",this._onPluginAdd),e.materialManager.registerMaterialExtension(this.materialExtension)}_onPluginAdd=e=>{if(e.plugin?.constructor?.PluginType!==i.PluginType)return;const t=e.plugin;t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass?.material.registerMaterialExtensions([t.unpackExtension]),this._viewer?.removeEventListener("addPlugin",this._onPluginAdd)};onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd);const t=e.getPlugin(i);t?.unregisterGBufferUpdater(this.constructor.PluginType),t&&this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),e.materialManager.unregisterMaterialExtension(this.materialExtension),super.onRemove(e)}updateGBufferFlags(t,r){if(!r.material||!r.material.userData)return;const i=!1===r.material.userData[e.PluginType]?.enable||r.material.userData.pluginsDisabled?0:1;t.w=E(t.w,2,i)}uiConfig={type:"folder",label:"Bloom Plugin",onChange:this.setDirty.bind(this),children:[...a(this)||[]]};static AddBloomData(t,r,i=!0){const a=t?.userData;if(!a)return null;a[e.PluginType]||(a[e.PluginType]={});const n=a[e.PluginType];return n.enable=!0,r&&Object.assign(n,r),i&&t.setDirty&&t.setDirty(),n}_getUiConfig(t){const r={type:"folder",label:"Bloom",children:[{type:"checkbox",label:"Enabled",get value(){return t.userData[e.PluginType]?.enable??!0},set value(i){let a=t.userData[e.PluginType];i!==a?.enable&&(a||(a=e.AddBloomData(t,void 0,!1)),a.enable=i,t.setDirty(),r.uiRefresh?.(!0,"postFrame"))},onChange:this.setDirty}]};return r}};ze([s(void 0,{unwrapContents:!0})],Ve.prototype,"_pass",2);let je=Ve,Ge=class extends o{uiConfig=void 0;before=["screen"];after=["render","progressive"];required=["render"];passId;constructor(e,t=16){super({vertexShader:u.vertexShader,defines:{PASS_STEP:1,MAX_INTENSITY:Math.min(t,16)},uniforms:{tSource:{value:null},tDiffuse:{value:null},opacity:{value:1},tDiffuseSize:{value:new l},weight:{value:1}},fragmentShader:"#include <packing>\nuniform float intensity;uniform float opacity;uniform vec2 tDiffuseSize;varying vec2 vUv;uniform float weight;\n#if PASS_STEP == 0\nuniform vec4 prefilter;vec4 Prefilter(vec4 c){\n#ifdef HAS_GBUFFER\n#if !BACKGROUND_BLOOM\nif(getDepth(vUv)>0.999){return vec4(0.0);}\n#endif\n#endif\nfloat brightness=max(c.r,max(c.g,c.b));float soft=brightness+prefilter.x*(prefilter.y-1.);soft=clamp(soft,0.,prefilter.z);soft=soft*soft*prefilter.w;float contribution=max(soft,brightness-prefilter.x);contribution/=max(brightness,0.001);return vec4(c.rgb*contribution,c.a);}\n#endif\nvec4 Sample(vec2 uv){return min(vec4(MAX_INTENSITY,MAX_INTENSITY,MAX_INTENSITY,1.),tDiffuseTexelToLinear(texture2D(tDiffuse,uv)));}vec4 SampleBox(vec2 uv,float delta){vec4 o=vec2(-delta,delta).xxyy/tDiffuseSize.xyxy;vec4 s=Sample(uv+o.xy)+Sample(uv+o.zy)+Sample(uv+o.xw)+Sample(uv+o.zw);return s*0.25;}int getBloomBit(in int number){\n#ifdef WebGL2Context\nreturn(number/4)% 2;\n#else\nreturn int(mod(floor(float(number)/4.),2.));\n#endif\n}void main(){\n#if PASS_STEP == 0\n#ifdef GBUFFER_HAS_FLAGS\nint doBloom=getBloomBit(getGBufferFlags(vUv).a);\n#else\nint doBloom=1;\n#endif\ngl_FragColor=float(doBloom)*weight*Prefilter(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 1\ngl_FragColor=weight*(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 2\ngl_FragColor=(SampleBox(vUv,0.5));gl_FragColor.a=1.;\n#elif PASS_STEP == 3\nvec4 texel=tSourceTexelToLinear(texture2D(tSource,vUv));vec4 bloom=intensity*SampleBox(vUv,0.5).rgba;float brightness=max(bloom.r,max(bloom.g,bloom.b));texel.rgb+=bloom.rgb;texel.a=min(1.,texel.a+brightness);gl_FragColor=texel;\n#elif PASS_STEP == 4\nvec4 texel=vec4(0.);texel.rgb+=intensity*SampleBox(vUv,0.5).rgb;texel.a=1.;gl_FragColor=texel;\n#endif\n#include <colorspace_fragment>\n}"},"tDiffuse","tSource"),this.passId=e,this._updateWeights=this._updateWeights.bind(this),this._thresholdsUpdated=this._thresholdsUpdated.bind(this),this._updateWeights(),this._thresholdsUpdated(),this.clear=!0}prefilter=new C(2,.5,0,0);threshold=2;softThreshold=.5;intensity=.2;backgroundBloom=!1;bloomIterations=4;_currentIterations=0;radius=.6;power=1;_thresholdsUpdated(){this.prefilter.x=this.threshold,this.prefilter.y=this.softThreshold,this.prefilter.z=2*this.prefilter.x*this.prefilter.y,this.prefilter.w=this.uniforms?.prefilter?.125/(this.uniforms.prefilter.value.z+1e-5):0}bloomDebug=!1;_weights=[];render(e,t,r,i,a){const n=e.renderManager;this.material.defines.PASS_STEP=0,this.clear=!0,this.needsSwap=!1;const s=r;if(!s)return void console.warn("BloomPluginPass: No source to read from");this.needsSwap=!0;let o=.5,l=s.width*o,c=s.height*o;const u=[];let d=n.getTempTarget({sizeMultiplier:1,type:R});u.push(d);let h=s;this.material.needsUpdate=!0,this.material.uniforms.weight.value=this._weights[0],super.render(e,d,h,i,a),h=d;const p=this._currentIterations;let f=1;const m=Math.max(2,this.bloomIterations);for(;f<m&&(l/=2,c/=2,o/=2,!(c<2||l<2));f++){d=n.getTempTarget({sizeMultiplier:o,type:R}),u.push(d),this.material.defines.PASS_STEP=1;let t=this._weights[f];t=0!==this._weights[f-1]?this._weights[f]/this._weights[f-1]:this._weights[f],this.material.uniforms.weight.value=t,this.material.needsUpdate=!0,super.render(e,d,h,i,a),h=d,this._currentIterations=f+1}p!==this._currentIterations&&this._updateWeights(!1),this.clear=!1;const g=e.autoClear;for(e.autoClear=!1,f-=2;f>=0;f--)d=u[f],u[f]=void 0,this.material.defines.PASS_STEP=2,this.material.transparent=!0,this.material.blending=A,this.material.needsUpdate=!0,e.autoClear=!1,super.render(e,d,h,i,a),this.material.blending=b,n.releaseTempTarget(h),h=d;this.clear=!0,e.autoClear=g,e.autoClear=!0,this.bloomDebug?(this.material.defines.PASS_STEP=4,this.material.needsUpdate=!0,super.render(e,t,h,i,a)):(this.uniforms.tSource.value=s.texture,this.material.defines.PASS_STEP=3,this.material.needsUpdate=!0,super.render(e,t,h,i,a),this.uniforms.tSource.value=null),n.releaseTempTarget(h)}_updateWeights(e=!0){if(!this._weights)return;const t=Math.max(Math.min(this.radius,1),0),r=Math.max(2,this._currentIterations||this.bloomIterations),i=1/(r-1);for(let a=0;a<r;a++){let e=a*i+.1,r=1.2-e;e=Math.pow(e,this.power),r=Math.pow(r,this.power),this._weights[a]=r*(1-t)+e*t}!1!==e&&this.setDirty()}};ze([p()],Ge.prototype,"prefilter",2),ze([U("Threshold",[0,2]),L(Ge.prototype._thresholdsUpdated),h()],Ge.prototype,"threshold",2),ze([U("Soft Threshold",[0,1]),L(Ge.prototype._thresholdsUpdated),h()],Ge.prototype,"softThreshold",2),ze([U("Intensity",[0,3]),h(),p()],Ge.prototype,"intensity",2),ze([n("Background Bloom"),h(),m("BACKGROUND_BLOOM")],Ge.prototype,"backgroundBloom",2),ze([U("Iterations",[2,7],1),B(Ge.prototype._updateWeights),h()],Ge.prototype,"bloomIterations",2),ze([U("Radius",[0,1],.01),B(Ge.prototype._updateWeights),h()],Ge.prototype,"radius",2),ze([U("Power",[.2,10],.01),B(Ge.prototype._updateWeights),h()],Ge.prototype,"power",2),ze([n("Debug")],Ge.prototype,"bloomDebug",2),Ge=ze([P("Bloom Pass")],Ge);var He=Object.defineProperty,We=Object.getOwnPropertyDescriptor,Ye=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?We(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&He(t,r,n),n};class Xe extends t{static PluginType="DepthOfField";static OldPluginType="DepthOfFieldPlugin";passId="depthOfField";enableEdit=!1;_focalPointHit=new N(0,0,0);crossFadeTime=200;_focalPointHitTime=0;get _frameFadeTime(){return 2.5*this.crossFadeTime}constructor(e=!0,t=!1){super(),this.enabled=e,this.enableEdit=t,this._onObjectHit=this._onObjectHit.bind(this),this.setDirty=this.setDirty.bind(this)}setFocalPoint(e,t=!0,r=!1){this._focalPointHit.copy(e),t&&this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime),r&&(this._focalPointHitTime=O()),this.setDirty()}getFocalPoint(){return this._focalPointHit}_onObjectHit(e){this._pass&&e.intersects.intersect&&!this.isDisabled()&&this.enableEdit&&(this._focalPointHit.copy(e.intersects.intersect.point),this._focalPointHitTime=e.time,e.intersects.selectedObject=null,this._viewer?.getPlugin(F)?.startTransition(this._frameFadeTime),this.setDirty())}_createPass(){return new qe(this.passId)}dependencies=[i];onAdded(e){super.onAdded(e),e.addEventListener("addPlugin",this._onPluginAdd),e.addEventListener("removePlugin",this._onPluginRemove),this._onPluginAdd({plugin:e.getPlugin(i)}),this._onPluginAdd({plugin:e.getPlugin(k)})}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd),e.removeEventListener("removePlugin",this._onPluginRemove),this._onPluginRemove({plugin:e.getPlugin(i)}),this._onPluginRemove({plugin:e.getPlugin(k)}),super.onRemove(e)}_onPluginAdd=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===i.PluginType){const e=t;this._pass?.material.registerMaterialExtensions([e.unpackExtension]),this._pass?.computeCocMaterial.registerMaterialExtensions([e.unpackExtension]),this._pass?.expandCocMaterial.registerMaterialExtensions([e.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){t.addEventListener("hitObject",this._onObjectHit)}}};_onPluginRemove=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===i.PluginType){const t=e.plugin;this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.computeCocMaterial.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.expandCocMaterial.unregisterMaterialExtensions([t.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){e.plugin.removeEventListener("hitObject",this._onObjectHit)}}};uiConfig={type:"folder",label:"DepthOfField",onChange:this.setDirty.bind(this),children:[...a(this)||[],()=>this._pass?.uiConfig]};_tempVec=new N;_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;if(!i)return!1;i.dofBlurMaterial.uniforms.frameCount&&r?.updateShaderProperties(i.dofBlurMaterial);const a=t;if(!a)return!1;a.updateMatrixWorld(!0),a.updateShaderProperties(i.material),a.getWorldPosition(this._tempVec),this._tempVec.subVectors(this._focalPointHit,this._tempVec),i.focalDepthRange.x=this._tempVec.length(),i.focalDepthRange.x*=a.getWorldDirection(new N).dot(this._tempVec.normalize());let n=(O()-this._focalPointHitTime)/this.crossFadeTime;if(n=1-Math.min(1,Math.max(0,n)),Math.abs(n-i.crossAlpha)>.01&&(i.crossAlpha=n,this.setDirty()),n>0){const e=this._tempVec.copy(this._focalPointHit).project(a).addScalar(1).divideScalar(2);i.crossCenter.set(e.x,e.y),i.computeCocMaterial.uniformsNeedUpdate=!0,i.expandCocMaterial.uniformsNeedUpdate=!0}return!0}}Ye([h(),n()],Xe.prototype,"enableEdit",2),Ye([h("focalPoint")],Xe.prototype,"_focalPointHit",2),Ye([h()],Xe.prototype,"crossFadeTime",2);const Ke=new I({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new l},direction:{value:new l},frameCount:{value:0},blurRadius:{value:16}},vertexShader:z.defaultVertex,fragmentShader:"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n#include <randomHelpers>\n#include <common>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform float blurRadius;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvec4 CircularBlur(){vec4 color=colorTextureTexelToLinear(texture2D(colorTexture,vUv));\n#ifdef DOF_MODE\nfloat blurDist=blurRadius*(2.*color.a-1.);\n#else\nfloat blurDist=blurRadius*color.a;\n#endif\nfloat rnd=PI2*random3(vec3(vUv,frameCount*0.1));float costheta=cos(rnd);float sintheta=sin(rnd);vec4 rotationMatrix=vec4(costheta,-sintheta,sintheta,costheta);vec3 colorSum=vec3(0.0);float weightSum=0.001;vec2 ofs;vec4 sampleColor;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));sampleColor=colorTextureTexelToLinear(texture2D(colorTexture,vUv+blurDist*ofs/colorTextureSize.xy));\n#ifdef DOF_MODE\nsampleColor.a=abs(sampleColor.a*2.0-1.0);sampleColor.a*=sampleColor.a*sampleColor.a;\n#endif\ncolorSum+=sampleColor.rgb*sampleColor.a;weightSum+=sampleColor.a;}\n#pragma unroll_loop_end\ncolorSum/=weightSum;return vec4(min(vec3(72.),max(vec3(0.),colorSum)),1.0);}void main(){gl_FragColor=CircularBlur();\n#include <colorspace_fragment>\n}",defines:{DOF_MODE:1}},["colorTexture"]);let qe=class extends o{uiConfig=void 0;before=["progressive","screen"];after=["render"];required=["render"];computeCocMaterial;expandCocMaterial;dofBlurMaterial=Ke;depthRange;nearBlurScale;farBlurScale;nearFarBlurScale=new l(.25,.25);focalDepthRange=new l(.5,1.5);crossCenter=new l(.5,.5);crossRadius=.04;crossAlpha=1;crossColor=new _(16750848);passId;constructor(e){super({uniforms:{colorTexture:{value:null},blurTexture:{value:null},cocTexture:{value:null},cocTextureSize:{value:new l},cameraNearFar:{value:new l}},vertexShader:z.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 cocTextureSize;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;uniform vec2 crossCenter;uniform float crossRadius;uniform float crossAlpha;uniform vec3 crossColor;float smoothBoundary(float d,float smooothFactor){smooothFactor*=0.5;float value=smoothstep(-smooothFactor,smooothFactor,d);return value;}float circle(vec2 p,float r){return min((length(p)-r),-(length(p)-r-0.01));}float computeCoc(){float depth=getDepth(vUv);if(depth>1.0-0.01)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){vec4 blur=blurTextureTexelToLinear(texture2D(blurTexture,vUv));float scale=0.5;blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,-1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,-1.0)/cocTextureSize));blur/=5.0;vec2 uvNearest=(floor(vUv*cocTextureSize)+0.5)/cocTextureSize;float coc=abs(min(2.*cocTextureTexelToLinear(texture2D(cocTexture,uvNearest)).a-1.,computeCoc()));float cocLower=0.005;float cocHigher=0.3;vec4 outColor=vec4(mix(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,blur.rgb,smoothstep(cocLower,cocHigher,coc)),1.0);vec2 d=vUv-crossCenter;if(length(d)>crossRadius+0.05){float dist=circle(d,crossRadius);gl_FragColor=outColor;}else{d.x*=cocTextureSize.x/cocTextureSize.y;float dist=circle(d,crossRadius);dist=smoothBoundary(dist,2.*fwidth(dist));vec4 color=outColor;vec3 dofCircleColor=mix(crossColor,color.rgb,1.-crossAlpha);gl_FragColor=vec4(mix(color.rgb,dofCircleColor,dist),color.a);}\n#include <colorspace_fragment>\n}"},"colorTexture","cocTexture","blurTexture"),this.passId=e,this.computeCocMaterial=new I({uniforms:{colorTexture:{value:null},cameraNearFar:this.uniforms.cameraNearFar,nearFarBlurScale:this.uniforms.nearFarBlurScale,focalDepthRange:this.uniforms.focalDepthRange},vertexShader:z.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;float computeCoc(){float depth=getDepth(vUv);if(depth==1.0)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*computeCoc()+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"]),this.expandCocMaterial=new I({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new l},direction:{value:new l},nearFarBlurScale:this.uniforms.nearFarBlurScale},vertexShader:z.defaultVertex,fragmentShader:"#include <common>\n#include <gbuffer_unpack>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform vec2 direction;uniform vec2 nearFarBlurScale;const float MAXIMUM_BLUR_SIZE=4.0;float expandNear(const in vec2 offset,const in bool isBackground){float coc=0.0;vec2 sampleOffsets=MAXIMUM_BLUR_SIZE*offset/5.0;float coc0=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv)).a-1.;float coc1=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-5.0*sampleOffsets)).a-1.;float coc2=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-4.0*sampleOffsets)).a-1.;float coc3=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-3.0*sampleOffsets)).a-1.;float coc4=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-2.0*sampleOffsets)).a-1.;float coc5=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-1.0*sampleOffsets)).a-1.;float coc6=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+1.0*sampleOffsets)).a-1.;float coc7=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+2.0*sampleOffsets)).a-1.;float coc8=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+3.0*sampleOffsets)).a-1.;float coc9=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+4.0*sampleOffsets)).a-1.;float coc10=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+5.0*sampleOffsets)).a-1.;if(isBackground){coc=abs(coc0)*0.095474+(abs(coc1)+abs(coc10))*0.084264+(abs(coc2)+abs(coc9))*0.088139+(abs(coc3)+abs(coc8))*0.091276+(abs(coc4)+abs(coc7))*0.093585+(abs(coc5)+abs(coc6))*0.094998;}else{coc=min(coc0,0.0);coc=min(coc1*0.3,coc);coc=min(coc2*0.5,coc);coc=min(coc3*0.75,coc);coc=min(coc4*0.8,coc);coc=min(coc5*0.95,coc);coc=min(coc6*0.95,coc);coc=min(coc7*0.8,coc);coc=min(coc8*0.75,coc);coc=min(coc9*0.5,coc);coc=min(coc10*0.3,coc);if(abs(coc0)>abs(coc))coc=coc0;}return coc;}void main(){vec2 offset=2.*direction/colorTextureSize;bool isBackground=getDepth(vUv)>1.0-0.001;float coc=expandNear(offset,isBackground);gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*coc+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"])}render(e,t,r,i,a){if(!this.enabled)return;if(!r)return void console.error("DepthOfFieldPluginPass: No readBuffer");const n=e.renderManager,s={minFilter:j,magFilter:j,type:R,colorSpace:g,sizeMultiplier:.5,format:V,depthBuffer:!1,generateMipmaps:!1},o=n.getTempTarget(s),l=n.getTempTarget(s);if(this.computeCocMaterial.uniforms.colorTexture.value=r.texture,n.blit(o,{material:this.computeCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=o.texture,this.expandCocMaterial.uniforms.direction.value.set(1,0),n.blit(l,{material:this.expandCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=l.texture,this.expandCocMaterial.uniforms.direction.value.set(0,1),n.blit(o,{material:this.expandCocMaterial}),this.dofBlurMaterial.uniforms.frameCount)this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,n.blit(l,{material:this.dofBlurMaterial});else{const e=n.getTempTarget(s);this.dofBlurMaterial.uniforms.cocTexture.value=o.texture,this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,this.dofBlurMaterial.uniforms.direction.value.set(1,0),n.blit(e,{material:this.dofBlurMaterial}),this.dofBlurMaterial.uniforms.colorTexture.value=e.texture,this.dofBlurMaterial.uniforms.direction.value.set(0,1),n.blit(l,{material:this.dofBlurMaterial}),n.releaseTempTarget(e)}this.material.uniforms.blurTexture.value=l.texture,this.material.uniforms.cocTexture.value=o.texture,super.render(e,t,r,i,a),n.releaseTempTarget(o),n.releaseTempTarget(l)}};Ye([G({obj:"focalDepthRange",key:"y"}),U("Depth Range",[.25,3])],qe.prototype,"depthRange",2),Ye([G({obj:"nearFarBlurScale",key:"x"}),U("Near Blur Scale",[0,1])],qe.prototype,"nearBlurScale",2),Ye([G({obj:"nearFarBlurScale",key:"y"}),U("Far Blur Scale",[0,1])],qe.prototype,"farBlurScale",2),Ye([h(),p()],qe.prototype,"nearFarBlurScale",2),Ye([h(),p()],qe.prototype,"focalDepthRange",2),Ye([p()],qe.prototype,"crossCenter",2),Ye([p()],qe.prototype,"crossRadius",2),Ye([p()],qe.prototype,"crossAlpha",2),Ye([p()],qe.prototype,"crossColor",2),qe=Ye([P("DepthOfField Pass")],qe);const Ze="#ifndef SSRT_PARS_SNIP\n#define SSRT_PARS_SNIP\n#define pow2(a) a*a\nfloat getDepth2(const in vec2 uv,const in float lod){float viewDepth=getDepth(uv);return depthToViewZ(viewDepth);}\n#define LOD_DEPTH 1.0\n#define LOD_COLOR 5.0\nvoid _traceRay(in vec4 ray_origin,in vec4 ray_dir,in float tolerance,inout vec3 state,in int loopMax,in float iStepCount){vec4 sample_uv;float d,hit;float dLod=0.;\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(UNROLLED_LOOP_INDEX<loopMax){sample_uv=ray_origin+ray_dir*state.y;d=getDepth2(sample_uv.xy,dLod);d=sample_uv.z/sample_uv.w-d;if(abs(d+tolerance)<tolerance){hit=clamp(state.x/(state.x-d),0.,1.)-1.;hit=(state.y+hit*iStepCount);state.z=min(state.z,hit);}state.x=d;state.y+=1.*iStepCount;}}\n#pragma unroll_loop_end\n}vec3 traceRay(in vec3 ray_origin_view,in vec3 ray_dir_view,in float tolerance,inout vec3 state,in int _STEP_COUNT){vec4 sample_uv;vec4 ray_origin=viewToScreen3(ray_origin_view);vec3 ray_end_view=ray_origin_view+ray_dir_view;vec4 ray_dir=viewToScreen3(ray_end_view);vec2 clamp_end=clamp(ray_dir.xy,vec2(0.),vec2(1.));vec2 correction=abs(ray_dir.xy-clamp_end);correction=(step(0.01,correction)*correction/(abs(clamp_end-ray_origin.xy)+0.01))+1.;correction.x=1./min(max(correction.y,correction.x),10.);ray_dir=ray_dir-ray_origin;ray_dir.xyw*=correction.x;float iStepCount=1./float(_STEP_COUNT);tolerance*=0.125;_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT,iStepCount);if(_STEP_COUNT>8&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-8,iStepCount);if(_STEP_COUNT>15&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);if(_STEP_COUNT>23&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);sample_uv=ray_origin+ray_dir*state.z;sample_uv.z/=sample_uv.w;state.z=state.z<0.999 ? state.z : 9999999.;return sample_uv.xyz;}/**for ray clippinga=ray_originb=ray_endc=clamp(b)x=c.y-a.yy=b.y-c.y(c.y-a.y)/(b.y-c.y)=m/(l-m)m/(l-m)=km=kl-kmm=kl/(1+k)((c-a)/(b-c))/(1+(c-a)/(b-c))x/(y*(1+x/y))x/(y+x)1/(y/x+1)x/(y+yx)1/(y/x+y)ray scale=k/(1+k)1/(1/k+1)=1/((b-c)/(c-a)+1)**/\n#endif\n";var Je=Object.defineProperty,$e=Object.getOwnPropertyDescriptor,Qe=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?$e(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&Je(t,r,n),n},et=(e,t,r)=>((e,t,r)=>t in e?Je(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);const tt=e.ShaderChunk;let rt=class extends H{enabled=!0;_uniforms={sscsRadius:{value:.03},sscsIntensity:{value:1},sscsTolerance:{value:1.5},frameCount:{value:0},projection:{value:new c},cameraPositionWorld:{value:new N},cameraNearFar:{value:new l(.1,1e3)},sceneBoundingRadius:{value:0}};radius=.015;intensity=1;tolerance=1.5;_defines={PERSPECTIVE_CAMERA:1};onlySSCSDebug=!1;stepCount=2;dependencies=[i];materialExtension={uuid:rt.PluginType,priority:5,shaderExtender:(e,t,r)=>{if(!e.defines.SSCS_ENABLED)return;const i=Y`
1
+ var e,t;import{RenderManager as r,PipelinePassPlugin as i,GBufferPlugin as a,ProgressivePlugin as s,generateUiConfig as n,uiToggle as o,uiConfig as l,ExtendedShaderPass as c,Vector2 as d,Matrix4 as u,CopyShader as h,getOrCall as p,serialize as f,uniform as m,uiVector as g,matDefineBool as v,UnsignedByteType as _,shaderReplaceString as y,LinearSRGBColorSpace as x,GBufferRenderPass as S,Color as b,ShaderMaterial as w,NoBlending as T,Matrix3 as D,DoubleSide as P,uiImage as M,uiFolderContainer as E,uiConfigMaterialExtension as C,updateBit as R,Vector4 as A,HalfFloatType as U,AdditiveBlending as L,uiSlider as B,onChange as N,onChange2 as O,Vector3 as F,PickingPlugin as k,now as I,FrameFadePlugin as z,shaderUtils as V,ExtendedShaderMaterial as j,RGBAFormat as G,NearestFilter as H,bindToValue as W,AViewerPluginSync as Y,updateMaterialDefines as X,glsl as K,BaseGroundPlugin as q,matDefine as Z,SSAAPlugin as J,getTexelDecoding as $,AScreenPassExtensionPlugin as Q,animateTarget as ee,RenderPass as te,uiColor as re,makeSamplerUi as ie,SRGBColorSpace as ae,Mesh2 as se,Plane as ne,PerspectiveCamera as oe,MathUtils as le,DirectionalLight2 as ce,copyObject3DUserData as de,Serialization as ue,ThreeSerialization as he,ShadowMaterial as pe,SimpleEventDispatcher as fe,BasicShadowMap as me,ShaderMaterial2 as ge,NoColorSpace as ve,Layers as _e,LinearFilter as ye,LinearMipmapLinearFilter as xe,PCFShadowMap as Se,PCFSoftShadowMap as be,VSMShadowMap as we,uiDropdown as Te,uiInput as De,uiButton as Pe}from"threepipe";const Me={computeScreenSpaceVelocity:"uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;vec2 computeScreenSpaceVelocity(const in vec3 worldPosition){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(worldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(worldPosition,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}",getWorldPositionFromViewZ:"uniform mat4 inverseViewMatrix;vec3 getWorldPositionFromViewZ(const in vec2 uv,const in float viewDepth){vec2 uv_=2.*uv-1.;float xe=-(uv_.x+projection[2][0])*viewDepth/projection[0][0];float ye=-(uv_.y+projection[2][1])*viewDepth/projection[1][1];return(inverseViewMatrix*vec4(xe,ye,viewDepth,1.)).xyz;}",temporalAA:"#include <common>\n#include <gbuffer_unpack>\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#include <cameraHelpers>\nvarying vec2 vUv;uniform vec2 previousRTSize;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;vec3 find_closest_fragment_3x3(const in vec2 uv){const vec3 offset=vec3(-1.0,1.0,0.0);vec2 texelSize=1.0/previousRTSize;vec3 dtr=vec3(1,1,getDepth(uv+offset.yy*texelSize));vec3 dtc=vec3(0,1,getDepth(uv+offset.zy*texelSize));vec3 dtl=vec3(-1,1,getDepth(uv+offset.xy*texelSize));vec3 dml=vec3(-1,0,getDepth(uv+offset.xz*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dmr=vec3(1,0,getDepth(uv+offset.yz*texelSize));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.xx*texelSize));vec3 dbc=vec3(0,-1,getDepth(uv+offset.zx*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.yx*texelSize));vec3 dmin=dtl;if(dmin.z>dtc.z)dmin=dtc;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dml.z)dmin=dml;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dmr.z)dmin=dmr;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbc.z)dmin=dbc;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+texelSize.xy*dmin.xy,dmin.z);}vec3 find_closest_fragment_5tap(const in vec2 uv){vec2 texelSize=1.0/previousRTSize;vec2 offset=vec2(1.0,-1.0);vec3 dtl=vec3(-1,1,getDepth(uv+offset.yx*texelSize));vec3 dtr=vec3(1,1,getDepth(uv+offset.xx*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.yy*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.xy*texelSize));vec3 dmin=dtl;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+dmin.xy*texelSize,dmin.z);}vec4 clip_aabb(const in vec4 aabb_min,const in vec4 aabb_max,vec4 p){const float FLT_EPS=1e-8;vec4 p_clip=0.5*(aabb_max+aabb_min);vec4 e_clip=0.5*(aabb_max-aabb_min)+FLT_EPS;vec4 v_clip=p-p_clip;vec4 v_unit=abs(v_clip/e_clip);float ma_unit=max(v_unit.x,max(v_unit.y,v_unit.z));if(ma_unit>1.0)return p_clip+v_clip/ma_unit;else return p;}\n#if HAS_VELOCITY_BUFFER == 0 || defined(DEBUG_VELOCITY)\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec4 currentRTTexelToLinear1(vec4 a){if(isinf(a.x)||isinf(a.y)||isinf(a.z)||isinf(a.w)){return vec4(1.);}return currentRTTexelToLinear(a);}vec4 computeTAA(const in vec2 uv,const in vec2 screenSpaceVelocity,const in float feedbackScale){vec2 uvUnJitter=uv;vec4 currentColor=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter));vec4 previousColor=previousRTTexelToLinear(texture2D(previousRT,uv-screenSpaceVelocity));const vec3 offset=vec3(1.,-1.,0.);vec2 texelSize=1./previousRTSize;float texelSpeed=length(screenSpaceVelocity);vec4 tl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yx*texelSize));vec4 tc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zx*texelSize));vec4 tr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xx*texelSize));vec4 ml=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yz*texelSize));vec4 mc=currentColor;vec4 mr=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xz*texelSize));vec4 bl=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.yy*texelSize));vec4 bc=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.zy*texelSize));vec4 br=currentRTTexelToLinear1(texture2D(currentRT,uvUnJitter+offset.xy*texelSize));vec4 corners=2.0*(tr+bl+br+tl)-2.0*mc;mc+=(mc-(corners*0.166667))*2.718282*0.3;mc=max(vec4(0.0),mc);vec4 min5=min(tc,min(ml,min(mc,min(mr,bc))));vec4 max5=max(tc,max(ml,max(mc,max(mr,bc))));vec4 cmin=min(min5,min(tl,min(tr,min(bl,br))));vec4 cmax=max(min5,max(tl,max(tr,max(bl,br))));;cmin=0.5*(cmin+min5);cmax=0.5*(cmax+max5);previousColor=clip_aabb(cmin,cmax,previousColor);float lum0=luminance(currentColor.rgb);float lum1=luminance(previousColor.rgb);float unbiased_diff=abs(lum0-lum1)/max(lum0,max(lum1,0.2));float unbiased_weight=1.0-unbiased_diff;float unbiased_weight_sqr=unbiased_weight*unbiased_weight;float k_feedback=mix(feedBack.x,feedBack.y,unbiased_weight_sqr);return mix(currentColor,previousColor,clamp(k_feedback*feedbackScale,0.,1.));}void main(){\n#if HAS_VELOCITY_BUFFER == 0\n#if QUALITY == 1\nvec3 c_frag=find_closest_fragment_3x3(vUv);\n#else\nvec3 c_frag=find_closest_fragment_5tap(vUv);\n#endif\n#else\nvec3 c_frag=vec3(vUv,0.);\n#endif\nbool bg=firstFrame;\n#if BACKGROUND_TAA\nfloat d=c_frag.z;float edgef=min(1.,max(0.,1.-(d*100.-99.)));\n#else\nbg=bg||c_frag.z>0.999;\n#endif\nif(bg){gl_FragColor=currentRTTexelToLinear1(texture2D(currentRT,vUv));}else{\n#if HAS_VELOCITY_BUFFER == 0\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(c_frag.xy);\n#endif\n#if BACKGROUND_TAA\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity*edgef,edgef);\n#else\ngl_FragColor=computeTAA(vUv,screenSpaceVelocity,1.);\n#endif\n}\n#include <colorspace_fragment>\n#ifdef DEBUG_VELOCITY\nfloat sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);gl_FragColor=vec4(10.*length(screenSpaceVelocity),0.,0.,1.);\n#endif\n}",ssReflection:"uniform float currentFrameCount;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nuniform float objectRadius;uniform float radius;uniform float tolerance;uniform float ssrRoughnessFactor;uniform bool autoRadius;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#if SSREFL_ENABLED == 2\nuniform float ssrSplitX;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeReflectionL(vec3 N,vec2 E,vec3 V,float rough){float rough4=rough*rough*rough*rough;float phi=2.0*PI*E.x;float cos_theta=pow(max(E.y,0.000001),rough4/(2.0-rough4));float sin_theta=sqrt(max(0.,1.0-cos_theta*cos_theta));vec3 half_vec=vec3(sin_theta*cos(phi),sin_theta*sin(phi),cos_theta);vec3 tangentX=normalize(cross(abs(N.z)<0.999 ? vec3(0.0,0.0,1.0): vec3(1.0,0.0,0.0),N));vec3 tangentY=cross(N,tangentX);half_vec=half_vec.x*tangentX+half_vec.y*tangentY+half_vec.z*N;vec3 ray_dir=(2.0*dot(V,half_vec))*half_vec-V;return ray_dir;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=interleavedGradientNoise(gl_FragCoord.xy,frameCount*34.+seed);rand_e.y=fract(rand_e.x*38.65435);rand_e.y=mix(rand_e.y,1.0,0.7);return rand_e;}vec4 calculateSSR(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor,in float roughness){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeReflectionL(normal,E,-normalize(viewPos),roughness*ssrRoughnessFactor);L=normalize(L);float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,frameCount+seed);rayLen=max(rayLen,0.001);int steps=SSR_STEP_COUNT/(currentFrameCount<float(SSR_LOW_QUALITY_FRAMES)? 2 : 1);vec3 state=vec3(0.,(r+0.5)/float(steps),2.);viewPos+=normal*max(-0.0001*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,steps);if(state.z<0.99){if(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}",calculateGI:"uniform float currentFrameCount;uniform float intensity;uniform float objectRadius;uniform float rayCount;uniform float power;uniform float bias;uniform float falloff;uniform float tolerance;uniform bool autoRadius;uniform vec2 screenSize;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#else\n#define HAS_VELOCITY_BUFFER 0\n#endif\n#if HAS_VELOCITY_BUFFER == 0\n#include <computeScreenSpaceVelocity>\n#include <getWorldPositionFromViewZ>\n#endif\nvec3 ComputeUniformL(vec3 N,vec2 E){vec3 L;L.xy=E;L.z=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*5.);L=L*2.-1.;return L;}vec2 GetRandomE(float seed){vec2 rand_e;rand_e.x=random3(vec3(gl_FragCoord.xy,currentFrameCount+seed));rand_e.y=random3(vec3(gl_FragCoord.yx,rand_e.x+(currentFrameCount)*7.));return rand_e;}float saturate2(float v,float mx){return max(0.,min(mx,v));}vec4 calculateGI(in float seed,in vec3 screenPos,in vec3 normal,in float radiusFactor){vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);normal=normalize(normal);vec2 E=GetRandomE(seed);vec3 L=ComputeUniformL(normal,E);L=normalize(L);L*=sign(dot(L,normal));float cameraDist=length(cameraPositionWorld);float rayLen=objectRadius*sceneBoundingRadius;rayLen=autoRadius ?min(max(mix(max(0.0,(cameraDist+rayLen)+viewPos.z),max(0.0,-viewPos.z-max(0.0,cameraDist-rayLen)),L.z*0.5+0.5),rayLen*0.1),rayLen*5.):rayLen;rayLen*=radiusFactor;float r=interleavedGradientNoise(gl_FragCoord.xy,currentFrameCount*14.+seed)+0.05;rayLen=max(rayLen,0.001);vec3 state=vec3(1.,(r+0.5)/float(RTAO_STEP_COUNT),2.);viewPos+=normal*max(-0.01*viewPos.z,0.001);vec3 screenHitP=traceRay(viewPos,L*rayLen,tolerance*rayLen,state,RTAO_STEP_COUNT);vec3 viewHitP=screenToView3(screenHitP.xy,screenHitP.z);vec3 LRes=viewHitP-viewPos;if(state.z>1.)LRes=vec3(9999999.);float dist=length(LRes)*falloff;float EPS=0.01;float zBias=(viewPos.z)*bias;float ao=(max(dot(normal,L)+zBias,0.))/(dist*dist+EPS);\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nif(currentFrameCount<1.){\n#if HAS_VELOCITY_BUFFER == 0\nvec3 worldPosition=getWorldPositionFromViewZ(screenHitP.xy,screenHitP.z);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);\n#else\nvec2 screenSpaceVelocity=getVelocity(screenHitP.xy);\n#endif\nscreenHitP.xy-=screenSpaceVelocity;}vec3 hitColor=tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy)).rgb;vec3 hitNormal=getViewNormal(screenHitP.xy);float giWeight=1.;giWeight=saturate2(giWeight/(dist+EPS),1.);giWeight*=saturate2((dot(normal,L)),1.0);giWeight*=saturate2((dot(hitNormal,-L)),1.0);return vec4(hitColor*giWeight,ao);\n#endif\nreturn vec4(0,0,0,ao);}float normpdf(in float x,in float sigma){return exp(-0.5*x*x/(sigma*sigma));}vec4 getLastThis(sampler2D tex,float depth,vec3 normal){vec2 direction=vec2(1,1);vec4 color=clamp(tLastThisTexelToLinear(texture2D(tex,vUv.xy)),0.,5.);return color;}void main(){float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>0.99){discard;gl_FragColor=getLastThis(tLastThis,depth,normal);return;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec4 gi=vec4(0.);gi+=calculateGI(8.,screenPos,normal,1.);if(rayCount>1.5)gi=max(gi,calculateGI(2.,screenPos,normal,0.4));if(rayCount>2.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.5));if(rayCount>3.5)gi=max(gi,calculateGI(1.,screenPos,normal,0.6));if(rayCount>4.5)gi=max(gi,calculateGI(3.,screenPos,normal,1.));gi.a=min(1.,gi.a);gi.a=max(0.,gi.a);gi.rgb=min(vec3(3.),gi.rgb);gi.rgb=max(vec3(0.),gi.rgb);if(currentFrameCount<3.){gl_FragColor=gi;return;}gl_FragColor=(texture2D(tLastThis,vUv));gl_FragColor=((gi+(gl_FragColor)*currentFrameCount)/(currentFrameCount+1.));}",__inited:!1};function Ee(){return Me.__inited||(Me.__inited=!0,Object.assign(r.ShaderChunk,Me)),Me}var Ce=Object.defineProperty,Re=Object.getOwnPropertyDescriptor,Ae=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Re(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Ce(t,r,s),s};const Ue=class extends i{constructor(e=!0){super(),this.passId="taa",this._stableNoise=!0,this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("TemporalAAPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]):this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed"))},this.dependencies=[a,s],this.uiConfig={type:"folder",label:"TemporalAA Plugin",onChange:this.setDirty.bind(this),children:[...n(this)||[]]},this.enabled=e,this.setDirty=this.setDirty.bind(this)}get stableNoise(){return this._viewer?.renderManager.stableNoise??this._stableNoise}set stableNoise(e){this._viewer&&(this._viewer.renderManager.stableNoise=e),this._stableNoise=e}_createPass(){if(!this._viewer)throw new Error("TemporalAAPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");const e=!!this._viewer.renderManager.msaa;return new Be(this.passId,()=>this._viewer?.getPlugin(s)?.target,e)}onAdded(e){super.onAdded(e),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.addEventListener("resize",this._pass.onSizeUpdate)}onRemove(e){e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.renderManager.removeEventListener("resize",this._pass.onSizeUpdate),super.onRemove(e)}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass,a=this._viewer;if(!i||!a)return!1;const n=r.frameCount;if(i.taaEnabled=n<=1&&e.renderCamera===e.mainCamera,!i.taaEnabled)return!1;const o=t;return!!o&&(o.updateMatrixWorld(!0),o.updateShaderProperties(i.material),i.updateCameraProperties(o),i.target=a.getPlugin(s).target,!0)}};Ue.PluginType="TAA",Ue.OldPluginType="TemporalAAPlugin";let Le=Ue;Ae([o("Stable Noise (Total frame count)")],Le.prototype,"stableNoise",1),Ae([l(void 0,{unwrapContents:!0})],Le.prototype,"_pass",2);class Be extends c{constructor(e,t,r=!1){super({vertexShader:h.vertexShader,fragmentShader:Ee().temporalAA,uniforms:{currentRT:{value:null},previousRT:{value:null},previousRTSize:{value:new d},cameraNearFar:{value:new d},lastProjectionViewMatrix:{value:new u},currentProjectionViewMatrix:{value:new u},projection:{value:new u},inverseViewMatrix:{value:new u},jitterSample:{value:new d},firstFrame:{value:!0}},defines:{QUALITY:1,UNJITTER:0,BACKGROUND_TAA:r?1:0}},"currentRT","previousRT"),this.before=["progressive"],this.after=[],this.required=["render","progressive"],this.taaEnabled=!0,this.feedBack=new d(.88,.97),this.debugVelocity=!1,this.uiConfig={type:"folder",label:"Temporal AA Pass",onChange:this.setDirty,children:[{type:"checkbox",label:"Enabled",property:[this,"enabled"],onChange:()=>this.onSizeUpdate()},...n(this)?.filter(e=>e&&"Enabled"!==e.label)||[]]},this.passId=e,this.onSizeUpdate=this.onSizeUpdate.bind(this),this.target=t,this.clear=!1,this.needsSwap=!0}render(e,t,r,i,a){this.taaEnabled&&this.enabled?(this.needsSwap=!0,this.uniforms.previousRT.value=p(this.target)?.texture??null,super.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value),this.uniforms.firstFrame.value=!1):this.needsSwap=!1}updateCameraProperties(e){e&&(this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(e.matrixWorld))}onSizeUpdate(){this.uniforms.firstFrame.value=!0,this.setDirty()}setSize(e,t){super.setSize(e,t),this.onSizeUpdate()}}Ae([f(),m(),g("Feedback",void 0,1e-4)],Be.prototype,"feedBack",2),Ae([o(),v("DEBUG_VELOCITY",void 0,!1,void 0,!0)],Be.prototype,"debugVelocity",2);var Ne=Object.defineProperty,Oe=Object.getOwnPropertyDescriptor,Fe=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Oe(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Ne(t,r,s),s};let ke=class extends i{constructor(e=_,t=!0,r=!0){super(),this.passId="velocityBuffer",this.material=new Ie,this.unpackExtension={shaderExtender:e=>{this.isDisabled()||(e.fragmentShader=y(e.fragmentShader,"#pragma <velocity_unpack>","\n#if defined(HAS_VELOCITY_BUFFER)\nuniform sampler2D tVelocity;vec2 getVelocity(const in vec2 uv){vec2 screenSpaceVelocity=texture2D(tVelocity,uv).xy*2.0-1.0;return sign(screenSpaceVelocity)*pow(abs(screenSpaceVelocity),vec2(4.));}\n#endif\n\n"))},computeCacheKey:()=>this.isDisabled()?"":"vb",extraUniforms:{tVelocity:()=>({value:this.isDisabled()?null:this.target?.texture})},extraDefines:{HAS_VELOCITY_BUFFER:()=>!this.isDisabled()&&this.target?.texture?1:void 0},priority:100,isCompatible:()=>!0},this.enabled=t,this.bufferType=e,this._attachToTaa=r}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!0,samples:0,type:this.bufferType,generateMipmaps:!1,colorSpace:x})),this.texture=this.target.texture,this.texture.name="velocityBuffer",this._pass&&(this._pass.target=this.target))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("VelocityBufferPlugin: target not created");this.material.userData.isGBufferMaterial=!0;const e=this._viewer,t=new class extends S{constructor(){super(...arguments),this._firstCall=!0}render(t,r,i,a,s){if(e.renderManager.frameCount>0)return;if(!this.enabled||!this.camera)return;const n=this.overrideMaterial;n.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse),this._firstCall&&(n.uniforms.lastProjectionViewMatrix.value.copy(n.uniforms.currentProjectionViewMatrix.value),this._firstCall=!1),super.render(t,r,i,a,s),n.uniforms.lastProjectionViewMatrix.value.copy(n.uniforms.currentProjectionViewMatrix.value)}}(this.passId,this.target,this.material,new b(.5,.5,.5),1),r=t.preprocessMaterial;return t.preprocessMaterial=e=>r(e,e.userData[ke.PluginType]?.disabled),t.before=["render"],t.after=[],t.required=["render"],t}onAdded(e){super.onAdded(e),e.forPlugin(Le,e=>{this._attachToTaa&&e.pass?.material.registerMaterialExtensions([this.unpackExtension])},e=>{e.pass?.material?.unregisterMaterialExtensions([this.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),super.onRemove(e)}setDirty(){super.setDirty(),this.unpackExtension.setDirty?.()}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;return!!i&&(!(r.frameCount>0)&&(i.scene=e,i.camera=t,t.updateShaderProperties(i.overrideMaterial),!0))}};ke.PluginType="VelocityBuffer",ke.OldPluginType="VelocityBufferPlugin",Fe([M("Velocity Buffer",{readOnly:!0})],ke.prototype,"texture",2),ke=Fe([E("Velocity Buffer Plugin (for TAA)")],ke);class Ie extends w{constructor(){super({vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <uv_pars_vertex>\n#include <batching_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 modelMatrixPrevious;void main(){\n#include <uv_vertex>\n#include <batching_vertex>\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\nvec4 mvPosition=vec4(transformed,1.0);\n#ifdef USE_INSTANCING\nmvPosition=instanceMatrix*mvPosition;\n#endif\nvWorldPosition=(modelMatrix*mvPosition).xyz;vWorldPositionPrevious=(modelMatrixPrevious*mvPosition).xyz;mvPosition=modelViewMatrix*mvPosition;gl_Position=projectionMatrix*mvPosition;\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\n}",fragmentShader:"varying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 currentProjectionViewMatrix;uniform mat4 lastProjectionViewMatrix;vec2 computeScreenSpaceVelocity2(){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(vWorldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(vWorldPositionPrevious,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}void main(){vec2 velocity=clamp(computeScreenSpaceVelocity2(),-1.0,1.0);velocity=sign(velocity)*pow(abs(velocity),vec2(1./4.));velocity=velocity*0.5+0.5;gl_FragColor=vec4(velocity.x,velocity.y,1.,1.);}",uniforms:{cameraNearFar:{value:new d(.1,1e3)},alphaMap:{value:null},alphaTest:{value:null},alphaMapTransform:{value:/* @__PURE__ */new D},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u}},blending:T}),this.extraUniformsToUpload={modelMatrixPrevious:{value:(new u).identity()}},this._previousWorldMatrices={}}onBeforeRender(e,t,r,i,a,s){super.onBeforeRender(e,t,r,i,a,s);const n=this._previousWorldMatrices[a.uuid];this.extraUniformsToUpload.modelMatrixPrevious.value.copy(n??a.matrixWorld),n?n.copy(a.matrixWorld):this._previousWorldMatrices[a.uuid]=a.matrixWorld.clone();let o=a.material;Array.isArray(o)&&(o=o[0]),this.uniforms.alphaMap.value=o?.alphaMap??null,this.uniforms.alphaTest.value=!o||!o.alphaTest||o.alphaTest<1e-7?.001:o.alphaTest;let l=this.uniforms.alphaMap.value?1:void 0;l!==this.defines.USE_ALPHAMAP&&(void 0===l?delete this.defines.USE_ALPHAMAP:this.defines.USE_ALPHAMAP=l,this.needsUpdate=!0),l=o?.userData.ALPHA_I_RGBA_PACKING?1:void 0,l!==this.defines.ALPHA_I_RGBA_PACKING&&(void 0===l?delete this.defines.ALPHA_I_RGBA_PACKING:this.defines.ALPHA_I_RGBA_PACKING=l,this.needsUpdate=!0),this.side=o?.side??P}}var ze=Object.defineProperty,Ve=Object.getOwnPropertyDescriptor,je=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Ve(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ze(t,r,s),s};const Ge=(e=class extends i{constructor(t=!0){super(),this.passId="bloom",this.materialExtension=C(this._getUiConfig.bind(this),e.PluginType),this.dependencies=[a],this._onPluginAdd=e=>{if(e.plugin?.constructor?.PluginType!==a.PluginType)return;const t=e.plugin;t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass?.material.registerMaterialExtensions([t.unpackExtension]),this._viewer?.removeEventListener("addPlugin",this._onPluginAdd)},this.uiConfig={type:"folder",label:"Bloom Plugin",onChange:this.setDirty.bind(this),children:[...n(this)||[]]},this.enabled=t}_createPass(){return new We(this.passId,Math.min(8,this._viewer?.renderManager.maxHDRIntensity||8))}onAdded(e){super.onAdded(e);const t=e.getPlugin(a);t?(t.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass.material.registerMaterialExtensions([t.unpackExtension])):e.addEventListener("addPlugin",this._onPluginAdd),e.materialManager.registerMaterialExtension(this.materialExtension)}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd);const t=e.getPlugin(a);t?.unregisterGBufferUpdater(this.constructor.PluginType),t&&this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),e.materialManager.unregisterMaterialExtension(this.materialExtension),super.onRemove(e)}updateGBufferFlags(t,r){if(!r.material||!r.material.userData)return;const i=!1===r.material.userData[e.PluginType]?.enable||r.material.userData.pluginsDisabled?0:1;t.w=R(t.w,2,i)}static AddBloomData(t,r,i=!0){const a=t?.userData;if(!a)return null;a[e.PluginType]||(a[e.PluginType]={});const s=a[e.PluginType];return s.enable=!0,r&&Object.assign(s,r),i&&t.setDirty&&t.setDirty(),s}_getUiConfig(t){const r={type:"folder",label:"Bloom",children:[{type:"checkbox",label:"Enabled",get value(){return t.userData[e.PluginType]?.enable??!0},set value(i){let a=t.userData[e.PluginType];i!==a?.enable&&(a||(a=e.AddBloomData(t,void 0,!1)),a.enable=i,t.setDirty(),r.uiRefresh?.(!0,"postFrame"))},onChange:this.setDirty}]};return r}},e.PluginType="Bloom",e.OldPluginType="BloomPlugin",e);je([l(void 0,{unwrapContents:!0})],Ge.prototype,"_pass",2);let He=Ge,We=class extends c{constructor(e,t=16){super({vertexShader:h.vertexShader,defines:{PASS_STEP:1,MAX_INTENSITY:Math.min(t,16)},uniforms:{tSource:{value:null},tDiffuse:{value:null},opacity:{value:1},tDiffuseSize:{value:new d},weight:{value:1}},fragmentShader:"#include <packing>\nuniform float intensity;uniform float opacity;uniform vec2 tDiffuseSize;varying vec2 vUv;uniform float weight;\n#if PASS_STEP == 0\nuniform vec4 prefilter;vec4 Prefilter(vec4 c){\n#ifdef HAS_GBUFFER\n#if !BACKGROUND_BLOOM\nif(getDepth(vUv)>0.999){return vec4(0.0);}\n#endif\n#endif\nfloat brightness=max(c.r,max(c.g,c.b));float soft=brightness+prefilter.x*(prefilter.y-1.);soft=clamp(soft,0.,prefilter.z);soft=soft*soft*prefilter.w;float contribution=max(soft,brightness-prefilter.x);contribution/=max(brightness,0.001);return vec4(c.rgb*contribution,c.a);}\n#endif\nvec4 Sample(vec2 uv){return min(vec4(MAX_INTENSITY,MAX_INTENSITY,MAX_INTENSITY,1.),tDiffuseTexelToLinear(texture2D(tDiffuse,uv)));}vec4 SampleBox(vec2 uv,float delta){vec4 o=vec2(-delta,delta).xxyy/tDiffuseSize.xyxy;vec4 s=Sample(uv+o.xy)+Sample(uv+o.zy)+Sample(uv+o.xw)+Sample(uv+o.zw);return s*0.25;}int getBloomBit(in int number){\n#ifdef WebGL2Context\nreturn(number/4)% 2;\n#else\nreturn int(mod(floor(float(number)/4.),2.));\n#endif\n}void main(){\n#if PASS_STEP == 0\n#ifdef GBUFFER_HAS_FLAGS\nint doBloom=getBloomBit(getGBufferFlags(vUv).a);\n#else\nint doBloom=1;\n#endif\ngl_FragColor=float(doBloom)*weight*Prefilter(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 1\ngl_FragColor=weight*(SampleBox(vUv,1.));gl_FragColor.a=1.;\n#elif PASS_STEP == 2\ngl_FragColor=(SampleBox(vUv,0.5));gl_FragColor.a=1.;\n#elif PASS_STEP == 3\nvec4 texel=tSourceTexelToLinear(texture2D(tSource,vUv));vec4 bloom=intensity*SampleBox(vUv,0.5).rgba;float brightness=max(bloom.r,max(bloom.g,bloom.b));texel.rgb+=bloom.rgb;texel.a=min(1.,texel.a+brightness);gl_FragColor=texel;\n#elif PASS_STEP == 4\nvec4 texel=vec4(0.);texel.rgb+=intensity*SampleBox(vUv,0.5).rgb;texel.a=1.;gl_FragColor=texel;\n#endif\n#include <colorspace_fragment>\n}"},"tDiffuse","tSource"),this.uiConfig=void 0,this.before=["screen"],this.after=["render","progressive"],this.required=["render"],this.prefilter=new A(2,.5,0,0),this.threshold=2,this.softThreshold=.5,this.intensity=.2,this.backgroundBloom=!1,this.bloomIterations=4,this._currentIterations=0,this.radius=.6,this.power=1,this.bloomDebug=!1,this._weights=[],this.passId=e,this._updateWeights=this._updateWeights.bind(this),this._thresholdsUpdated=this._thresholdsUpdated.bind(this),this._updateWeights(),this._thresholdsUpdated(),this.clear=!0}_thresholdsUpdated(){this.prefilter.x=this.threshold,this.prefilter.y=this.softThreshold,this.prefilter.z=2*this.prefilter.x*this.prefilter.y,this.prefilter.w=this.uniforms?.prefilter?.125/(this.uniforms.prefilter.value.z+1e-5):0}render(e,t,r,i,a){const s=e.renderManager;this.material.defines.PASS_STEP=0,this.clear=!0,this.needsSwap=!1;const n=r;if(!n)return void console.warn("BloomPluginPass: No source to read from");this.needsSwap=!0;let o=.5,l=n.width*o,c=n.height*o;const d=[];let u=s.getTempTarget({sizeMultiplier:1,type:U});d.push(u);let h=n;this.material.needsUpdate=!0,this.material.uniforms.weight.value=this._weights[0],super.render(e,u,h,i,a),h=u;const p=this._currentIterations;let f=1;const m=Math.max(2,this.bloomIterations);for(;f<m&&(l/=2,c/=2,o/=2,!(c<2||l<2));f++){u=s.getTempTarget({sizeMultiplier:o,type:U}),d.push(u),this.material.defines.PASS_STEP=1;let t=this._weights[f];t=0!==this._weights[f-1]?this._weights[f]/this._weights[f-1]:this._weights[f],this.material.uniforms.weight.value=t,this.material.needsUpdate=!0,super.render(e,u,h,i,a),h=u,this._currentIterations=f+1}p!==this._currentIterations&&this._updateWeights(!1),this.clear=!1;const g=e.autoClear;for(e.autoClear=!1,f-=2;f>=0;f--)u=d[f],d[f]=void 0,this.material.defines.PASS_STEP=2,this.material.transparent=!0,this.material.blending=L,this.material.needsUpdate=!0,e.autoClear=!1,super.render(e,u,h,i,a),this.material.blending=T,s.releaseTempTarget(h),h=u;this.clear=!0,e.autoClear=g,e.autoClear=!0,this.bloomDebug?(this.material.defines.PASS_STEP=4,this.material.needsUpdate=!0,super.render(e,t,h,i,a)):(this.uniforms.tSource.value=n.texture,this.material.defines.PASS_STEP=3,this.material.needsUpdate=!0,super.render(e,t,h,i,a),this.uniforms.tSource.value=null),s.releaseTempTarget(h)}_updateWeights(e=!0){if(!this._weights)return;const t=Math.max(Math.min(this.radius,1),0),r=Math.max(2,this._currentIterations||this.bloomIterations),i=1/(r-1);for(let a=0;a<r;a++){let e=a*i+.1,r=1.2-e;e=Math.pow(e,this.power),r=Math.pow(r,this.power),this._weights[a]=r*(1-t)+e*t}!1!==e&&this.setDirty()}};je([m()],We.prototype,"prefilter",2),je([B("Threshold",[0,2]),N(We.prototype._thresholdsUpdated),f()],We.prototype,"threshold",2),je([B("Soft Threshold",[0,1]),N(We.prototype._thresholdsUpdated),f()],We.prototype,"softThreshold",2),je([B("Intensity",[0,3]),f(),m()],We.prototype,"intensity",2),je([o("Background Bloom"),f(),v("BACKGROUND_BLOOM")],We.prototype,"backgroundBloom",2),je([B("Iterations",[2,7],1),O(We.prototype._updateWeights),f()],We.prototype,"bloomIterations",2),je([B("Radius",[0,1],.01),O(We.prototype._updateWeights),f()],We.prototype,"radius",2),je([B("Power",[.2,10],.01),O(We.prototype._updateWeights),f()],We.prototype,"power",2),je([o("Debug")],We.prototype,"bloomDebug",2),We=je([E("Bloom Pass")],We);var Ye=Object.defineProperty,Xe=Object.getOwnPropertyDescriptor,Ke=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Xe(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Ye(t,r,s),s};const qe=class extends i{constructor(e=!0,t=!1){super(),this.passId="depthOfField",this.enableEdit=!1,this._focalPointHit=new F(0,0,0),this.crossFadeTime=200,this._focalPointHitTime=0,this.dependencies=[a],this._onPluginAdd=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===a.PluginType){const e=t;this._pass?.material.registerMaterialExtensions([e.unpackExtension]),this._pass?.computeCocMaterial.registerMaterialExtensions([e.unpackExtension]),this._pass?.expandCocMaterial.registerMaterialExtensions([e.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){t.addEventListener("hitObject",this._onObjectHit)}}},this._onPluginRemove=e=>{const t=e.plugin;if(t){if(t.constructor?.PluginType===a.PluginType){const t=e.plugin;this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.computeCocMaterial.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.expandCocMaterial.unregisterMaterialExtensions([t.unpackExtension])}if(t.constructor?.PluginType===k.PluginType){e.plugin.removeEventListener("hitObject",this._onObjectHit)}}},this.uiConfig={type:"folder",label:"DepthOfField",onChange:this.setDirty.bind(this),children:[...n(this)||[],()=>this._pass?.uiConfig]},this._tempVec=new F,this.enabled=e,this.enableEdit=t,this._onObjectHit=this._onObjectHit.bind(this),this.setDirty=this.setDirty.bind(this)}get _frameFadeTime(){return 2.5*this.crossFadeTime}setFocalPoint(e,t=!0,r=!1){this._focalPointHit.copy(e),t&&this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime),r&&(this._focalPointHitTime=I()),this.setDirty()}getFocalPoint(){return this._focalPointHit}_onObjectHit(e){this._pass&&e.intersects.intersect&&!this.isDisabled()&&this.enableEdit&&(this._focalPointHit.copy(e.intersects.intersect.point),this._focalPointHitTime=e.time,e.intersects.selectedObject=null,this._viewer?.getPlugin(z)?.startTransition(this._frameFadeTime),this.setDirty())}_createPass(){return new $e(this.passId)}onAdded(e){super.onAdded(e),e.addEventListener("addPlugin",this._onPluginAdd),e.addEventListener("removePlugin",this._onPluginRemove),this._onPluginAdd({plugin:e.getPlugin(a)}),this._onPluginAdd({plugin:e.getPlugin(k)})}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd),e.removeEventListener("removePlugin",this._onPluginRemove),this._onPluginRemove({plugin:e.getPlugin(a)}),this._onPluginRemove({plugin:e.getPlugin(k)}),super.onRemove(e)}_beforeRender(e,t,r){if(!super._beforeRender(e,t,r))return!1;const i=this.pass;if(!i)return!1;i.dofBlurMaterial.uniforms.frameCount&&r?.updateShaderProperties(i.dofBlurMaterial);const a=t;if(!a)return!1;a.updateMatrixWorld(!0),a.updateShaderProperties(i.material),a.getWorldPosition(this._tempVec),this._tempVec.subVectors(this._focalPointHit,this._tempVec),i.focalDepthRange.x=this._tempVec.length(),i.focalDepthRange.x*=a.getWorldDirection(new F).dot(this._tempVec.normalize());let s=(I()-this._focalPointHitTime)/this.crossFadeTime;if(s=1-Math.min(1,Math.max(0,s)),Math.abs(s-i.crossAlpha)>.01&&(i.crossAlpha=s,this.setDirty()),s>0){const e=this._tempVec.copy(this._focalPointHit).project(a).addScalar(1).divideScalar(2);i.crossCenter.set(e.x,e.y),i.computeCocMaterial.uniformsNeedUpdate=!0,i.expandCocMaterial.uniformsNeedUpdate=!0}return!0}};qe.PluginType="DepthOfField",qe.OldPluginType="DepthOfFieldPlugin";let Ze=qe;Ke([f(),o()],Ze.prototype,"enableEdit",2),Ke([f("focalPoint")],Ze.prototype,"_focalPointHit",2),Ke([f()],Ze.prototype,"crossFadeTime",2);const Je=new j({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new d},direction:{value:new d},frameCount:{value:0},blurRadius:{value:16}},vertexShader:V.defaultVertex,fragmentShader:"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n#include <randomHelpers>\n#include <common>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform float blurRadius;\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvec4 CircularBlur(){vec4 color=colorTextureTexelToLinear(texture2D(colorTexture,vUv));\n#ifdef DOF_MODE\nfloat blurDist=blurRadius*(2.*color.a-1.);\n#else\nfloat blurDist=blurRadius*color.a;\n#endif\nfloat rnd=PI2*random3(vec3(vUv,frameCount*0.1));float costheta=cos(rnd);float sintheta=sin(rnd);vec4 rotationMatrix=vec4(costheta,-sintheta,sintheta,costheta);vec3 colorSum=vec3(0.0);float weightSum=0.001;vec2 ofs;vec4 sampleColor;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));sampleColor=colorTextureTexelToLinear(texture2D(colorTexture,vUv+blurDist*ofs/colorTextureSize.xy));\n#ifdef DOF_MODE\nsampleColor.a=abs(sampleColor.a*2.0-1.0);sampleColor.a*=sampleColor.a*sampleColor.a;\n#endif\ncolorSum+=sampleColor.rgb*sampleColor.a;weightSum+=sampleColor.a;}\n#pragma unroll_loop_end\ncolorSum/=weightSum;return vec4(min(vec3(72.),max(vec3(0.),colorSum)),1.0);}void main(){gl_FragColor=CircularBlur();\n#include <colorspace_fragment>\n}",defines:{DOF_MODE:1}},["colorTexture"]);let $e=class extends c{constructor(e){super({uniforms:{colorTexture:{value:null},blurTexture:{value:null},cocTexture:{value:null},cocTextureSize:{value:new d},cameraNearFar:{value:new d}},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 cocTextureSize;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;uniform vec2 crossCenter;uniform float crossRadius;uniform float crossAlpha;uniform vec3 crossColor;float smoothBoundary(float d,float smooothFactor){smooothFactor*=0.5;float value=smoothstep(-smooothFactor,smooothFactor,d);return value;}float circle(vec2 p,float r){return min((length(p)-r),-(length(p)-r-0.01));}float computeCoc(){float depth=getDepth(vUv);if(depth>1.0-0.01)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){vec4 blur=blurTextureTexelToLinear(texture2D(blurTexture,vUv));float scale=0.5;blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(-1.0,-1.0)/cocTextureSize));blur+=blurTextureTexelToLinear(texture2D(blurTexture,vUv+scale*vec2(1.0,-1.0)/cocTextureSize));blur/=5.0;vec2 uvNearest=(floor(vUv*cocTextureSize)+0.5)/cocTextureSize;float coc=abs(min(2.*cocTextureTexelToLinear(texture2D(cocTexture,uvNearest)).a-1.,computeCoc()));float cocLower=0.005;float cocHigher=0.3;vec4 outColor=vec4(mix(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,blur.rgb,smoothstep(cocLower,cocHigher,coc)),1.0);vec2 d=vUv-crossCenter;if(length(d)>crossRadius+0.05){float dist=circle(d,crossRadius);gl_FragColor=outColor;}else{d.x*=cocTextureSize.x/cocTextureSize.y;float dist=circle(d,crossRadius);dist=smoothBoundary(dist,2.*fwidth(dist));vec4 color=outColor;vec3 dofCircleColor=mix(crossColor,color.rgb,1.-crossAlpha);gl_FragColor=vec4(mix(color.rgb,dofCircleColor,dist),color.a);}\n#include <colorspace_fragment>\n}"},"colorTexture","cocTexture","blurTexture"),this.uiConfig=void 0,this.before=["progressive","screen"],this.after=["render"],this.required=["render"],this.dofBlurMaterial=Je,this.nearFarBlurScale=new d(.25,.25),this.focalDepthRange=new d(.5,1.5),this.crossCenter=new d(.5,.5),this.crossRadius=.04,this.crossAlpha=1,this.crossColor=new b(16750848),this.passId=e,this.computeCocMaterial=new j({uniforms:{colorTexture:{value:null},cameraNearFar:this.uniforms.cameraNearFar,nearFarBlurScale:this.uniforms.nearFarBlurScale,focalDepthRange:this.uniforms.focalDepthRange},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <packing>\nvarying vec2 vUv;uniform vec2 nearFarBlurScale;uniform vec2 cameraNearFar;uniform vec2 focalDepthRange;float computeCoc(){float depth=getDepth(vUv);if(depth==1.0)return max(nearFarBlurScale.x,nearFarBlurScale.y);depth=mix(cameraNearFar.x,cameraNearFar.y,depth);float coc=(depth-focalDepthRange.x)/focalDepthRange.y;coc=clamp(coc,-1.,1.);return(coc>0.0 ? coc*nearFarBlurScale.y : coc*nearFarBlurScale.x);}void main(){gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*computeCoc()+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"]),this.expandCocMaterial=new j({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new d},direction:{value:new d},nearFarBlurScale:this.uniforms.nearFarBlurScale},vertexShader:V.defaultVertex,fragmentShader:"#include <common>\n#include <gbuffer_unpack>\nvarying vec2 vUv;uniform vec2 colorTextureSize;uniform vec2 direction;uniform vec2 nearFarBlurScale;const float MAXIMUM_BLUR_SIZE=4.0;float expandNear(const in vec2 offset,const in bool isBackground){float coc=0.0;vec2 sampleOffsets=MAXIMUM_BLUR_SIZE*offset/5.0;float coc0=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv)).a-1.;float coc1=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-5.0*sampleOffsets)).a-1.;float coc2=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-4.0*sampleOffsets)).a-1.;float coc3=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-3.0*sampleOffsets)).a-1.;float coc4=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-2.0*sampleOffsets)).a-1.;float coc5=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv-1.0*sampleOffsets)).a-1.;float coc6=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+1.0*sampleOffsets)).a-1.;float coc7=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+2.0*sampleOffsets)).a-1.;float coc8=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+3.0*sampleOffsets)).a-1.;float coc9=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+4.0*sampleOffsets)).a-1.;float coc10=2.*colorTextureTexelToLinear(texture2D(colorTexture,vUv+5.0*sampleOffsets)).a-1.;if(isBackground){coc=abs(coc0)*0.095474+(abs(coc1)+abs(coc10))*0.084264+(abs(coc2)+abs(coc9))*0.088139+(abs(coc3)+abs(coc8))*0.091276+(abs(coc4)+abs(coc7))*0.093585+(abs(coc5)+abs(coc6))*0.094998;}else{coc=min(coc0,0.0);coc=min(coc1*0.3,coc);coc=min(coc2*0.5,coc);coc=min(coc3*0.75,coc);coc=min(coc4*0.8,coc);coc=min(coc5*0.95,coc);coc=min(coc6*0.95,coc);coc=min(coc7*0.8,coc);coc=min(coc8*0.75,coc);coc=min(coc9*0.5,coc);coc=min(coc10*0.3,coc);if(abs(coc0)>abs(coc))coc=coc0;}return coc;}void main(){vec2 offset=2.*direction/colorTextureSize;bool isBackground=getDepth(vUv)>1.0-0.001;float coc=expandNear(offset,isBackground);gl_FragColor=vec4(colorTextureTexelToLinear(texture2D(colorTexture,vUv)).rgb,0.5*coc+0.5);\n#include <colorspace_fragment>\n}"},["colorTexture"])}render(e,t,r,i,a){if(!this.enabled)return;if(!r)return void console.error("DepthOfFieldPluginPass: No readBuffer");const s=e.renderManager,n={minFilter:H,magFilter:H,type:U,colorSpace:x,sizeMultiplier:.5,format:G,depthBuffer:!1,generateMipmaps:!1},o=s.getTempTarget(n),l=s.getTempTarget(n);if(this.computeCocMaterial.uniforms.colorTexture.value=r.texture,s.blit(o,{material:this.computeCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=o.texture,this.expandCocMaterial.uniforms.direction.value.set(1,0),s.blit(l,{material:this.expandCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=l.texture,this.expandCocMaterial.uniforms.direction.value.set(0,1),s.blit(o,{material:this.expandCocMaterial}),this.dofBlurMaterial.uniforms.frameCount)this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,s.blit(l,{material:this.dofBlurMaterial});else{const e=s.getTempTarget(n);this.dofBlurMaterial.uniforms.cocTexture.value=o.texture,this.dofBlurMaterial.uniforms.colorTexture.value=o.texture,this.dofBlurMaterial.uniforms.direction.value.set(1,0),s.blit(e,{material:this.dofBlurMaterial}),this.dofBlurMaterial.uniforms.colorTexture.value=e.texture,this.dofBlurMaterial.uniforms.direction.value.set(0,1),s.blit(l,{material:this.dofBlurMaterial}),s.releaseTempTarget(e)}this.material.uniforms.blurTexture.value=l.texture,this.material.uniforms.cocTexture.value=o.texture,super.render(e,t,r,i,a),s.releaseTempTarget(o),s.releaseTempTarget(l)}};Ke([W({obj:"focalDepthRange",key:"y"}),B("Depth Range",[.25,3])],$e.prototype,"depthRange",2),Ke([W({obj:"nearFarBlurScale",key:"x"}),B("Near Blur Scale",[0,1])],$e.prototype,"nearBlurScale",2),Ke([W({obj:"nearFarBlurScale",key:"y"}),B("Far Blur Scale",[0,1])],$e.prototype,"farBlurScale",2),Ke([f(),m()],$e.prototype,"nearFarBlurScale",2),Ke([f(),m()],$e.prototype,"focalDepthRange",2),Ke([m()],$e.prototype,"crossCenter",2),Ke([m()],$e.prototype,"crossRadius",2),Ke([m()],$e.prototype,"crossAlpha",2),Ke([m()],$e.prototype,"crossColor",2),$e=Ke([E("DepthOfField Pass")],$e);const Qe="#ifndef SSRT_PARS_SNIP\n#define SSRT_PARS_SNIP\n#define pow2(a) a*a\nfloat getDepth2(const in vec2 uv,const in float lod){float viewDepth=getDepth(uv);return depthToViewZ(viewDepth);}\n#define LOD_DEPTH 1.0\n#define LOD_COLOR 5.0\nvoid _traceRay(in vec4 ray_origin,in vec4 ray_dir,in float tolerance,inout vec3 state,in int loopMax,in float iStepCount){vec4 sample_uv;float d,hit;float dLod=0.;\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(UNROLLED_LOOP_INDEX<loopMax){sample_uv=ray_origin+ray_dir*state.y;d=getDepth2(sample_uv.xy,dLod);d=sample_uv.z/sample_uv.w-d;if(abs(d+tolerance)<tolerance){hit=clamp(state.x/(state.x-d),0.,1.)-1.;hit=(state.y+hit*iStepCount);state.z=min(state.z,hit);}state.x=d;state.y+=1.*iStepCount;}}\n#pragma unroll_loop_end\n}vec3 traceRay(in vec3 ray_origin_view,in vec3 ray_dir_view,in float tolerance,inout vec3 state,in int _STEP_COUNT){vec4 sample_uv;vec4 ray_origin=viewToScreen3(ray_origin_view);vec3 ray_end_view=ray_origin_view+ray_dir_view;vec4 ray_dir=viewToScreen3(ray_end_view);vec2 clamp_end=clamp(ray_dir.xy,vec2(0.),vec2(1.));vec2 correction=abs(ray_dir.xy-clamp_end);correction=(step(0.01,correction)*correction/(abs(clamp_end-ray_origin.xy)+0.01))+1.;correction.x=1./min(max(correction.y,correction.x),10.);ray_dir=ray_dir-ray_origin;ray_dir.xyw*=correction.x;float iStepCount=1./float(_STEP_COUNT);tolerance*=0.125;_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT,iStepCount);if(_STEP_COUNT>8&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-8,iStepCount);if(_STEP_COUNT>15&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);if(_STEP_COUNT>23&&state.z>0.98)_traceRay(ray_origin,ray_dir,tolerance,state,_STEP_COUNT-16,iStepCount);sample_uv=ray_origin+ray_dir*state.z;sample_uv.z/=sample_uv.w;state.z=state.z<0.999 ? state.z : 9999999.;return sample_uv.xyz;}/**for ray clippinga=ray_originb=ray_endc=clamp(b)x=c.y-a.yy=b.y-c.y(c.y-a.y)/(b.y-c.y)=m/(l-m)m/(l-m)=km=kl-kmm=kl/(1+k)((c-a)/(b-c))/(1+(c-a)/(b-c))x/(y*(1+x/y))x/(y+x)1/(y/x+1)x/(y+yx)1/(y/x+y)ray scale=k/(1+k)1/(1/k+1)=1/((b-c)/(c-a)+1)**/\n#endif\n";var et=Object.defineProperty,tt=Object.getOwnPropertyDescriptor,rt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?tt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&et(t,r,s),s};const it=r.ShaderChunk;let at=class extends Y{constructor(e=!0){super(),this.enabled=!0,this._uniforms={sscsRadius:{value:.03},sscsIntensity:{value:1},sscsTolerance:{value:1.5},frameCount:{value:0},projection:{value:new u},cameraPositionWorld:{value:new F},cameraNearFar:{value:new d(.1,1e3)},sceneBoundingRadius:{value:0}},this.radius=.015,this.intensity=1,this.tolerance=1.5,this._defines={PERSPECTIVE_CAMERA:1},this.onlySSCSDebug=!1,this.stepCount=2,this.dependencies=[a],this.materialExtension={uuid:at.PluginType,priority:5,shaderExtender:(e,t,r)=>{if(!e.defines.SSCS_ENABLED)return;const i=K`
2
2
  #ifndef D_sceneBoundingRadius
3
3
  #define D_sceneBoundingRadius
4
4
  uniform float sceneBoundingRadius;
@@ -19,7 +19,7 @@ import{RenderManager as e,PipelinePassPlugin as t,ProgressivePlugin as r,GBuffer
19
19
  #if defined(SSCS_DEBUG) && SSCS_DEBUG > 0
20
20
  return state.z;
21
21
  #endif
22
- `,a=`\n#if SSCS_ENABLED\n\n uniform float sscsIntensity;\n uniform float sscsRadius;\n uniform float sscsTolerance;\n\n #define THREE_PACKING_INCLUDED // by threejs\n #include <cameraHelpers>\n #include <randomHelpers>\n ${Ze}\n \n#endif\n `+x(tt.shadowmap_pars_fragment,"float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {",`${i}\n`).replace("return shadow;","return min(shadow, state.z);");e.fragmentShader=x(e.fragmentShader,"#include <shadowmap_pars_fragment>",a),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",tt.lights_fragment_begin),e.fragmentShader=x(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;"),e.fragmentShader=x(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;"),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{const i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.sscsDisabled?0:1;W({...this._defines,SSCS_ENABLED:i},t)},extraUniforms:{...this._uniforms},extraDefines:{},computeCacheKey:e=>this.isDisabled()?"0":"1",isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.getPlugin(r),this._viewer?.scene.renderCamera,this._viewer?.renderManager,this._viewer?.scene]};setDirty(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}constructor(e=!0){super(),this.enabled=e}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.getPlugin(X)&&(e.getPlugin(X).material.userData.sscsDisabled=!1),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}_gbufferUnpackExtension=void 0;_gbufferUnpackExtensionChanged=()=>{if(!this._viewer)throw new Error("SSContactShadowPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed"))};setGBufferUnpackExtension(e){this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines))}};et(rt,"PluginType","SSContactShadows"),et(rt,"OldPluginType","SSContactShadowsPlugin"),Qe([n("Enabled"),h(),L(rt.prototype.setDirty)],rt.prototype,"enabled",2),Qe([p({propKey:"sscsRadius",onChange:rt.prototype.setDirty}),U("Radius",[1e-4,.1],1e-4),h()],rt.prototype,"radius",2),Qe([p({propKey:"sscsIntensity",onChange:rt.prototype.setDirty}),U("Intensity",[1e-4,1],1e-4),h()],rt.prototype,"intensity",2),Qe([p({propKey:"sscsTolerance",onChange:rt.prototype.setDirty}),U("Tolerance",[.1,5]),h()],rt.prototype,"tolerance",2),Qe([K("SSCS_DEBUG",void 0,!0,rt.prototype.setDirty),n("Debug only SSCS"),h()],rt.prototype,"onlySSCSDebug",2),Qe([K("SSCS_STEP_COUNT",void 0,!0,rt.prototype.setDirty),U("Step count",[1,8],1),h()],rt.prototype,"stepCount",2),rt=Qe([P("SS Contact Shadows")],rt);const it="#define PI 3.141592653589793\nmat3 GetTangentBasis(vec3 TangentZ){vec3 up=vec3(0.0,0.0,1.0);vec3 TangentX=normalize(cross(dot(TangentZ,up)<0.8 ? up : vec3(1.0,0.0,0.0),TangentZ));vec3 TangentY=cross(TangentZ,TangentX);return mat3(TangentX,TangentY,TangentZ);}vec4 CosineSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=sqrt(E.y);float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=CosTheta*(1.0/PI);return vec4(H,PDF);}vec4 UniformSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=E.y;float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=1.0/(2.*PI);return vec4(H,PDF);}vec2 UniformSampleDiskConcentric(vec2 E){vec2 p=2.*E-1.;float Radius;float Phi;if(abs(p.x)>abs(p.y)){Radius=p.x;Phi=(PI/4.)*(p.y/p.x);}else{Radius=p.y;Phi=(PI/2.)-(PI/4.)*(p.x/p.y);}return vec2(Radius*cos(Phi),Radius*sin(Phi));}vec2 UniformSampleDiskConcentricApprox(vec2 E){vec2 sf=E*sqrt(2.0)-sqrt(0.5);vec2 sq=sf*sf;float root=sqrt(2.0*max(sq.x,sq.y)-min(sq.x,sq.y));if(sq.x>sq.y){sf.x=sf.x>0. ? root :-root;}else{sf.y=sf.y>0. ? root :-root;}return sf;}";var at=Object.defineProperty,nt=Object.getOwnPropertyDescriptor,st=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?nt(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&at(t,r,n),n},ot=(e,t,r)=>((e,t,r)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let lt=class extends t{constructor(e=!0,t=y,r=1,i=!0){super(),this.inlineShaderRayTrace=e,this.enabled=i,this.bufferType=t,this.sizeMultiplier=r}passId="ssrefl";dependencies=[i,q];target;texture;bufferType;sizeMultiplier;_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.inlineShaderRayTrace||(this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssreflBuffer"))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_gbufferUnpackExtension=void 0;_gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSReflectionPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed"))};_createPass(){if(!this._viewer)throw new Error("SSReflectionPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new ct(this.passId,()=>this.target,this.inlineShaderRayTrace)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSReflectionPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(Oe,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}_beforeRender(e,t,i){if(!this._viewer)return!1;const a=super._beforeRender(e,t,i);if(!a)return a;const n=this._viewer.getPlugin(r);return this._pass?.updateShaderProperties([n]),a}get ssrTarget(){return console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead"),this.target}fromJSON(e,t){return e.passes?.ssr&&((e={...e}).pass=e.passes.ssr,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}_viewerListeners={preRender:()=>{if(!this._viewer||this.isDisabled())return;if(!this._pass)return;const e=this._viewer.scene.renderCamera;this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._pass.uniforms.inverseViewMatrix.value.copy(e.matrixWorld)},postRender:()=>{this._viewer&&!this.isDisabled()&&this._pass&&this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value)}}};ot(lt,"PluginType","SSReflectionPlugin"),ot(lt,"OldPluginType","SSReflection"),st([D("SSReflection Buffer",{readOnly:!0,hideOnEmpty:!0})],lt.prototype,"texture",2),st([s(void 0,{unwrapContents:!0})],lt.prototype,"_pass",2),lt=st([P("SSReflection Plugin")],lt);let ct=class extends o{constructor(e,t,r=!0){super({defines:{SSR_STEP_COUNT:16,SSR_RAY_COUNT:4,SSR_RAY_BLEND_MAX:0,SSR_LOW_QUALITY_FRAMES:0,SSR_INLINE:r?"1":"0",SSR_MASK_FRONT_RAYS:!0,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new l(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new l(.1,1e3)},cameraPositionWorld:{value:new N},projection:{value:new c},opacity:{value:1},intensity:{value:0},boost:{value:new N(0,0,0)},objectRadius:{value:0},autoRadius:{value:!1},power:{value:0},maskFrontFactor:{value:-.1},tolerance:{value:0},ssrRoughnessFactor:{value:1},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new c},lastProjectionViewMatrix:{value:new c},inverseViewMatrix:{value:new c},ssrSplitX:{value:.5}},vertexShader:z.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${it}\n\n${Ze}\n\n${Pe().ssReflection}\n\nvoid main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.inlineShaderRayTrace=r,this.passId=e,this.needsSwap=!1,this.clear=!0,r&&Object.assign(this.materialExtension.extraUniforms,{tNormalDepth:this.material.uniforms.tNormalDepth,tLastFrame:this.material.uniforms.tLastFrame,objectRadius:this.material.uniforms.objectRadius,autoRadius:this.material.uniforms.autoRadius,tolerance:this.material.uniforms.tolerance,ssrRoughnessFactor:this.material.uniforms.ssrRoughnessFactor,frameCount:this.material.uniforms.frameCount,currentFrameCount:this.material.uniforms.currentFrameCount,projection:this.material.uniforms.projection,cameraPositionWorld:this.material.uniforms.cameraPositionWorld,cameraNearFar:this.material.uniforms.cameraNearFar,sceneBoundingRadius:this.material.uniforms.sceneBoundingRadius,currentProjectionViewMatrix:this.material.uniforms.currentProjectionViewMatrix,lastProjectionViewMatrix:this.material.uniforms.lastProjectionViewMatrix,inverseViewMatrix:this.material.uniforms.inverseViewMatrix,ssrSplitX:this.material.uniforms.ssrSplitX})}before=["render"];after=["gbuffer","depth"];required=["render","progressive"];intensity=1;boost=new N(1,1,1);objectRadius=1;autoRadius=!0;power=1.1;tolerance=.5;roughnessFactor=1;stepCount=16;rayCount=1;rayBlendMax=!1;setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}lowQualityFrames=0;maskFrontRays=!0;maskFrontFactor=-.2;passId;split=0;render(e,t,r,i,a){if(!this.enabled)return;if(this.inlineShaderRayTrace)return void(this.needsSwap=!1);const n=d(this.target);n?(this.material.defines.HAS_GBUFFER||console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl"),e.renderManager.blit(t,{source:n.texture}),this.uniforms.tLastThis.value=t.texture,super.render(e,n,r,i,a),this.needsSwap=!1):console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false")}beforeRender(e,t,r){this.enabled&&this.updateShaderProperties([e,t,r])}materialExtension={extraUniforms:{tSSReflMap:()=>({value:d(this.target)?.texture??null}),ssrPower:this.material.uniforms.power,ssrIntensity:this.material.uniforms.intensity,ssrMaskFrontFactor:this.material.uniforms.maskFrontFactor,ssrBoost:this.material.uniforms.boost},extraDefines:{SSR_STEP_COUNT:()=>this.material.defines.SSR_STEP_COUNT,SSR_RAY_COUNT:()=>this.material.defines.SSR_RAY_COUNT,SSR_RAY_BLEND_MAX:()=>this.material.defines.SSR_RAY_BLEND_MAX,SSR_LOW_QUALITY_FRAMES:()=>this.material.defines.SSR_LOW_QUALITY_FRAMES,SSR_INLINE:()=>this.material.defines.SSR_INLINE,SSR_MASK_FRONT_RAYS:()=>this.material.defines.SSR_MASK_FRONT_RAYS,PERSPECTIVE_CAMERA:()=>this.material.defines.PERSPECTIVE_CAMERA},shaderExtender:(e,t,r)=>{if(!e.defines?.SSREFL_ENABLED)return;e.fragmentShader=x(e.fragmentShader,"#glMarker beforeModulation","\n \n \n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n\n \n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n \n ",{prepend:!0}),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{let i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssreflDisabled?0:this.split>0?2:1;t.defines.SSREFL_ENABLED!==i&&(t.defines.SSREFL_ENABLED=i,t.needsUpdate=!0),i=t.userData?.ssreflNonPhysical?1:0,t.defines.SSR_NON_PHYSICAL!==i&&(t.defines.SSR_NON_PHYSICAL=i,t.needsUpdate=!0)},parsFragmentSnippet:()=>Y`
22
+ `,a=`\n#if SSCS_ENABLED\n\n uniform float sscsIntensity;\n uniform float sscsRadius;\n uniform float sscsTolerance;\n\n #define THREE_PACKING_INCLUDED // by threejs\n #include <cameraHelpers>\n #include <randomHelpers>\n ${Qe}\n \n#endif\n `+y(it.shadowmap_pars_fragment,"float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {",`${i}\n`).replace("return shadow;","return min(shadow, state.z);");e.fragmentShader=y(e.fragmentShader,"#include <shadowmap_pars_fragment>",a),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",it.lights_fragment_begin),e.fragmentShader=y(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;"),e.fragmentShader=y(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;"),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{const i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.sscsDisabled?0:1;X({...this._defines,SSCS_ENABLED:i},t)},extraUniforms:{...this._uniforms},extraDefines:{},computeCacheKey:e=>this.isDisabled()?"0":"1",isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.getPlugin(s),this._viewer?.scene.renderCamera,this._viewer?.renderManager,this._viewer?.scene]},this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._viewer)throw new Error("SSContactShadowPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed"))},this.enabled=e}setDirty(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.getPlugin(q)&&(e.getPlugin(q).material.userData.sscsDisabled=!1),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}setGBufferUnpackExtension(e){this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines))}};at.PluginType="SSContactShadows",at.OldPluginType="SSContactShadowsPlugin",rt([o("Enabled"),f(),N(at.prototype.setDirty)],at.prototype,"enabled",2),rt([m({propKey:"sscsRadius",onChange:at.prototype.setDirty}),B("Radius",[1e-4,.1],1e-4),f()],at.prototype,"radius",2),rt([m({propKey:"sscsIntensity",onChange:at.prototype.setDirty}),B("Intensity",[1e-4,1],1e-4),f()],at.prototype,"intensity",2),rt([m({propKey:"sscsTolerance",onChange:at.prototype.setDirty}),B("Tolerance",[.1,5]),f()],at.prototype,"tolerance",2),rt([Z("SSCS_DEBUG",void 0,!0,at.prototype.setDirty),o("Debug only SSCS"),f()],at.prototype,"onlySSCSDebug",2),rt([Z("SSCS_STEP_COUNT",void 0,!0,at.prototype.setDirty),B("Step count",[1,8],1),f()],at.prototype,"stepCount",2),at=rt([E("SS Contact Shadows")],at);const st="#define PI 3.141592653589793\nmat3 GetTangentBasis(vec3 TangentZ){vec3 up=vec3(0.0,0.0,1.0);vec3 TangentX=normalize(cross(dot(TangentZ,up)<0.8 ? up : vec3(1.0,0.0,0.0),TangentZ));vec3 TangentY=cross(TangentZ,TangentX);return mat3(TangentX,TangentY,TangentZ);}vec4 CosineSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=sqrt(E.y);float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=CosTheta*(1.0/PI);return vec4(H,PDF);}vec4 UniformSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=E.y;float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=1.0/(2.*PI);return vec4(H,PDF);}vec2 UniformSampleDiskConcentric(vec2 E){vec2 p=2.*E-1.;float Radius;float Phi;if(abs(p.x)>abs(p.y)){Radius=p.x;Phi=(PI/4.)*(p.y/p.x);}else{Radius=p.y;Phi=(PI/2.)-(PI/4.)*(p.x/p.y);}return vec2(Radius*cos(Phi),Radius*sin(Phi));}vec2 UniformSampleDiskConcentricApprox(vec2 E){vec2 sf=E*sqrt(2.0)-sqrt(0.5);vec2 sq=sf*sf;float root=sqrt(2.0*max(sq.x,sq.y)-min(sq.x,sq.y));if(sq.x>sq.y){sf.x=sf.x>0. ? root :-root;}else{sf.y=sf.y>0. ? root :-root;}return sf;}";var nt=Object.defineProperty,ot=Object.getOwnPropertyDescriptor,lt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ot(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&nt(t,r,s),s};let ct=class extends i{constructor(e=!0,t=_,r=1,i=!0){super(),this.inlineShaderRayTrace=e,this.passId="ssrefl",this.dependencies=[a,J],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSReflectionPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed"))},this._viewerListeners={preRender:()=>{if(!this._viewer||this.isDisabled())return;if(!this._pass)return;const e=this._viewer.scene.renderCamera;this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._pass.uniforms.inverseViewMatrix.value.copy(e.matrixWorld)},postRender:()=>{this._viewer&&!this.isDisabled()&&this._pass&&this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value)}},this.enabled=i,this.bufferType=t,this.sizeMultiplier=r}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.inlineShaderRayTrace||(this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssreflBuffer"))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSReflectionPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new dt(this.passId,()=>this.target,this.inlineShaderRayTrace)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSReflectionPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(ke,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}_beforeRender(e,t,r){if(!this._viewer)return!1;const i=super._beforeRender(e,t,r);if(!i)return i;const a=this._viewer.getPlugin(s);return this._pass?.updateShaderProperties([a]),i}get ssrTarget(){return console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead"),this.target}fromJSON(e,t){return e.passes?.ssr&&((e={...e}).pass=e.passes.ssr,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}};ct.PluginType="SSReflectionPlugin",ct.OldPluginType="SSReflection",lt([M("SSReflection Buffer",{readOnly:!0,hideOnEmpty:!0})],ct.prototype,"texture",2),lt([l(void 0,{unwrapContents:!0})],ct.prototype,"_pass",2),ct=lt([E("SSReflection Plugin")],ct);let dt=class extends c{constructor(e,t,r=!0){super({defines:{SSR_STEP_COUNT:16,SSR_RAY_COUNT:4,SSR_RAY_BLEND_MAX:0,SSR_LOW_QUALITY_FRAMES:0,SSR_INLINE:r?"1":"0",SSR_MASK_FRONT_RAYS:!0,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new d(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new d(.1,1e3)},cameraPositionWorld:{value:new F},projection:{value:new u},opacity:{value:1},intensity:{value:0},boost:{value:new F(0,0,0)},objectRadius:{value:0},autoRadius:{value:!1},power:{value:0},maskFrontFactor:{value:-.1},tolerance:{value:0},ssrRoughnessFactor:{value:1},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u},inverseViewMatrix:{value:new u},ssrSplitX:{value:.5}},vertexShader:V.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n\n${Qe}\n\n${Ee().ssReflection}\n\nvoid main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.inlineShaderRayTrace=r,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render","progressive"],this.intensity=1,this.boost=new F(1,1,1),this.objectRadius=1,this.autoRadius=!0,this.power=1.1,this.tolerance=.5,this.roughnessFactor=1,this.stepCount=16,this.rayCount=1,this.rayBlendMax=!1,this.lowQualityFrames=0,this.maskFrontRays=!0,this.maskFrontFactor=-.2,this.split=0,this.materialExtension={extraUniforms:{tSSReflMap:()=>({value:p(this.target)?.texture??null}),ssrPower:this.material.uniforms.power,ssrIntensity:this.material.uniforms.intensity,ssrMaskFrontFactor:this.material.uniforms.maskFrontFactor,ssrBoost:this.material.uniforms.boost},extraDefines:{SSR_STEP_COUNT:()=>this.material.defines.SSR_STEP_COUNT,SSR_RAY_COUNT:()=>this.material.defines.SSR_RAY_COUNT,SSR_RAY_BLEND_MAX:()=>this.material.defines.SSR_RAY_BLEND_MAX,SSR_LOW_QUALITY_FRAMES:()=>this.material.defines.SSR_LOW_QUALITY_FRAMES,SSR_INLINE:()=>this.material.defines.SSR_INLINE,SSR_MASK_FRONT_RAYS:()=>this.material.defines.SSR_MASK_FRONT_RAYS,PERSPECTIVE_CAMERA:()=>this.material.defines.PERSPECTIVE_CAMERA},shaderExtender:(e,t,r)=>{if(!e.defines?.SSREFL_ENABLED)return;e.fragmentShader=y(e.fragmentShader,"#glMarker beforeModulation","\n \n \n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n\n \n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n \n ",{prepend:!0}),this._gbufferUnpackExtension?.shaderExtender?.(e,t,r)},onObjectRender:(e,t,r)=>{let i=!this.enabled||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssreflDisabled?0:this.split>0?2:1;t.defines.SSREFL_ENABLED!==i&&(t.defines.SSREFL_ENABLED=i,t.needsUpdate=!0),i=t.userData?.ssreflNonPhysical?1:0,t.defines.SSR_NON_PHYSICAL!==i&&(t.defines.SSR_NON_PHYSICAL=i,t.needsUpdate=!0)},parsFragmentSnippet:()=>K`
23
23
  #if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0
24
24
  uniform float ssrPower;
25
25
  uniform float ssrIntensity;
@@ -27,14 +27,14 @@ import{RenderManager as e,PipelinePassPlugin as t,ProgressivePlugin as r,GBuffer
27
27
  uniform vec3 ssrBoost;
28
28
  uniform sampler2D tSSReflMap;
29
29
  uniform sampler2D tLastFrame;
30
- ${Z("tSSReflMap",d(this.target)?.texture.colorSpace)}
31
- ${Z("tLastFrame",this.material.uniforms.tLastFrame.value?.colorSpace)}
32
- ${this.inlineShaderRayTrace?`\n#define THREE_PACKING_INCLUDED // by threejs\n#include <cameraHelpers>\n#include <randomHelpers>\n${it}\n${Ze}\n${Pe().ssReflection}\n `:""}
30
+ ${$("tSSReflMap",p(this.target)?.texture.colorSpace)}
31
+ ${$("tLastFrame",this.material.uniforms.tLastFrame.value?.colorSpace)}
32
+ ${this.inlineShaderRayTrace?`\n#define THREE_PACKING_INCLUDED // by threejs\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n${Qe}\n${Ee().ssReflection}\n `:""}
33
33
  #include <simpleCameraHelpers>
34
34
  #endif
35
- `,computeCacheKey:()=>(this.enabled?"1":"0")+d(this.target)?.texture?.colorSpace+Object.values(this.material.defines).map(e=>e+"").join(","),uuid:lt.PluginType,...M(this._getUiConfig.bind(this),lt.PluginType),isCompatible:e=>e.isPhysicalMaterial};_getUiConfig(e){return{type:"folder",label:"SSReflection",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssreflDisabled},set value(t){t!==!e.userData.ssreflDisabled&&(e.userData.ssreflDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Non Physical",get value(){return e.userData.ssreflNonPhysical??!1},set value(t){t!==(e.userData.ssreflNonPhysical??!1)&&(e.userData.ssreflNonPhysical=t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}_gbufferUnpackExtension;setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines)))}};st([U("Intensity",[0,4]),h(),p()],ct.prototype,"intensity",2),st([f("Boost"),h(),p()],ct.prototype,"boost",2),st([U("Object Radius",[.01,2]),h(),p()],ct.prototype,"objectRadius",2),st([n("Auto radius"),h(),p()],ct.prototype,"autoRadius",2),st([U("Power",[0,3]),h(),p()],ct.prototype,"power",2),st([U("Tolerance",[.1,5]),h(),p()],ct.prototype,"tolerance",2),st([U("Roughness Factor",[.1,1.25]),h(),p({propKey:"ssrRoughnessFactor"})],ct.prototype,"roughnessFactor",2),st([U("Step count",[1,32],1,{tags:["performance"]}),h(),K("SSR_STEP_COUNT",void 0,void 0,ct.prototype.setDirty)],ct.prototype,"stepCount",2),st([U("Ray count",[1,8],1,{tags:["performance"]}),h(),K("SSR_RAY_COUNT",void 0,void 0,ct.prototype.setDirty)],ct.prototype,"rayCount",2),st([n("Ray Blend MAX"),h(),m("SSR_RAY_BLEND_MAX",void 0,void 0,ct.prototype.setDirty,!0)],ct.prototype,"rayBlendMax",2),st([U("Low Quality Frames",[0,4],1),h(),K("SSR_LOW_QUALITY_FRAMES",void 0,void 0,ct.prototype.setDirty)],ct.prototype,"lowQualityFrames",2),st([n("Ignore front rays"),h(),m("SSR_MASK_FRONT_RAYS",void 0,void 0,ct.prototype.setDirty)],ct.prototype,"maskFrontRays",2),st([U("Mask front rays factor",[-1,1],.01,e=>({hidden:()=>!e.maskFrontRays})),h(),p()],ct.prototype,"maskFrontFactor",2),st([U("Split",[0,1],.01,{tags:["debug"]}),h(),p({propKey:"ssrSplitX",onChange:ct.prototype.setDirty})],ct.prototype,"split",2),ct=st([P("SSReflection Pass")],ct);var ut=Object.defineProperty,dt=Object.getOwnPropertyDescriptor,ht=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?dt(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&ut(t,r,n),n},pt=(e,t,r)=>((e,t,r)=>t in e?ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let ft=class extends J{passId="outline";extraUniforms={outlineIntensity:{value:1},outlineThickness:{value:2},highlightTransparency:{value:1},outlineColor:{value:new _(15305317)},enableHighlight:{value:!0},dpr:{value:1},outlineBuffer:{value:null},tDiffuseSize:{value:new l(1024,1024)}};extraDefines={DEBUG_OUTLINE:"0"};priority=-101;enabled;enableHighlight=!1;enableDynamicSelection=!0;intensity=2;highlightTransparency=.84;color=new _(15305317);thickness=2;debugOutline=!1;highlightSelectedMaterials=!1;highlightMaterialSameNames=!1;transparency=0;parsFragmentSnippet=()=>this.isDisabled()?"":Y`
35
+ `,computeCacheKey:()=>(this.enabled?"1":"0")+p(this.target)?.texture?.colorSpace+Object.values(this.material.defines).map(e=>e+"").join(","),uuid:ct.PluginType,...C(this._getUiConfig.bind(this),ct.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.passId=e,this.needsSwap=!1,this.clear=!0,r&&Object.assign(this.materialExtension.extraUniforms,{tNormalDepth:this.material.uniforms.tNormalDepth,tLastFrame:this.material.uniforms.tLastFrame,objectRadius:this.material.uniforms.objectRadius,autoRadius:this.material.uniforms.autoRadius,tolerance:this.material.uniforms.tolerance,ssrRoughnessFactor:this.material.uniforms.ssrRoughnessFactor,frameCount:this.material.uniforms.frameCount,currentFrameCount:this.material.uniforms.currentFrameCount,projection:this.material.uniforms.projection,cameraPositionWorld:this.material.uniforms.cameraPositionWorld,cameraNearFar:this.material.uniforms.cameraNearFar,sceneBoundingRadius:this.material.uniforms.sceneBoundingRadius,currentProjectionViewMatrix:this.material.uniforms.currentProjectionViewMatrix,lastProjectionViewMatrix:this.material.uniforms.lastProjectionViewMatrix,inverseViewMatrix:this.material.uniforms.inverseViewMatrix,ssrSplitX:this.material.uniforms.ssrSplitX})}setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}render(e,t,r,i,a){if(!this.enabled)return;if(this.inlineShaderRayTrace)return void(this.needsSwap=!1);const s=p(this.target);s?(this.material.defines.HAS_GBUFFER||console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl"),e.renderManager.blit(t,{source:s.texture}),this.uniforms.tLastThis.value=t.texture,super.render(e,s,r,i,a),this.needsSwap=!1):console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false")}beforeRender(e,t,r){this.enabled&&this.updateShaderProperties([e,t,r])}_getUiConfig(e){return{type:"folder",label:"SSReflection",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssreflDisabled},set value(t){t!==!e.userData.ssreflDisabled&&(e.userData.ssreflDisabled=!t,e.setDirty())},onChange:this.setDirty},{type:"checkbox",label:"Non Physical",get value(){return e.userData.ssreflNonPhysical??!1},set value(t){t!==(e.userData.ssreflNonPhysical??!1)&&(e.userData.ssreflNonPhysical=t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines)))}};lt([B("Intensity",[0,4]),f(),m()],dt.prototype,"intensity",2),lt([g("Boost"),f(),m()],dt.prototype,"boost",2),lt([B("Object Radius",[.01,2]),f(),m()],dt.prototype,"objectRadius",2),lt([o("Auto radius"),f(),m()],dt.prototype,"autoRadius",2),lt([B("Power",[0,3]),f(),m()],dt.prototype,"power",2),lt([B("Tolerance",[.1,5]),f(),m()],dt.prototype,"tolerance",2),lt([B("Roughness Factor",[.1,1.25]),f(),m({propKey:"ssrRoughnessFactor"})],dt.prototype,"roughnessFactor",2),lt([B("Step count",[1,32],1,{tags:["performance"]}),f(),Z("SSR_STEP_COUNT",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"stepCount",2),lt([B("Ray count",[1,8],1,{tags:["performance"]}),f(),Z("SSR_RAY_COUNT",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"rayCount",2),lt([o("Ray Blend MAX"),f(),v("SSR_RAY_BLEND_MAX",void 0,void 0,dt.prototype.setDirty,!0)],dt.prototype,"rayBlendMax",2),lt([B("Low Quality Frames",[0,4],1),f(),Z("SSR_LOW_QUALITY_FRAMES",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"lowQualityFrames",2),lt([o("Ignore front rays"),f(),v("SSR_MASK_FRONT_RAYS",void 0,void 0,dt.prototype.setDirty)],dt.prototype,"maskFrontRays",2),lt([B("Mask front rays factor",[-1,1],.01,e=>({hidden:()=>!e.maskFrontRays})),f(),m()],dt.prototype,"maskFrontFactor",2),lt([B("Split",[0,1],.01,{tags:["debug"]}),f(),m({propKey:"ssrSplitX",onChange:dt.prototype.setDirty})],dt.prototype,"split",2),dt=lt([E("SSReflection Pass")],dt);var ut=Object.defineProperty,ht=Object.getOwnPropertyDescriptor,pt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ht(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ut(t,r,s),s};let ft=class extends Q{constructor(e=!0,t=_){super(),this.passId="outline",this.extraUniforms={outlineIntensity:{value:1},outlineThickness:{value:2},highlightTransparency:{value:1},outlineColor:{value:new b(15305317)},enableHighlight:{value:!0},dpr:{value:1},outlineBuffer:{value:null},tDiffuseSize:{value:new d(1024,1024)}},this.extraDefines={DEBUG_OUTLINE:"0"},this.priority=-101,this.enableHighlight=!1,this.enableDynamicSelection=!0,this.intensity=2,this.highlightTransparency=.84,this.color=new b(15305317),this.thickness=2,this.debugOutline=!1,this.highlightSelectedMaterials=!1,this.highlightMaterialSameNames=!1,this.transparency=0,this.parsFragmentSnippet=()=>this.isDisabled()?"":K`
36
36
  ${"uniform sampler2D outlineBuffer;uniform vec2 tDiffuseSize;uniform vec3 outlineColor;uniform float outlineThickness;uniform float outlineIntensity;uniform float highlightTransparency;uniform bool enableHighlight;uniform float dpr;float isSelected(vec2 uv){return 1.-texture2D(outlineBuffer,uv).b;}vec4 outline(in vec4 color){vec2 invSize=1.0/tDiffuseSize;\n#if DEBUG_OUTLINE > 0\ncolor=vec4(0.,0.,0.,1.);\n#endif\nvec3 finalColor=color.rgb;float c=isSelected(vUv);if(c>0.){vec4 uvOffset=1.5*dpr*outlineThickness*vec4(1.0,0.0,-1.0,1.0)*vec4(invSize,invSize);float c1=isSelected(vUv+uvOffset.xy);float c2=isSelected(vUv-uvOffset.xy);float c3=isSelected(vUv+uvOffset.yw);float c4=isSelected(vUv-uvOffset.yw);float diff1=(c1-c2)*0.5;float diff2=(c3-c4)*0.5;float d=length(vec2(diff1,diff2));vec4 highlightColor=enableHighlight ? vec4(c*outlineColor,(1.-highlightTransparency)*c): vec4(0.);vec4 edgeColor=vec4(outlineColor,1.)*vec4(d);float gbufferDepth=getDepth(vUv);float outlineDepth=unpack16(texture2D(outlineBuffer,vUv).xy);outlineDepth*=outlineDepth;outlineDepth-=0.005;if(gbufferDepth<outlineDepth){highlightColor.rgb=highlightColor.rgb*0.3;edgeColor.rgb=edgeColor.rgb*0.5;}vec4 outColor=edgeColor+highlightColor*(1.-d);finalColor=mix(color.rgb,outlineIntensity*outColor.rgb,outColor.a);}else{finalColor.rgb=color.rgb;}return vec4(finalColor.rgb,color.a);}"}
37
- `;_shaderPatch="diffuseColor = outline(diffuseColor);";constructor(e=!0,t=y){super(),this.enabled=e,this.bufferType=t}dependencies=[k,i];_pickingWidgetDisabled=!1;setDirty(){if(super.setDirty(),!this._viewer)return;const e=this._viewer.getPlugin(k);let t=!this.isDisabled();if(t){const r=e?.getSelectedObject();"string"==typeof r?.type&&r?.type?.includes("Line")&&(t=!1)}e&&(t&&e.widgetEnabled?(e.widgetEnabled=!1,this._pickingWidgetDisabled=!0):!t&&this._pickingWidgetDisabled&&(e.widgetEnabled=!0,this._pickingWidgetDisabled=!1)),this._viewer.setDirty()}_pass;onAdded(e){super.onAdded(e),this.setDirty(),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),e.renderManager.registerPass(this._pass);const t=e.getPlugin(k);t?.addEventListener("selectedObjectChanged",()=>{!this._animationCallBack&&this&&(t?.getSelectedObject()?this.enableDynamicSelection?(this.transparency=1,this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,400)):this.transparency=this.highlightTransparency:this.transparency=1)}),document.addEventListener("mousemove",r=>{if(!this)return;if(!this.mouseInOutAnimationEnabled)return;if(!this.enableHighlight)return;const i=t?.getSelectedObject();i&&this.enableDynamicSelection?r.target!==e.canvas?this._animationCallBack||"in"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(this.highlightTransparency,1,600),this._state="out"):this._animationCallBack||"out"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,600),this._state="in"):this.transparency=i?this.highlightTransparency:1})}onRemove(e){return this._disposeTarget(),this._pass&&(e.renderManager.unregisterPass(this._pass),this._pass.dispose&&this._pass.dispose()),this._pass=void 0,super.onRemove(e)}target;texture;material=new S({uniforms:{cameraNearFar:{value:new l(.1,100)}},vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vViewPosition;void main(){\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\nvViewPosition=-mvPosition.xyz;}",fragmentShader:"uniform vec2 cameraNearFar;varying vec3 vViewPosition;vec2 pack16(float value){float sMax=65535.0;int v=int(clamp(value,0.0,1.0)*sMax+0.5);int digit0=v/256;int digit1=v-digit0*256;return vec2(float(digit0)/255.0,float(digit1)/255.0);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));gl_FragColor=vec4(packedZ.x,packedZ.y,0.,0.);}",side:T});bufferType;_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({sizeMultiplier:1,type:this.bufferType})),this.texture=this.target.texture,this.texture.name="normalBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_getSelectedObject=()=>{if(!this._viewer)return null;const e=this._viewer.getPlugin(k);if(this.highlightSelectedMaterials){const t=e?.getSelectedObject()?.material||null;if(this.highlightMaterialSameNames&&t){const e=Array.isArray(t)?t.map(e=>e.name):[t.name],r=/* @__PURE__ */new Set;for(const t of e){const e=this._viewer?.assetManager?.materials?.findMaterialsByName(t);e?.forEach(e=>r.add(e))}return[...r]}return t}return e?.getSelectedObject()||null};_createPass(){if(this._createTarget(!0),!this.target)throw new Error("OutlinePlugin: target not created");this.material.userData.isOutlinePluginMaterial=!0;return new mt(this.passId,this._getSelectedObject,()=>this.target,this.material)}_viewerListeners={preRender:()=>{!this.isDisabled()&&this._viewer&&(this.extraUniforms.dpr.value=2*this._viewer.renderManager.renderScale)}};mouseInOutAnimationEnabled=!0;_state="in";_animationCallBack;async _startTransparencyAnimation(e,t,r){return $(this,"transparency",{from:e,to:t,duration:r,onComplete:()=>{this._animationCallBack=void 0}})}get outlineIntensity(){return console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineIntensity(e){console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}get outlineColor(){return console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineColor(e){console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}};pt(ft,"PluginType","OutlinePlugin"),pt(ft,"OldPluginType","Outline"),ht([L(ft.prototype.setDirty),n("Enable"),h()],ft.prototype,"enabled",2),ht([n("Highlight"),p({propKey:"enableHighlight"}),h()],ft.prototype,"enableHighlight",2),ht([L(ft.prototype.setDirty),n("DynamicSelection"),h()],ft.prototype,"enableDynamicSelection",2),ht([U("Intensity",[0,4],.001),p({propKey:"outlineIntensity"}),h("outlineIntensity")],ft.prototype,"intensity",2),ht([L(ft.prototype.setDirty),U("Transparency",[0,1],.01),h()],ft.prototype,"highlightTransparency",2),ht([ee("Color"),p({propKey:"outlineColor"}),h("outlineColor")],ft.prototype,"color",2),ht([U("Thickness",[0,10],.01),p({propKey:"outlineThickness"}),h("outlineThickness")],ft.prototype,"thickness",2),ht([n("Debug"),m("DEBUG_OUTLINE",void 0,!0)],ft.prototype,"debugOutline",2),ht([L(ft.prototype.setDirty),n("Highlight Selected Materials")],ft.prototype,"highlightSelectedMaterials",2),ht([L(ft.prototype.setDirty),n("Highlight Materials (same name)")],ft.prototype,"highlightMaterialSameNames",2),ht([p({propKey:"highlightTransparency"})],ft.prototype,"transparency",2),ht([p({propKey:"outlineBuffer"}),D("Outline Buffer",{readOnly:!0})],ft.prototype,"texture",2),ft=ht([P("Selection Outline")],ft);let mt=class extends Q{constructor(e,t,r,i){super(void 0,void 0,i,new _(1,1,1),1),this.passId=e,this._getSelectedObjectOrMaterial=t,this.target=r}isOutlineRenderPass=!0;enabled=!0;before=["render"];after=["gbuffer"];required=["render","gbuffer"];render(e,t,r,i,a){if(!this.scene||!this.camera||!this.enabled)return;const n=e.getRenderTarget(),s=e.getActiveCubeFace(),o=e.getActiveMipmapLevel(),l=this._getSelectedObjectOrMaterial();if(l)this._renderSelectedObject(e,l,t||null,i,a);else{e.setRenderTarget(d(this.target)||null);const t=new _;e.getClearColor(t),e.setClearColor(new _(16777215)),e.clear(!0,!0),e.setClearColor(t)}e.setRenderTarget(n,s,o)}_renderSelectedObject(e,t,r,i,a){if(!this.camera||!t)return;const n=(Array.isArray(t)?t:[t]).flatMap(e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e).flatMap(e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e);for(const l of n)l&&l.traverse(e=>{e.layers.enable(6)});const s=this.camera.layers.mask;this.camera.layers.set(6);const o=e.userData;o||console.error("threejs is not patched?"),o.transmissionRenderTarget=r,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!0,transmissionRender:!0,mainRenderPass:!1},()=>super.render(e,r,d(this.target),i,a)),o.transmissionRenderTarget=void 0,n.forEach(e=>e.traverse(e=>{e.layers.disable(6)})),this.camera.layers.mask=s}onDirty=[];dispose(){this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach(e=>e())}beforeRender(e,t,r){this.scene=e,this.camera=t,t.updateShaderProperties(this.overrideMaterial)}};ht([n("Enabled")],mt.prototype,"enabled",2),mt=ht([P(e=>e.passId+" Render Pass")],mt);var gt=Object.defineProperty,vt=(e,t,r,i)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,r,n)||n);return n&&gt(t,r,n),n};class _t extends o{constructor(e,t="rgba"){super({vertexShader:u.vertexShader,fragmentShader:"\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\nuniform vec2 tDiffuseSize;uniform vec2 bilDirection;varying vec2 vUv;uniform bool smoothEnabled;uniform float edgeSharpness;vec4 bilaterialAO(){vec4 color=clamp((texture2D(tDiffuse,vUv.xy)).B_SRC_ACCESSOR,0.,5.);if(!smoothEnabled)return color;float depth;vec3 normal;getDepthNormal(vUv.xy,depth,normal);float gaussianWeights[4];gaussianWeights[0]=0.153170;gaussianWeights[1]=0.144893;gaussianWeights[2]=0.122649;gaussianWeights[3]=0.092902;float Z=gaussianWeights[0]+0.03;vec4 final_colour=Z*color;vec2 nuv;vec4 cc;float dp;vec3 nor;vec2 direction=bilDirection/tDiffuseSize.xy;\n#pragma unroll_loop_start\nfor(int i=0;i<6;i++){direction*=-1.;nuv=vUv+2.*direction*float(UNROLLED_LOOP_INDEX/2+1);getDepthNormal(nuv,dp,nor);if(dp<0.999){float normalCloseness=dot(normal,nor);normalCloseness*=normalCloseness;float normalError=(1.0-normalCloseness)*8.;float normalWeight=max((1.0-normalError*edgeSharpness),0.00);float depthWeight=max(0.0,1.0-edgeSharpness*4000.*abs(depth-dp));float kernelWeight=gaussianWeights[UNROLLED_LOOP_INDEX/2]+0.03;float bilateralWeight=kernelWeight*depthWeight*normalWeight;Z+=bilateralWeight;cc=clamp((texture2D(tDiffuse,nuv)).B_SRC_ACCESSOR,0.,5.);final_colour+=bilateralWeight*cc;}}\n#pragma unroll_loop_end\nfinal_colour/=Z;return final_colour;}void main(){vec4 ao=clamp(bilaterialAO(),vec4(0.),vec4(1.));gl_FragColor=ao;}",uniforms:{bilDirection:{value:new l(1,0)},tDiffuse:{value:null},tDiffuseSize:{value:new l}},defines:{B_SRC_ACCESSOR:t}},"tDiffuse"),this.target=e,this.clear=!1,this.needsSwap=!1}smoothEnabled=!0;edgeSharpness=.1;render(e,t,r,i,a){if(!this.enabled)return;const n=d(this.target);n&&(this.uniforms.bilDirection.value.set(1,0),this.uniforms.tDiffuse.value=n.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,t,n,i,a),this.uniforms.bilDirection.value.set(0,1),this.uniforms.tDiffuse.value=t.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,n,t,i,a))}}vt([h(),p()],_t.prototype,"smoothEnabled"),vt([h(),p()],_t.prototype,"edgeSharpness");var yt=Object.defineProperty,xt=Object.getOwnPropertyDescriptor,St=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?xt(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&yt(t,r,n),n},bt=(e,t,r)=>((e,t,r)=>t in e?yt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);let wt=class extends t{passId="ssrtgi";dependencies=[i,q];target;texture;bufferType;sizeMultiplier;constructor(e=y,t=1,r=!0){super(),this.enabled=r,this.bufferType=e,this.sizeMultiplier=t}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssgiBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_gbufferUnpackExtension=void 0;_gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSGIPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed"))};_createPass(){if(!this._viewer)throw new Error("SSGIPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new Tt(this.passId,()=>this.target)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSGIPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(Oe,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssrtgi&&((e={...e}).pass=e.passes.ssrtgi,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}_beforeRender(e,t,i){if(!this._viewer)return!1;const a=super._beforeRender(e,t,i);if(a){const e=this._viewer?.getPlugin("SSAOPlugin");e&&!e.isDisabled()&&e.disable(wt.PluginType)}if(!a)return a;const n=this._viewer.getPlugin(r);return this._pass?.updateShaderProperties([n]),a}get rtgiTarget(){return console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead"),this.target}};bt(wt,"PluginType","SSGIPlugin"),bt(wt,"OldPluginType","SSGI"),St([D("SSGI Buffer",{readOnly:!0})],wt.prototype,"texture",2),St([s(void 0,{unwrapContents:!0})],wt.prototype,"_pass",2),wt=St([P("SSGI Plugin")],wt);let Tt=class extends o{constructor(e,t,r=!0){super({defines:{RTAO_STEP_COUNT:16,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new l(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new l(.1,1e3)},cameraPositionWorld:{value:new N},projection:{value:new c},opacity:{value:1},intensity:{value:0},objectRadius:{value:0},autoRadius:{value:!r},rayCount:{value:.1},bias:{value:.015},falloff:{value:.7},power:{value:1.1},tolerance:{value:0},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new c},lastProjectionViewMatrix:{value:new c},inverseViewMatrix:{value:new c},ssrtaoSplitX:{value:.5}},vertexShader:z.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${it}\n\n${Ze}\n\n${Pe().calculateGI}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.passId=e,this.needsSwap=!0,this.clear=!0,this.giEnabled=r,this.bilateralPass=new _t(this.target,"rgba")}before=["render"];after=["gbuffer","depth"];required=["render","progressive"];bilateralPass;giEnabled=!0;intensity=2;power=1.1;autoRadius=!0;objectRadius=1;tolerance=1;bias=.001;falloff=.7;rayCount=4;stepCount=8;smoothEnabled=!0;renderWithCamera=!0;split=0;passId;render(e,t,r,i,a){if(!this.enabled)return;if(this.needsSwap=!1,!this.renderWithCamera&&e.renderManager.frameCount<2)return;const n=d(this.target);n?(e.renderManager.blit(t,{source:n.texture}),this.material.defines.HAS_GBUFFER||console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi"),this.uniforms.tLastThis.value=t.texture,super.render(e,n,r,i,a),this.smoothEnabled&&this.bilateralPass.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value)):console.warn("SSGIPluginPass: target not defined.")}beforeRender(e,t,r){this.enabled&&(this.updateShaderProperties([e,t,r]),this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(t.matrixWorld))}materialExtension={extraUniforms:{tSSGIMap:()=>({value:d(this.target)?.texture??null}),ssaoPower:this.material.uniforms.power,ssgiIntensity:this.material.uniforms.intensity,ssrtaoSplitX:this.material.uniforms.ssrtaoSplitX},extraDefines:{SSGI_ENABLED:()=>this.material.defines.SSGI_ENABLED},shaderExtender:(e,t,r)=>{if(!e.defines?.SSRTAO_ENABLED)return;e.fragmentShader=x(e.fragmentShader,"vec3 totalDiffuse =","\n \n \n#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0\nvec3 screenPos_gi=viewToScreen(vViewPosition.xyz);\n#if SSRTAO_ENABLED == 2\nif(screenPos_gi.x>ssrtaoSplitX){\n#endif\nvec4 ssgi=tSSGIMapTexelToLinear(texture2D(tSSGIMap,screenPos_gi.xy));float ambientOcclusion=1.-ssgi.a;ambientOcclusion=max(0.,ambientOcclusion);ambientOcclusion=pow(ambientOcclusion,ssaoPower);ambientOcclusion=min(1.,ambientOcclusion);reflectedLight.indirectDiffuse*=ambientOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nvec3 ssgiColor=ssgi.rgb*ssgiIntensity;reflectedLight.indirectDiffuse+=ssgiColor*(material.diffuseColor.rgb);\n#endif\n#if defined( USE_ENVMAP )\nfloat dotNV=saturate(dot(geometryNormal,geometryViewDir));float specularOcclusion=saturate(pow(dotNV+ambientOcclusion,exp2(-16.0*material.roughness-1.0))-1.0+ambientOcclusion);reflectedLight.indirectSpecular*=specularOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n#if !defined(SSR_ENABLED) || SSR_ENABLED < 1\nreflectedLight.indirectSpecular+=ssgiColor*material.specularColor;\n#endif\n#endif\n#endif\n#if SSRTAO_ENABLED == 2\n}\n#endif\n#endif\n\n \n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n#endif \n ",{prepend:!0}),e.fragmentShader=x(e.fragmentShader,"#include <aomap_fragment>","")},onObjectRender:(e,t,r)=>{let i=!this.enabled||!(this.renderWithCamera||r.renderManager.frameCount>1)||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssrtaoDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSRTAO_ENABLED!==i&&(t.defines.SSRTAO_ENABLED=i,t.needsUpdate=!0)},parsFragmentSnippet:e=>Y`
37
+ `,this._shaderPatch="diffuseColor = outline(diffuseColor);",this.dependencies=[k,a],this._pickingWidgetDisabled=!1,this.material=new w({uniforms:{cameraNearFar:{value:new d(.1,100)}},vertexShader:"#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec3 vViewPosition;void main(){\n#include <skinbase_vertex>\n#include <begin_vertex>\n#include <morphtarget_vertex>\n#include <skinning_vertex>\n#include <displacementmap_vertex>\n#include <project_vertex>\n#include <logdepthbuf_vertex>\n#include <clipping_planes_vertex>\nvViewPosition=-mvPosition.xyz;}",fragmentShader:"uniform vec2 cameraNearFar;varying vec3 vViewPosition;vec2 pack16(float value){float sMax=65535.0;int v=int(clamp(value,0.0,1.0)*sMax+0.5);int digit0=v/256;int digit1=v-digit0*256;return vec2(float(digit0)/255.0,float(digit1)/255.0);}float linstep(float edge0,float edge1,float value){return clamp((value-edge0)/(edge1-edge0),0.0,1.0);}void main(){float linearZ=linstep(-cameraNearFar.x,-cameraNearFar.y,-vViewPosition.z);vec2 packedZ=pack16(pow(max(0.,linearZ),0.5));gl_FragColor=vec4(packedZ.x,packedZ.y,0.,0.);}",side:P}),this._getSelectedObject=()=>{if(!this._viewer)return null;const e=this._viewer.getPlugin(k);if(this.highlightSelectedMaterials){const t=e?.getSelectedObject()?.material||null;if(this.highlightMaterialSameNames&&t){const e=Array.isArray(t)?t.map(e=>e.name):[t.name],r=/* @__PURE__ */new Set;for(const t of e){const e=this._viewer?.assetManager?.materials?.findMaterialsByName(t);e?.forEach(e=>r.add(e))}return[...r]}return t}return e?.getSelectedObject()||null},this._viewerListeners={preRender:()=>{!this.isDisabled()&&this._viewer&&(this.extraUniforms.dpr.value=2*this._viewer.renderManager.renderScale)}},this.mouseInOutAnimationEnabled=!0,this._state="in",this.enabled=e,this.bufferType=t}setDirty(){if(super.setDirty(),!this._viewer)return;const e=this._viewer.getPlugin(k);let t=!this.isDisabled();if(t){const r=e?.getSelectedObject();"string"==typeof r?.type&&r?.type?.includes("Line")&&(t=!1)}e&&(t&&e.widgetEnabled?(e.widgetEnabled=!1,this._pickingWidgetDisabled=!0):!t&&this._pickingWidgetDisabled&&(e.widgetEnabled=!0,this._pickingWidgetDisabled=!1)),this._viewer.setDirty()}onAdded(e){super.onAdded(e),this.setDirty(),this._pass=this._createPass(),this._pass.onDirty?.push(e.setDirty),e.renderManager.registerPass(this._pass);const t=e.getPlugin(k);t?.addEventListener("selectedObjectChanged",()=>{!this._animationCallBack&&this&&(t?.getSelectedObject()?this.enableDynamicSelection?(this.transparency=1,this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,400)):this.transparency=this.highlightTransparency:this.transparency=1)}),document.addEventListener("mousemove",r=>{if(!this)return;if(!this.mouseInOutAnimationEnabled)return;if(!this.enableHighlight)return;const i=t?.getSelectedObject();i&&this.enableDynamicSelection?r.target!==e.canvas?this._animationCallBack||"in"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(this.highlightTransparency,1,600),this._state="out"):this._animationCallBack||"out"!==this._state||(this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,600),this._state="in"):this.transparency=i?this.highlightTransparency:1})}onRemove(e){return this._disposeTarget(),this._pass&&(e.renderManager.unregisterPass(this._pass),this._pass.dispose&&this._pass.dispose()),this._pass=void 0,super.onRemove(e)}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({sizeMultiplier:1,type:this.bufferType})),this.texture=this.target.texture,this.texture.name="normalBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(this._createTarget(!0),!this.target)throw new Error("OutlinePlugin: target not created");this.material.userData.isOutlinePluginMaterial=!0;return new mt(this.passId,this._getSelectedObject,()=>this.target,this.material)}async _startTransparencyAnimation(e,t,r){return ee(this,"transparency",{from:e,to:t,duration:r,onComplete:()=>{this._animationCallBack=void 0}})}get outlineIntensity(){return console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineIntensity(e){console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}get outlineColor(){return console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity}set outlineColor(e){console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead"),this.intensity=e}};ft.PluginType="OutlinePlugin",ft.OldPluginType="Outline",pt([N(ft.prototype.setDirty),o("Enable"),f()],ft.prototype,"enabled",2),pt([o("Highlight"),m({propKey:"enableHighlight"}),f()],ft.prototype,"enableHighlight",2),pt([N(ft.prototype.setDirty),o("DynamicSelection"),f()],ft.prototype,"enableDynamicSelection",2),pt([B("Intensity",[0,4],.001),m({propKey:"outlineIntensity"}),f("outlineIntensity")],ft.prototype,"intensity",2),pt([N(ft.prototype.setDirty),B("Transparency",[0,1],.01),f()],ft.prototype,"highlightTransparency",2),pt([re("Color"),m({propKey:"outlineColor"}),f("outlineColor")],ft.prototype,"color",2),pt([B("Thickness",[0,10],.01),m({propKey:"outlineThickness"}),f("outlineThickness")],ft.prototype,"thickness",2),pt([o("Debug"),v("DEBUG_OUTLINE",void 0,!0)],ft.prototype,"debugOutline",2),pt([N(ft.prototype.setDirty),o("Highlight Selected Materials")],ft.prototype,"highlightSelectedMaterials",2),pt([N(ft.prototype.setDirty),o("Highlight Materials (same name)")],ft.prototype,"highlightMaterialSameNames",2),pt([m({propKey:"highlightTransparency"})],ft.prototype,"transparency",2),pt([m({propKey:"outlineBuffer"}),M("Outline Buffer",{readOnly:!0})],ft.prototype,"texture",2),ft=pt([E("Selection Outline")],ft);let mt=class extends te{constructor(e,t,r,i){super(void 0,void 0,i,new b(1,1,1),1),this.passId=e,this._getSelectedObjectOrMaterial=t,this.target=r,this.isOutlineRenderPass=!0,this.enabled=!0,this.before=["render"],this.after=["gbuffer"],this.required=["render","gbuffer"],this.onDirty=[]}render(e,t,r,i,a){if(!this.scene||!this.camera||!this.enabled)return;const s=e.getRenderTarget(),n=e.getActiveCubeFace(),o=e.getActiveMipmapLevel(),l=this._getSelectedObjectOrMaterial();if(l)this._renderSelectedObject(e,l,t||null,i,a);else{e.setRenderTarget(p(this.target)||null);const t=new b;e.getClearColor(t),e.setClearColor(new b(16777215)),e.clear(!0,!0),e.setClearColor(t)}e.setRenderTarget(s,n,o)}_renderSelectedObject(e,t,r,i,a){if(!this.camera||!t)return;const s=(Array.isArray(t)?t:[t]).flatMap(e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e).flatMap(e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e);for(const l of s)l&&l.traverse(e=>{e.layers.enable(6)});const n=this.camera.layers.mask;this.camera.layers.set(6);const o=e.userData;o||console.error("threejs is not patched?"),o.transmissionRenderTarget=r,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!0,transmissionRender:!0,mainRenderPass:!1},()=>super.render(e,r,p(this.target),i,a)),o.transmissionRenderTarget=void 0,s.forEach(e=>e.traverse(e=>{e.layers.disable(6)})),this.camera.layers.mask=n}dispose(){this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach(e=>e())}beforeRender(e,t,r){this.scene=e,this.camera=t,t.updateShaderProperties(this.overrideMaterial)}};pt([o("Enabled")],mt.prototype,"enabled",2),mt=pt([E(e=>e.passId+" Render Pass")],mt);var gt=Object.defineProperty,vt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&gt(t,r,s),s};class _t extends c{constructor(e,t="rgba"){super({vertexShader:h.vertexShader,fragmentShader:"\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\nuniform vec2 tDiffuseSize;uniform vec2 bilDirection;varying vec2 vUv;uniform bool smoothEnabled;uniform float edgeSharpness;vec4 bilaterialAO(){vec4 color=clamp((texture2D(tDiffuse,vUv.xy)).B_SRC_ACCESSOR,0.,5.);if(!smoothEnabled)return color;float depth;vec3 normal;getDepthNormal(vUv.xy,depth,normal);float gaussianWeights[4];gaussianWeights[0]=0.153170;gaussianWeights[1]=0.144893;gaussianWeights[2]=0.122649;gaussianWeights[3]=0.092902;float Z=gaussianWeights[0]+0.03;vec4 final_colour=Z*color;vec2 nuv;vec4 cc;float dp;vec3 nor;vec2 direction=bilDirection/tDiffuseSize.xy;\n#pragma unroll_loop_start\nfor(int i=0;i<6;i++){direction*=-1.;nuv=vUv+2.*direction*float(UNROLLED_LOOP_INDEX/2+1);getDepthNormal(nuv,dp,nor);if(dp<0.999){float normalCloseness=dot(normal,nor);normalCloseness*=normalCloseness;float normalError=(1.0-normalCloseness)*8.;float normalWeight=max((1.0-normalError*edgeSharpness),0.00);float depthWeight=max(0.0,1.0-edgeSharpness*4000.*abs(depth-dp));float kernelWeight=gaussianWeights[UNROLLED_LOOP_INDEX/2]+0.03;float bilateralWeight=kernelWeight*depthWeight*normalWeight;Z+=bilateralWeight;cc=clamp((texture2D(tDiffuse,nuv)).B_SRC_ACCESSOR,0.,5.);final_colour+=bilateralWeight*cc;}}\n#pragma unroll_loop_end\nfinal_colour/=Z;return final_colour;}void main(){vec4 ao=clamp(bilaterialAO(),vec4(0.),vec4(1.));gl_FragColor=ao;}",uniforms:{bilDirection:{value:new d(1,0)},tDiffuse:{value:null},tDiffuseSize:{value:new d}},defines:{B_SRC_ACCESSOR:t}},"tDiffuse"),this.target=e,this.smoothEnabled=!0,this.edgeSharpness=.1,this.clear=!1,this.needsSwap=!1}render(e,t,r,i,a){if(!this.enabled)return;const s=p(this.target);s&&(this.uniforms.bilDirection.value.set(1,0),this.uniforms.tDiffuse.value=s.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,t,s,i,a),this.uniforms.bilDirection.value.set(0,1),this.uniforms.tDiffuse.value=t.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,s,t,i,a))}}vt([f(),m()],_t.prototype,"smoothEnabled"),vt([f(),m()],_t.prototype,"edgeSharpness");var yt=Object.defineProperty,xt=Object.getOwnPropertyDescriptor,St=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?xt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&yt(t,r,s),s};let bt=class extends i{constructor(e=_,t=1,r=!0){super(),this.passId="ssrtgi",this.dependencies=[a,J],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSGIPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed"))},this.enabled=r,this.bufferType=e,this.sizeMultiplier=t}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssgiBuffer")}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSGIPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new wt(this.passId,()=>this.target)}onAdded(e){super.onAdded(e),(e.getPlugin("Ground")||e.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSGIPlugin"),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),e.forPlugin(ke,e=>{this._pass?.material.registerMaterialExtensions([e.unpackExtension])},e=>{this._pass?.material?.unregisterMaterialExtensions([e.unpackExtension])},this)}onRemove(e){return this._disposeTarget(),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}fromJSON(e,t){return e.passes?.ssrtgi&&((e={...e}).pass=e.passes.ssrtgi,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}_beforeRender(e,t,r){if(!this._viewer)return!1;const i=super._beforeRender(e,t,r);if(i){const e=this._viewer?.getPlugin("SSAOPlugin");e&&!e.isDisabled()&&e.disable(bt.PluginType)}if(!i)return i;const a=this._viewer.getPlugin(s);return this._pass?.updateShaderProperties([a]),i}get rtgiTarget(){return console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead"),this.target}};bt.PluginType="SSGIPlugin",bt.OldPluginType="SSGI",St([M("SSGI Buffer",{readOnly:!0})],bt.prototype,"texture",2),St([l(void 0,{unwrapContents:!0})],bt.prototype,"_pass",2),bt=St([E("SSGI Plugin")],bt);let wt=class extends c{constructor(e,t,r=!0){super({defines:{RTAO_STEP_COUNT:16,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new d(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new d(.1,1e3)},cameraPositionWorld:{value:new F},projection:{value:new u},opacity:{value:1},intensity:{value:0},objectRadius:{value:0},autoRadius:{value:!r},rayCount:{value:.1},bias:{value:.015},falloff:{value:.7},power:{value:1.1},tolerance:{value:0},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new u},lastProjectionViewMatrix:{value:new u},inverseViewMatrix:{value:new u},ssrtaoSplitX:{value:.5}},vertexShader:V.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${st}\n\n${Qe}\n\n${Ee().calculateGI}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=t,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render","progressive"],this.giEnabled=!0,this.intensity=2,this.power=1.1,this.autoRadius=!0,this.objectRadius=1,this.tolerance=1,this.bias=.001,this.falloff=.7,this.rayCount=4,this.stepCount=8,this.smoothEnabled=!0,this.renderWithCamera=!0,this.split=0,this.materialExtension={extraUniforms:{tSSGIMap:()=>({value:p(this.target)?.texture??null}),ssaoPower:this.material.uniforms.power,ssgiIntensity:this.material.uniforms.intensity,ssrtaoSplitX:this.material.uniforms.ssrtaoSplitX},extraDefines:{SSGI_ENABLED:()=>this.material.defines.SSGI_ENABLED},shaderExtender:(e,t,r)=>{if(!e.defines?.SSRTAO_ENABLED)return;e.fragmentShader=y(e.fragmentShader,"vec3 totalDiffuse =","\n \n \n#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0\nvec3 screenPos_gi=viewToScreen(vViewPosition.xyz);\n#if SSRTAO_ENABLED == 2\nif(screenPos_gi.x>ssrtaoSplitX){\n#endif\nvec4 ssgi=tSSGIMapTexelToLinear(texture2D(tSSGIMap,screenPos_gi.xy));float ambientOcclusion=1.-ssgi.a;ambientOcclusion=max(0.,ambientOcclusion);ambientOcclusion=pow(ambientOcclusion,ssaoPower);ambientOcclusion=min(1.,ambientOcclusion);reflectedLight.indirectDiffuse*=ambientOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\nvec3 ssgiColor=ssgi.rgb*ssgiIntensity;reflectedLight.indirectDiffuse+=ssgiColor*(material.diffuseColor.rgb);\n#endif\n#if defined( USE_ENVMAP )\nfloat dotNV=saturate(dot(geometryNormal,geometryViewDir));float specularOcclusion=saturate(pow(dotNV+ambientOcclusion,exp2(-16.0*material.roughness-1.0))-1.0+ambientOcclusion);reflectedLight.indirectSpecular*=specularOcclusion;\n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n#if !defined(SSR_ENABLED) || SSR_ENABLED < 1\nreflectedLight.indirectSpecular+=ssgiColor*material.specularColor;\n#endif\n#endif\n#endif\n#if SSRTAO_ENABLED == 2\n}\n#endif\n#endif\n\n \n#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0\n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n#endif \n ",{prepend:!0}),e.fragmentShader=y(e.fragmentShader,"#include <aomap_fragment>","")},onObjectRender:(e,t,r)=>{let i=!this.enabled||!(this.renderWithCamera||r.renderManager.frameCount>1)||!1===r.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssrtaoDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSRTAO_ENABLED!==i&&(t.defines.SSRTAO_ENABLED=i,t.needsUpdate=!0)},parsFragmentSnippet:e=>K`
38
38
  #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0
39
39
  uniform float ssaoPower;
40
40
  uniform float ssgiIntensity;
@@ -42,23 +42,23 @@ import{RenderManager as e,PipelinePassPlugin as t,ProgressivePlugin as r,GBuffer
42
42
  #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED == 2
43
43
  uniform float ssrtaoSplitX;
44
44
  #endif
45
- ${Z("tSSGIMap",d(this.target)?.texture.colorSpace)}
45
+ ${$("tSSGIMap",p(this.target)?.texture.colorSpace)}
46
46
  ${""}
47
47
  #include <simpleCameraHelpers>
48
48
  #endif
49
- `,computeCacheKey:()=>{const e=d(this.target)?.texture;return(this.enabled?"1":"0")+e?.colorSpace+e?.uuid+Object.values(this.material.defines).map(e=>e+"").join(",")},uuid:wt.PluginType,...M(this._getUiConfig.bind(this),wt.PluginType),isCompatible:e=>e.isPhysicalMaterial};_getUiConfig(e){return{type:"folder",label:"SSGI",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssgiDisabled},set value(t){t!==!e.userData.ssgiDisabled&&(e.userData.ssgiDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}_gbufferUnpackExtension;setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&(this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension)}setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}};St([h()],Tt.prototype,"bilateralPass",2),St([n("GI Enabled"),h(),m("SSGI_ENABLED",void 0,void 0,Tt.prototype.setDirty,!1)],Tt.prototype,"giEnabled",2),St([U("Intensity",[0,4]),h(),p()],Tt.prototype,"intensity",2),St([U("Power",[0,3]),h(),p()],Tt.prototype,"power",2),St([n("Auto radius"),h(),p()],Tt.prototype,"autoRadius",2),St([U("Object Radius",[.01,10]),h(),p()],Tt.prototype,"objectRadius",2),St([U("Tolerance",[.1,5]),h(),p()],Tt.prototype,"tolerance",2),St([U("Bias",[-.3,.3]),h(),p()],Tt.prototype,"bias",2),St([U("Falloff",[1e-4,4]),h(),p()],Tt.prototype,"falloff",2),St([U("Ray Count",[1,5],1,{tags:["performance"]}),h(),p()],Tt.prototype,"rayCount",2),St([U("Step count",[1,16],1,{tags:["performance"]}),h(),K("RTAO_STEP_COUNT",void 0,void 0,Tt.prototype.setDirty)],Tt.prototype,"stepCount",2),St([n("Smooth Enabled"),h()],Tt.prototype,"smoothEnabled",2),St([n("Render with Camera")],Tt.prototype,"renderWithCamera",2),St([U("Split",[0,1],.01,{tags:["debug"]}),h(),p({propKey:"ssrtaoSplitX",onChange:Tt.prototype.setDirty})],Tt.prototype,"split",2),Tt=St([P("SSGI Pass")],Tt);var Dt=Object.defineProperty,Pt=Object.getOwnPropertyDescriptor,Mt=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?Pt(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&Dt(t,r,n),n},Et=(e,t,r)=>((e,t,r)=>t in e?Dt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);const Ct=e.ShaderChunk;let Rt=class extends H{enabled=!0;_defines={};_uniforms={anisotropyFactor:{value:1},anisotropyNoise:{value:1},anisotropyDirection:{value:1},anisotropyDirectionMap:{value:null},anisotropy2MapUvTransform:{value:new w},frameCount:{value:0}};enableAnisotropy(e,t,r,i,a){const n=e?.userData;if(!n)return!1;if(void 0===n._isAnisotropic){const t=e.appliedMeshes;let r=!0;if(t)for(const{geometry:e}of t)!e||e.attributes.position&&e.attributes.normal&&e.attributes.uv||(r=!1),r&&e&&!e.attributes.tangent&&e.computeTangents();if(!r)return!1}return n._isAnisotropic=!0,n._anisotropyFactor=r??n._anisotropyFactor??1,n._anisotropyNoise=i??n._anisotropyNoise??0,n._anisotropyDirection=n._anisotropyDirection??1,n._anisotropyDirectionMode=a??n._anisotropyDirectionMode??"DIRECTION",n._anisotropyDirectionMap=t??n._anisotropyDirectionMap??null,e.setDirty&&e.setDirty(),!0}materialExtension={uuid:Rt.PluginType,priority:10,shaderExtender:(e,t,r)=>{if(this.isDisabled()||!t?.userData._isAnisotropic)return;const i=t.userData?._anisotropyDirectionMap,a=Y`
49
+ `,computeCacheKey:()=>{const e=p(this.target)?.texture;return(this.enabled?"1":"0")+e?.colorSpace+e?.uuid+Object.values(this.material.defines).map(e=>e+"").join(",")},uuid:bt.PluginType,...C(this._getUiConfig.bind(this),bt.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.passId=e,this.needsSwap=!0,this.clear=!0,this.giEnabled=r,this.bilateralPass=new _t(this.target,"rgba")}render(e,t,r,i,a){if(!this.enabled)return;if(this.needsSwap=!1,!this.renderWithCamera&&e.renderManager.frameCount<2)return;const s=p(this.target);s?(e.renderManager.blit(t,{source:s.texture}),this.material.defines.HAS_GBUFFER||console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi"),this.uniforms.tLastThis.value=t.texture,super.render(e,s,r,i,a),this.smoothEnabled&&this.bilateralPass.render(e,t,r,i,a),this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value)):console.warn("SSGIPluginPass: target not defined.")}beforeRender(e,t,r){this.enabled&&(this.updateShaderProperties([e,t,r]),this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this.uniforms.inverseViewMatrix.value.copy(t.matrixWorld))}_getUiConfig(e){return{type:"folder",label:"SSGI",children:[{type:"checkbox",label:"Enabled",get value(){return!e.userData.ssgiDisabled},set value(t){t!==!e.userData.ssgiDisabled&&(e.userData.ssgiDisabled=!t,e.setDirty())},onChange:this.setDirty}]}}set uniformsNeedUpdate(e){this.material.uniformsNeedUpdate=e,this.setDirty()}setGBufferUnpackExtension(e){this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&(this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(this.material.registerMaterialExtensions([this._gbufferUnpackExtension]),this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension])),this._gbufferUnpackExtension)}setDirty(){this.materialExtension?.setDirty?.(),super.setDirty()}};St([f()],wt.prototype,"bilateralPass",2),St([o("GI Enabled"),f(),v("SSGI_ENABLED",void 0,void 0,wt.prototype.setDirty,!1)],wt.prototype,"giEnabled",2),St([B("Intensity",[0,4]),f(),m()],wt.prototype,"intensity",2),St([B("Power",[0,3]),f(),m()],wt.prototype,"power",2),St([o("Auto radius"),f(),m()],wt.prototype,"autoRadius",2),St([B("Object Radius",[.01,10]),f(),m()],wt.prototype,"objectRadius",2),St([B("Tolerance",[.1,5]),f(),m()],wt.prototype,"tolerance",2),St([B("Bias",[-.3,.3]),f(),m()],wt.prototype,"bias",2),St([B("Falloff",[1e-4,4]),f(),m()],wt.prototype,"falloff",2),St([B("Ray Count",[1,5],1,{tags:["performance"]}),f(),m()],wt.prototype,"rayCount",2),St([B("Step count",[1,16],1,{tags:["performance"]}),f(),Z("RTAO_STEP_COUNT",void 0,void 0,wt.prototype.setDirty)],wt.prototype,"stepCount",2),St([o("Smooth Enabled"),f()],wt.prototype,"smoothEnabled",2),St([o("Render with Camera")],wt.prototype,"renderWithCamera",2),St([B("Split",[0,1],.01,{tags:["debug"]}),f(),m({propKey:"ssrtaoSplitX",onChange:wt.prototype.setDirty})],wt.prototype,"split",2),wt=St([E("SSGI Pass")],wt);var Tt=Object.defineProperty,Dt=Object.getOwnPropertyDescriptor,Pt=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?Dt(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&Tt(t,r,s),s};const Mt=r.ShaderChunk;let Et=class extends Y{constructor(){super(),this.enabled=!0,this._defines={},this._uniforms={anisotropyFactor:{value:1},anisotropyNoise:{value:1},anisotropyDirection:{value:1},anisotropyDirectionMap:{value:null},anisotropy2MapUvTransform:{value:new D},frameCount:{value:0}},this.materialExtension={uuid:Et.PluginType,priority:10,shaderExtender:(e,t,r)=>{if(this.isDisabled()||!t?.userData._isAnisotropic)return;const i=t.userData?._anisotropyDirectionMap,a=K`
50
50
  //#if ANISOTROPY_ENABLED
51
51
  #include <randomHelpers>
52
52
  #ifndef D_frameCount
53
53
  #define D_frameCount
54
54
  uniform float frameCount;
55
55
  #endif
56
- ${i?Z("anisotropyDirectionMap",i?.colorSpace):""}\n
57
- `;e.fragmentShader=x(e.fragmentShader,"#include <common>",a,{append:!0}),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",Ct.lights_fragment_begin),e.fragmentShader=x(x(e.fragmentShader,"IncidentLight directLight;","float rnd=(random2(vUv.xy,frameCount)-0.5)*anisotropyNoise*material.roughness;\n#if ANISOTROPY_TEX_MODE < 2\n#if ANISOTROPY_TEX_MODE == 0\nfloat rot=saturate(anisotropyDirection);\n#else\nfloat rot=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).r);\n#endif\nrot=rot*2.*PI+rnd;vec2 rot2=vec2(sin(rot),cos(rot));\n#else\nvec2 rot2=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).rg*2.-1.)+vec2(rnd,rnd);rot2=normalize(rot2);const float anisoSpecMultiplier=0.25;float matSpecAniso=(length(material.specularColor.rgb))*2.*PI;rot2=mix(rot2,vec2(sin(matSpecAniso),cos(matSpecAniso)),anisoSpecMultiplier);rot2=normalize(rot2);\n#endif\nvec3 anisotropicT=(tbn[0]*rot2.x+tbn[1]*rot2.y);anisotropicT=normalize(anisotropicT-normal*dot(anisotropicT,normal));vec3 anisotropicB=normalize(cross(normal,anisotropicT));",{prepend:!0}),"RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )","RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )",{replaceAll:!0});let n=x(Ct.lights_physical_pars_fragment,"void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {","void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight, const in vec3 anisotropicT, const in vec3 anisotropicB ) {");n=x(n,"vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {","uniform float anisotropyFactor;uniform float anisotropyNoise;\n#if ANISOTROPY_TEX_MODE == 0\nuniform float anisotropyDirection;\n#else\nuniform sampler2D anisotropyDirectionMap;varying vec2 vAnisotropy2MapUv;\n#endif\nconst float MIN_ROUGHNESS=0.05;vec3 indirectAnisotropyBentNormal(const in vec3 normal,const in vec3 viewDir,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){vec3 aDirection=anisotropyFactor>=0.0 ? anisotropicB : anisotropicT;vec3 aTangent=cross(aDirection,viewDir);vec3 aNormal=cross(aTangent,aDirection);float bendFactor=abs(anisotropyFactor)*saturate(5.0*max(roughness,MIN_ROUGHNESS));return normalize(mix(normal,aNormal,bendFactor));}vec3 BRDF_GGX_Anisotropy(const in vec3 lightDir,const in vec3 viewDir,const in vec3 normal,const in vec3 f0,const in float f90,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){float alpha=pow2(roughness);vec3 halfDir=normalize(lightDir+viewDir);float dotNL=saturate(dot(normal,lightDir));float dotNV=saturate(dot(normal,viewDir));float dotNH=saturate(dot(normal,halfDir));float dotVH=saturate(dot(viewDir,halfDir));float dotTV=dot(anisotropicT,viewDir);float dotBV=dot(anisotropicB,viewDir);float dotTL=dot(anisotropicT,lightDir);float dotBL=dot(anisotropicB,lightDir);float dotTH=dot(anisotropicT,halfDir);float dotBH=dot(anisotropicB,halfDir);float aspect=sqrt(1.0-min(1.-MIN_ROUGHNESS,abs(anisotropyFactor)*0.9));if(anisotropyFactor>0.0)aspect=1.0/aspect;float at=roughness*aspect;float ab=roughness/aspect;vec3 F=F_Schlick(f0,f90,dotVH);float V=V_GGX_SmithCorrelated_Anisotropic(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropic(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}\n",{prepend:!0}),n=x(n,"BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )","BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )"),e.fragmentShader=x(e.fragmentShader,"#include <lights_physical_pars_fragment>",n),e.fragmentShader=x(e.fragmentShader,"#include <normal_fragment_begin>",Ct.normal_fragment_begin),e.fragmentShader=x(e.fragmentShader,"#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )","#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )");let s=Y`
56
+ ${i?$("anisotropyDirectionMap",i?.colorSpace):""}\n
57
+ `;e.fragmentShader=y(e.fragmentShader,"#include <common>",a,{append:!0}),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",Mt.lights_fragment_begin),e.fragmentShader=y(y(e.fragmentShader,"IncidentLight directLight;","float rnd=(random2(vUv.xy,frameCount)-0.5)*anisotropyNoise*material.roughness;\n#if ANISOTROPY_TEX_MODE < 2\n#if ANISOTROPY_TEX_MODE == 0\nfloat rot=saturate(anisotropyDirection);\n#else\nfloat rot=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).r);\n#endif\nrot=rot*2.*PI+rnd;vec2 rot2=vec2(sin(rot),cos(rot));\n#else\nvec2 rot2=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).rg*2.-1.)+vec2(rnd,rnd);rot2=normalize(rot2);const float anisoSpecMultiplier=0.25;float matSpecAniso=(length(material.specularColor.rgb))*2.*PI;rot2=mix(rot2,vec2(sin(matSpecAniso),cos(matSpecAniso)),anisoSpecMultiplier);rot2=normalize(rot2);\n#endif\nvec3 anisotropicT=(tbn[0]*rot2.x+tbn[1]*rot2.y);anisotropicT=normalize(anisotropicT-normal*dot(anisotropicT,normal));vec3 anisotropicB=normalize(cross(normal,anisotropicT));",{prepend:!0}),"RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )","RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )",{replaceAll:!0});let s=y(Mt.lights_physical_pars_fragment,"void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {","void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight, const in vec3 anisotropicT, const in vec3 anisotropicB ) {");s=y(s,"vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {","uniform float anisotropyFactor;uniform float anisotropyNoise;\n#if ANISOTROPY_TEX_MODE == 0\nuniform float anisotropyDirection;\n#else\nuniform sampler2D anisotropyDirectionMap;varying vec2 vAnisotropy2MapUv;\n#endif\nconst float MIN_ROUGHNESS=0.05;vec3 indirectAnisotropyBentNormal(const in vec3 normal,const in vec3 viewDir,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){vec3 aDirection=anisotropyFactor>=0.0 ? anisotropicB : anisotropicT;vec3 aTangent=cross(aDirection,viewDir);vec3 aNormal=cross(aTangent,aDirection);float bendFactor=abs(anisotropyFactor)*saturate(5.0*max(roughness,MIN_ROUGHNESS));return normalize(mix(normal,aNormal,bendFactor));}vec3 BRDF_GGX_Anisotropy(const in vec3 lightDir,const in vec3 viewDir,const in vec3 normal,const in vec3 f0,const in float f90,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){float alpha=pow2(roughness);vec3 halfDir=normalize(lightDir+viewDir);float dotNL=saturate(dot(normal,lightDir));float dotNV=saturate(dot(normal,viewDir));float dotNH=saturate(dot(normal,halfDir));float dotVH=saturate(dot(viewDir,halfDir));float dotTV=dot(anisotropicT,viewDir);float dotBV=dot(anisotropicB,viewDir);float dotTL=dot(anisotropicT,lightDir);float dotBL=dot(anisotropicB,lightDir);float dotTH=dot(anisotropicT,halfDir);float dotBH=dot(anisotropicB,halfDir);float aspect=sqrt(1.0-min(1.-MIN_ROUGHNESS,abs(anisotropyFactor)*0.9));if(anisotropyFactor>0.0)aspect=1.0/aspect;float at=roughness*aspect;float ab=roughness/aspect;vec3 F=F_Schlick(f0,f90,dotVH);float V=V_GGX_SmithCorrelated_Anisotropic(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropic(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}\n",{prepend:!0}),s=y(s,"BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )","BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )"),e.fragmentShader=y(e.fragmentShader,"#include <lights_physical_pars_fragment>",s),e.fragmentShader=y(e.fragmentShader,"#include <normal_fragment_begin>",Mt.normal_fragment_begin),e.fragmentShader=y(e.fragmentShader,"#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )","#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )");let n=K`
58
58
  #if defined( USE_ENVMAP )
59
59
  vec3 anisotropyBentNormal = indirectAnisotropyBentNormal(geometryNormal, geometryViewDir, material.roughness, anisotropicT, anisotropicB);
60
60
  #endif
61
- `+Ct.lights_fragment_maps;s=x(s,"getIBLIrradiance( geometryNormal )","getIBLIrradiance( anisotropyBentNormal )"),s=x(s,"getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )","getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )"),e.fragmentShader=x(e.fragmentShader,"#include <lights_fragment_maps>",s),e.vertexShader=x(e.vertexShader,"#include <uv_pars_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n varying vec2 vAnisotropy2MapUv;\n uniform mat3 anisotropy2MapUvTransform;\n#endif\n ",{prepend:!0}),e.vertexShader=x(e.vertexShader,"#include <uv_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;\n#endif\n ",{prepend:!0}),e.defines||(e.defines={}),e.defines.USE_ANISOTROPY_BRDF="",e.defines.USE_UV="",e.vertexTangents=!0},onObjectRender:(e,t)=>{const r=t.userData;if(!r?._isAnisotropic)return;if(!e.isMesh||!e.geometry)return;e.geometry.attributes.tangent||this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.",e),this._uniforms.anisotropyFactor.value=r._anisotropyFactor??1,this._uniforms.anisotropyNoise.value=r._anisotropyNoise??0,this._uniforms.anisotropyDirection.value=r._anisotropyDirection??1;const i=r._anisotropyDirectionMap?.isTexture?r._anisotropyDirectionMap:null;this._uniforms.anisotropyDirectionMap.value=i,i&&(i.updateMatrix(),this._uniforms.anisotropy2MapUvTransform.value.copy(i.matrix)),W({...this._defines,ANISOTROPY_ENABLED:+this.enabled,ANISOTROPY_TEX_MODE:i?"DIRECTION"===r._anisotropyDirectionMode?2:"ROTATION"===r._anisotropyDirectionMode?1:0:0},t)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData?._isAnisotropic?"1":"0")+e.userData?._anisotropyDirectionMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.renderManager],getUiConfig:e=>{const t=this._viewer,r=this.enableAnisotropy.bind(this),i=e.userData,a={type:"folder",label:"Anisotropy",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i._isAnisotropic||!1},set value(n){n!==i._isAnisotropic&&(n?r(e)||t.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic."):(i._isAnisotropic=!1,e.setDirty&&e.setDirty()),a.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Factor",bounds:[-2,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyFactor"]},{type:"slider",label:"Noise",bounds:[0,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyNoise"]},{type:"dropdown",label:"Mode",hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyDirectionMode"],children:["CONSTANT","ROTATION","DIRECTION"].map(e=>({label:e})),onChange:()=>{e.setDirty&&e.setDirty(),a.uiRefresh?.(!0,"postFrame")}},{type:"slider",label:"Direction",bounds:[0,5],hidden:()=>"CONSTANT"===i._anisotropyDirectionMode||!i._isAnisotropic,property:[i,"_anisotropicDirection"]},{type:"image",label:"Texture",hidden:()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,property:[i,"_anisotropyDirectionMap"],onChange:()=>{e.setDirty&&e.setDirty()}},te(i,"_anisotropyDirectionMap","Sampler",()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,()=>e.setDirty&&e.setDirty())]};return a},onMaterialUpdate:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onRegister:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onAddToMesh:e=>{if(!e.isMesh)return;const t=e,r=Array.isArray(t.material)?t.material:[t.material];r.find(e=>e?.userData?._isAnisotropic)&&this.tryComputeTangents(t,r)}};tryComputeTangents(e,t){if(e.geometry&&!e.geometry.attributes.tangent){let r=!0;e.geometry.index&&e.geometry.attributes.position&&e.geometry.attributes.normal&&e.geometry.attributes.uv||(r=!1),r?e.geometry.computeTangents():t.map(e=>{e?.userData?._isAnisotropic&&(e.userData._isAnisotropic=!1)})}}setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()};constructor(){super(),Object.assign(this.materialExtension.extraUniforms,this._uniforms)}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Ut)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Ut.name),super.onRemove(e)}makeAnisotropic(e){return this.enableAnisotropy(e)}};Et(Rt,"PluginType","AnisotropyPlugin"),Et(Rt,"ANISOTROPY_GLTF_EXTENSION","WEBGI_materials_anisotropy"),Mt([n("Enabled",e=>({onChange:e.setDirty})),h()],Rt.prototype,"enabled",2),Rt=Mt([P("Anisotropy (MatExt)")],Rt);class At{name;parser;constructor(e){this.parser=e,this.name=Ut.name}async extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const a=[],n=i.extensions[this.name];t.userData||(t.userData={}),t.userData._isAnisotropic=!0,t.userData._anisotropyFactor=n.anisotropyFactor??0,t.userData._anisotropyNoise=n.anisotropyNoiseFactor??n.anisotropyNoise??0;let{anisotropyDirectionMode:s,anisotropyDirection:o}=n;return s||(s=n.anisotropyTextureMode),o||(o=n.anisotropyRotation),t.userData._anisotropyDirectionMode=s&&"number"==typeof o?.index?s:"CONSTANT","ROTATION"===s||"DIRECTION"===s?a.push(r.assignTexture(t.userData,"_anisotropyDirectionMap",o).then(e=>{e.colorSpace=re})):t.userData._anisotropyDirection=o??0,Promise.all(a)}afterRoot(e){return e.scene?.traverse(e=>{const t=e.material?.userData?._isAnisotropic;if(!t)return;const r=e.geometry;r.attributes.tangent||(r.computeTangents(),r.attributes.tangent.needsUpdate=!0)}),null}}const Ut={name:"WEBGI_materials_anisotropy",import:e=>new At(e),export:e=>({writeMaterial:(t,r)=>{if(!t.isMeshStandardMaterial||!t.userData._isAnisotropic)return;if((t.userData._anisotropyFactor||0)<.001)return;r.extensions=r.extensions||{};const i={};if(i.anisotropyFactor=t.userData._anisotropyFactor||1,i.anisotropyNoiseFactor=t.userData._anisotropyNoise||0,i.anisotropyDirectionMode=t.userData._anisotropyDirectionMode||"CONSTANT",e.checkEmptyMap(t.userData._anisotropyDirectionMap)&&"CONSTANT"!==i.anisotropyDirectionMode){const r={index:e.processTexture(t.userData._anisotropyDirectionMap)};e.applyTextureTransform(r,t.userData._anisotropyDirectionMap),i.anisotropyDirection=r}else i.anisotropyDirectionMode="CONSTANT",i.anisotropyDirection=t.userData._anisotropyDirection||0;r.extensions[Ut.name]=i,e.extensionsUsed[Ut.name]=!0}}),textures:{anisotropyDirection:"RGB"}};var Lt=Object.defineProperty,Bt=(e,t,r,i)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,r,n)||n);return n&&Lt(t,r,n),n};const Nt=class extends ie{type="Reflector";isReflector2=!0;_renderTarget;textureMatrix;_getRenderTarget(){const e=d(this._renderTarget);return e&&(!e.texture.generateMipmaps||ae.isPowerOfTwo(e.texture.image.width)&&ae.isPowerOfTwo(e.texture.image.height)||(e.texture.generateMipmaps=!1),this.materialExtension.extraUniforms.tRefDiffuse.value=e.texture,this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(e.width,e.height)),e}enabled=!0;reflectorModePhysical=!0;reflectionTargetNeedsUpdate=!0;transparentReflectionBackground=!0;_updateExtension(){this.transparentReflectionBackground=this.reflectorModePhysical,this.materialExtension?.setDirty?.()}constructor(e,t,r=0,i){super(e,i),this._renderTarget=t;const a=new ne,n=new N,s=new N,o=new N,l=new c,u=new N(0,0,-1),d=new C,h=new N,p=new N,f=new C,m=new c,g=new se;this.onBeforeRender=(e,t,i)=>{if(!this.enabled||!e.userData.mainRenderPass)return;if(!this.reflectionTargetNeedsUpdate)return;const c=this._getRenderTarget();if(!c)return void console.warn("Reflector2: No render target set.");const v=i.view?Object.assign({},i.view):null;if(v&&i.clearViewOffset&&i.clearViewOffset(),s.setFromMatrixPosition(this.matrixWorld),o.setFromMatrixPosition(i.matrixWorld),l.extractRotation(this.matrixWorld),n.set(0,0,1),n.applyMatrix4(l),h.subVectors(s,o),h.dot(n)>0)return;h.reflect(n).negate(),h.add(s),l.extractRotation(i.matrixWorld),u.set(0,0,-1),u.applyMatrix4(l),u.add(o),p.subVectors(s,u),p.reflect(n).negate(),p.add(s),g.position.copy(h),g.up.set(0,1,0),g.up.applyMatrix4(l),g.up.reflect(n),g.lookAt(p),g.far=2,g.near=0,g.updateMatrixWorld(),g.projectionMatrix.copy(i.projectionMatrix),m.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),m.multiply(g.projectionMatrix),m.multiply(g.matrixWorldInverse),m.multiply(this.matrixWorld),a.setFromNormalAndCoplanarPoint(n,s),a.applyMatrix4(g.matrixWorldInverse),d.set(a.normal.x,a.normal.y,a.normal.z,a.constant);const _=g.projectionMatrix;f.x=(Math.sign(d.x)+_.elements[8])/_.elements[0],f.y=(Math.sign(d.y)+_.elements[9])/_.elements[5],f.z=-1,f.w=(1+_.elements[10])/_.elements[14],d.multiplyScalar(2/d.dot(f)),_.elements[2]=d.x,_.elements[6]=d.y,_.elements[10]=d.z+1-r,_.elements[14]=d.w,this.visible=!1;const y=e.getRenderTarget(),x=e.xr.enabled,S=e.shadowMap.autoUpdate;e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,e.setRenderTarget(c),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear();const b=t.background;this.transparentReflectionBackground&&(t.background=null);const w=!this.transparentReflectionBackground;b?.isTexture&&w&&(b.userData||(b.userData={}),b.userData.flipX=!b.userData.flipX),e.renderWithModes({shadowMapRender:!1,backgroundRender:w,opaqueRender:!0,transparentRender:!0,transmissionRender:!1,screenSpaceRendering:!1},()=>e.render(t,g)),b?.isTexture&&w&&(b.userData.flipX=!b.userData.flipX||void 0),this.transparentReflectionBackground&&(t.background=b),e.xr.enabled=x,e.shadowMap.autoUpdate=S,e.setRenderTarget(y),v?.enabled&&i.setViewOffset&&i.setViewOffset(v.fullWidth,v.fullHeight,v.offsetX,v.offsetY,v.width,v.height);const T=i.viewport;void 0!==T&&e.state.viewport(T),this.visible=!0,this.reflectionTargetNeedsUpdate=!1},this.textureMatrix=m,this.materialExtension.extraUniforms.refTextureMatrix.value=m}getRenderTarget(){return this._renderTarget}materialExtension={extraUniforms:{tRefDiffuse:{value:null},tRefDiffuseSize:{value:new l},refTextureMatrix:{value:new c},frameCount:{value:0},sceneBoundingRadius:{value:0}},extraDefines:{USE_UV:""},updaters:[],shaderExtender:(e,t,r)=>{if(this.enabled){e.vertexShader=x(e.vertexShader,"void main() {","void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");const t="#glMarker beforeModulation";e.fragmentShader=x(e.fragmentShader,t,"\n if(roughnessFactor < 0.95) {\n float d = 0.;//textureProj(tRefDepth, vRefUv).r;\n // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));\n vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);\n // refBaseColor.rgb = vec3(refBaseColor.a);\n // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);\n "+(this.reflectorModePhysical?"\n #if !defined(SSR_ENABLED) || SSR_ENABLED < 1 \n vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);\n #endif\n reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);\n ":"\n reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);\n diffuseColor.a *= refBaseColor.a;\n ")+"}\n"+t)}},parsVertexSnippet:()=>this.enabled?"\n\t\tuniform mat4 refTextureMatrix;\n\t\tvarying vec4 vRefUv;\n":"",parsFragmentSnippet:()=>this.enabled?"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}":"",computeCacheKey:e=>this.enabled+" "+e.transparent+" "+this.reflectorModePhysical+" ",onObjectRender:(e,t)=>{t.userData.__lastTransparent!==t.transparent&&(t.needsUpdate=!0,t.userData.__lastTransparent=t.transparent)},isCompatible:e=>e.isPhysicalMaterial,setDirty:()=>this.materialExtension.__setDirty?.()}};Bt([L(Nt.prototype._updateExtension)],Nt.prototype,"enabled"),Bt([L(Nt.prototype._updateExtension)],Nt.prototype,"reflectorModePhysical");let Ot=Nt;Ot.prototype.isReflector=!0;class Ft{static _xfnv1a(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return()=>(t+=t<<13,t^=t>>>7,t+=t<<3,t^=t>>>17,(t+=t<<5)>>>0)}}class kt extends Ft{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.a=kt._xfnv1a(e)()}next(){let e=this.a+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}class It extends Ft{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=It._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){this.a>>>=0,this.b>>>=0,this.c>>>=0,this.d>>>=0;let e=this.a+this.b|0;return this.a=this.b^this.b>>>9,this.b=this.c+(this.c<<3)|0,this.c=this.c<<21|this.c>>>11,this.d=this.d+1|0,e=e+this.d|0,this.c=this.c+e|0,(e>>>0)/4294967296}}class zt extends Ft{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=zt._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){const e=this.b<<9;let t=5*this.b;return t=9*(t<<7|t>>>25),this.c^=this.a,this.d^=this.b,this.b^=this.c,this.a^=this.d,this.c^=e,this.d=this.d<<11|this.d>>>21,(t>>>0)/4294967296}}var Vt,jt;(jt=Vt||(Vt={})).sfc32="sfc32",jt.mulberry32="mulberry32",jt.xoshiro128ss="xoshiro128ss";class Gt{constructor(e,t=Vt.sfc32){Object.defineProperty(this,"str",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prng",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.str=e,this.prng=t,this.generator=this._initializeGenerator()}next(){return this.generator.next()}_initializeGenerator(){if(/* @__PURE__ */(e=>null===e)(e=this.str)||/* @__PURE__ */(e=>void 0===e)(e))return this.wrap();var e;switch(this.prng){case"sfc32":return new It(this.str);case"mulberry32":return new kt(this.str);case"xoshiro128ss":return new zt(this.str);default:return this.wrap()}}wrap(){return{next:()=>Math.random()}}}var Ht=Object.defineProperty,Wt=(e,t,r,i)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,r,n)||n);return n&&Ht(t,r,n),n};class Yt extends oe{_shadowParams={enabled:!0,radius:2,width:1024,height:1024,bias:-.001,normalBias:0,near:1.5,far:4,frustumSize:4};_randomParams={focus:1,spread:.01,distanceScale:50,minDistanceScale:new N(10,10,10),normalDirection:new N(.01,.98,.01).normalize(),direction:new N(-.9,.5,-1)};isRandomizedDirectionalLight=!0;constructor(e,t,r,i){super(e,t),this.shadowParams=r??{},this.randomParams=i??{},this.updateShadowParams=this.updateShadowParams.bind(this)}get shadowParams(){return this._shadowParams}set shadowParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this._shadowParams={...this._shadowParams,...e},this.updateShadowParams()}get randomParams(){return this._randomParams}set randomParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),Object.assign(this._randomParams,e)}updateShadowParams(){this.castShadow=this._shadowParams.enabled,this.shadow.mapSize.x=this._shadowParams.width,this.shadow.mapSize.y=this._shadowParams.height,this.shadow.bias=this._shadowParams.bias,this.shadow.normalBias=this._shadowParams.normalBias,this.refreshShadowCamNearFar(),this.shadow.radius=this._shadowParams.radius,this.shadow.camera.right=this._shadowParams.frustumSize/2,this.shadow.camera.left=-this._shadowParams.frustumSize/2,this.shadow.camera.top=this._shadowParams.frustumSize/2,this.shadow.camera.bottom=-this._shadowParams.frustumSize/2,this.shadow.camera.updateProjectionMatrix(),this.matrixWorldNeedsUpdate=!0}randomizePosition(e,t=null,r=null){const i=new Gt(e.toString()),a=new l(i.next()*Math.PI*2,Math.asin(2*i.next()-1));let n=new N(Math.cos(a.x)*Math.cos(a.y),Math.sin(a.y),Math.sin(a.x)*Math.cos(a.y));const s=new l;for(let o=0;o<5;o++){s.set(i.next(),i.next()),n=Xt(s,this._randomParams.normalDirection,.4),i.next()<Math.sqrt(t??this._randomParams.focus)&&(s.set(i.next(),i.next()),n=Xt(s,this._randomParams.direction,Math.pow((r??this._randomParams.spread)/2,2)));const e=n.dot(this._randomParams.normalDirection);if(e>0&&e<.4)break}n.normalize(),n.multiplyScalar(this._randomParams.distanceScale),this.position.set(0,0,0),this.target.position.copy(n.normalize().negate()),this.target.updateMatrixWorld(),this.refreshShadowCamNearFar(),this.updateMatrixWorld()}refreshShadowCamNearFar(){const e=(new N).subVectors(this.target.position,this.shadow.camera.position).length();this.shadow.camera.near=e-this._shadowParams.near*this._shadowParams.frustumSize/2,this.shadow.camera.far=e+this._shadowParams.far*this._shadowParams.frustumSize/2}dispose(){}toJSON(e,t=!1){const{userData:r,children:i}=this;this.userData={},this.children=[];const a=super.toJSON(e),n=le({},r);return a.userData=ce.Serialize(n),this.userData=r,this.children=i,a.type="DirectionalLight2",a.target=this.target.position.toArray(),{...a,...ue.Serialize(this,e,!0)}}fromJSON(e,t,r=!1){if("DirectionalLight2"!==e.type)return null;const i=e.target,a=e.object;return e.target&&(this.target.position.fromArray(e.target),this.target.updateMatrixWorld(),delete e.target),e.object&&delete e.object,ue.Deserialize(e,this,t,!0),i&&(e.target=i),a&&(void 0!==a.color&&this.color.set(a.color),void 0!==a.intensity&&(this.intensity=a.intensity),e.object=a),this.updateShadowParams(),this}}function Xt(e,t,r){t=t.clone().normalize();const i=new N(0,-t.z,t.y).normalize(),a=(new N).crossVectors(t,i).normalize(),n=e;n.x=2*n.x*Math.PI,n.y=1-n.y*r;const s=Math.sqrt(1-n.y*n.y);return i.multiplyScalar(Math.cos(n.x)*s).add(a.multiplyScalar(Math.sin(n.x)*s)).add(t.multiplyScalar(n.y))}Wt([h("shadowParams")],Yt.prototype,"_shadowParams"),Wt([h("randomParams")],Yt.prototype,"_randomParams");var Kt=Object.defineProperty;class qt extends de{typeSlug="fsShadow";assetType="material";_uniforms={};lastFrameTexture=null;get materialObject(){return this}onBeforeCompile(e,t){e.vertexShader=e.vertexShader.replace("#include <project_vertex>","\n#include <project_vertex>\ngl_Position = vec4(uv*2.-1., 0, 1.); \n "),e.vertexShader=e.vertexShader.replace("void main() {","\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n "),e.fragmentShader=e.fragmentShader.replace("void main() {","\nvarying vec2 vUv;\nuniform sampler2D tLastThis;\nvoid main() {\n "),e.fragmentShader=e.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );",Y`
61
+ `+Mt.lights_fragment_maps;n=y(n,"getIBLIrradiance( geometryNormal )","getIBLIrradiance( anisotropyBentNormal )"),n=y(n,"getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )","getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )"),e.fragmentShader=y(e.fragmentShader,"#include <lights_fragment_maps>",n),e.vertexShader=y(e.vertexShader,"#include <uv_pars_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n varying vec2 vAnisotropy2MapUv;\n uniform mat3 anisotropy2MapUvTransform;\n#endif\n ",{prepend:!0}),e.vertexShader=y(e.vertexShader,"#include <uv_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;\n#endif\n ",{prepend:!0}),e.defines||(e.defines={}),e.defines.USE_ANISOTROPY_BRDF="",e.defines.USE_UV="",e.vertexTangents=!0},onObjectRender:(e,t)=>{const r=t.userData;if(!r?._isAnisotropic)return;if(!e.isMesh||!e.geometry)return;e.geometry.attributes.tangent||this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.",e),this._uniforms.anisotropyFactor.value=r._anisotropyFactor??1,this._uniforms.anisotropyNoise.value=r._anisotropyNoise??0,this._uniforms.anisotropyDirection.value=r._anisotropyDirection??1;const i=r._anisotropyDirectionMap?.isTexture?r._anisotropyDirectionMap:null;this._uniforms.anisotropyDirectionMap.value=i,i&&(i.updateMatrix(),this._uniforms.anisotropy2MapUvTransform.value.copy(i.matrix)),X({...this._defines,ANISOTROPY_ENABLED:+this.enabled,ANISOTROPY_TEX_MODE:i?"DIRECTION"===r._anisotropyDirectionMode?2:"ROTATION"===r._anisotropyDirectionMode?1:0:0},t)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData?._isAnisotropic?"1":"0")+e.userData?._anisotropyDirectionMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.renderManager],getUiConfig:e=>{const t=this._viewer,r=this.enableAnisotropy.bind(this),i=e.userData,a={type:"folder",label:"Anisotropy",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return i._isAnisotropic||!1},set value(s){s!==i._isAnisotropic&&(s?r(e)||t.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic."):(i._isAnisotropic=!1,e.setDirty&&e.setDirty()),a.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Factor",bounds:[-2,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyFactor"]},{type:"slider",label:"Noise",bounds:[0,2],hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyNoise"]},{type:"dropdown",label:"Mode",hidden:()=>!i._isAnisotropic,property:[i,"_anisotropyDirectionMode"],children:["CONSTANT","ROTATION","DIRECTION"].map(e=>({label:e})),onChange:()=>{e.setDirty&&e.setDirty(),a.uiRefresh?.(!0,"postFrame")}},{type:"slider",label:"Direction",bounds:[0,5],hidden:()=>"CONSTANT"===i._anisotropyDirectionMode||!i._isAnisotropic,property:[i,"_anisotropicDirection"]},{type:"image",label:"Texture",hidden:()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,property:[i,"_anisotropyDirectionMap"],onChange:()=>{e.setDirty&&e.setDirty()}},ie(i,"_anisotropyDirectionMap","Sampler",()=>!i._isAnisotropic||"CONSTANT"===i._anisotropyDirectionMode,()=>e.setDirty&&e.setDirty())]};return a},onMaterialUpdate:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onRegister:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onAddToMesh:e=>{if(!e.isMesh)return;const t=e,r=Array.isArray(t.material)?t.material:[t.material];r.find(e=>e?.userData?._isAnisotropic)&&this.tryComputeTangents(t,r)}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}enableAnisotropy(e,t,r,i,a){const s=e?.userData;if(!s)return!1;if(void 0===s._isAnisotropic){const t=e.appliedMeshes;let r=!0;if(t)for(const{geometry:e}of t)!e||e.attributes.position&&e.attributes.normal&&e.attributes.uv||(r=!1),r&&e&&!e.attributes.tangent&&e.computeTangents();if(!r)return!1}return s._isAnisotropic=!0,s._anisotropyFactor=r??s._anisotropyFactor??1,s._anisotropyNoise=i??s._anisotropyNoise??0,s._anisotropyDirection=s._anisotropyDirection??1,s._anisotropyDirectionMode=a??s._anisotropyDirectionMode??"DIRECTION",s._anisotropyDirectionMap=t??s._anisotropyDirectionMap??null,e.setDirty&&e.setDirty(),!0}tryComputeTangents(e,t){if(e.geometry&&!e.geometry.attributes.tangent){let r=!0;e.geometry.index&&e.geometry.attributes.position&&e.geometry.attributes.normal&&e.geometry.attributes.uv||(r=!1),r?e.geometry.computeTangents():t.map(e=>{e?.userData?._isAnisotropic&&(e.userData._isAnisotropic=!1)})}}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Rt)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Rt.name),super.onRemove(e)}makeAnisotropic(e){return this.enableAnisotropy(e)}};Et.PluginType="AnisotropyPlugin",Et.ANISOTROPY_GLTF_EXTENSION="WEBGI_materials_anisotropy",Pt([o("Enabled",e=>({onChange:e.setDirty})),f()],Et.prototype,"enabled",2),Et=Pt([E("Anisotropy (MatExt)")],Et);class Ct{constructor(e){this.parser=e,this.name=Rt.name}async extendMaterialParams(e,t){const r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const a=[],s=i.extensions[this.name];t.userData||(t.userData={}),t.userData._isAnisotropic=!0,t.userData._anisotropyFactor=s.anisotropyFactor??0,t.userData._anisotropyNoise=s.anisotropyNoiseFactor??s.anisotropyNoise??0;let{anisotropyDirectionMode:n,anisotropyDirection:o}=s;return n||(n=s.anisotropyTextureMode),o||(o=s.anisotropyRotation),t.userData._anisotropyDirectionMode=n&&"number"==typeof o?.index?n:"CONSTANT","ROTATION"===n||"DIRECTION"===n?a.push(r.assignTexture(t.userData,"_anisotropyDirectionMap",o).then(e=>{e.colorSpace=ae})):t.userData._anisotropyDirection=o??0,Promise.all(a)}afterRoot(e){return e.scene?.traverse(e=>{const t=e.material?.userData?._isAnisotropic;if(!t)return;const r=e.geometry;r.attributes.tangent||(r.computeTangents(),r.attributes.tangent.needsUpdate=!0)}),null}}const Rt={name:"WEBGI_materials_anisotropy",import:e=>new Ct(e),export:e=>({writeMaterial:(t,r)=>{if(!t.isMeshStandardMaterial||!t.userData._isAnisotropic)return;if((t.userData._anisotropyFactor||0)<.001)return;r.extensions=r.extensions||{};const i={};if(i.anisotropyFactor=t.userData._anisotropyFactor||1,i.anisotropyNoiseFactor=t.userData._anisotropyNoise||0,i.anisotropyDirectionMode=t.userData._anisotropyDirectionMode||"CONSTANT",e.checkEmptyMap(t.userData._anisotropyDirectionMap)&&"CONSTANT"!==i.anisotropyDirectionMode){const r={index:e.processTexture(t.userData._anisotropyDirectionMap)};e.applyTextureTransform(r,t.userData._anisotropyDirectionMap),i.anisotropyDirection=r}else i.anisotropyDirectionMode="CONSTANT",i.anisotropyDirection=t.userData._anisotropyDirection||0;r.extensions[Rt.name]=i,e.extensionsUsed[Rt.name]=!0}}),textures:{anisotropyDirection:"RGB"}};var At=Object.defineProperty,Ut=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&At(t,r,s),s};const Lt=class extends se{constructor(e,t,r=0,i){super(e,i),this.type="Reflector",this.isReflector2=!0,this.enabled=!0,this.reflectorModePhysical=!0,this.reflectionTargetNeedsUpdate=!0,this.transparentReflectionBackground=!0,this.materialExtension={extraUniforms:{tRefDiffuse:{value:null},tRefDiffuseSize:{value:new d},refTextureMatrix:{value:new u},frameCount:{value:0},sceneBoundingRadius:{value:0}},extraDefines:{USE_UV:""},updaters:[],shaderExtender:(e,t,r)=>{if(this.enabled){e.vertexShader=y(e.vertexShader,"void main() {","void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");const t="#glMarker beforeModulation";e.fragmentShader=y(e.fragmentShader,t,"\n if(roughnessFactor < 0.95) {\n float d = 0.;//textureProj(tRefDepth, vRefUv).r;\n // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));\n vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);\n // refBaseColor.rgb = vec3(refBaseColor.a);\n // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);\n "+(this.reflectorModePhysical?"\n #if !defined(SSR_ENABLED) || SSR_ENABLED < 1 \n vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);\n #endif\n reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);\n ":"\n reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);\n diffuseColor.a *= refBaseColor.a;\n ")+"}\n"+t)}},parsVertexSnippet:()=>this.enabled?"\n\t\tuniform mat4 refTextureMatrix;\n\t\tvarying vec4 vRefUv;\n":"",parsFragmentSnippet:()=>this.enabled?"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}":"",computeCacheKey:e=>this.enabled+" "+e.transparent+" "+this.reflectorModePhysical+" ",onObjectRender:(e,t)=>{t.userData.__lastTransparent!==t.transparent&&(t.needsUpdate=!0,t.userData.__lastTransparent=t.transparent)},isCompatible:e=>e.isPhysicalMaterial,setDirty:()=>this.materialExtension.__setDirty?.()},this._renderTarget=t;const a=new ne,s=new F,n=new F,o=new F,l=new u,c=new F(0,0,-1),h=new A,p=new F,f=new F,m=new A,g=new u,v=new oe;this.onBeforeRender=(e,t,i)=>{if(!this.enabled||!e.userData.mainRenderPass)return;if(!this.reflectionTargetNeedsUpdate)return;const d=this._getRenderTarget();if(!d)return void console.warn("Reflector2: No render target set.");const u=i.view?Object.assign({},i.view):null;if(u&&i.clearViewOffset&&i.clearViewOffset(),n.setFromMatrixPosition(this.matrixWorld),o.setFromMatrixPosition(i.matrixWorld),l.extractRotation(this.matrixWorld),s.set(0,0,1),s.applyMatrix4(l),p.subVectors(n,o),p.dot(s)>0)return;p.reflect(s).negate(),p.add(n),l.extractRotation(i.matrixWorld),c.set(0,0,-1),c.applyMatrix4(l),c.add(o),f.subVectors(n,c),f.reflect(s).negate(),f.add(n),v.position.copy(p),v.up.set(0,1,0),v.up.applyMatrix4(l),v.up.reflect(s),v.lookAt(f),v.far=2,v.near=0,v.updateMatrixWorld(),v.projectionMatrix.copy(i.projectionMatrix),g.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),g.multiply(v.projectionMatrix),g.multiply(v.matrixWorldInverse),g.multiply(this.matrixWorld),a.setFromNormalAndCoplanarPoint(s,n),a.applyMatrix4(v.matrixWorldInverse),h.set(a.normal.x,a.normal.y,a.normal.z,a.constant);const _=v.projectionMatrix;m.x=(Math.sign(h.x)+_.elements[8])/_.elements[0],m.y=(Math.sign(h.y)+_.elements[9])/_.elements[5],m.z=-1,m.w=(1+_.elements[10])/_.elements[14],h.multiplyScalar(2/h.dot(m)),_.elements[2]=h.x,_.elements[6]=h.y,_.elements[10]=h.z+1-r,_.elements[14]=h.w,this.visible=!1;const y=e.getRenderTarget(),x=e.xr.enabled,S=e.shadowMap.autoUpdate;e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,e.setRenderTarget(d),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear();const b=t.background;this.transparentReflectionBackground&&(t.background=null);const w=!this.transparentReflectionBackground;b?.isTexture&&w&&(b.userData||(b.userData={}),b.userData.flipX=!b.userData.flipX),e.renderWithModes({shadowMapRender:!1,backgroundRender:w,opaqueRender:!0,transparentRender:!0,transmissionRender:!1,screenSpaceRendering:!1},()=>e.render(t,v)),b?.isTexture&&w&&(b.userData.flipX=!b.userData.flipX||void 0),this.transparentReflectionBackground&&(t.background=b),e.xr.enabled=x,e.shadowMap.autoUpdate=S,e.setRenderTarget(y),u?.enabled&&i.setViewOffset&&i.setViewOffset(u.fullWidth,u.fullHeight,u.offsetX,u.offsetY,u.width,u.height);const T=i.viewport;void 0!==T&&e.state.viewport(T),this.visible=!0,this.reflectionTargetNeedsUpdate=!1},this.textureMatrix=g,this.materialExtension.extraUniforms.refTextureMatrix.value=g}_getRenderTarget(){const e=p(this._renderTarget);return e&&(!e.texture.generateMipmaps||le.isPowerOfTwo(e.texture.image.width)&&le.isPowerOfTwo(e.texture.image.height)||(e.texture.generateMipmaps=!1),this.materialExtension.extraUniforms.tRefDiffuse.value=e.texture,this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(e.width,e.height)),e}_updateExtension(){this.transparentReflectionBackground=this.reflectorModePhysical,this.materialExtension?.setDirty?.()}getRenderTarget(){return this._renderTarget}};Ut([N(Lt.prototype._updateExtension)],Lt.prototype,"enabled"),Ut([N(Lt.prototype._updateExtension)],Lt.prototype,"reflectorModePhysical");let Bt=Lt;Bt.prototype.isReflector=!0;class Nt{static _xfnv1a(e){let t=2166136261;for(let r=0;r<e.length;r++)t=Math.imul(t^e.charCodeAt(r),16777619);return()=>(t+=t<<13,t^=t>>>7,t+=t<<3,t^=t>>>17,(t+=t<<5)>>>0)}}class Ot extends Nt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.a=Ot._xfnv1a(e)()}next(){let e=this.a+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}class Ft extends Nt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=Ft._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){this.a>>>=0,this.b>>>=0,this.c>>>=0,this.d>>>=0;let e=this.a+this.b|0;return this.a=this.b^this.b>>>9,this.b=this.c+(this.c<<3)|0,this.c=this.c<<21|this.c>>>11,this.d=this.d+1|0,e=e+this.d|0,this.c=this.c+e|0,(e>>>0)/4294967296}}class kt extends Nt{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=kt._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){const e=this.b<<9;let t=5*this.b;return t=9*(t<<7|t>>>25),this.c^=this.a,this.d^=this.b,this.b^=this.c,this.a^=this.d,this.c^=e,this.d=this.d<<11|this.d>>>21,(t>>>0)/4294967296}}var It,zt;(zt=It||(It={})).sfc32="sfc32",zt.mulberry32="mulberry32",zt.xoshiro128ss="xoshiro128ss";class Vt{constructor(e,t=It.sfc32){Object.defineProperty(this,"str",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prng",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.str=e,this.prng=t,this.generator=this._initializeGenerator()}next(){return this.generator.next()}_initializeGenerator(){if(/* @__PURE__ */(e=>null===e)(e=this.str)||/* @__PURE__ */(e=>void 0===e)(e))return this.wrap();var e;switch(this.prng){case"sfc32":return new Ft(this.str);case"mulberry32":return new Ot(this.str);case"xoshiro128ss":return new kt(this.str);default:return this.wrap()}}wrap(){return{next:()=>Math.random()}}}var jt=Object.defineProperty,Gt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&jt(t,r,s),s};class Ht extends ce{constructor(e,t,r,i){super(e,t),this._shadowParams={enabled:!0,radius:2,width:1024,height:1024,bias:-.001,normalBias:0,near:1.5,far:4,frustumSize:4},this._randomParams={focus:1,spread:.01,distanceScale:50,minDistanceScale:new F(10,10,10),normalDirection:new F(.01,.98,.01).normalize(),direction:new F(-.9,.5,-1)},this.isRandomizedDirectionalLight=!0,this.shadowParams=r??{},this.randomParams=i??{},this.updateShadowParams=this.updateShadowParams.bind(this)}get shadowParams(){return this._shadowParams}set shadowParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this._shadowParams={...this._shadowParams,...e},this.updateShadowParams()}get randomParams(){return this._randomParams}set randomParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),Object.assign(this._randomParams,e)}updateShadowParams(){this.castShadow=this._shadowParams.enabled,this.shadow.mapSize.x=this._shadowParams.width,this.shadow.mapSize.y=this._shadowParams.height,this.shadow.bias=this._shadowParams.bias,this.shadow.normalBias=this._shadowParams.normalBias,this.refreshShadowCamNearFar(),this.shadow.radius=this._shadowParams.radius,this.shadow.camera.right=this._shadowParams.frustumSize/2,this.shadow.camera.left=-this._shadowParams.frustumSize/2,this.shadow.camera.top=this._shadowParams.frustumSize/2,this.shadow.camera.bottom=-this._shadowParams.frustumSize/2,this.shadow.camera.updateProjectionMatrix(),this.matrixWorldNeedsUpdate=!0}randomizePosition(e,t=null,r=null){const i=new Vt(e.toString()),a=new d(i.next()*Math.PI*2,Math.asin(2*i.next()-1));let s=new F(Math.cos(a.x)*Math.cos(a.y),Math.sin(a.y),Math.sin(a.x)*Math.cos(a.y));const n=new d;for(let o=0;o<5;o++){n.set(i.next(),i.next()),s=Wt(n,this._randomParams.normalDirection,.4),i.next()<Math.sqrt(t??this._randomParams.focus)&&(n.set(i.next(),i.next()),s=Wt(n,this._randomParams.direction,Math.pow((r??this._randomParams.spread)/2,2)));const e=s.dot(this._randomParams.normalDirection);if(e>0&&e<.4)break}s.normalize(),s.multiplyScalar(this._randomParams.distanceScale),this.position.set(0,0,0),this.target.position.copy(s.normalize().negate()),this.target.updateMatrixWorld(),this.refreshShadowCamNearFar(),this.updateMatrixWorld()}refreshShadowCamNearFar(){const e=(new F).subVectors(this.target.position,this.shadow.camera.position).length();this.shadow.camera.near=e-this._shadowParams.near*this._shadowParams.frustumSize/2,this.shadow.camera.far=e+this._shadowParams.far*this._shadowParams.frustumSize/2}dispose(){}toJSON(e,t=!1){const{userData:r,children:i}=this;this.userData={},this.children=[];const a=super.toJSON(e),s=de({},r);return a.userData=ue.Serialize(s),this.userData=r,this.children=i,a.type="DirectionalLight2",a.target=this.target.position.toArray(),{...a,...he.Serialize(this,e,!0)}}fromJSON(e,t,r=!1){if("DirectionalLight2"!==e.type)return null;const i=e.target,a=e.object;return e.target&&(this.target.position.fromArray(e.target),this.target.updateMatrixWorld(),delete e.target),e.object&&delete e.object,he.Deserialize(e,this,t,!0),i&&(e.target=i),a&&(void 0!==a.color&&this.color.set(a.color),void 0!==a.intensity&&(this.intensity=a.intensity),e.object=a),this.updateShadowParams(),this}}function Wt(e,t,r){t=t.clone().normalize();const i=new F(0,-t.z,t.y).normalize(),a=(new F).crossVectors(t,i).normalize(),s=e;s.x=2*s.x*Math.PI,s.y=1-s.y*r;const n=Math.sqrt(1-s.y*s.y);return i.multiplyScalar(Math.cos(s.x)*n).add(a.multiplyScalar(Math.sin(s.x)*n)).add(t.multiplyScalar(s.y))}Gt([f("shadowParams")],Ht.prototype,"_shadowParams"),Gt([f("randomParams")],Ht.prototype,"_randomParams");var Yt=Object.defineProperty;class Xt extends pe{constructor(){super(...arguments),this.typeSlug="fsShadow",this.assetType="material",this._uniforms={},this.lastFrameTexture=null}get materialObject(){return this}onBeforeCompile(e,t){e.vertexShader=e.vertexShader.replace("#include <project_vertex>","\n#include <project_vertex>\ngl_Position = vec4(uv*2.-1., 0, 1.); \n "),e.vertexShader=e.vertexShader.replace("void main() {","\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n "),e.fragmentShader=e.fragmentShader.replace("void main() {","\nvarying vec2 vUv;\nuniform sampler2D tLastThis;\nvoid main() {\n "),e.fragmentShader=e.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );",K`
62
62
  float shadow = getShadowMask();
63
63
 
64
64
  //shift the color by dither_shift
@@ -68,9 +68,9 @@ float last = unpackRGBAToDepth(texture2D(tLastThis, vUv));
68
68
  gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
69
69
  //if not useMovingAverage:
70
70
  //gl_FragColor = packDepthToRGBA(shadow * opacity + last);
71
- `),Object.assign(e.uniforms,this._uniforms),super.onBeforeCompile(e,t)}customProgramCacheKey(){return super.customProgramCacheKey()}toJSON(){throw new Error("Method not supported for this material.")}fromJSON(){throw new Error("Method not supported for this material.")}copyProps(){throw new Error("Method not supported for this material.")}setDirty(e){this.needsUpdate=!0,this.dispatchEvent({...e,type:"materialUpdate"})}}((e,t,r)=>{for(var i,a=void 0,n=e.length-1;n>=0;n--)(i=e[n])&&(a=i(t,r,a)||a);a&&Kt(t,r,a)})([p({propKey:"tLastThis"})],qt.prototype,"lastFrameTexture");var Zt=Object.defineProperty,Jt=(e,t,r,i)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,r,n)||n);return n&&Zt(t,r,n),n};const $t=e.ShaderChunk,Qt=class extends he{enabled=!0;get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh!==e&&(this._attachedMesh&&this.cleanupMaterial(),this._attachedMesh=e,this._attachedMesh&&this._updateMaterial())}_shadowMat;_shadowBlurMat;get target(){return this._target}_target;get light(){return this._light}_light;_lightLayer=5;_viewer;constructor(e){super(),this._viewer=e;const t=new Yt(16777215,10,{near:1.5,far:20,bias:0,frustumSize:4,width:1024,height:1024,enabled:!0,radius:10,normalBias:0},{direction:new N(.2,1,.2).normalize(),spread:.9,focus:1,distanceScale:20,minDistanceScale:new N(10,10,10),normalDirection:new N(0,1,0)});t.shadow.camera.updateProjectionMatrix(),t.layers.disableAll(),t.layers.set(this._lightLayer),this._light=t,e.scene.addObject(this._light,{addToRoot:!0}),this._shadowMat=new qt({color:"#ffffff",toneMapped:!1,depthWrite:!1,depthTest:!1,premultipliedAlpha:!1,opacity:1,transparent:!1,blending:b}),this._shadowBlurMat=new pe({uniforms:{colorTexture:{value:null},step:{value:.1},size:{value:new l(.5,.5)},direction:{value:new l(.5,.5)}},vertexShader:z.defaultVertex,fragmentShader:"#include <packing>\nuniform sampler2D colorTexture;uniform vec2 size;uniform vec2 direction;uniform float step;varying vec2 vUv;void main(){float sum=0.0;vec2 uvDelta=step*direction/size;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv-1.*uvDelta))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vec2(vUv.x,vUv.y)))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv+1.*uvDelta))*0.3333;gl_FragColor=packDepthToRGBA(sum);}"})}dispose(){this._shadowMat.dispose(),this._target=void 0,this.reset()}cleanupMaterial(){this._updateMaterial(!0)}_frameNumber=0;maxFrameNumber=400;smoothShadow=!1;shadowMapType=fe;_attachedMesh;groundMapMode="aoMap";alphaVignette=!0;alphaVignetteAxis="xy";_groundMapModeChanged(){this._attachedMesh&&(this.cleanupMaterial(),this._updateMaterial(),"alphaMap"===this.groundMapMode?this._attachedMesh.material.transparent=!0:this._attachedMesh.material.transparent=!1),this.reset()}_alphaVignetteChanged(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}fromJSON(e,t,r=!1){return r?(ue.Deserialize(e,this,t,!0),this.reset(),this):ue.Deserialize(e,this,t,!1)}reset(){this._frameNumber=0}get frameNumber(){return this._frameNumber}shadowAutoUpdate=!0;_bakeCounter=0;maxBakeCount=1/0;autoUpdateShadow(){return!!this.shadowAutoUpdate&&(!(this._bakeCounter>=this.maxBakeCount)&&(!!this.updateShadow()&&(this._frameNumber===this.maxFrameNumber?this.dispatchEvent({type:"shadowBaked",bakeCount:++this._bakeCounter}):this._frameNumber>0&&this._frameNumber<this.maxFrameNumber&&this.dispatchEvent({type:"shadowBaking",progress:this._frameNumber/this.maxFrameNumber,bakeCount:this._bakeCounter}),!0)))}updateShadow(){if(!this.enabled)return!1;const e=this._attachedMesh;if(!e)return!1;if(++this._frameNumber>this.maxFrameNumber)return!1;const t=1024;this._target||(this._target=this._viewer.renderManager.createTarget({type:y,depthBuffer:!1,size:new l(t,t),sizeMultiplier:void 0,colorSpace:me,format:V})),this._frameNumber<3?this._light.randomizePosition(0,1,0):this._light.randomizePosition(this._frameNumber),e.castShadow=!1;const r=this._viewer.renderManager.renderer,i=r.shadowMap,a=i.type,n=i.needsUpdate,s=i.autoUpdate;i.type=this.shadowMapType,i.needsUpdate=!0,i.autoUpdate=!1;const o=this._viewer.scene,c=new ge;c.disableAll(),o.traverse(e=>{e.isLight&&e!==this._light&&(e.userData.__gp_layers=e.layers,e.layers=c)});const u=o.mainCamera;if(u.layers.mask&1<<this._lightLayer)throw"Camera can render pseudo directional light, check layers";u.layers.enable(this._lightLayer),e.layers.disable(this._lightLayer),r.renderWithModes({shadowMapRender:!0,backgroundRender:!1,sceneRender:!1},()=>r.render(o,o.mainCamera)),u.layers.disable(this._lightLayer);const d=u.layers.mask;u.layers.set(this._lightLayer),e.layers.enable(this._lightLayer);const h=this._viewer.renderManager.getTempTarget({type:y,depthBuffer:!1,size:new l(t,t),colorSpace:me,format:V}),p=h.texture,f=p.colorSpace;p.colorSpace=me,this._viewer.renderManager.blit(h,{clear:!0,source:this._target.texture});{const t=e.material,i=e.frustumCulled,a=r.getRenderTarget(),n=r.getActiveCubeFace(),s=r.getActiveMipmapLevel();e.material=this._shadowMat,e.frustumCulled=!1,r.setRenderTarget(this._target),this._shadowMat.opacity=Math.max(1/this.maxFrameNumber,1/this._frameNumber),this._shadowMat.lastFrameTexture=h.texture,this._shadowMat.needsUpdate=!0,r.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},()=>r.render(o,o.mainCamera)),r.setRenderTarget(a,n,s),e.frustumCulled=i,e.material=t,this.smoothShadow&&this._applySmoothFilter(this._target,h)}return h.texture.colorSpace=f,this._viewer.renderManager.releaseTempTarget(h),e.layers.disable(this._lightLayer),u.layers.mask=d,o.modelObject.traverse(e=>{e.isLight&&e!==this._light.lightObject&&(e.layers=e.userData.__gp_layers,delete e.userData.__gp_layers)}),i.type=a,i.needsUpdate=n,i.autoUpdate=s,e.castShadow=!0,(this._frameNumber<3||this._frameNumber>Math.min(100,this.maxFrameNumber)&&this._frameNumber%4==0)&&(this._updateMaterial(),e.material.setDirty()),!0}_updateMaterial(e=!1){this._attachedMesh&&(e?(this._attachedMesh.material.alphaMap===this._target?.texture&&(this._attachedMesh.material.alphaMap=null),this._attachedMesh.material.aoMap===this._target?.texture&&(this._attachedMesh.material.aoMap=null),this._attachedMesh.material.map===this._target?.texture&&(this._attachedMesh.material.map=null)):this._target&&("alphaMap"===this.groundMapMode&&(this._attachedMesh.material.alphaMap=this._target.texture),"aoMap"===this.groundMapMode&&(this._attachedMesh.material.aoMap=this._target.texture),"map"===this.groundMapMode&&(this._attachedMesh.material.map=this._target.texture)),this._attachedMesh.material&&(this._attachedMesh.material.userData.ALPHA_I_RGBA_PACKING=!e&&"alphaMap"===this.groundMapMode,this._attachedMesh.material.alphaTest=e||"alphaMap"!==this.groundMapMode?0:.01,this._attachedMesh.material.needsUpdate=!0))}_applySmoothFilter(e,t){this._shadowBlurMat.uniforms.colorTexture.value=e.texture,this._shadowBlurMat.uniforms.direction.value.set(1,0),this._shadowBlurMat.uniforms.size.value.set(e.width,e.height),this._viewer.renderManager.blit(t,{material:this._shadowBlurMat}),this._shadowBlurMat.uniforms.colorTexture.value=t.texture,this._shadowBlurMat.uniforms.direction.value.set(0,1),this._shadowBlurMat.uniforms.size.value.set(t.width,t.height),this._viewer.renderManager.blit(e,{material:this._shadowBlurMat})}materialExtension={parsFragmentSnippet:(e,t)=>Y`
71
+ `),Object.assign(e.uniforms,this._uniforms),super.onBeforeCompile(e,t)}customProgramCacheKey(){return super.customProgramCacheKey()}toJSON(){throw new Error("Method not supported for this material.")}fromJSON(){throw new Error("Method not supported for this material.")}copyProps(){throw new Error("Method not supported for this material.")}setDirty(e){this.needsUpdate=!0,this.dispatchEvent({...e,type:"materialUpdate"})}}((e,t,r)=>{for(var i,a=void 0,s=e.length-1;s>=0;s--)(i=e[s])&&(a=i(t,r,a)||a);a&&Yt(t,r,a)})([m({propKey:"tLastThis"})],Xt.prototype,"lastFrameTexture");var Kt=Object.defineProperty,qt=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&Kt(t,r,s),s};const Zt=r.ShaderChunk,Jt=class extends fe{constructor(e){super(),this.enabled=!0,this._lightLayer=5,this._frameNumber=0,this.maxFrameNumber=400,this.smoothShadow=!1,this.shadowMapType=me,this.groundMapMode="aoMap",this.alphaVignette=!0,this.alphaVignetteAxis="xy",this.shadowAutoUpdate=!0,this._bakeCounter=0,this.maxBakeCount=1/0,this.materialExtension={parsFragmentSnippet:(e,t)=>K`
72
72
  uniform float transitionOpacity;
73
- `,extraUniforms:{transitionOpacity:{value:1}},shaderExtender:(e,t,r)=>{"aoMap"===this.groundMapMode?e.fragmentShader=x(e.fragmentShader,"#include <aomap_fragment>",x($t.aomap_fragment,"float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;","float ambientOcclusion = ( mix(1., unpackRGBAToDepth(texture2D( aoMap, vAoMapUv ) ), transitionOpacity) - 1.0) * aoMapIntensity + 1.0;")):"map"===this.groundMapMode?e.fragmentShader=x(e.fragmentShader,"#include <map_fragment>",x($t.map_fragment,"diffuseColor *= sampledDiffuseColor","float groundShadow = mix(1., unpackRGBAToDepth(sampledDiffuseColor), transitionOpacity); diffuseColor.rgb *= groundShadow; diffuseColor.a *= max(0., 1.-groundShadow) * transitionOpacity;")):"alphaMap"===this.groundMapMode&&(e.fragmentShader=x(e.fragmentShader,"#include <alphamap_fragment>",x($t.alphamap_fragment,"texture2D( alphaMap, vAlphaMapUv ).g","1. - unpackRGBAToDepth( texture2D( alphaMap, vAlphaMapUv ) )",{replaceAll:!0}))),e.fragmentShader=x(e.fragmentShader,"#include <opaque_fragment>",Y`#include <opaque_fragment>
73
+ `,extraUniforms:{transitionOpacity:{value:1}},shaderExtender:(e,t,r)=>{"aoMap"===this.groundMapMode?e.fragmentShader=y(e.fragmentShader,"#include <aomap_fragment>",y(Zt.aomap_fragment,"float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;","float ambientOcclusion = ( mix(1., unpackRGBAToDepth(texture2D( aoMap, vAoMapUv ) ), transitionOpacity) - 1.0) * aoMapIntensity + 1.0;")):"map"===this.groundMapMode?e.fragmentShader=y(e.fragmentShader,"#include <map_fragment>",y(Zt.map_fragment,"diffuseColor *= sampledDiffuseColor","float groundShadow = mix(1., unpackRGBAToDepth(sampledDiffuseColor), transitionOpacity); diffuseColor.rgb *= groundShadow; diffuseColor.a *= max(0., 1.-groundShadow) * transitionOpacity;")):"alphaMap"===this.groundMapMode&&(e.fragmentShader=y(e.fragmentShader,"#include <alphamap_fragment>",y(Zt.alphamap_fragment,"texture2D( alphaMap, vAlphaMapUv ).g","1. - unpackRGBAToDepth( texture2D( alphaMap, vAlphaMapUv ) )",{replaceAll:!0}))),e.fragmentShader=y(e.fragmentShader,"#include <opaque_fragment>",K`#include <opaque_fragment>
74
74
  #ifndef OPAQUE
75
75
  #ifdef USE_AOMAP
76
76
  #if NUM_DIR_LIGHT_SHADOWS > 0
@@ -85,7 +85,7 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
85
85
  gl_FragColor.a *= max(t, 0.);
86
86
  #endif
87
87
  #endif
88
- `),this.alphaVignette&&r.capabilities.isWebGL2&&(e.defines.USE_UV="",e.fragmentShader=x(e.fragmentShader,"#include <opaque_fragment>",Y`#include <opaque_fragment>
88
+ `),this.alphaVignette&&r.capabilities.isWebGL2&&(e.defines.USE_UV="",e.fragmentShader=y(e.fragmentShader,"#include <opaque_fragment>",K`#include <opaque_fragment>
89
89
  #ifndef OPAQUE
90
90
  float weight = 0.;
91
91
  #ifdef USE_UV // why are we checking for this? this is always supposed to be true
@@ -102,5 +102,5 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
102
102
  gl_FragColor = saturate(gl_FragColor);
103
103
  //gl_FragColor.a = 0.5;
104
104
  #endif
105
- `))},computeCacheKey:()=>this.groundMapMode+"."+this.alphaVignette+"."+this.alphaVignetteAxis,onObjectRender:(e,t)=>{t.userData.gMapMode!==this.groundMapMode&&(t.userData.gMapMode=this.groundMapMode,t.needsUpdate=!0)},isCompatible:e=>e.isPhysicalMaterial}};Jt([h("randomizedLight")],Qt.prototype,"_light"),Jt([L(Qt.prototype.reset),h()],Qt.prototype,"maxFrameNumber"),Jt([L(Qt.prototype.reset),h()],Qt.prototype,"smoothShadow"),Jt([h(),L(Qt.prototype.reset)],Qt.prototype,"shadowMapType"),Jt([L(Qt.prototype._groundMapModeChanged),h()],Qt.prototype,"groundMapMode"),Jt([h(),L(Qt.prototype._alphaVignetteChanged)],Qt.prototype,"alphaVignette"),Jt([h(),L(Qt.prototype._alphaVignetteChanged)],Qt.prototype,"alphaVignetteAxis"),Jt([h()],Qt.prototype,"maxBakeCount");let er=Qt;var tr=Object.defineProperty,rr=(e,t,r,i)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,r,n)||n);return n&&tr(t,r,n),n};const ir=class extends X{static PluginType="AdvancedGroundPlugin";get shadowBaker(){return this._shadowBaker}bakedShadows=!0;groundReflection=!1;physicalReflections=!1;autoFrustumSize=!0;_refresh3(){this.refresh()}_shadowBaker;autoBakeShadows=!0;bakeShadows(){this._shadowBaker?.reset()}constructor(){super(),this._onSceneUpdate=this._onSceneUpdate.bind(this);const e=a(this),t=e.find(e=>"function"==typeof e);this.uiConfig={label:"Ground",type:"folder",children:[...e.filter(e=>e!==t),...this._extraUiConfig(),t]}}_createMesh(e){if(e)throw new Error("AdvancedGroundPlugin - mesh should not be provided");const t=new Ot(this._geometry,()=>this._viewer?.renderManager.createTarget({type:y,format:V,colorSpace:me,size:{width:1024,height:1024},generateMipmaps:!0,depthBuffer:!0,minFilter:_e,magFilter:ve}),0,this._createMaterial()),r=t.onBeforeRender;return t.onBeforeRender=(...e)=>{let i=this._viewer?.getPluginByType("SSReflectionPlugin");i&&i.isDisabled()&&(i=void 0),i&&i.disable(t.uuid,!1),r(...e),i&&i.enable(t.uuid,!1)},t}onAdded(e){super.onAdded(e)}_postFrame(){super._postFrame(),this._viewer&&this.enabled&&this._shadowBaker&&this.bakedShadows&&this._shadowBaker.autoUpdateShadow()}_preRender(){super._preRender(),this._viewer&&(this._mesh.reflectionTargetNeedsUpdate=this._viewer.renderManager.frameCount<1)}onRemove(e){return super.onRemove(e)}_removeMaterial(){if(this._material){if(this._shadowBaker&&this._material.groundMatExtension&&(this._material.unregisterMaterialExtensions?.([this._shadowBaker.materialExtension]),delete this._material.groundMatExtension),this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e||this._viewer?.console.warn("AdavancedGroundPlugin: unable to find the extension to unregister"),this._material.unregisterMaterialExtensions?.([e]),delete this._material.reflectorMatExtension}super._removeMaterial()}}_onSceneUpdate(e){super._onSceneUpdate(e),!1!==e.geometryChanged&&this.autoResetShadows()}autoResetShadows=()=>{this.autoBakeShadows&&this._shadowBaker?.reset()};refresh(){if(this._viewer){if(!this.isDisabled()){this.bakedShadows&&!this._shadowBaker?(this._shadowBaker=new er(this._viewer),this._shadowBaker.attachedMesh=this._mesh):!this.bakedShadows&&this._shadowBaker&&(this._shadowBaker.reset(),this._shadowBaker.cleanupMaterial());const e=this._mesh;e.isReflector2&&(e.enabled=this.groundReflection,e.reflectorModePhysical=this.physicalReflections)}super.refresh()}}_refreshTransform(){if(!super._refreshTransform())return!1;if(this.autoFrustumSize){const e=this.shadowBaker;if(e){const t=this.size/2;t!==e.light.shadowParams.frustumSize&&(e.light.shadowParams.frustumSize=t,e.light.updateShadowParams(),e.reset())}}return!0}fromJSON(e,t){return super.fromJSON(e,t)?(void 0===e.autoFrustumSize&&(this.autoFrustumSize=!1),this):null}_refreshMaterial(){if(!this._viewer)return!1;if(super._refreshMaterial(),this._material){if(this.groundReflection&&this._mesh.isReflector2&&!this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e.updaters=[this._viewer.scene,this._viewer.renderManager],this._material.registerMaterialExtensions?.([e]),this._material.reflectorMatExtension=!0}this.bakedShadows&&this._shadowBaker&&!this._material.groundMatExtension&&(this._material.registerMaterialExtensions?.([this._shadowBaker.materialExtension]),this._material.groundMatExtension=!0),this._material.userData.ssreflDisabled=this.groundReflection,this._material.userData.ssreflNonPhysical=!this.physicalReflections,this._material.userData.ssaoDisabled=!0,this._material.userData.sscsDisabled=!0,this._viewer.setDirty(this)}}uiConfig;_extraUiConfig(){return[{label:"Shadow Frames",type:"input",hidden:()=>!this._shadowBaker,stepSize:1,bounds:[1,1e3],property:()=>[this._shadowBaker,"maxFrameNumber"]},{label:"Alpha Vignette",type:"checkbox",hidden:()=>!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignette"],limitedUi:!0,onChange:()=>this.uiConfig?.uiRefresh?.(!0,"postFrame")},{label:"Alpha Vignette Axis",type:"dropdown",hidden:()=>!this._shadowBaker?.alphaVignette||!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignetteAxis"],children:["x","y","xy"].map(e=>({label:e,value:e})),limitedUi:!0},{label:"Shadow type",type:"dropdown",hidden:()=>!this._shadowBaker,property:()=>[this._shadowBaker,"groundMapMode"],children:[{label:"aoMap"},{label:"map"},{label:"alphaMap"}],limitedUi:!0},{label:"Smooth Shadow",type:"checkbox",property:()=>[this._shadowBaker,"smoothShadow"]},{label:"Baked shadow type",type:"dropdown",children:[["Basic",fe],["PCF",ye],["PCFSoft",xe],["VSM",Se]].map(e=>({label:e[0].toString(),value:e[1]})),property:()=>[this._shadowBaker,"shadowMapType"]},{type:"folder",label:"Randomized Light",hidden:()=>!this._shadowBaker,limitedUi:!0,children:[{type:"color",label:"Color",property:()=>[this._shadowBaker?.light,"color"]},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"focus"],onChange:this.autoResetShadows},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"spread"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,60],property:()=>[this._shadowBaker?.light?.randomParams,"distanceScale"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"direction"],onChange:this.autoResetShadows,limitedUi:!0},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"normalDirection"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,10],property:()=>[this._shadowBaker?.light?.shadowParams,"radius"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"input",property:()=>[this._shadowBaker?.light?.shadowParams,"frustumSize"],hidden:()=>this.autoFrustumSize,onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"slider",bounds:[-.1,.1],property:()=>[this._shadowBaker?.light?.shadowParams,"bias"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]}]}]}planarReflections};rr([L(ir.prototype._refresh3),n("Baked Shadows"),h()],ir.prototype,"bakedShadows"),rr([L(ir.prototype._refresh3),n("Planar Reflections"),h()],ir.prototype,"groundReflection"),rr([L(ir.prototype._refresh3),n("Physical Reflections"),h()],ir.prototype,"physicalReflections"),rr([L(ir.prototype._refresh3),n("Auto Shadow Frustum Size"),h()],ir.prototype,"autoFrustumSize"),rr([h("shadowBaker")],ir.prototype,"_shadowBaker"),rr([G({key:"groundReflection"})],ir.prototype,"planarReflections");let ar=ir;var nr=Object.defineProperty,sr=Object.getOwnPropertyDescriptor,or=(e,t,r,i)=>{for(var a,n=i>1?void 0:i?sr(t,r):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(i?a(t,r,n):a(n))||n);return i&&n&&nr(t,r,n),n};let lr=class extends H{enabled=!0;dependencies=[];axis="y";invertAxis=!1;analog=!0;hourOffset=0;minuteOffset=0;secondOffset=0;hour=".*hour.*";minute=".*minute.*";second=".*second.*";regex=!0;hands=[];onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject),e.addEventListener("preFrame",this._preFrame)}onRemove(e){e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.removeEventListener("preFrame",this._preFrame),super.onRemove(e)}_lastEnabled=!0;_preFrame=()=>{if(!this.enabled){if(this._lastEnabled){if(this._lastEnabled=!1,!this.hands.length)return;for(const e of this.hands)e.object.rotation.fromArray(e.object.userData.initRotation),e.object.updateMatrixWorld();this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}return}if(this._lastEnabled=!0,!this.hands.length)return;const e=this._viewer?.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(0===e)return;const t=/* @__PURE__ */new Date,r=this.invertAxis?-1:1,i=r*(t.getSeconds()+(this.analog?t.getMilliseconds()/1e3:0)-this.secondOffset)*(2*Math.PI)/60,a=r*(t.getMinutes()-this.minuteOffset)*(2*Math.PI)/60+i/60,n=r*(t.getHours()-this.hourOffset)*(2*Math.PI)/12+a/12;if(this.hands.find(e=>"second"===e.type&&Math.abs(i-e.object.rotation[this.axis])>.001)){for(const e of this.hands)"second"===e.type&&(e.object.rotation[this.axis]=i),"minute"===e.type&&(e.object.rotation[this.axis]=a),"hour"===e.type&&(e.object.rotation[this.axis]=n);this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}};_addSceneObject=async e=>{e.object&&this.refresh()};refresh(){this.hands=[],this._viewer?.scene.modelRoot.traverse(e=>{let t=!1;e.traverseAncestors(e=>{t||this.hands.find(t=>t.object===e)&&(t=!0)}),t||(e.name.match(this.regex?new RegExp(this.hour):this.hour)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"hour",object:e})),e.name.match(this.regex?new RegExp(this.minute):this.minute)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"minute",object:e})),e.name.match(this.regex?new RegExp(this.second):this.second)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"second",object:e})))})}};((e,t,r)=>{t in e?nr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r})(lr,"PluginType"+"","WatchHandsPlugin"),or([n(),h()],lr.prototype,"enabled",2),or([be(void 0,["x","y","z"].map(e=>({label:e}))),h()],lr.prototype,"axis",2),or([n(),h()],lr.prototype,"invertAxis",2),or([n(),h()],lr.prototype,"analog",2),or([U(void 0,[0,12],.001),h()],lr.prototype,"hourOffset",2),or([U(void 0,[0,60],.001),h()],lr.prototype,"minuteOffset",2),or([U(void 0,[0,60],.001),h()],lr.prototype,"secondOffset",2),or([we(),h()],lr.prototype,"hour",2),or([we(),h()],lr.prototype,"minute",2),or([we(),h()],lr.prototype,"second",2),or([n(),L("refresh"),h()],lr.prototype,"regex",2),or([Te()],lr.prototype,"refresh",1),lr=or([P("Watch Hands Time")],lr);const cr=[Re,Oe,je,lt,rt,Xe,ft,wt,Rt,ar,lr];export{ar as AdvancedGroundPlugin,Rt as AnisotropyPlugin,je as BloomPlugin,Ge as BloomPluginPass,Xe as DepthOfFieldPlugin,qe as DepthOfFieldPluginPass,ft as OutlinePlugin,mt as OutlineRenderPass,rt as SSContactShadowsPlugin,wt as SSGIPlugin,Tt as SSGIPluginPass,lt as SSReflectionPlugin,ct as SSReflectionPluginPass,Fe as SSVelocityMaterial,Re as TemporalAAPlugin,Ae as TemporalAAPluginPass,Oe as VelocityBufferPlugin,lr as WatchHandsPlugin,Ut as anisotropyGLTFExtension,cr as webgiPlugins};
105
+ `))},computeCacheKey:()=>this.groundMapMode+"."+this.alphaVignette+"."+this.alphaVignetteAxis,onObjectRender:(e,t)=>{t.userData.gMapMode!==this.groundMapMode&&(t.userData.gMapMode=this.groundMapMode,t.needsUpdate=!0)},isCompatible:e=>e.isPhysicalMaterial},this._viewer=e;const t=new Ht(16777215,10,{near:1.5,far:20,bias:0,frustumSize:4,width:1024,height:1024,enabled:!0,radius:10,normalBias:0},{direction:new F(.2,1,.2).normalize(),spread:.9,focus:1,distanceScale:20,minDistanceScale:new F(10,10,10),normalDirection:new F(0,1,0)});t.shadow.camera.updateProjectionMatrix(),t.layers.disableAll(),t.layers.set(this._lightLayer),this._light=t,e.scene.addObject(this._light,{addToRoot:!0}),this._shadowMat=new Xt({color:"#ffffff",toneMapped:!1,depthWrite:!1,depthTest:!1,premultipliedAlpha:!1,opacity:1,transparent:!1,blending:T}),this._shadowBlurMat=new ge({uniforms:{colorTexture:{value:null},step:{value:.1},size:{value:new d(.5,.5)},direction:{value:new d(.5,.5)}},vertexShader:V.defaultVertex,fragmentShader:"#include <packing>\nuniform sampler2D colorTexture;uniform vec2 size;uniform vec2 direction;uniform float step;varying vec2 vUv;void main(){float sum=0.0;vec2 uvDelta=step*direction/size;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv-1.*uvDelta))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vec2(vUv.x,vUv.y)))*0.3333;sum+=unpackRGBAToDepth(texture2D(colorTexture,vUv+1.*uvDelta))*0.3333;gl_FragColor=packDepthToRGBA(sum);}"})}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh!==e&&(this._attachedMesh&&this.cleanupMaterial(),this._attachedMesh=e,this._attachedMesh&&this._updateMaterial())}get target(){return this._target}get light(){return this._light}dispose(){this._shadowMat.dispose(),this._target=void 0,this.reset()}cleanupMaterial(){this._updateMaterial(!0)}_groundMapModeChanged(){this._attachedMesh&&(this.cleanupMaterial(),this._updateMaterial(),"alphaMap"===this.groundMapMode?this._attachedMesh.material.transparent=!0:this._attachedMesh.material.transparent=!1),this.reset()}_alphaVignetteChanged(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}fromJSON(e,t,r=!1){return r?(he.Deserialize(e,this,t,!0),this.reset(),this):he.Deserialize(e,this,t,!1)}reset(){this._frameNumber=0}get frameNumber(){return this._frameNumber}autoUpdateShadow(){return!!this.shadowAutoUpdate&&(!(this._bakeCounter>=this.maxBakeCount)&&(!!this.updateShadow()&&(this._frameNumber===this.maxFrameNumber?this.dispatchEvent({type:"shadowBaked",bakeCount:++this._bakeCounter}):this._frameNumber>0&&this._frameNumber<this.maxFrameNumber&&this.dispatchEvent({type:"shadowBaking",progress:this._frameNumber/this.maxFrameNumber,bakeCount:this._bakeCounter}),!0)))}updateShadow(){if(!this.enabled)return!1;const e=this._attachedMesh;if(!e)return!1;if(++this._frameNumber>this.maxFrameNumber)return!1;const t=1024;this._target||(this._target=this._viewer.renderManager.createTarget({type:_,depthBuffer:!1,size:new d(t,t),sizeMultiplier:void 0,colorSpace:ve,format:G})),this._frameNumber<3?this._light.randomizePosition(0,1,0):this._light.randomizePosition(this._frameNumber),e.castShadow=!1;const r=this._viewer.renderManager.renderer,i=r.shadowMap,a=i.type,s=i.needsUpdate,n=i.autoUpdate;i.type=this.shadowMapType,i.needsUpdate=!0,i.autoUpdate=!1;const o=this._viewer.scene,l=new _e;l.disableAll(),o.traverse(e=>{e.isLight&&e!==this._light&&(e.userData.__gp_layers=e.layers,e.layers=l)});const c=o.mainCamera;if(c.layers.mask&1<<this._lightLayer)throw"Camera can render pseudo directional light, check layers";c.layers.enable(this._lightLayer),e.layers.disable(this._lightLayer),r.renderWithModes({shadowMapRender:!0,backgroundRender:!1,sceneRender:!1},()=>r.render(o,o.mainCamera)),c.layers.disable(this._lightLayer);const u=c.layers.mask;c.layers.set(this._lightLayer),e.layers.enable(this._lightLayer);const h=this._viewer.renderManager.getTempTarget({type:_,depthBuffer:!1,size:new d(t,t),colorSpace:ve,format:G}),p=h.texture,f=p.colorSpace;p.colorSpace=ve,this._viewer.renderManager.blit(h,{clear:!0,source:this._target.texture});{const t=e.material,i=e.frustumCulled,a=r.getRenderTarget(),s=r.getActiveCubeFace(),n=r.getActiveMipmapLevel();e.material=this._shadowMat,e.frustumCulled=!1,r.setRenderTarget(this._target),this._shadowMat.opacity=Math.max(1/this.maxFrameNumber,1/this._frameNumber),this._shadowMat.lastFrameTexture=h.texture,this._shadowMat.needsUpdate=!0,r.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!1,transmissionRender:!1},()=>r.render(o,o.mainCamera)),r.setRenderTarget(a,s,n),e.frustumCulled=i,e.material=t,this.smoothShadow&&this._applySmoothFilter(this._target,h)}return h.texture.colorSpace=f,this._viewer.renderManager.releaseTempTarget(h),e.layers.disable(this._lightLayer),c.layers.mask=u,o.modelObject.traverse(e=>{e.isLight&&e!==this._light.lightObject&&(e.layers=e.userData.__gp_layers,delete e.userData.__gp_layers)}),i.type=a,i.needsUpdate=s,i.autoUpdate=n,e.castShadow=!0,(this._frameNumber<3||this._frameNumber>Math.min(100,this.maxFrameNumber)&&this._frameNumber%4==0)&&(this._updateMaterial(),e.material.setDirty()),!0}_updateMaterial(e=!1){this._attachedMesh&&(e?(this._attachedMesh.material.alphaMap===this._target?.texture&&(this._attachedMesh.material.alphaMap=null),this._attachedMesh.material.aoMap===this._target?.texture&&(this._attachedMesh.material.aoMap=null),this._attachedMesh.material.map===this._target?.texture&&(this._attachedMesh.material.map=null)):this._target&&("alphaMap"===this.groundMapMode&&(this._attachedMesh.material.alphaMap=this._target.texture),"aoMap"===this.groundMapMode&&(this._attachedMesh.material.aoMap=this._target.texture),"map"===this.groundMapMode&&(this._attachedMesh.material.map=this._target.texture)),this._attachedMesh.material&&(this._attachedMesh.material.userData.ALPHA_I_RGBA_PACKING=!e&&"alphaMap"===this.groundMapMode,this._attachedMesh.material.alphaTest=e||"alphaMap"!==this.groundMapMode?0:.01,this._attachedMesh.material.needsUpdate=!0))}_applySmoothFilter(e,t){this._shadowBlurMat.uniforms.colorTexture.value=e.texture,this._shadowBlurMat.uniforms.direction.value.set(1,0),this._shadowBlurMat.uniforms.size.value.set(e.width,e.height),this._viewer.renderManager.blit(t,{material:this._shadowBlurMat}),this._shadowBlurMat.uniforms.colorTexture.value=t.texture,this._shadowBlurMat.uniforms.direction.value.set(0,1),this._shadowBlurMat.uniforms.size.value.set(t.width,t.height),this._viewer.renderManager.blit(e,{material:this._shadowBlurMat})}};qt([f("randomizedLight")],Jt.prototype,"_light"),qt([N(Jt.prototype.reset),f()],Jt.prototype,"maxFrameNumber"),qt([N(Jt.prototype.reset),f()],Jt.prototype,"smoothShadow"),qt([f(),N(Jt.prototype.reset)],Jt.prototype,"shadowMapType"),qt([N(Jt.prototype._groundMapModeChanged),f()],Jt.prototype,"groundMapMode"),qt([f(),N(Jt.prototype._alphaVignetteChanged)],Jt.prototype,"alphaVignette"),qt([f(),N(Jt.prototype._alphaVignetteChanged)],Jt.prototype,"alphaVignetteAxis"),qt([f()],Jt.prototype,"maxBakeCount");let $t=Jt;var Qt=Object.defineProperty,er=(e,t,r,i)=>{for(var a,s=void 0,n=e.length-1;n>=0;n--)(a=e[n])&&(s=a(t,r,s)||s);return s&&Qt(t,r,s),s};const tr=((t=class extends q{constructor(){super(),this.bakedShadows=!0,this.groundReflection=!1,this.physicalReflections=!1,this.autoFrustumSize=!0,this.autoBakeShadows=!0,this.autoResetShadows=()=>{this.autoBakeShadows&&this._shadowBaker?.reset()},this._onSceneUpdate=this._onSceneUpdate.bind(this);const e=n(this),t=e.find(e=>"function"==typeof e);this.uiConfig={label:"Ground",type:"folder",children:[...e.filter(e=>e!==t),...this._extraUiConfig(),t]}}get shadowBaker(){return this._shadowBaker}_refresh3(){this.refresh()}bakeShadows(){this._shadowBaker?.reset()}_createMesh(e){if(e)throw new Error("AdvancedGroundPlugin - mesh should not be provided");const t=new Bt(this._geometry,()=>this._viewer?.renderManager.createTarget({type:_,format:G,colorSpace:ve,size:{width:1024,height:1024},generateMipmaps:!0,depthBuffer:!0,minFilter:xe,magFilter:ye}),0,this._createMaterial()),r=t.onBeforeRender;return t.onBeforeRender=(...e)=>{let i=this._viewer?.getPluginByType("SSReflectionPlugin");i&&i.isDisabled()&&(i=void 0),i&&i.disable(t.uuid,!1),r(...e),i&&i.enable(t.uuid,!1)},t}onAdded(e){super.onAdded(e)}_postFrame(){super._postFrame(),this._viewer&&this.enabled&&this._shadowBaker&&this.bakedShadows&&this._shadowBaker.autoUpdateShadow()}_preRender(){super._preRender(),this._viewer&&(this._mesh.reflectionTargetNeedsUpdate=this._viewer.renderManager.frameCount<1)}onRemove(e){return super.onRemove(e)}_removeMaterial(){if(this._material){if(this._shadowBaker&&this._material.groundMatExtension&&(this._material.unregisterMaterialExtensions?.([this._shadowBaker.materialExtension]),delete this._material.groundMatExtension),this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e||this._viewer?.console.warn("AdavancedGroundPlugin: unable to find the extension to unregister"),this._material.unregisterMaterialExtensions?.([e]),delete this._material.reflectorMatExtension}super._removeMaterial()}}_onSceneUpdate(e){super._onSceneUpdate(e),!1!==e.geometryChanged&&this.autoResetShadows()}refresh(){if(this._viewer){if(!this.isDisabled()){this.bakedShadows&&!this._shadowBaker?(this._shadowBaker=new $t(this._viewer),this._shadowBaker.attachedMesh=this._mesh):!this.bakedShadows&&this._shadowBaker&&(this._shadowBaker.reset(),this._shadowBaker.cleanupMaterial());const e=this._mesh;e.isReflector2&&(e.enabled=this.groundReflection,e.reflectorModePhysical=this.physicalReflections)}super.refresh()}}_refreshTransform(){if(!super._refreshTransform())return!1;if(this.autoFrustumSize){const e=this.shadowBaker;if(e){const t=this.size/2;t!==e.light.shadowParams.frustumSize&&(e.light.shadowParams.frustumSize=t,e.light.updateShadowParams(),e.reset())}}return!0}fromJSON(e,t){return super.fromJSON(e,t)?(void 0===e.autoFrustumSize&&(this.autoFrustumSize=!1),this):null}_refreshMaterial(){if(!this._viewer)return!1;if(super._refreshMaterial(),this._material){if(this.groundReflection&&this._mesh.isReflector2&&!this._material.reflectorMatExtension){const e=this._mesh.materialExtension;e.updaters=[this._viewer.scene,this._viewer.renderManager],this._material.registerMaterialExtensions?.([e]),this._material.reflectorMatExtension=!0}this.bakedShadows&&this._shadowBaker&&!this._material.groundMatExtension&&(this._material.registerMaterialExtensions?.([this._shadowBaker.materialExtension]),this._material.groundMatExtension=!0),this._material.userData.ssreflDisabled=this.groundReflection,this._material.userData.ssreflNonPhysical=!this.physicalReflections,this._material.userData.ssaoDisabled=!0,this._material.userData.sscsDisabled=!0,this._viewer.setDirty(this)}}_extraUiConfig(){return[{label:"Shadow Frames",type:"input",hidden:()=>!this._shadowBaker,stepSize:1,bounds:[1,1e3],property:()=>[this._shadowBaker,"maxFrameNumber"]},{label:"Alpha Vignette",type:"checkbox",hidden:()=>!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignette"],limitedUi:!0,onChange:()=>this.uiConfig?.uiRefresh?.(!0,"postFrame")},{label:"Alpha Vignette Axis",type:"dropdown",hidden:()=>!this._shadowBaker?.alphaVignette||!this._material||(this._material.transmission||0)<1e-4&&!this._material.transparent,property:()=>[this._shadowBaker,"alphaVignetteAxis"],children:["x","y","xy"].map(e=>({label:e,value:e})),limitedUi:!0},{label:"Shadow type",type:"dropdown",hidden:()=>!this._shadowBaker,property:()=>[this._shadowBaker,"groundMapMode"],children:[{label:"aoMap"},{label:"map"},{label:"alphaMap"}],limitedUi:!0},{label:"Smooth Shadow",type:"checkbox",property:()=>[this._shadowBaker,"smoothShadow"]},{label:"Baked shadow type",type:"dropdown",children:[["Basic",me],["PCF",Se],["PCFSoft",be],["VSM",we]].map(e=>({label:e[0].toString(),value:e[1]})),property:()=>[this._shadowBaker,"shadowMapType"]},{type:"folder",label:"Randomized Light",hidden:()=>!this._shadowBaker,limitedUi:!0,children:[{type:"color",label:"Color",property:()=>[this._shadowBaker?.light,"color"]},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"focus"],onChange:this.autoResetShadows},{type:"slider",bounds:[0,1],property:()=>[this._shadowBaker?.light?.randomParams,"spread"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,60],property:()=>[this._shadowBaker?.light?.randomParams,"distanceScale"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"direction"],onChange:this.autoResetShadows,limitedUi:!0},{type:"vec3",bounds:[-1,1],property:()=>[this._shadowBaker?.light?.randomParams,"normalDirection"],onChange:this.autoResetShadows,limitedUi:!0},{type:"slider",bounds:[.01,10],property:()=>[this._shadowBaker?.light?.shadowParams,"radius"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"input",property:()=>[this._shadowBaker?.light?.shadowParams,"frustumSize"],hidden:()=>this.autoFrustumSize,onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]},{type:"slider",bounds:[-.1,.1],property:()=>[this._shadowBaker?.light?.shadowParams,"bias"],onChange:[this._shadowBaker?.light?.updateShadowParams,this.autoResetShadows]}]}]}}).PluginType="AdvancedGroundPlugin",t);er([N(tr.prototype._refresh3),o("Baked Shadows"),f()],tr.prototype,"bakedShadows"),er([N(tr.prototype._refresh3),o("Planar Reflections"),f()],tr.prototype,"groundReflection"),er([N(tr.prototype._refresh3),o("Physical Reflections"),f()],tr.prototype,"physicalReflections"),er([N(tr.prototype._refresh3),o("Auto Shadow Frustum Size"),f()],tr.prototype,"autoFrustumSize"),er([f("shadowBaker")],tr.prototype,"_shadowBaker"),er([W({key:"groundReflection"})],tr.prototype,"planarReflections");let rr=tr;var ir=Object.defineProperty,ar=Object.getOwnPropertyDescriptor,sr=(e,t,r,i)=>{for(var a,s=i>1?void 0:i?ar(t,r):t,n=e.length-1;n>=0;n--)(a=e[n])&&(s=(i?a(t,r,s):a(s))||s);return i&&s&&ir(t,r,s),s};let nr=class extends Y{constructor(){super(...arguments),this.enabled=!0,this.dependencies=[],this.axis="y",this.invertAxis=!1,this.analog=!0,this.hourOffset=0,this.minuteOffset=0,this.secondOffset=0,this.hour=".*hour.*",this.minute=".*minute.*",this.second=".*second.*",this.regex=!0,this.hands=[],this._lastEnabled=!0,this._preFrame=()=>{if(!this.enabled){if(this._lastEnabled){if(this._lastEnabled=!1,!this.hands.length)return;for(const e of this.hands)e.object.rotation.fromArray(e.object.userData.initRotation),e.object.updateMatrixWorld();this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}return}if(this._lastEnabled=!0,!this.hands.length)return;const e=this._viewer?.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta();if(0===e)return;const t=/* @__PURE__ */new Date,r=this.invertAxis?-1:1,i=r*(t.getSeconds()+(this.analog?t.getMilliseconds()/1e3:0)-this.secondOffset)*(2*Math.PI)/60,a=r*(t.getMinutes()-this.minuteOffset)*(2*Math.PI)/60+i/60,s=r*(t.getHours()-this.hourOffset)*(2*Math.PI)/12+a/12;if(this.hands.find(e=>"second"===e.type&&Math.abs(i-e.object.rotation[this.axis])>.001)){for(const e of this.hands)"second"===e.type&&(e.object.rotation[this.axis]=i),"minute"===e.type&&(e.object.rotation[this.axis]=a),"hour"===e.type&&(e.object.rotation[this.axis]=s);this._viewer?.renderManager.resetShadows(),this._viewer?.setDirty()}},this._addSceneObject=async e=>{e.object&&this.refresh()}}onAdded(e){super.onAdded(e),e.scene.addEventListener("addSceneObject",this._addSceneObject),e.addEventListener("preFrame",this._preFrame)}onRemove(e){e.scene.removeEventListener("addSceneObject",this._addSceneObject),e.removeEventListener("preFrame",this._preFrame),super.onRemove(e)}refresh(){this.hands=[],this._viewer?.scene.modelRoot.traverse(e=>{let t=!1;e.traverseAncestors(e=>{t||this.hands.find(t=>t.object===e)&&(t=!0)}),t||(e.name.match(this.regex?new RegExp(this.hour):this.hour)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"hour",object:e})),e.name.match(this.regex?new RegExp(this.minute):this.minute)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"minute",object:e})),e.name.match(this.regex?new RegExp(this.second):this.second)&&(e.userData.initRotation||(e.userData.initRotation=e.rotation.toArray()),this.hands.push({type:"second",object:e})))})}};nr.PluginType="WatchHandsPlugin",sr([o(),f()],nr.prototype,"enabled",2),sr([Te(void 0,["x","y","z"].map(e=>({label:e}))),f()],nr.prototype,"axis",2),sr([o(),f()],nr.prototype,"invertAxis",2),sr([o(),f()],nr.prototype,"analog",2),sr([B(void 0,[0,12],.001),f()],nr.prototype,"hourOffset",2),sr([B(void 0,[0,60],.001),f()],nr.prototype,"minuteOffset",2),sr([B(void 0,[0,60],.001),f()],nr.prototype,"secondOffset",2),sr([De(),f()],nr.prototype,"hour",2),sr([De(),f()],nr.prototype,"minute",2),sr([De(),f()],nr.prototype,"second",2),sr([o(),N("refresh"),f()],nr.prototype,"regex",2),sr([Pe()],nr.prototype,"refresh",1),nr=sr([E("Watch Hands Time")],nr);const or=[Le,ke,He,ct,at,Ze,ft,bt,Et,rr,nr];export{rr as AdvancedGroundPlugin,Et as AnisotropyPlugin,He as BloomPlugin,We as BloomPluginPass,Ze as DepthOfFieldPlugin,$e as DepthOfFieldPluginPass,ft as OutlinePlugin,mt as OutlineRenderPass,at as SSContactShadowsPlugin,bt as SSGIPlugin,wt as SSGIPluginPass,ct as SSReflectionPlugin,dt as SSReflectionPluginPass,Ie as SSVelocityMaterial,Le as TemporalAAPlugin,Be as TemporalAAPluginPass,ke as VelocityBufferPlugin,nr as WatchHandsPlugin,Rt as anisotropyGLTFExtension,or as webgiPlugins};
106
106
  //# sourceMappingURL=index.mjs.map