@threepipe/webgi-plugins 0.5.10 → 0.5.11

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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("threepipe")):"function"==typeof define&&define.amd?define(["exports","threepipe"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@threepipe/webgi-plugins"]={},e.threepipe)}(this,(function(e,t){"use strict";
2
2
  /**
3
3
  * @license
4
- * @threepipe/webgi-plugins v0.5.10
4
+ * @threepipe/webgi-plugins v0.5.11
5
5
  * Copyright 2022-2025 repalash <palash@shaders.app> (https://repalash.com)
6
6
  * SEE LICENSE IN LICENSE
7
7
  */var i,r;const a={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 n(){return a.__inited||(a.__inited=!0,Object.assign(t.RenderManager.ShaderChunk,a)),a}var s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?o(t,i):t,l=e.length-1;l>=0;l--)(a=e[l])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&s(t,i,n),n};const c=class extends t.PipelinePassPlugin{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=[t.GBufferPlugin,t.ProgressivePlugin],this.uiConfig={type:"folder",label:"TemporalAA Plugin",onChange:this.setDirty.bind(this),children:[...t.generateUiConfig(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 d(this.passId,(()=>this._viewer?.getPlugin(t.ProgressivePlugin)?.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,i,r){if(!super._beforeRender(e,i,r))return!1;const a=this.pass,n=this._viewer;if(!a||!n)return!1;const s=r.frameCount;if(a.taaEnabled=s<=1&&e.renderCamera===e.mainCamera,!a.taaEnabled)return!1;const o=i;return!!o&&(o.updateMatrixWorld(!0),o.updateShaderProperties(a.material),a.updateCameraProperties(o),a.target=n.getPlugin(t.ProgressivePlugin).target,!0)}};c.PluginType="TAA",c.OldPluginType="TemporalAAPlugin";let u=c;l([t.uiToggle("Stable Noise (Total frame count)")],u.prototype,"stableNoise",1),l([t.uiConfig(void 0,{unwrapContents:!0})],u.prototype,"_pass",2);class d extends t.ExtendedShaderPass{constructor(e,i,r=!1){super({vertexShader:t.CopyShader.vertexShader,fragmentShader:n().temporalAA,uniforms:{currentRT:{value:null},previousRT:{value:null},previousRTSize:{value:new t.Vector2},cameraNearFar:{value:new t.Vector2},lastProjectionViewMatrix:{value:new t.Matrix4},currentProjectionViewMatrix:{value:new t.Matrix4},projection:{value:new t.Matrix4},inverseViewMatrix:{value:new t.Matrix4},jitterSample:{value:new t.Vector2},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 t.Vector2(.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()},...t.generateUiConfig(this)?.filter((e=>e&&"Enabled"!==e.label))||[]]},this.passId=e,this.onSizeUpdate=this.onSizeUpdate.bind(this),this.target=i,this.clear=!1,this.needsSwap=!0}render(e,i,r,a,n){this.taaEnabled&&this.enabled?(this.needsSwap=!0,this.uniforms.previousRT.value=t.getOrCall(this.target)?.texture??null,super.render(e,i,r,a,n),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()}}l([t.serialize(),t.uniform(),t.uiVector("Feedback",void 0,1e-4)],d.prototype,"feedBack",2),l([t.uiToggle(),t.matDefineBool("DEBUG_VELOCITY",void 0,!1,void 0,!0)],d.prototype,"debugVelocity",2);var h=Object.defineProperty,p=Object.getOwnPropertyDescriptor,f=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?p(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&h(t,i,n),n};e.VelocityBufferPlugin=class extends t.PipelinePassPlugin{constructor(e=t.UnsignedByteType,i=!0,r=!0){super(),this.passId="velocityBuffer",this.material=new g,this.unpackExtension={shaderExtender:e=>{this.isDisabled()||(e.fragmentShader=t.shaderReplaceString(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=i,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:t.LinearSRGBColorSpace})),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 i=this._viewer,r=new class extends t.GBufferRenderPass{constructor(){super(...arguments),this._firstCall=!0}render(e,t,r,a,n){if(i.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(e,t,r,a,n),s.uniforms.lastProjectionViewMatrix.value.copy(s.uniforms.currentProjectionViewMatrix.value)}}(this.passId,this.target,this.material,new t.Color(.5,.5,.5),1),a=r.preprocessMaterial;return r.preprocessMaterial=t=>a(t,t.userData[e.VelocityBufferPlugin.PluginType]?.disabled),r.before=["render"],r.after=[],r.required=["render"],r}onAdded(e){super.onAdded(e),e.forPlugin(u,(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,i){if(!super._beforeRender(e,t,i))return!1;const r=this.pass;return!!r&&(!(i.frameCount>0)&&(r.scene=e,r.camera=t,t.updateShaderProperties(r.overrideMaterial),!0))}},e.VelocityBufferPlugin.PluginType="VelocityBuffer",e.VelocityBufferPlugin.OldPluginType="VelocityBufferPlugin",f([t.uiImage("Velocity Buffer",{readOnly:!0})],e.VelocityBufferPlugin.prototype,"texture",2),e.VelocityBufferPlugin=f([t.uiFolderContainer("Velocity Buffer Plugin (for TAA)")],e.VelocityBufferPlugin);class g extends t.ShaderMaterial{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 t.Vector2(.1,1e3)},alphaMap:{value:null},alphaTest:{value:null},alphaMapTransform:{value:new t.Matrix3},currentProjectionViewMatrix:{value:new t.Matrix4},lastProjectionViewMatrix:{value:new t.Matrix4}},blending:t.NoBlending}),this.extraUniformsToUpload={modelMatrixPrevious:{value:(new t.Matrix4).identity()}},this._previousWorldMatrices={}}onBeforeRender(e,i,r,a,n){const s=this._previousWorldMatrices[n.uuid];this.extraUniformsToUpload.modelMatrixPrevious.value.copy(s??n.matrixWorld),s?s.copy(n.matrixWorld):this._previousWorldMatrices[n.uuid]=n.matrixWorld.clone();let o=n.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.DoubleSide}}var m=Object.defineProperty,v=Object.getOwnPropertyDescriptor,_=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?v(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&m(t,i,n),n};const S=(i=class extends t.PipelinePassPlugin{constructor(){super(...arguments),this.passId="bloom",this.materialExtension=t.uiConfigMaterialExtension(this._getUiConfig.bind(this),i.PluginType),this.dependencies=[t.GBufferPlugin],this._onPluginAdd=e=>{if(e.plugin?.constructor?.PluginType!==t.GBufferPlugin.PluginType)return;const i=e.plugin;i.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass?.material.registerMaterialExtensions([i.unpackExtension]),this._viewer?.removeEventListener("addPlugin",this._onPluginAdd)},this.uiConfig={type:"folder",label:"Bloom Plugin",onChange:this.setDirty.bind(this),children:[...t.generateUiConfig(this)||[]]}}_createPass(){return new e.BloomPluginPass(this.passId,Math.min(8,this._viewer?.renderManager.maxHDRIntensity||8))}onAdded(e){super.onAdded(e);const i=e.getPlugin(t.GBufferPlugin);i?(i.registerGBufferUpdater(this.constructor.PluginType,this.updateGBufferFlags.bind(this)),this._pass.material.registerMaterialExtensions([i.unpackExtension])):e.addEventListener("addPlugin",this._onPluginAdd),e.materialManager.registerMaterialExtension(this.materialExtension)}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd);const i=e.getPlugin(t.GBufferPlugin);i?.unregisterGBufferUpdater(this.constructor.PluginType),i&&this._pass?.material.unregisterMaterialExtensions([i.unpackExtension]),e.materialManager.unregisterMaterialExtension(this.materialExtension),super.onRemove(e)}updateGBufferFlags(e,r){if(!r.material||!r.material.userData)return;const a=!1===r.material.userData[i.PluginType]?.enable||r.material.userData.pluginsDisabled?0:1;e.w=t.updateBit(e.w,2,a)}static AddBloomData(e,t,r=!0){const a=e?.userData;if(!a)return null;a[i.PluginType]||(a[i.PluginType]={});const n=a[i.PluginType];return n.enable=!0,t&&Object.assign(n,t),r&&e.setDirty&&e.setDirty(),n}_getUiConfig(e){const t={type:"folder",label:"Bloom",children:[{type:"checkbox",label:"Enabled",get value(){return e.userData[i.PluginType]?.enable??!0},set value(r){let a=e.userData[i.PluginType];r!==a?.enable&&(a||(a=i.AddBloomData(e,void 0,!1)),a.enable=r,e.setDirty(),t.uiRefresh?.(!0,"postFrame"))},onChange:this.setDirty}]};return t}},i.PluginType="Bloom",i.OldPluginType="BloomPlugin",i);_([t.uiConfig(void 0,{unwrapContents:!0})],S.prototype,"_pass",2);let y=S;e.BloomPluginPass=class extends t.ExtendedShaderPass{constructor(e,i=16){super({vertexShader:t.CopyShader.vertexShader,defines:{PASS_STEP:1,MAX_INTENSITY:Math.min(i,16)},uniforms:{tSource:{value:null},tDiffuse:{value:null},opacity:{value:1},tDiffuseSize:{value:new t.Vector2},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 t.Vector4(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,i,r,a,n){const s=e.renderManager;this.material.defines.PASS_STEP=0,this.clear=!0,this.needsSwap=!1;const o=r;if(!o)return void console.warn("BloomPluginPass: No source to read from");this.needsSwap=!0;let l=.5,c=o.width*l,u=o.height*l;const d=[];let h=s.getTempTarget({sizeMultiplier:1,type:t.HalfFloatType});d.push(h);let p=o;this.material.needsUpdate=!0,this.material.uniforms.weight.value=this._weights[0],super.render(e,h,p,a,n),p=h;const f=this._currentIterations;let g=1;const m=Math.max(2,this.bloomIterations);for(;g<m&&(c/=2,u/=2,l/=2,!(u<2||c<2));g++){h=s.getTempTarget({sizeMultiplier:l,type:t.HalfFloatType}),d.push(h),this.material.defines.PASS_STEP=1;let i=this._weights[g];i=0!==this._weights[g-1]?this._weights[g]/this._weights[g-1]:this._weights[g],this.material.uniforms.weight.value=i,this.material.needsUpdate=!0,super.render(e,h,p,a,n),p=h,this._currentIterations=g+1}f!==this._currentIterations&&this._updateWeights(!1),this.clear=!1;const v=e.autoClear;for(e.autoClear=!1,g-=2;g>=0;g--)h=d[g],d[g]=void 0,this.material.defines.PASS_STEP=2,this.material.transparent=!0,this.material.blending=t.AdditiveBlending,this.material.needsUpdate=!0,e.autoClear=!1,super.render(e,h,p,a,n),this.material.blending=t.NoBlending,s.releaseTempTarget(p),p=h;this.clear=!0,e.autoClear=v,e.autoClear=!0,this.bloomDebug?(this.material.defines.PASS_STEP=4,this.material.needsUpdate=!0,super.render(e,i,p,a,n)):(this.uniforms.tSource.value=o.texture,this.material.defines.PASS_STEP=3,this.material.needsUpdate=!0,super.render(e,i,p,a,n),this.uniforms.tSource.value=null),s.releaseTempTarget(p)}_updateWeights(e=!0){if(!this._weights)return;const t=Math.max(Math.min(this.radius,1),0),i=Math.max(2,this._currentIterations||this.bloomIterations),r=1/(i-1);for(let a=0;a<i;a++){let e=a*r+.1,i=1.2-e;e=Math.pow(e,this.power),i=Math.pow(i,this.power),this._weights[a]=i*(1-t)+e*t}!1!==e&&this.setDirty()}},_([t.uniform()],e.BloomPluginPass.prototype,"prefilter",2),_([t.uiSlider("Threshold",[0,2]),t.onChange(e.BloomPluginPass.prototype._thresholdsUpdated),t.serialize()],e.BloomPluginPass.prototype,"threshold",2),_([t.uiSlider("Soft Threshold",[0,1]),t.onChange(e.BloomPluginPass.prototype._thresholdsUpdated),t.serialize()],e.BloomPluginPass.prototype,"softThreshold",2),_([t.uiSlider("Intensity",[0,3]),t.serialize(),t.uniform()],e.BloomPluginPass.prototype,"intensity",2),_([t.uiToggle("Background Bloom"),t.serialize(),t.matDefineBool("BACKGROUND_BLOOM")],e.BloomPluginPass.prototype,"backgroundBloom",2),_([t.uiSlider("Iterations",[2,7],1),t.onChange2(e.BloomPluginPass.prototype._updateWeights),t.serialize()],e.BloomPluginPass.prototype,"bloomIterations",2),_([t.uiSlider("Radius",[0,1],.01),t.onChange2(e.BloomPluginPass.prototype._updateWeights),t.serialize()],e.BloomPluginPass.prototype,"radius",2),_([t.uiSlider("Power",[.2,10],.01),t.onChange2(e.BloomPluginPass.prototype._updateWeights),t.serialize()],e.BloomPluginPass.prototype,"power",2),_([t.uiToggle("Debug")],e.BloomPluginPass.prototype,"bloomDebug",2),e.BloomPluginPass=_([t.uiFolderContainer("Bloom Pass")],e.BloomPluginPass);var x=Object.defineProperty,P=Object.getOwnPropertyDescriptor,b=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?P(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&x(t,i,n),n};const w=class extends t.PipelinePassPlugin{constructor(e=!0,i=!1){super(),this.passId="depthOfField",this.enableEdit=!1,this._focalPointHit=new t.Vector3(0,0,0),this.crossFadeTime=200,this._focalPointHitTime=0,this.dependencies=[t.GBufferPlugin],this._onPluginAdd=e=>{const i=e.plugin;if(i){if(i.constructor?.PluginType===t.GBufferPlugin.PluginType){const e=i;this._pass?.material.registerMaterialExtensions([e.unpackExtension]),this._pass?.computeCocMaterial.registerMaterialExtensions([e.unpackExtension]),this._pass?.expandCocMaterial.registerMaterialExtensions([e.unpackExtension])}if(i.constructor?.PluginType===t.PickingPlugin.PluginType){i.addEventListener("hitObject",this._onObjectHit)}}},this._onPluginRemove=e=>{const i=e.plugin;if(i){if(i.constructor?.PluginType===t.GBufferPlugin.PluginType){const t=e.plugin;this._pass?.material.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.computeCocMaterial.unregisterMaterialExtensions([t.unpackExtension]),this._pass?.expandCocMaterial.unregisterMaterialExtensions([t.unpackExtension])}if(i.constructor?.PluginType===t.PickingPlugin.PluginType){e.plugin.removeEventListener("hitObject",this._onObjectHit)}}},this.uiConfig={type:"folder",label:"DepthOfField",onChange:this.setDirty.bind(this),children:[...t.generateUiConfig(this)||[],()=>this._pass?.uiConfig]},this._tempVec=new t.Vector3,this.enabled=e,this.enableEdit=i,this._onObjectHit=this._onObjectHit.bind(this),this.setDirty=this.setDirty.bind(this)}get _frameFadeTime(){return 2.5*this.crossFadeTime}setFocalPoint(e,i=!0,r=!1){this._focalPointHit.copy(e),i&&this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime),r&&(this._focalPointHitTime=t.now()),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(t.FrameFadePlugin)?.startTransition(this._frameFadeTime),this.setDirty())}_createPass(){return new e.DepthOfFieldPluginPass(this.passId)}onAdded(e){super.onAdded(e),e.addEventListener("addPlugin",this._onPluginAdd),e.addEventListener("removePlugin",this._onPluginRemove),this._onPluginAdd({plugin:e.getPlugin(t.GBufferPlugin)}),this._onPluginAdd({plugin:e.getPlugin(t.PickingPlugin)})}onRemove(e){e.removeEventListener("addPlugin",this._onPluginAdd),e.removeEventListener("removePlugin",this._onPluginRemove),this._onPluginRemove({plugin:e.getPlugin(t.GBufferPlugin)}),this._onPluginRemove({plugin:e.getPlugin(t.PickingPlugin)}),super.onRemove(e)}_beforeRender(e,i,r){if(!super._beforeRender(e,i,r))return!1;const a=this.pass;if(!a)return!1;a.dofBlurMaterial.uniforms.frameCount&&r?.updateShaderProperties(a.dofBlurMaterial);const n=i;if(!n)return!1;n.updateMatrixWorld(!0),n.updateShaderProperties(a.material),n.getWorldPosition(this._tempVec),this._tempVec.subVectors(this._focalPointHit,this._tempVec),a.focalDepthRange.x=this._tempVec.length(),a.focalDepthRange.x*=n.getWorldDirection(new t.Vector3).dot(this._tempVec.normalize());let s=(t.now()-this._focalPointHitTime)/this.crossFadeTime;if(s=1-Math.min(1,Math.max(0,s)),Math.abs(s-a.crossAlpha)>.01&&(a.crossAlpha=s,this.setDirty()),s>0){const e=this._tempVec.copy(this._focalPointHit).project(n).addScalar(1).divideScalar(2);a.crossCenter.set(e.x,e.y),a.computeCocMaterial.uniformsNeedUpdate=!0,a.expandCocMaterial.uniformsNeedUpdate=!0}return!0}};w.PluginType="DepthOfField",w.OldPluginType="DepthOfFieldPlugin";let T=w;b([t.serialize(),t.uiToggle()],T.prototype,"enableEdit",2),b([t.serialize("focalPoint")],T.prototype,"_focalPointHit",2),b([t.serialize()],T.prototype,"crossFadeTime",2);const D=new t.ExtendedShaderMaterial({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new t.Vector2},direction:{value:new t.Vector2},frameCount:{value:0},blurRadius:{value:16}},vertexShader:t.shaderUtils.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"]);e.DepthOfFieldPluginPass=class extends t.ExtendedShaderPass{constructor(e){super({uniforms:{colorTexture:{value:null},blurTexture:{value:null},cocTexture:{value:null},cocTextureSize:{value:new t.Vector2},cameraNearFar:{value:new t.Vector2}},vertexShader:t.shaderUtils.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=D,this.nearFarBlurScale=new t.Vector2(.25,.25),this.focalDepthRange=new t.Vector2(.5,1.5),this.crossCenter=new t.Vector2(.5,.5),this.crossRadius=.04,this.crossAlpha=1,this.crossColor=new t.Color(16750848),this.passId=e,this.computeCocMaterial=new t.ExtendedShaderMaterial({uniforms:{colorTexture:{value:null},cameraNearFar:this.uniforms.cameraNearFar,nearFarBlurScale:this.uniforms.nearFarBlurScale,focalDepthRange:this.uniforms.focalDepthRange},vertexShader:t.shaderUtils.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 t.ExtendedShaderMaterial({uniforms:{colorTexture:{value:null},colorTextureSize:{value:new t.Vector2},direction:{value:new t.Vector2},nearFarBlurScale:this.uniforms.nearFarBlurScale},vertexShader:t.shaderUtils.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,i,r,a,n){if(!this.enabled)return;if(!r)return void console.error("DepthOfFieldPluginPass: No readBuffer");const s=e.renderManager,o={minFilter:t.NearestFilter,magFilter:t.NearestFilter,type:t.HalfFloatType,colorSpace:t.LinearSRGBColorSpace,sizeMultiplier:.5,format:t.RGBAFormat,depthBuffer:!1,generateMipmaps:!1},l=s.getTempTarget(o),c=s.getTempTarget(o);if(this.computeCocMaterial.uniforms.colorTexture.value=r.texture,s.blit(l,{material:this.computeCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=l.texture,this.expandCocMaterial.uniforms.direction.value.set(1,0),s.blit(c,{material:this.expandCocMaterial}),this.expandCocMaterial.uniforms.colorTexture.value=c.texture,this.expandCocMaterial.uniforms.direction.value.set(0,1),s.blit(l,{material:this.expandCocMaterial}),this.dofBlurMaterial.uniforms.frameCount)this.dofBlurMaterial.uniforms.colorTexture.value=l.texture,s.blit(c,{material:this.dofBlurMaterial});else{const e=s.getTempTarget(o);this.dofBlurMaterial.uniforms.cocTexture.value=l.texture,this.dofBlurMaterial.uniforms.colorTexture.value=l.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(c,{material:this.dofBlurMaterial}),s.releaseTempTarget(e)}this.material.uniforms.blurTexture.value=c.texture,this.material.uniforms.cocTexture.value=l.texture,super.render(e,i,r,a,n),s.releaseTempTarget(l),s.releaseTempTarget(c)}},b([t.bindToValue({obj:"focalDepthRange",key:"y"}),t.uiSlider("Depth Range",[.25,3])],e.DepthOfFieldPluginPass.prototype,"depthRange",2),b([t.bindToValue({obj:"nearFarBlurScale",key:"x"}),t.uiSlider("Near Blur Scale",[0,1])],e.DepthOfFieldPluginPass.prototype,"nearBlurScale",2),b([t.bindToValue({obj:"nearFarBlurScale",key:"y"}),t.uiSlider("Far Blur Scale",[0,1])],e.DepthOfFieldPluginPass.prototype,"farBlurScale",2),b([t.serialize(),t.uniform()],e.DepthOfFieldPluginPass.prototype,"nearFarBlurScale",2),b([t.serialize(),t.uniform()],e.DepthOfFieldPluginPass.prototype,"focalDepthRange",2),b([t.uniform()],e.DepthOfFieldPluginPass.prototype,"crossCenter",2),b([t.uniform()],e.DepthOfFieldPluginPass.prototype,"crossRadius",2),b([t.uniform()],e.DepthOfFieldPluginPass.prototype,"crossAlpha",2),b([t.uniform()],e.DepthOfFieldPluginPass.prototype,"crossColor",2),e.DepthOfFieldPluginPass=b([t.uiFolderContainer("DepthOfField Pass")],e.DepthOfFieldPluginPass);const C="#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 M=Object.defineProperty,R=Object.getOwnPropertyDescriptor,E=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?R(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&M(t,i,n),n};const B=t.RenderManager.ShaderChunk;e.SSContactShadowsPlugin=class extends t.AViewerPluginSync{constructor(i=!0){super(),this.enabled=!0,this._uniforms={sscsRadius:{value:.03},sscsIntensity:{value:1},sscsTolerance:{value:1.5},frameCount:{value:0},projection:{value:new t.Matrix4},cameraPositionWorld:{value:new t.Vector3},cameraNearFar:{value:new t.Vector2(.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=[t.GBufferPlugin],this.materialExtension={uuid:e.SSContactShadowsPlugin.PluginType,priority:5,shaderExtender:(e,i,r)=>{if(!e.defines.SSCS_ENABLED)return;const a=t.glsl`
@@ -40,7 +40,7 @@
40
40
  #endif
41
41
  `,computeCacheKey:()=>(this.enabled?"1":"0")+t.getOrCall(this.target)?.texture?.colorSpace+Object.values(this.material.defines).map((e=>e+"")).join(","),uuid:e.SSReflectionPlugin.PluginType,...t.uiConfigMaterialExtension(this._getUiConfig.bind(this),e.SSReflectionPlugin.PluginType),isCompatible:e=>e.isPhysicalMaterial},this.passId=i,this.needsSwap=!1,this.clear=!0,a&&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,i,r,a,n){if(!this.enabled)return;if(this.inlineShaderRayTrace)return void(this.needsSwap=!1);const s=t.getOrCall(this.target);s?(this.material.defines.HAS_GBUFFER||console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl"),e.renderManager.blit(i,{source:s.texture}),this.uniforms.tLastThis.value=i.texture,super.render(e,s,r,a,n),this.needsSwap=!1):console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false")}beforeRender(e,t,i){this.enabled&&this.updateShaderProperties([e,t,i])}_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)))}},L([t.uiSlider("Intensity",[0,4]),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"intensity",2),L([t.uiVector("Boost"),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"boost",2),L([t.uiSlider("Object Radius",[.01,2]),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"objectRadius",2),L([t.uiToggle("Auto radius"),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"autoRadius",2),L([t.uiSlider("Power",[0,3]),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"power",2),L([t.uiSlider("Tolerance",[.1,5]),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"tolerance",2),L([t.uiSlider("Roughness Factor",[.1,1.25]),t.serialize(),t.uniform({propKey:"ssrRoughnessFactor"})],e.SSReflectionPluginPass.prototype,"roughnessFactor",2),L([t.uiSlider("Step count",[1,32],1,{tags:["performance"]}),t.serialize(),t.matDefine("SSR_STEP_COUNT",void 0,void 0,e.SSReflectionPluginPass.prototype.setDirty)],e.SSReflectionPluginPass.prototype,"stepCount",2),L([t.uiSlider("Ray count",[1,8],1,{tags:["performance"]}),t.serialize(),t.matDefine("SSR_RAY_COUNT",void 0,void 0,e.SSReflectionPluginPass.prototype.setDirty)],e.SSReflectionPluginPass.prototype,"rayCount",2),L([t.uiToggle("Ray Blend MAX"),t.serialize(),t.matDefineBool("SSR_RAY_BLEND_MAX",void 0,void 0,e.SSReflectionPluginPass.prototype.setDirty,!0)],e.SSReflectionPluginPass.prototype,"rayBlendMax",2),L([t.uiSlider("Low Quality Frames",[0,4],1),t.serialize(),t.matDefine("SSR_LOW_QUALITY_FRAMES",void 0,void 0,e.SSReflectionPluginPass.prototype.setDirty)],e.SSReflectionPluginPass.prototype,"lowQualityFrames",2),L([t.uiToggle("Ignore front rays"),t.serialize(),t.matDefineBool("SSR_MASK_FRONT_RAYS",void 0,void 0,e.SSReflectionPluginPass.prototype.setDirty)],e.SSReflectionPluginPass.prototype,"maskFrontRays",2),L([t.uiSlider("Mask front rays factor",[-1,1],.01,(e=>({hidden:()=>!e.maskFrontRays}))),t.serialize(),t.uniform()],e.SSReflectionPluginPass.prototype,"maskFrontFactor",2),L([t.uiSlider("Split",[0,1],.01,{tags:["debug"]}),t.serialize(),t.uniform({propKey:"ssrSplitX",onChange:e.SSReflectionPluginPass.prototype.setDirty})],e.SSReflectionPluginPass.prototype,"split",2),e.SSReflectionPluginPass=L([t.uiFolderContainer("SSReflection Pass")],e.SSReflectionPluginPass);var N=Object.defineProperty,F=Object.getOwnPropertyDescriptor,k=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?F(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&N(t,i,n),n};e.OutlinePlugin=class extends t.AScreenPassExtensionPlugin{constructor(e=!0,i=t.UnsignedByteType){super(),this.passId="outline",this.extraUniforms={outlineIntensity:{value:1},outlineThickness:{value:2},highlightTransparency:{value:1},outlineColor:{value:new t.Color(15305317)},enableHighlight:{value:!0},dpr:{value:1},outlineBuffer:{value:null},tDiffuseSize:{value:new t.Vector2(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 t.Color(15305317),this.thickness=2,this.debugOutline=!1,this.highlightSelectedMaterials=!1,this.highlightMaterialSameNames=!1,this.transparency=0,this.parsFragmentSnippet=()=>this.isDisabled()?"":t.glsl`
42
42
  ${"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);}"}
43
- `,this._shaderPatch="diffuseColor = outline(diffuseColor);",this.dependencies=[t.PickingPlugin,t.GBufferPlugin],this._pickingWidgetDisabled=!1,this.material=new t.ShaderMaterial({uniforms:{cameraNearFar:{value:new t.Vector2(.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.DoubleSide}),this._getSelectedObject=()=>{if(!this._viewer)return null;const e=this._viewer.getPlugin(t.PickingPlugin);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],i=new Set;for(const t of e){const e=this._viewer?.assetManager?.materials?.findMaterialsByName(t);e?.forEach((e=>i.add(e)))}return[...i]}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=i}setDirty(){if(super.setDirty(),!this._viewer)return;const e=this._viewer.getPlugin(t.PickingPlugin);let i=!this.isDisabled();if(i){const t=e?.getSelectedObject();"string"==typeof t?.type&&t?.type?.includes("Line")&&(i=!1)}e&&(i&&e.widgetEnabled?(e.widgetEnabled=!1,this._pickingWidgetDisabled=!0):!i&&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 i=e.getPlugin(t.PickingPlugin);i?.addEventListener("selectedObjectChanged",(()=>{!this._animationCallBack&&this&&(i?.getSelectedObject()?this.enableDynamicSelection?(this.transparency=1,this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,400)):this.transparency=this.highlightTransparency:this.transparency=1)})),document.addEventListener("mousemove",(t=>{if(!this)return;if(!this.mouseInOutAnimationEnabled)return;if(!this.enableHighlight)return;const r=i?.getSelectedObject();r&&this.enableDynamicSelection?t.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=r?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 e.OutlineRenderPass(this.passId,this._getSelectedObject,(()=>this.target),this.material)}async _startTransparencyAnimation(e,i,r){return t.animateTarget(this,"transparency",{from:e,to:i,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}},e.OutlinePlugin.PluginType="OutlinePlugin",e.OutlinePlugin.OldPluginType="Outline",k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Enable"),t.serialize()],e.OutlinePlugin.prototype,"enabled",2),k([t.uiToggle("Highlight"),t.uniform({propKey:"enableHighlight"}),t.serialize()],e.OutlinePlugin.prototype,"enableHighlight",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("DynamicSelection"),t.serialize()],e.OutlinePlugin.prototype,"enableDynamicSelection",2),k([t.uiSlider("Intensity",[0,4],.001),t.uniform({propKey:"outlineIntensity"}),t.serialize("outlineIntensity")],e.OutlinePlugin.prototype,"intensity",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiSlider("Transparency",[0,1],.01),t.serialize()],e.OutlinePlugin.prototype,"highlightTransparency",2),k([t.uiColor("Color"),t.uniform({propKey:"outlineColor"}),t.serialize("outlineColor")],e.OutlinePlugin.prototype,"color",2),k([t.uiSlider("Thickness",[0,10],.01),t.uniform({propKey:"outlineThickness"}),t.serialize("outlineThickness")],e.OutlinePlugin.prototype,"thickness",2),k([t.uiToggle("Debug"),t.matDefineBool("DEBUG_OUTLINE",void 0,!0)],e.OutlinePlugin.prototype,"debugOutline",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Highlight Selected Materials")],e.OutlinePlugin.prototype,"highlightSelectedMaterials",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Highlight Materials (same name)")],e.OutlinePlugin.prototype,"highlightMaterialSameNames",2),k([t.uniform({propKey:"highlightTransparency"})],e.OutlinePlugin.prototype,"transparency",2),k([t.uniform({propKey:"outlineBuffer"}),t.uiImage("Outline Buffer",{readOnly:!0})],e.OutlinePlugin.prototype,"texture",2),e.OutlinePlugin=k([t.uiFolderContainer("Outline")],e.OutlinePlugin),e.OutlineRenderPass=class extends t.RenderPass{constructor(e,i,r,a){super(void 0,void 0,a,new t.Color(1,1,1),1),this.passId=e,this._getSelectedObjectOrMaterial=i,this.target=r,this.isOutlineRenderPass=!0,this.enabled=!0,this.before=["render"],this.after=["gbuffer"],this.required=["render","gbuffer"],this.onDirty=[]}render(e,i,r,a,n){if(!this.scene||!this.camera||!this.enabled)return;const s=e.getRenderTarget(),o=e.getActiveCubeFace(),l=e.getActiveMipmapLevel(),c=this._getSelectedObjectOrMaterial();if(c)this._renderSelectedObject(e,c,i||null,a,n);else{e.setRenderTarget(t.getOrCall(this.target)||null);const i=new t.Color;e.getClearColor(i),e.setClearColor(new t.Color(16777215)),e.clear(!0,!0),e.setClearColor(i)}e.setRenderTarget(s,o,l)}_renderSelectedObject(e,i,r,a,n){if(!this.camera||!i)return;const s=(Array.isArray(i)?i:[i]).flatMap((e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e)).flatMap((e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e));for(const t of s)t&&t.traverse((e=>{e.layers.enable(6)}));const o=this.camera.layers.mask;this.camera.layers.set(6);const l=e.userData;l||console.error("threejs is not patched?"),l.transmissionRenderTarget=r,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!0,transmissionRender:!0,mainRenderPass:!1},(()=>super.render(e,r,t.getOrCall(this.target),a,n))),l.transmissionRenderTarget=void 0,s.forEach((e=>e.traverse((e=>{e.layers.disable(6)})))),this.camera.layers.mask=o}dispose(){this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach((e=>e()))}beforeRender(e,t,i){this.scene=e,this.camera=t,t.updateShaderProperties(this.overrideMaterial)}},k([t.uiToggle("Enabled")],e.OutlineRenderPass.prototype,"enabled",2),e.OutlineRenderPass=k([t.uiFolderContainer((e=>e.passId+" Render Pass"))],e.OutlineRenderPass);var z=Object.defineProperty,I=(e,t,i,r)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,i,n)||n);return n&&z(t,i,n),n};class V extends t.ExtendedShaderPass{constructor(e,i="rgba"){super({vertexShader:t.CopyShader.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 t.Vector2(1,0)},tDiffuse:{value:null},tDiffuseSize:{value:new t.Vector2}},defines:{B_SRC_ACCESSOR:i}},"tDiffuse"),this.target=e,this.smoothEnabled=!0,this.edgeSharpness=.1,this.clear=!1,this.needsSwap=!1}render(e,i,r,a,n){if(!this.enabled)return;const s=t.getOrCall(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,i,s,a,n),this.uniforms.bilDirection.value.set(0,1),this.uniforms.tDiffuse.value=i.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,s,i,a,n))}}I([t.serialize(),t.uniform()],V.prototype,"smoothEnabled"),I([t.serialize(),t.uniform()],V.prototype,"edgeSharpness");var G=Object.defineProperty,j=Object.getOwnPropertyDescriptor,H=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?j(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&G(t,i,n),n};e.SSGIPlugin=class extends t.PipelinePassPlugin{constructor(e=t.UnsignedByteType,i=1,r=!0){super(),this.passId="ssrtgi",this.dependencies=[t.GBufferPlugin,t.SSAAPlugin],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=i}_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 e.SSGIPluginPass(this.passId,(()=>this.target))}onAdded(t){super.onAdded(t),(t.getPlugin("Ground")||t.getPlugin("BaseGroundPlugin"))&&console.error("GroundPlugin must be added after SSGIPlugin"),this._gbufferUnpackExtensionChanged(),t.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),t.forPlugin(e.VelocityBufferPlugin,(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(i,r,a){if(!this._viewer)return!1;const n=super._beforeRender(i,r,a);if(n){const t=this._viewer?.getPlugin("SSAOPlugin");t&&!t.isDisabled()&&t.disable(e.SSGIPlugin.PluginType)}if(!n)return n;const s=this._viewer.getPlugin(t.ProgressivePlugin);return this._pass?.updateShaderProperties([s]),n}get rtgiTarget(){return console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead"),this.target}},e.SSGIPlugin.PluginType="SSGIPlugin",e.SSGIPlugin.OldPluginType="SSGI",H([t.uiImage("SSGI Buffer",{readOnly:!0})],e.SSGIPlugin.prototype,"texture",2),H([t.uiConfig(void 0,{unwrapContents:!0})],e.SSGIPlugin.prototype,"_pass",2),e.SSGIPlugin=H([t.uiFolderContainer("SSGI Plugin")],e.SSGIPlugin),e.SSGIPluginPass=class extends t.ExtendedShaderPass{constructor(i,r,a=!0){super({defines:{RTAO_STEP_COUNT:16,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new t.Vector2(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new t.Vector2(.1,1e3)},cameraPositionWorld:{value:new t.Vector3},projection:{value:new t.Matrix4},opacity:{value:1},intensity:{value:0},objectRadius:{value:0},autoRadius:{value:!a},rayCount:{value:.1},bias:{value:.015},falloff:{value:.7},power:{value:1.1},tolerance:{value:0},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new t.Matrix4},lastProjectionViewMatrix:{value:new t.Matrix4},inverseViewMatrix:{value:new t.Matrix4},ssrtaoSplitX:{value:.5}},vertexShader:t.shaderUtils.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${A}\n\n${C}\n\n${n().calculateGI}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=r,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:t.getOrCall(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,i,r)=>{if(!e.defines?.SSRTAO_ENABLED)return;e.fragmentShader=t.shaderReplaceString(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=t.shaderReplaceString(e.fragmentShader,"#include <aomap_fragment>","")},onObjectRender:(e,t,i)=>{let r=!this.enabled||!(this.renderWithCamera||i.renderManager.frameCount>1)||!1===i.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssrtaoDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSRTAO_ENABLED!==r&&(t.defines.SSRTAO_ENABLED=r,t.needsUpdate=!0)},parsFragmentSnippet:e=>t.glsl`
43
+ `,this._shaderPatch="diffuseColor = outline(diffuseColor);",this.dependencies=[t.PickingPlugin,t.GBufferPlugin],this._pickingWidgetDisabled=!1,this.material=new t.ShaderMaterial({uniforms:{cameraNearFar:{value:new t.Vector2(.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.DoubleSide}),this._getSelectedObject=()=>{if(!this._viewer)return null;const e=this._viewer.getPlugin(t.PickingPlugin);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],i=new Set;for(const t of e){const e=this._viewer?.assetManager?.materials?.findMaterialsByName(t);e?.forEach((e=>i.add(e)))}return[...i]}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=i}setDirty(){if(super.setDirty(),!this._viewer)return;const e=this._viewer.getPlugin(t.PickingPlugin);let i=!this.isDisabled();if(i){const t=e?.getSelectedObject();"string"==typeof t?.type&&t?.type?.includes("Line")&&(i=!1)}e&&(i&&e.widgetEnabled?(e.widgetEnabled=!1,this._pickingWidgetDisabled=!0):!i&&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 i=e.getPlugin(t.PickingPlugin);i?.addEventListener("selectedObjectChanged",(()=>{!this._animationCallBack&&this&&(i?.getSelectedObject()?this.enableDynamicSelection?(this.transparency=1,this._animationCallBack=this._startTransparencyAnimation(1,this.highlightTransparency,400)):this.transparency=this.highlightTransparency:this.transparency=1)})),document.addEventListener("mousemove",(t=>{if(!this)return;if(!this.mouseInOutAnimationEnabled)return;if(!this.enableHighlight)return;const r=i?.getSelectedObject();r&&this.enableDynamicSelection?t.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=r?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 e.OutlineRenderPass(this.passId,this._getSelectedObject,(()=>this.target),this.material)}async _startTransparencyAnimation(e,i,r){return t.animateTarget(this,"transparency",{from:e,to:i,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}},e.OutlinePlugin.PluginType="OutlinePlugin",e.OutlinePlugin.OldPluginType="Outline",k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Enable"),t.serialize()],e.OutlinePlugin.prototype,"enabled",2),k([t.uiToggle("Highlight"),t.uniform({propKey:"enableHighlight"}),t.serialize()],e.OutlinePlugin.prototype,"enableHighlight",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("DynamicSelection"),t.serialize()],e.OutlinePlugin.prototype,"enableDynamicSelection",2),k([t.uiSlider("Intensity",[0,4],.001),t.uniform({propKey:"outlineIntensity"}),t.serialize("outlineIntensity")],e.OutlinePlugin.prototype,"intensity",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiSlider("Transparency",[0,1],.01),t.serialize()],e.OutlinePlugin.prototype,"highlightTransparency",2),k([t.uiColor("Color"),t.uniform({propKey:"outlineColor"}),t.serialize("outlineColor")],e.OutlinePlugin.prototype,"color",2),k([t.uiSlider("Thickness",[0,10],.01),t.uniform({propKey:"outlineThickness"}),t.serialize("outlineThickness")],e.OutlinePlugin.prototype,"thickness",2),k([t.uiToggle("Debug"),t.matDefineBool("DEBUG_OUTLINE",void 0,!0)],e.OutlinePlugin.prototype,"debugOutline",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Highlight Selected Materials")],e.OutlinePlugin.prototype,"highlightSelectedMaterials",2),k([t.onChange(e.OutlinePlugin.prototype.setDirty),t.uiToggle("Highlight Materials (same name)")],e.OutlinePlugin.prototype,"highlightMaterialSameNames",2),k([t.uniform({propKey:"highlightTransparency"})],e.OutlinePlugin.prototype,"transparency",2),k([t.uniform({propKey:"outlineBuffer"}),t.uiImage("Outline Buffer",{readOnly:!0})],e.OutlinePlugin.prototype,"texture",2),e.OutlinePlugin=k([t.uiFolderContainer("Selection Outline")],e.OutlinePlugin),e.OutlineRenderPass=class extends t.RenderPass{constructor(e,i,r,a){super(void 0,void 0,a,new t.Color(1,1,1),1),this.passId=e,this._getSelectedObjectOrMaterial=i,this.target=r,this.isOutlineRenderPass=!0,this.enabled=!0,this.before=["render"],this.after=["gbuffer"],this.required=["render","gbuffer"],this.onDirty=[]}render(e,i,r,a,n){if(!this.scene||!this.camera||!this.enabled)return;const s=e.getRenderTarget(),o=e.getActiveCubeFace(),l=e.getActiveMipmapLevel(),c=this._getSelectedObjectOrMaterial();if(c)this._renderSelectedObject(e,c,i||null,a,n);else{e.setRenderTarget(t.getOrCall(this.target)||null);const i=new t.Color;e.getClearColor(i),e.setClearColor(new t.Color(16777215)),e.clear(!0,!0),e.setClearColor(i)}e.setRenderTarget(s,o,l)}_renderSelectedObject(e,i,r,a,n){if(!this.camera||!i)return;const s=(Array.isArray(i)?i:[i]).flatMap((e=>e?.isTexture?[...e.appliedObjects?.values()||[]]:e)).flatMap((e=>e?.isMaterial||e?.isBufferGeometry?[...e.appliedMeshes?.values()||[]]:e));for(const t of s)t&&t.traverse((e=>{e.layers.enable(6)}));const o=this.camera.layers.mask;this.camera.layers.set(6);const l=e.userData;l||console.error("threejs is not patched?"),l.transmissionRenderTarget=r,e.renderWithModes({shadowMapRender:!1,backgroundRender:!1,opaqueRender:!0,transparentRender:!0,transmissionRender:!0,mainRenderPass:!1},(()=>super.render(e,r,t.getOrCall(this.target),a,n))),l.transmissionRenderTarget=void 0,s.forEach((e=>e.traverse((e=>{e.layers.disable(6)})))),this.camera.layers.mask=o}dispose(){this.onDirty=[],this.scene=void 0,this.camera=void 0,super.dispose?.()}setDirty(){this.onDirty.forEach((e=>e()))}beforeRender(e,t,i){this.scene=e,this.camera=t,t.updateShaderProperties(this.overrideMaterial)}},k([t.uiToggle("Enabled")],e.OutlineRenderPass.prototype,"enabled",2),e.OutlineRenderPass=k([t.uiFolderContainer((e=>e.passId+" Render Pass"))],e.OutlineRenderPass);var z=Object.defineProperty,I=(e,t,i,r)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,i,n)||n);return n&&z(t,i,n),n};class V extends t.ExtendedShaderPass{constructor(e,i="rgba"){super({vertexShader:t.CopyShader.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 t.Vector2(1,0)},tDiffuse:{value:null},tDiffuseSize:{value:new t.Vector2}},defines:{B_SRC_ACCESSOR:i}},"tDiffuse"),this.target=e,this.smoothEnabled=!0,this.edgeSharpness=.1,this.clear=!1,this.needsSwap=!1}render(e,i,r,a,n){if(!this.enabled)return;const s=t.getOrCall(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,i,s,a,n),this.uniforms.bilDirection.value.set(0,1),this.uniforms.tDiffuse.value=i.texture,this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width||0,this.uniforms.tDiffuse.value?.image.height||0),super.render(e,s,i,a,n))}}I([t.serialize(),t.uniform()],V.prototype,"smoothEnabled"),I([t.serialize(),t.uniform()],V.prototype,"edgeSharpness");var G=Object.defineProperty,j=Object.getOwnPropertyDescriptor,H=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?j(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&G(t,i,n),n};e.SSGIPlugin=class extends t.PipelinePassPlugin{constructor(e=t.UnsignedByteType,i=1,r=!0){super(),this.passId="ssrtgi",this.dependencies=[t.GBufferPlugin,t.SSAAPlugin],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=i}_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 e.SSGIPluginPass(this.passId,(()=>this.target))}onAdded(t){super.onAdded(t),(t.getPlugin("Ground")||t.getPlugin("BaseGroundPlugin"))&&console.error("GroundPlugin must be added after SSGIPlugin"),this._gbufferUnpackExtensionChanged(),t.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),t.forPlugin(e.VelocityBufferPlugin,(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(i,r,a){if(!this._viewer)return!1;const n=super._beforeRender(i,r,a);if(n){const t=this._viewer?.getPlugin("SSAOPlugin");t&&!t.isDisabled()&&t.disable(e.SSGIPlugin.PluginType)}if(!n)return n;const s=this._viewer.getPlugin(t.ProgressivePlugin);return this._pass?.updateShaderProperties([s]),n}get rtgiTarget(){return console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead"),this.target}},e.SSGIPlugin.PluginType="SSGIPlugin",e.SSGIPlugin.OldPluginType="SSGI",H([t.uiImage("SSGI Buffer",{readOnly:!0})],e.SSGIPlugin.prototype,"texture",2),H([t.uiConfig(void 0,{unwrapContents:!0})],e.SSGIPlugin.prototype,"_pass",2),e.SSGIPlugin=H([t.uiFolderContainer("SSGI Plugin")],e.SSGIPlugin),e.SSGIPluginPass=class extends t.ExtendedShaderPass{constructor(i,r,a=!0){super({defines:{RTAO_STEP_COUNT:16,PERSPECTIVE_CAMERA:1},uniforms:{tLastThis:{value:null},tLastFrame:{value:null},screenSize:{value:new t.Vector2(0,0)},currentFrameCount:{value:0},frameCount:{value:0},cameraNearFar:{value:new t.Vector2(.1,1e3)},cameraPositionWorld:{value:new t.Vector3},projection:{value:new t.Matrix4},opacity:{value:1},intensity:{value:0},objectRadius:{value:0},autoRadius:{value:!a},rayCount:{value:.1},bias:{value:.015},falloff:{value:.7},power:{value:1.1},tolerance:{value:0},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new t.Matrix4},lastProjectionViewMatrix:{value:new t.Matrix4},inverseViewMatrix:{value:new t.Matrix4},ssrtaoSplitX:{value:.5}},vertexShader:t.shaderUtils.defaultVertex,fragmentShader:`\nvarying vec2 vUv;\n\n// for gbuffer\n#include <packing>\n#define THREE_PACKING_INCLUDED\n#include <cameraHelpers>\n#include <randomHelpers>\n${A}\n\n${C}\n\n${n().calculateGI}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=r,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:t.getOrCall(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,i,r)=>{if(!e.defines?.SSRTAO_ENABLED)return;e.fragmentShader=t.shaderReplaceString(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=t.shaderReplaceString(e.fragmentShader,"#include <aomap_fragment>","")},onObjectRender:(e,t,i)=>{let r=!this.enabled||!(this.renderWithCamera||i.renderManager.frameCount>1)||!1===i.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssrtaoDisabled||t.userData?.ssaoDisabled?0:this.split>0?2:1;t.defines.SSRTAO_ENABLED!==r&&(t.defines.SSRTAO_ENABLED=r,t.needsUpdate=!0)},parsFragmentSnippet:e=>t.glsl`
44
44
  #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0
45
45
  uniform float ssaoPower;
46
46
  uniform float ssgiIntensity;
@@ -108,5 +108,5 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
108
108
  gl_FragColor = saturate(gl_FragColor);
109
109
  //gl_FragColor.a = 0.5;
110
110
  #endif
111
- `))},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 i=new ue(16777215,10,{near:1.5,far:20,bias:0,frustumSize:4,width:1024,height:1024,enabled:!0,radius:10,normalBias:0},{direction:new t.Vector3(.2,1,.2).normalize(),spread:.9,focus:1,distanceScale:20,minDistanceScale:new t.Vector3(10,10,10),normalDirection:new t.Vector3(0,1,0)});i.shadow.camera.updateProjectionMatrix(),i.layers.disableAll(),i.layers.set(this._lightLayer),this._light=i,e.scene.addObject(this._light,{addToRoot:!0}),this._shadowMat=new pe({color:"#ffffff",toneMapped:!1,depthWrite:!1,depthTest:!1,premultipliedAlpha:!1,opacity:1,transparent:!1,blending:t.NoBlending}),this._shadowBlurMat=new t.ShaderMaterial2({uniforms:{colorTexture:{value:null},step:{value:.1},size:{value:new t.Vector2(.5,.5)},direction:{value:new t.Vector2(.5,.5)}},vertexShader:t.shaderUtils.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,i,r=!1){return r?(t.ThreeSerialization.Deserialize(e,this,i,!0),this.reset(),this):t.ThreeSerialization.Deserialize(e,this,i,!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 i=1024;this._target||(this._target=this._viewer.renderManager.createTarget({type:t.UnsignedByteType,depthBuffer:!1,size:new t.Vector2(i,i),sizeMultiplier:void 0,colorSpace:t.NoColorSpace,format:t.RGBAFormat})),this._frameNumber<3?this._light.randomizePosition(0,1,0):this._light.randomizePosition(this._frameNumber),e.castShadow=!1;const r=this._viewer.renderManager.renderer,a=r.shadowMap,n=a.type,s=a.needsUpdate,o=a.autoUpdate;a.type=this.shadowMapType,a.needsUpdate=!0,a.autoUpdate=!1;const l=this._viewer.scene,c=new t.Layers;c.disableAll(),l.traverse((e=>{e.isLight&&e!==this._light&&(e.userData.__gp_layers=e.layers,e.layers=c)}));const u=l.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(l,l.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:t.UnsignedByteType,depthBuffer:!1,size:new t.Vector2(i,i),colorSpace:t.NoColorSpace,format:t.RGBAFormat}),p=h.texture,f=p.colorSpace;p.colorSpace=t.NoColorSpace,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(l,l.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,l.modelObject.traverse((e=>{e.isLight&&e!==this._light.lightObject&&(e.layers=e.userData.__gp_layers,delete e.userData.__gp_layers)})),a.type=n,a.needsUpdate=s,a.autoUpdate=o,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})}};ge([t.serialize("randomizedLight")],ve.prototype,"_light"),ge([t.onChange(ve.prototype.reset),t.serialize()],ve.prototype,"maxFrameNumber"),ge([t.onChange(ve.prototype.reset),t.serialize()],ve.prototype,"smoothShadow"),ge([t.serialize(),t.onChange(ve.prototype.reset)],ve.prototype,"shadowMapType"),ge([t.onChange(ve.prototype._groundMapModeChanged),t.serialize()],ve.prototype,"groundMapMode"),ge([t.serialize(),t.onChange(ve.prototype._alphaVignetteChanged)],ve.prototype,"alphaVignette"),ge([t.serialize(),t.onChange(ve.prototype._alphaVignetteChanged)],ve.prototype,"alphaVignetteAxis"),ge([t.serialize()],ve.prototype,"maxBakeCount");let _e=ve;var Se=Object.defineProperty,ye=(e,t,i,r)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,i,n)||n);return n&&Se(t,i,n),n};const xe=((r=class extends t.BaseGroundPlugin{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=t.generateUiConfig(this),i=e.find((e=>"function"==typeof e));this.uiConfig={label:"Ground",type:"folder",children:[...e.filter((e=>e!==i)),...this._extraUiConfig(),i]}}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 i=new ee(this._geometry,(()=>this._viewer?.renderManager.createTarget({type:t.UnsignedByteType,format:t.RGBAFormat,colorSpace:t.NoColorSpace,size:{width:1024,height:1024},generateMipmaps:!0,depthBuffer:!0,minFilter:t.LinearMipmapLinearFilter,magFilter:t.LinearFilter})),0,this._createMaterial()),r=i.onBeforeRender;return i.onBeforeRender=(...e)=>{let t=this._viewer?.getPluginByType("SSReflectionPlugin");t&&t.isDisabled()&&(t=void 0),t&&t.disable(i.uuid,!1),r(...e),t&&t.enable(i.uuid,!1)},i}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 _e(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._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",t.BasicShadowMap],["PCF",t.PCFShadowMap],["PCFSoft",t.PCFSoftShadowMap],["VSM",t.VSMShadowMap]].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",r);ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Baked Shadows"),t.serialize()],xe.prototype,"bakedShadows"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Planar Reflections"),t.serialize()],xe.prototype,"groundReflection"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Physical Reflections"),t.serialize()],xe.prototype,"physicalReflections"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Auto Shadow Frustum Size"),t.serialize()],xe.prototype,"autoFrustumSize"),ye([t.serialize("shadowBaker")],xe.prototype,"_shadowBaker"),ye([t.bindToValue({key:"groundReflection"})],xe.prototype,"planarReflections");let Pe=xe;var be=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?we(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&be(t,i,n),n};e.WatchHandsPlugin=class extends t.AViewerPluginSync{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=new Date,i=this.invertAxis?-1:1,r=i*(t.getSeconds()+(this.analog?t.getMilliseconds()/1e3:0)-this.secondOffset)*(2*Math.PI)/60,a=i*(t.getMinutes()-this.minuteOffset)*(2*Math.PI)/60+r/60,n=i*(t.getHours()-this.hourOffset)*(2*Math.PI)/12+a/12;if(this.hands.find((e=>"second"===e.type&&Math.abs(r-e.object.rotation[this.axis])>.001))){for(const e of this.hands)"second"===e.type&&(e.object.rotation[this.axis]=r),"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()}},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})))}))}},e.WatchHandsPlugin.PluginType="WatchHandsPlugin",Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"enabled",2),Te([t.uiDropdown(void 0,["x","y","z"].map((e=>({label:e})))),t.serialize()],e.WatchHandsPlugin.prototype,"axis",2),Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"invertAxis",2),Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"analog",2),Te([t.uiSlider(void 0,[0,12],.001),t.serialize()],e.WatchHandsPlugin.prototype,"hourOffset",2),Te([t.uiSlider(void 0,[0,60],.001),t.serialize()],e.WatchHandsPlugin.prototype,"minuteOffset",2),Te([t.uiSlider(void 0,[0,60],.001),t.serialize()],e.WatchHandsPlugin.prototype,"secondOffset",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"hour",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"minute",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"second",2),Te([t.uiToggle(),t.onChange("refresh"),t.serialize()],e.WatchHandsPlugin.prototype,"regex",2),Te([t.uiButton()],e.WatchHandsPlugin.prototype,"refresh",1),e.WatchHandsPlugin=Te([t.uiFolderContainer("Watch Hands Time")],e.WatchHandsPlugin);const De=[u,e.VelocityBufferPlugin,y,e.SSReflectionPlugin,e.SSContactShadowsPlugin,T,e.OutlinePlugin,e.SSGIPlugin,e.AnisotropyPlugin,Pe,e.WatchHandsPlugin];e.AdvancedGroundPlugin=Pe,e.BloomPlugin=y,e.DepthOfFieldPlugin=T,e.SSVelocityMaterial=g,e.TemporalAAPlugin=u,e.TemporalAAPluginPass=d,e.anisotropyGLTFExtension=Z,e.webgiPlugins=De,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
111
+ `))},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 i=new ue(16777215,10,{near:1.5,far:20,bias:0,frustumSize:4,width:1024,height:1024,enabled:!0,radius:10,normalBias:0},{direction:new t.Vector3(.2,1,.2).normalize(),spread:.9,focus:1,distanceScale:20,minDistanceScale:new t.Vector3(10,10,10),normalDirection:new t.Vector3(0,1,0)});i.shadow.camera.updateProjectionMatrix(),i.layers.disableAll(),i.layers.set(this._lightLayer),this._light=i,e.scene.addObject(this._light,{addToRoot:!0}),this._shadowMat=new pe({color:"#ffffff",toneMapped:!1,depthWrite:!1,depthTest:!1,premultipliedAlpha:!1,opacity:1,transparent:!1,blending:t.NoBlending}),this._shadowBlurMat=new t.ShaderMaterial2({uniforms:{colorTexture:{value:null},step:{value:.1},size:{value:new t.Vector2(.5,.5)},direction:{value:new t.Vector2(.5,.5)}},vertexShader:t.shaderUtils.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,i,r=!1){return r?(t.ThreeSerialization.Deserialize(e,this,i,!0),this.reset(),this):t.ThreeSerialization.Deserialize(e,this,i,!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 i=1024;this._target||(this._target=this._viewer.renderManager.createTarget({type:t.UnsignedByteType,depthBuffer:!1,size:new t.Vector2(i,i),sizeMultiplier:void 0,colorSpace:t.NoColorSpace,format:t.RGBAFormat})),this._frameNumber<3?this._light.randomizePosition(0,1,0):this._light.randomizePosition(this._frameNumber),e.castShadow=!1;const r=this._viewer.renderManager.renderer,a=r.shadowMap,n=a.type,s=a.needsUpdate,o=a.autoUpdate;a.type=this.shadowMapType,a.needsUpdate=!0,a.autoUpdate=!1;const l=this._viewer.scene,c=new t.Layers;c.disableAll(),l.traverse((e=>{e.isLight&&e!==this._light&&(e.userData.__gp_layers=e.layers,e.layers=c)}));const u=l.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(l,l.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:t.UnsignedByteType,depthBuffer:!1,size:new t.Vector2(i,i),colorSpace:t.NoColorSpace,format:t.RGBAFormat}),p=h.texture,f=p.colorSpace;p.colorSpace=t.NoColorSpace,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(l,l.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,l.modelObject.traverse((e=>{e.isLight&&e!==this._light.lightObject&&(e.layers=e.userData.__gp_layers,delete e.userData.__gp_layers)})),a.type=n,a.needsUpdate=s,a.autoUpdate=o,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})}};ge([t.serialize("randomizedLight")],ve.prototype,"_light"),ge([t.onChange(ve.prototype.reset),t.serialize()],ve.prototype,"maxFrameNumber"),ge([t.onChange(ve.prototype.reset),t.serialize()],ve.prototype,"smoothShadow"),ge([t.serialize(),t.onChange(ve.prototype.reset)],ve.prototype,"shadowMapType"),ge([t.onChange(ve.prototype._groundMapModeChanged),t.serialize()],ve.prototype,"groundMapMode"),ge([t.serialize(),t.onChange(ve.prototype._alphaVignetteChanged)],ve.prototype,"alphaVignette"),ge([t.serialize(),t.onChange(ve.prototype._alphaVignetteChanged)],ve.prototype,"alphaVignetteAxis"),ge([t.serialize()],ve.prototype,"maxBakeCount");let _e=ve;var Se=Object.defineProperty,ye=(e,t,i,r)=>{for(var a,n=void 0,s=e.length-1;s>=0;s--)(a=e[s])&&(n=a(t,i,n)||n);return n&&Se(t,i,n),n};const xe=((r=class extends t.BaseGroundPlugin{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=t.generateUiConfig(this),i=e.find((e=>"function"==typeof e));this.uiConfig={label:"Ground",type:"folder",children:[...e.filter((e=>e!==i)),...this._extraUiConfig(),i]}}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 i=new ee(this._geometry,(()=>this._viewer?.renderManager.createTarget({type:t.UnsignedByteType,format:t.RGBAFormat,colorSpace:t.NoColorSpace,size:{width:1024,height:1024},generateMipmaps:!0,depthBuffer:!0,minFilter:t.LinearMipmapLinearFilter,magFilter:t.LinearFilter})),0,this._createMaterial()),r=i.onBeforeRender;return i.onBeforeRender=(...e)=>{let t=this._viewer?.getPluginByType("SSReflectionPlugin");t&&t.isDisabled()&&(t=void 0),t&&t.disable(i.uuid,!1),r(...e),t&&t.enable(i.uuid,!1)},i}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 _e(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",t.BasicShadowMap],["PCF",t.PCFShadowMap],["PCFSoft",t.PCFSoftShadowMap],["VSM",t.VSMShadowMap]].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",r);ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Baked Shadows"),t.serialize()],xe.prototype,"bakedShadows"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Planar Reflections"),t.serialize()],xe.prototype,"groundReflection"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Physical Reflections"),t.serialize()],xe.prototype,"physicalReflections"),ye([t.onChange(xe.prototype._refresh3),t.uiToggle("Auto Shadow Frustum Size"),t.serialize()],xe.prototype,"autoFrustumSize"),ye([t.serialize("shadowBaker")],xe.prototype,"_shadowBaker"),ye([t.bindToValue({key:"groundReflection"})],xe.prototype,"planarReflections");let Pe=xe;var be=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?we(t,i):t,s=e.length-1;s>=0;s--)(a=e[s])&&(n=(r?a(t,i,n):a(n))||n);return r&&n&&be(t,i,n),n};e.WatchHandsPlugin=class extends t.AViewerPluginSync{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=new Date,i=this.invertAxis?-1:1,r=i*(t.getSeconds()+(this.analog?t.getMilliseconds()/1e3:0)-this.secondOffset)*(2*Math.PI)/60,a=i*(t.getMinutes()-this.minuteOffset)*(2*Math.PI)/60+r/60,n=i*(t.getHours()-this.hourOffset)*(2*Math.PI)/12+a/12;if(this.hands.find((e=>"second"===e.type&&Math.abs(r-e.object.rotation[this.axis])>.001))){for(const e of this.hands)"second"===e.type&&(e.object.rotation[this.axis]=r),"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()}},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})))}))}},e.WatchHandsPlugin.PluginType="WatchHandsPlugin",Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"enabled",2),Te([t.uiDropdown(void 0,["x","y","z"].map((e=>({label:e})))),t.serialize()],e.WatchHandsPlugin.prototype,"axis",2),Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"invertAxis",2),Te([t.uiToggle(),t.serialize()],e.WatchHandsPlugin.prototype,"analog",2),Te([t.uiSlider(void 0,[0,12],.001),t.serialize()],e.WatchHandsPlugin.prototype,"hourOffset",2),Te([t.uiSlider(void 0,[0,60],.001),t.serialize()],e.WatchHandsPlugin.prototype,"minuteOffset",2),Te([t.uiSlider(void 0,[0,60],.001),t.serialize()],e.WatchHandsPlugin.prototype,"secondOffset",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"hour",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"minute",2),Te([t.uiInput(),t.serialize()],e.WatchHandsPlugin.prototype,"second",2),Te([t.uiToggle(),t.onChange("refresh"),t.serialize()],e.WatchHandsPlugin.prototype,"regex",2),Te([t.uiButton()],e.WatchHandsPlugin.prototype,"refresh",1),e.WatchHandsPlugin=Te([t.uiFolderContainer("Watch Hands Time")],e.WatchHandsPlugin);const De=[u,e.VelocityBufferPlugin,y,e.SSReflectionPlugin,e.SSContactShadowsPlugin,T,e.OutlinePlugin,e.SSGIPlugin,e.AnisotropyPlugin,Pe,e.WatchHandsPlugin];e.AdvancedGroundPlugin=Pe,e.BloomPlugin=y,e.DepthOfFieldPlugin=T,e.SSVelocityMaterial=g,e.TemporalAAPlugin=u,e.TemporalAAPluginPass=d,e.anisotropyGLTFExtension=Z,e.webgiPlugins=De,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
112
112
  //# sourceMappingURL=index.js.map