@threepipe/webgi-plugins 0.6.4 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +99 -0
- package/LICENSE +133 -16
- package/README.md +29 -26
- package/THIRD_PARTY_NOTICES.md +243 -0
- package/dist/dependencies.txt +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3907 -18
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3824 -18
- package/dist/index.mjs.map +1 -1
- package/dist/passes/BilateralFilterPass.d.ts +1 -1
- package/dist/passes/BilateralFilterPass.d.ts.map +1 -1
- package/dist/plugins/buffer/VelocityBufferPlugin.d.ts.map +1 -1
- package/dist/plugins/extras/AdvancedGroundPlugin.d.ts +4 -3
- package/dist/plugins/extras/AdvancedGroundPlugin.d.ts.map +1 -1
- package/dist/plugins/extras/AnisotropyPlugin.d.ts +5 -4
- package/dist/plugins/extras/AnisotropyPlugin.d.ts.map +1 -1
- package/dist/plugins/extras/WatchHandsPlugin.d.ts +1 -1
- package/dist/plugins/extras/WatchHandsPlugin.d.ts.map +1 -1
- package/dist/plugins/index.d.ts +23 -23
- package/dist/plugins/postprocessing/BloomPlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/DepthOfFieldPlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/OutlinePlugin.d.ts +1 -1
- package/dist/plugins/postprocessing/OutlinePlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/SSContactShadowsPlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/SSGIPlugin.d.ts +3 -2
- package/dist/plugins/postprocessing/SSGIPlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts +1 -1
- package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts.map +1 -1
- package/dist/plugins/postprocessing/TemporalAAPlugin.d.ts.map +1 -1
- package/dist/utils/FSShadowMaterial.d.ts.map +1 -1
- package/dist/utils/RandomizedDirectionalLight.d.ts.map +1 -1
- package/dist/utils/Reflector2.d.ts +4 -4
- package/dist/utils/Reflector2.d.ts.map +1 -1
- package/dist/utils/ShadowMapBaker.d.ts +1 -1
- package/dist/utils/ShadowMapBaker.d.ts.map +1 -1
- package/docs/.nojekyll +1 -0
- package/docs/assets/hierarchy.js +1 -0
- package/docs/assets/highlight.css +22 -0
- package/docs/assets/icons.js +18 -0
- package/docs/assets/icons.svg +1 -0
- package/docs/assets/main.js +60 -0
- package/docs/assets/navigation.js +1 -0
- package/docs/assets/search.js +1 -0
- package/docs/assets/style.css +1648 -0
- package/docs/classes/AdvancedGroundPlugin.html +736 -0
- package/docs/classes/AnisotropyPlugin.html +432 -0
- package/docs/classes/BloomPlugin.html +466 -0
- package/docs/classes/BloomPluginPass.html +323 -0
- package/docs/classes/DepthOfFieldPlugin.html +493 -0
- package/docs/classes/DepthOfFieldPluginPass.html +340 -0
- package/docs/classes/OutlinePlugin.html +696 -0
- package/docs/classes/OutlineRenderPass.html +252 -0
- package/docs/classes/SSContactShadowsPlugin.html +421 -0
- package/docs/classes/SSGIPlugin.html +488 -0
- package/docs/classes/SSGIPluginPass.html +404 -0
- package/docs/classes/SSReflectionPlugin.html +495 -0
- package/docs/classes/SSReflectionPluginPass.html +410 -0
- package/docs/classes/SSVelocityMaterial.html +110 -0
- package/docs/classes/TemporalAAPlugin.html +447 -0
- package/docs/classes/TemporalAAPluginPass.html +337 -0
- package/docs/classes/VelocityBufferPlugin.html +480 -0
- package/docs/classes/WatchHandsPlugin.html +443 -0
- package/docs/hierarchy.html +28 -0
- package/docs/index.html +38 -0
- package/docs/types/OutlinePluginPass.html +32 -0
- package/docs/types/OutlinePluginTarget.html +32 -0
- package/docs/types/SSGIPluginTarget.html +32 -0
- package/docs/types/SSReflectionPluginTarget.html +32 -0
- package/docs/types/VelocityBufferPluginPass.html +32 -0
- package/docs/types/VelocityBufferPluginTarget.html +32 -0
- package/docs/variables/anisotropyGLTFExtension.html +43 -0
- package/docs/variables/webgiPlugins.html +32 -0
- package/package.json +23 -22
- package/src/global.d.ts +27 -0
- package/src/index.ts +1 -0
- package/src/passes/BilateralFilterPass.ts +62 -0
- package/src/passes/shaders/ssaoBilateral.glsl +89 -0
- package/src/plugins/buffer/VelocityBufferPlugin.ts +270 -0
- package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl +46 -0
- package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl +51 -0
- package/src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl +8 -0
- package/src/plugins/extras/AdvancedGroundPlugin.ts +385 -0
- package/src/plugins/extras/AnisotropyPlugin.ts +519 -0
- package/src/plugins/extras/WatchHandsPlugin.ts +156 -0
- package/src/plugins/extras/shaders/anisotropyBsdf.glsl +64 -0
- package/src/plugins/extras/shaders/anisotropyTBN.glsl +35 -0
- package/src/plugins/index.ts +38 -0
- package/src/plugins/postprocessing/BloomPlugin.ts +377 -0
- package/src/plugins/postprocessing/DepthOfFieldPlugin.ts +470 -0
- package/src/plugins/postprocessing/OutlinePlugin.ts +476 -0
- package/src/plugins/postprocessing/SSContactShadowsPlugin.ts +374 -0
- package/src/plugins/postprocessing/SSGIPlugin.ts +597 -0
- package/src/plugins/postprocessing/SSReflectionPlugin.ts +563 -0
- package/src/plugins/postprocessing/TemporalAAPlugin.ts +301 -0
- package/src/plugins/postprocessing/shaders/dofBlurBox.glsl +46 -0
- package/src/plugins/postprocessing/shaders/dofCombine.glsl +68 -0
- package/src/plugins/postprocessing/shaders/dofComputeCoC.glsl +21 -0
- package/src/plugins/postprocessing/shaders/dofExpandCoC.glsl +56 -0
- package/src/plugins/postprocessing/shaders/dofPoissonBox.glsl +90 -0
- package/src/plugins/postprocessing/shaders/giPatch.glsl +53 -0
- package/src/plugins/postprocessing/shaders/hdrBloom.glsl +101 -0
- package/src/plugins/postprocessing/shaders/outline.glsl +60 -0
- package/src/plugins/postprocessing/shaders/outlineDepthFrag.glsl +22 -0
- package/src/plugins/postprocessing/shaders/outlineDepthVert.glsl +26 -0
- package/src/plugins/postprocessing/shaders/poissonDiskSamples.glsl +19 -0
- package/src/plugins/postprocessing/shaders/samplePointHelpers.glsl +3 -0
- package/src/plugins/postprocessing/shaders/ssrPatch.glsl +145 -0
- package/src/plugins/postprocessing/shaders/ssreflectionMain.glsl +69 -0
- package/src/plugins/postprocessing/shaders/ssrt.glsl +118 -0
- package/src/utils/FSShadowMaterial.ts +65 -0
- package/src/utils/RandomizedDirectionalLight.ts +288 -0
- package/src/utils/Reflector2.ts +309 -0
- package/src/utils/ShadowMapBaker.ts +527 -0
- package/src/utils/shaders/computeScreenSpaceVelocity.glsl +16 -0
- package/src/utils/shaders/getWorldPositionFromViewZ.glsl +9 -0
- package/src/utils/shaders/poissonDiskSamples.glsl +19 -0
- package/src/utils/shaders/reflectorSample.glsl +54 -0
- package/src/utils/shaders/seperableBlurShaderMasked.glsl +28 -0
- package/src/utils/shaders/seperableShadowBlur.glsl +21 -0
- package/src/utils/shaders/ssreflection.glsl +141 -0
- package/src/utils/shaders/ssrtao.glsl +275 -0
- package/src/utils/shaders/temporalaa.glsl +233 -0
- package/src/utils/shaders.ts +24 -0
- package/tsconfig.json +40 -44
- package/dist/version.d.ts +0 -2
- package/dist/version.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,963 @@
|
|
|
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";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,s){super.onBeforeRender(e,i,r,a,n,s);const o=this._previousWorldMatrices[n.uuid];this.extraUniformsToUpload.modelMatrixPrevious.value.copy(o??n.matrixWorld),o?o.copy(n.matrixWorld):this._previousWorldMatrices[n.uuid]=n.matrixWorld.clone();let l=n.material;Array.isArray(l)&&(l=l[0]),this.uniforms.alphaMap.value=l?.alphaMap??null,this.uniforms.alphaTest.value=!l||!l.alphaTest||l.alphaTest<1e-7?.001:l.alphaTest;let c=this.uniforms.alphaMap.value?1:void 0;c!==this.defines.USE_ALPHAMAP&&(void 0===c?delete this.defines.USE_ALPHAMAP:this.defines.USE_ALPHAMAP=c,this.needsUpdate=!0),c=l?.userData.ALPHA_I_RGBA_PACKING?1:void 0,c!==this.defines.ALPHA_I_RGBA_PACKING&&(void 0===c?delete this.defines.ALPHA_I_RGBA_PACKING:this.defines.ALPHA_I_RGBA_PACKING=c,this.needsUpdate=!0),this.side=l?.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(e=!0){super(),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)||[]]},this.enabled=e}_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`
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* @threepipe/webgi-plugins v0.8.0
|
|
4
|
+
* Copyright 2023-2026 repalash <palash@shaders.app> (https://repalash.com)
|
|
5
|
+
* webgi Free Forever License, see LICENSE
|
|
6
|
+
* See ./dependencies.txt for any bundled third-party dependencies and licenses.
|
|
7
|
+
*/
|
|
8
|
+
(function(global, factory) {
|
|
9
|
+
typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("threepipe")) : typeof define === "function" && define.amd ? define(["exports", "threepipe"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["@threepipe/webgi-plugins"] = {}, global.threepipe));
|
|
10
|
+
})(this, function(exports, threepipe) {
|
|
11
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
12
|
+
// src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl
|
|
13
|
+
var VelocityBufferPlugin_unpack_default = "#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";
|
|
14
|
+
// src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl
|
|
15
|
+
var VelocityBufferPlugin_mat_vert_default = "#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}";
|
|
16
|
+
// src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl
|
|
17
|
+
var VelocityBufferPlugin_mat_frag_default = "#ifdef USE_ALPHAMAP\n#define USE_UV\n#include <packing>\nuniform sampler2D alphaMap;uniform float alphaTest;\n#endif\n#include <uv_pars_fragment>\nvarying 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(){\n#ifdef USE_ALPHAMAP\nfloat alphaMapValue=\n#ifdef ALPHA_I_RGBA_PACKING\n1.-unpackRGBAToDepth(texture2D(alphaMap,vAlphaMapUv));\n#else\ntexture2D(alphaMap,vAlphaMapUv).g;\n#endif\nif(alphaMapValue<alphaTest)discard;\n#endif\nvec2 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.);}";
|
|
18
|
+
// src/utils/shaders.ts
|
|
19
|
+
var shadersUtils2 = {
|
|
20
|
+
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);}",
|
|
21
|
+
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;}",
|
|
22
|
+
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));mc=max(vec4(0.0),mc+0.2718*(4.0*mc-(tl+tr+bl+br)));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}",
|
|
23
|
+
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.);}",
|
|
24
|
+
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.));}",
|
|
25
|
+
["__inited"]: false
|
|
26
|
+
};
|
|
27
|
+
function getShaders() {
|
|
28
|
+
if (!shadersUtils2.__inited) {
|
|
29
|
+
shadersUtils2.__inited = true;
|
|
30
|
+
Object.assign(threepipe.RenderManager.ShaderChunk, shadersUtils2);
|
|
31
|
+
}
|
|
32
|
+
return shadersUtils2;
|
|
33
|
+
}
|
|
34
|
+
// \0@oxc-project+runtime@0.155.0/helpers/esm/decorate.js
|
|
35
|
+
function __decorate(decorators, target, key, desc) {
|
|
36
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
37
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
38
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
39
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
40
|
+
}
|
|
41
|
+
// src/plugins/postprocessing/TemporalAAPlugin.ts
|
|
42
|
+
var passId$4 = "taa";
|
|
43
|
+
/**
|
|
44
|
+
* Temporal Anti-Aliasing Plugin
|
|
45
|
+
*
|
|
46
|
+
* This plugin uses a temporal anti-aliasing pass to smooth out the final image when the camera or some mesh is moving
|
|
47
|
+
* @category Plugins
|
|
48
|
+
*/
|
|
49
|
+
var TemporalAAPlugin = class extends threepipe.PipelinePassPlugin {
|
|
50
|
+
static {
|
|
51
|
+
this.PluginType = "TAA";
|
|
52
|
+
}
|
|
53
|
+
static {
|
|
54
|
+
this.OldPluginType = "TemporalAAPlugin";
|
|
55
|
+
}
|
|
56
|
+
constructor(enabled = true) {
|
|
57
|
+
super();
|
|
58
|
+
this.passId = passId$4;
|
|
59
|
+
this._stableNoise = true;
|
|
60
|
+
this._gbufferUnpackExtension = void 0;
|
|
61
|
+
this._gbufferUnpackExtensionChanged = () => {
|
|
62
|
+
if (!this._pass || !this._viewer) throw new Error("TemporalAAPlugin: pass/viewer not created yet");
|
|
63
|
+
const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
|
|
64
|
+
if (this._gbufferUnpackExtension === newExtension) return;
|
|
65
|
+
if (this._gbufferUnpackExtension) this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
|
|
66
|
+
this._gbufferUnpackExtension = newExtension;
|
|
67
|
+
if (this._gbufferUnpackExtension) this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
|
|
68
|
+
else this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed");
|
|
69
|
+
};
|
|
70
|
+
this.dependencies = [threepipe.GBufferPlugin, threepipe.ProgressivePlugin];
|
|
71
|
+
this.uiConfig = {
|
|
72
|
+
type: "folder",
|
|
73
|
+
label: "TemporalAA Plugin",
|
|
74
|
+
onChange: this.setDirty.bind(this),
|
|
75
|
+
children: [...(0, threepipe.generateUiConfig)(this) || []]
|
|
76
|
+
};
|
|
77
|
+
this.enabled = enabled;
|
|
78
|
+
this.setDirty = this.setDirty.bind(this);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Same as BaseRenderer.stableNoise Use total frame count, if this is set to true, then frameCount won't be reset when the viewer is set to dirty.
|
|
82
|
+
* Which will generate different random numbers for each frame during postprocessing steps. With TAA set properly, this will give a smoother result.
|
|
83
|
+
*/
|
|
84
|
+
get stableNoise() {
|
|
85
|
+
return this._viewer?.renderManager.stableNoise ?? this._stableNoise;
|
|
86
|
+
}
|
|
87
|
+
set stableNoise(v) {
|
|
88
|
+
if (this._viewer) this._viewer.renderManager.stableNoise = v;
|
|
89
|
+
this._stableNoise = v;
|
|
90
|
+
}
|
|
91
|
+
_createPass() {
|
|
92
|
+
if (!this._viewer) throw new Error("TemporalAAPlugin: viewer not set");
|
|
93
|
+
if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");
|
|
94
|
+
const applyOnBackground = !!this._viewer.renderManager.msaa;
|
|
95
|
+
return new TemporalAAPluginPass(this.passId, () => this._viewer?.getPlugin(threepipe.ProgressivePlugin)?.target, applyOnBackground);
|
|
96
|
+
}
|
|
97
|
+
onAdded(viewer) {
|
|
98
|
+
super.onAdded(viewer);
|
|
99
|
+
this._gbufferUnpackExtensionChanged();
|
|
100
|
+
viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
101
|
+
viewer.renderManager.addEventListener("resize", this._pass.onSizeUpdate);
|
|
102
|
+
}
|
|
103
|
+
onRemove(viewer) {
|
|
104
|
+
viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
105
|
+
viewer.renderManager.removeEventListener("resize", this._pass.onSizeUpdate);
|
|
106
|
+
super.onRemove(viewer);
|
|
107
|
+
}
|
|
108
|
+
_beforeRender(scene, camera, renderManager) {
|
|
109
|
+
if (!super._beforeRender(scene, camera, renderManager)) return false;
|
|
110
|
+
const pass = this.pass;
|
|
111
|
+
const v = this._viewer;
|
|
112
|
+
if (!pass || !v) return false;
|
|
113
|
+
pass.taaEnabled = renderManager.frameCount <= 1 && scene.renderCamera === scene.mainCamera;
|
|
114
|
+
if (!pass.taaEnabled) return false;
|
|
115
|
+
const cam = camera;
|
|
116
|
+
if (!cam) return false;
|
|
117
|
+
cam.updateMatrixWorld(true);
|
|
118
|
+
cam.updateShaderProperties(pass.material);
|
|
119
|
+
pass.updateCameraProperties(cam);
|
|
120
|
+
pass.target = v.getPlugin(threepipe.ProgressivePlugin).target;
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
__decorate([(0, threepipe.uiToggle)("Stable Noise (Total frame count)")], TemporalAAPlugin.prototype, "stableNoise", null);
|
|
125
|
+
__decorate([(0, threepipe.uiConfig)(void 0, { unwrapContents: true })], TemporalAAPlugin.prototype, "_pass", void 0);
|
|
126
|
+
var TemporalAAPluginPass = class extends threepipe.ExtendedShaderPass {
|
|
127
|
+
constructor(pid, target, applyOnBackground = false) {
|
|
128
|
+
super({
|
|
129
|
+
vertexShader: threepipe.CopyShader.vertexShader,
|
|
130
|
+
fragmentShader: getShaders().temporalAA,
|
|
131
|
+
uniforms: {
|
|
132
|
+
currentRT: { value: null },
|
|
133
|
+
previousRT: { value: null },
|
|
134
|
+
previousRTSize: { value: new threepipe.Vector2() },
|
|
135
|
+
cameraNearFar: { value: new threepipe.Vector2() },
|
|
136
|
+
lastProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
137
|
+
currentProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
138
|
+
projection: { value: new threepipe.Matrix4() },
|
|
139
|
+
inverseViewMatrix: { value: new threepipe.Matrix4() },
|
|
140
|
+
jitterSample: { value: new threepipe.Vector2() },
|
|
141
|
+
firstFrame: { value: true }
|
|
142
|
+
},
|
|
143
|
+
defines: {
|
|
144
|
+
["QUALITY"]: 1,
|
|
145
|
+
["UNJITTER"]: 0,
|
|
146
|
+
["BACKGROUND_TAA"]: applyOnBackground ? 1 : 0
|
|
147
|
+
}
|
|
148
|
+
}, "currentRT", "previousRT");
|
|
149
|
+
this.before = ["progressive"];
|
|
150
|
+
this.after = [];
|
|
151
|
+
this.required = ["render", "progressive"];
|
|
152
|
+
this.taaEnabled = true;
|
|
153
|
+
this.feedBack = new threepipe.Vector2(.88, .97);
|
|
154
|
+
this.debugVelocity = false;
|
|
155
|
+
this.uiConfig = {
|
|
156
|
+
type: "folder",
|
|
157
|
+
label: "Temporal AA Pass",
|
|
158
|
+
onChange: this.setDirty,
|
|
159
|
+
children: [{
|
|
160
|
+
type: "checkbox",
|
|
161
|
+
label: "Enabled",
|
|
162
|
+
property: [this, "enabled"],
|
|
163
|
+
onChange: () => this.onSizeUpdate()
|
|
164
|
+
}, ...(0, threepipe.generateUiConfig)(this)?.filter((c) => c && c.label !== "Enabled") || []]
|
|
165
|
+
};
|
|
166
|
+
this.passId = pid;
|
|
167
|
+
this.onSizeUpdate = this.onSizeUpdate.bind(this);
|
|
168
|
+
this.target = target;
|
|
169
|
+
this.clear = false;
|
|
170
|
+
this.needsSwap = true;
|
|
171
|
+
}
|
|
172
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
173
|
+
if (!this.taaEnabled || !this.enabled) {
|
|
174
|
+
this.needsSwap = false;
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.needsSwap = true;
|
|
178
|
+
this.uniforms.previousRT.value = (0, threepipe.getOrCall)(this.target)?.texture ?? null;
|
|
179
|
+
super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
|
|
180
|
+
this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value);
|
|
181
|
+
this.uniforms.firstFrame.value = false;
|
|
182
|
+
}
|
|
183
|
+
updateCameraProperties(camera) {
|
|
184
|
+
if (!camera) return;
|
|
185
|
+
this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
|
|
186
|
+
this.uniforms.inverseViewMatrix.value.copy(camera.matrixWorld);
|
|
187
|
+
}
|
|
188
|
+
onSizeUpdate() {
|
|
189
|
+
this.uniforms.firstFrame.value = true;
|
|
190
|
+
this.setDirty();
|
|
191
|
+
}
|
|
192
|
+
setSize(width, height) {
|
|
193
|
+
super.setSize(width, height);
|
|
194
|
+
this.onSizeUpdate();
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
__decorate([
|
|
198
|
+
(0, threepipe.serialize)(),
|
|
199
|
+
(0, threepipe.uniform)(),
|
|
200
|
+
(0, threepipe.uiVector)("Feedback", void 0, 1e-4)
|
|
201
|
+
], TemporalAAPluginPass.prototype, "feedBack", void 0);
|
|
202
|
+
__decorate([(0, threepipe.uiToggle)(), (0, threepipe.matDefineBool)("DEBUG_VELOCITY", void 0, false, void 0, true)], TemporalAAPluginPass.prototype, "debugVelocity", void 0);
|
|
203
|
+
// src/plugins/buffer/VelocityBufferPlugin.ts
|
|
204
|
+
var _VelocityBufferPlugin;
|
|
205
|
+
var VelocityBufferPlugin = class VelocityBufferPlugin extends threepipe.PipelinePassPlugin {
|
|
206
|
+
static {
|
|
207
|
+
_VelocityBufferPlugin = this;
|
|
208
|
+
}
|
|
209
|
+
static {
|
|
210
|
+
this.PluginType = "VelocityBuffer";
|
|
211
|
+
}
|
|
212
|
+
static {
|
|
213
|
+
this.OldPluginType = "VelocityBufferPlugin";
|
|
214
|
+
}
|
|
215
|
+
_createTarget(recreate = true) {
|
|
216
|
+
if (!this._viewer) return;
|
|
217
|
+
if (recreate) this._disposeTarget();
|
|
218
|
+
if (!this.target) this.target = this._viewer.renderManager.createTarget({
|
|
219
|
+
depthBuffer: true,
|
|
220
|
+
samples: 0,
|
|
221
|
+
type: this.bufferType,
|
|
222
|
+
generateMipmaps: false,
|
|
223
|
+
colorSpace: threepipe.LinearSRGBColorSpace
|
|
224
|
+
});
|
|
225
|
+
this.texture = this.target.texture;
|
|
226
|
+
this.texture.name = "velocityBuffer";
|
|
227
|
+
if (this._pass) this._pass.target = this.target;
|
|
228
|
+
}
|
|
229
|
+
_disposeTarget() {
|
|
230
|
+
if (!this._viewer) return;
|
|
231
|
+
if (this.target) {
|
|
232
|
+
this._viewer.renderManager.disposeTarget(this.target);
|
|
233
|
+
this.target = void 0;
|
|
234
|
+
}
|
|
235
|
+
this.texture = void 0;
|
|
236
|
+
}
|
|
237
|
+
_createPass() {
|
|
238
|
+
this._createTarget(true);
|
|
239
|
+
if (!this.target) throw new Error("VelocityBufferPlugin: target not created");
|
|
240
|
+
this.material.userData.isGBufferMaterial = true;
|
|
241
|
+
const v = this._viewer;
|
|
242
|
+
const pass = new class extends threepipe.GBufferRenderPass {
|
|
243
|
+
constructor(..._args) {
|
|
244
|
+
super(..._args);
|
|
245
|
+
this._firstCall = true;
|
|
246
|
+
}
|
|
247
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
248
|
+
if (v.renderManager.frameCount > 0) return;
|
|
249
|
+
if (!this.enabled || !this.camera) return;
|
|
250
|
+
const mat = this.overrideMaterial;
|
|
251
|
+
mat.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse);
|
|
252
|
+
if (this._firstCall) {
|
|
253
|
+
mat.uniforms.lastProjectionViewMatrix.value.copy(mat.uniforms.currentProjectionViewMatrix.value);
|
|
254
|
+
this._firstCall = false;
|
|
255
|
+
}
|
|
256
|
+
super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
|
|
257
|
+
mat.uniforms.lastProjectionViewMatrix.value.copy(mat.uniforms.currentProjectionViewMatrix.value);
|
|
258
|
+
}
|
|
259
|
+
}(this.passId, this.target, this.material, new threepipe.Color(.5, .5, .5), 1);
|
|
260
|
+
const preprocessMaterial = pass.preprocessMaterial;
|
|
261
|
+
pass.preprocessMaterial = (m) => {
|
|
262
|
+
const disabled = m.userData[_VelocityBufferPlugin.PluginType]?.disabled;
|
|
263
|
+
return preprocessMaterial(m, disabled === void 0 ? void 0 : !disabled);
|
|
264
|
+
};
|
|
265
|
+
pass.before = ["render"];
|
|
266
|
+
pass.after = [];
|
|
267
|
+
pass.required = ["render"];
|
|
268
|
+
return pass;
|
|
269
|
+
}
|
|
270
|
+
constructor(bufferType = threepipe.UnsignedByteType, enabled = true, _attachToTaa = true) {
|
|
271
|
+
super();
|
|
272
|
+
this.passId = "velocityBuffer";
|
|
273
|
+
this.material = new SSVelocityMaterial();
|
|
274
|
+
this.unpackExtension = {
|
|
275
|
+
shaderExtender: (shader) => {
|
|
276
|
+
if (this.isDisabled()) return;
|
|
277
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#pragma <velocity_unpack>", "\n" + VelocityBufferPlugin_unpack_default + "\n");
|
|
278
|
+
},
|
|
279
|
+
computeCacheKey: () => this.isDisabled() ? "" : "vb",
|
|
280
|
+
extraUniforms: { tVelocity: () => ({ value: !this.isDisabled() ? this.target?.texture : null }) },
|
|
281
|
+
extraDefines: { ["HAS_VELOCITY_BUFFER"]: () => !this.isDisabled() && this.target?.texture ? 1 : void 0 },
|
|
282
|
+
priority: 100,
|
|
283
|
+
isCompatible: () => true
|
|
284
|
+
};
|
|
285
|
+
this.enabled = enabled;
|
|
286
|
+
this.bufferType = bufferType;
|
|
287
|
+
this._attachToTaa = _attachToTaa;
|
|
288
|
+
}
|
|
289
|
+
onAdded(viewer) {
|
|
290
|
+
super.onAdded(viewer);
|
|
291
|
+
viewer.forPlugin(TemporalAAPlugin, (taa) => {
|
|
292
|
+
this._attachToTaa && taa.pass?.material.registerMaterialExtensions([this.unpackExtension]);
|
|
293
|
+
}, (taa) => {
|
|
294
|
+
taa.pass?.material?.unregisterMaterialExtensions([this.unpackExtension]);
|
|
295
|
+
}, this);
|
|
296
|
+
}
|
|
297
|
+
onRemove(viewer) {
|
|
298
|
+
this._disposeTarget();
|
|
299
|
+
return super.onRemove(viewer);
|
|
300
|
+
}
|
|
301
|
+
setDirty() {
|
|
302
|
+
super.setDirty();
|
|
303
|
+
this.unpackExtension.setDirty?.();
|
|
304
|
+
}
|
|
305
|
+
_beforeRender(scene, camera, renderManager) {
|
|
306
|
+
if (!super._beforeRender(scene, camera, renderManager)) return false;
|
|
307
|
+
const pass = this.pass;
|
|
308
|
+
if (!pass) return false;
|
|
309
|
+
if (renderManager.frameCount > 0) return false;
|
|
310
|
+
pass.scene = scene;
|
|
311
|
+
pass.camera = camera;
|
|
312
|
+
camera.updateShaderProperties(pass.overrideMaterial);
|
|
313
|
+
return true;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
__decorate([(0, threepipe.uiImage)("Velocity Buffer", { readOnly: true })], VelocityBufferPlugin.prototype, "texture", void 0);
|
|
317
|
+
VelocityBufferPlugin = _VelocityBufferPlugin = __decorate([(0, threepipe.uiFolderContainer)("Velocity Buffer Plugin (for TAA)")], VelocityBufferPlugin);
|
|
318
|
+
var SSVelocityMaterial = class extends threepipe.ShaderMaterial {
|
|
319
|
+
constructor() {
|
|
320
|
+
super({
|
|
321
|
+
vertexShader: VelocityBufferPlugin_mat_vert_default,
|
|
322
|
+
fragmentShader: VelocityBufferPlugin_mat_frag_default,
|
|
323
|
+
uniforms: {
|
|
324
|
+
cameraNearFar: { value: new threepipe.Vector2(.1, 1e3) },
|
|
325
|
+
alphaMap: { value: null },
|
|
326
|
+
alphaTest: { value: null },
|
|
327
|
+
alphaMapTransform: { value: /* @__PURE__*/ new threepipe.Matrix3() },
|
|
328
|
+
currentProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
329
|
+
lastProjectionViewMatrix: { value: new threepipe.Matrix4() }
|
|
330
|
+
},
|
|
331
|
+
blending: threepipe.NoBlending
|
|
332
|
+
});
|
|
333
|
+
this.extraUniformsToUpload = { modelMatrixPrevious: { value: new threepipe.Matrix4().identity() } };
|
|
334
|
+
this._previousWorldMatrices = {};
|
|
335
|
+
}
|
|
336
|
+
onBeforeRender(_r, _s, _c, _geometry, object, group) {
|
|
337
|
+
super.onBeforeRender(_r, _s, _c, _geometry, object, group);
|
|
338
|
+
const prevMatrix = this._previousWorldMatrices[object.uuid];
|
|
339
|
+
this.extraUniformsToUpload.modelMatrixPrevious.value.copy(prevMatrix ?? object.matrixWorld);
|
|
340
|
+
if (prevMatrix) prevMatrix.copy(object.matrixWorld);
|
|
341
|
+
else this._previousWorldMatrices[object.uuid] = object.matrixWorld.clone();
|
|
342
|
+
let mat = object.material;
|
|
343
|
+
if (Array.isArray(mat)) mat = mat[0];
|
|
344
|
+
this.uniforms.alphaMap.value = mat?.alphaMap ?? null;
|
|
345
|
+
this.uniforms.alphaTest.value = !mat || !mat.alphaTest || mat.alphaTest < 1e-7 ? .001 : mat.alphaTest;
|
|
346
|
+
let x = this.uniforms.alphaMap.value ? 1 : void 0;
|
|
347
|
+
if (x !== this.defines.USE_ALPHAMAP) {
|
|
348
|
+
if (x === void 0) {
|
|
349
|
+
delete this.defines.USE_ALPHAMAP;
|
|
350
|
+
delete this.defines.ALPHAMAP_UV;
|
|
351
|
+
} else {
|
|
352
|
+
this.defines.USE_ALPHAMAP = x;
|
|
353
|
+
this.defines.ALPHAMAP_UV = "uv";
|
|
354
|
+
}
|
|
355
|
+
this.needsUpdate = true;
|
|
356
|
+
}
|
|
357
|
+
const alphaMap = this.uniforms.alphaMap.value;
|
|
358
|
+
if (alphaMap) {
|
|
359
|
+
if (alphaMap.matrixAutoUpdate) alphaMap.updateMatrix();
|
|
360
|
+
this.uniforms.alphaMapTransform.value.copy(alphaMap.matrix);
|
|
361
|
+
}
|
|
362
|
+
x = mat?.userData.ALPHA_I_RGBA_PACKING ? 1 : void 0;
|
|
363
|
+
if (x !== this.defines.ALPHA_I_RGBA_PACKING) {
|
|
364
|
+
if (x === void 0) delete this.defines.ALPHA_I_RGBA_PACKING;
|
|
365
|
+
else this.defines.ALPHA_I_RGBA_PACKING = x;
|
|
366
|
+
this.needsUpdate = true;
|
|
367
|
+
}
|
|
368
|
+
this.side = mat?.side ?? threepipe.DoubleSide;
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
// src/plugins/postprocessing/shaders/hdrBloom.glsl
|
|
372
|
+
var hdrBloom_default = "#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}";
|
|
373
|
+
// src/plugins/postprocessing/BloomPlugin.ts
|
|
374
|
+
var passId$3 = "bloom";
|
|
375
|
+
/**
|
|
376
|
+
* Bloom Plugin
|
|
377
|
+
*
|
|
378
|
+
* Adds HDR Bloom post-processing effect to the scene
|
|
379
|
+
* @category Plugins
|
|
380
|
+
*/
|
|
381
|
+
var BloomPlugin = class BloomPlugin extends threepipe.PipelinePassPlugin {
|
|
382
|
+
static {
|
|
383
|
+
this.PluginType = "Bloom";
|
|
384
|
+
}
|
|
385
|
+
static {
|
|
386
|
+
this.OldPluginType = "BloomPlugin";
|
|
387
|
+
}
|
|
388
|
+
_createPass() {
|
|
389
|
+
return new BloomPluginPass(this.passId, Math.min(8, this._viewer?.renderManager.maxHDRIntensity || 8));
|
|
390
|
+
}
|
|
391
|
+
constructor(enabled = true) {
|
|
392
|
+
super();
|
|
393
|
+
this.passId = passId$3;
|
|
394
|
+
this.materialExtension = (0, threepipe.uiConfigMaterialExtension)(this._getUiConfig.bind(this), BloomPlugin.PluginType);
|
|
395
|
+
this.dependencies = [threepipe.GBufferPlugin];
|
|
396
|
+
this._onPluginAdd = (e) => {
|
|
397
|
+
if (e.plugin?.constructor?.PluginType !== threepipe.GBufferPlugin.PluginType) return;
|
|
398
|
+
const gbuffer = e.plugin;
|
|
399
|
+
gbuffer.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this));
|
|
400
|
+
this._pass?.material.registerMaterialExtensions([gbuffer.unpackExtension]);
|
|
401
|
+
this._viewer?.removeEventListener("addPlugin", this._onPluginAdd);
|
|
402
|
+
};
|
|
403
|
+
this.uiConfig = {
|
|
404
|
+
type: "folder",
|
|
405
|
+
label: "Bloom Plugin",
|
|
406
|
+
onChange: this.setDirty.bind(this),
|
|
407
|
+
children: [...(0, threepipe.generateUiConfig)(this) || []]
|
|
408
|
+
};
|
|
409
|
+
this.enabled = enabled;
|
|
410
|
+
}
|
|
411
|
+
onAdded(viewer) {
|
|
412
|
+
super.onAdded(viewer);
|
|
413
|
+
const gbuffer = viewer.getPlugin(threepipe.GBufferPlugin);
|
|
414
|
+
if (gbuffer) {
|
|
415
|
+
gbuffer.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this));
|
|
416
|
+
this._pass.material.registerMaterialExtensions([gbuffer.unpackExtension]);
|
|
417
|
+
} else viewer.addEventListener("addPlugin", this._onPluginAdd);
|
|
418
|
+
viewer.materialManager.registerMaterialExtension(this.materialExtension);
|
|
419
|
+
}
|
|
420
|
+
onRemove(viewer) {
|
|
421
|
+
viewer.removeEventListener("addPlugin", this._onPluginAdd);
|
|
422
|
+
const gbuffer = viewer.getPlugin(threepipe.GBufferPlugin);
|
|
423
|
+
gbuffer?.unregisterGBufferUpdater(this.constructor.PluginType);
|
|
424
|
+
gbuffer && this._pass?.material.unregisterMaterialExtensions([gbuffer.unpackExtension]);
|
|
425
|
+
viewer.materialManager.unregisterMaterialExtension(this.materialExtension);
|
|
426
|
+
super.onRemove(viewer);
|
|
427
|
+
}
|
|
428
|
+
updateGBufferFlags(data, c) {
|
|
429
|
+
if (!c.material || !c.material.userData) return;
|
|
430
|
+
const x = c.material.userData[BloomPlugin.PluginType]?.enable === false || c.material.userData.pluginsDisabled ? 0 : 1;
|
|
431
|
+
data.w = (0, threepipe.updateBit)(data.w, 2, x);
|
|
432
|
+
}
|
|
433
|
+
static AddBloomData(material, params, setDirty = true) {
|
|
434
|
+
const ud = material?.userData;
|
|
435
|
+
if (!ud) return null;
|
|
436
|
+
if (!ud[BloomPlugin.PluginType]) ud[BloomPlugin.PluginType] = {};
|
|
437
|
+
const data = ud[BloomPlugin.PluginType];
|
|
438
|
+
data.enable = true;
|
|
439
|
+
params && Object.assign(data, params);
|
|
440
|
+
if (setDirty && material.setDirty) material.setDirty();
|
|
441
|
+
return data;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* This uiConfig is added to each material by extension
|
|
445
|
+
* @param material
|
|
446
|
+
* @private
|
|
447
|
+
*/
|
|
448
|
+
_getUiConfig(material) {
|
|
449
|
+
const config = {
|
|
450
|
+
type: "folder",
|
|
451
|
+
label: "Bloom",
|
|
452
|
+
children: [{
|
|
453
|
+
type: "checkbox",
|
|
454
|
+
label: "Enabled",
|
|
455
|
+
get value() {
|
|
456
|
+
return material.userData[BloomPlugin.PluginType]?.enable ?? true;
|
|
457
|
+
},
|
|
458
|
+
set value(v) {
|
|
459
|
+
let data = material.userData[BloomPlugin.PluginType];
|
|
460
|
+
if (v === data?.enable) return;
|
|
461
|
+
if (!data) data = BloomPlugin.AddBloomData(material, void 0, false);
|
|
462
|
+
data.enable = v;
|
|
463
|
+
material.setDirty();
|
|
464
|
+
config.uiRefresh?.(true, "postFrame");
|
|
465
|
+
},
|
|
466
|
+
onChange: this.setDirty
|
|
467
|
+
}]
|
|
468
|
+
};
|
|
469
|
+
return config;
|
|
470
|
+
}
|
|
471
|
+
};
|
|
472
|
+
__decorate([(0, threepipe.uiConfig)(void 0, { unwrapContents: true })], BloomPlugin.prototype, "_pass", void 0);
|
|
473
|
+
var BloomPluginPass = class BloomPluginPass extends threepipe.ExtendedShaderPass {
|
|
474
|
+
constructor(pid, maxIntensity = 16) {
|
|
475
|
+
super({
|
|
476
|
+
vertexShader: threepipe.CopyShader.vertexShader,
|
|
477
|
+
defines: {
|
|
478
|
+
["PASS_STEP"]: 1,
|
|
479
|
+
["MAX_INTENSITY"]: Math.min(maxIntensity, 16)
|
|
480
|
+
},
|
|
481
|
+
uniforms: {
|
|
482
|
+
tSource: { value: null },
|
|
483
|
+
tDiffuse: { value: null },
|
|
484
|
+
opacity: { value: 1 },
|
|
485
|
+
tDiffuseSize: { value: new threepipe.Vector2() },
|
|
486
|
+
weight: { value: 1 }
|
|
487
|
+
},
|
|
488
|
+
fragmentShader: hdrBloom_default
|
|
489
|
+
}, "tDiffuse", "tSource");
|
|
490
|
+
this.uiConfig = void 0;
|
|
491
|
+
this.before = ["screen"];
|
|
492
|
+
this.after = ["render", "progressive"];
|
|
493
|
+
this.required = ["render"];
|
|
494
|
+
this.prefilter = new threepipe.Vector4(2, .5, 0, 0);
|
|
495
|
+
this.threshold = 2;
|
|
496
|
+
this.softThreshold = .5;
|
|
497
|
+
this.intensity = .2;
|
|
498
|
+
this.backgroundBloom = false;
|
|
499
|
+
this.bloomIterations = 4;
|
|
500
|
+
this._currentIterations = 0;
|
|
501
|
+
this.radius = .6;
|
|
502
|
+
this.power = 1;
|
|
503
|
+
this.bloomDebug = false;
|
|
504
|
+
this._weights = [];
|
|
505
|
+
this.passId = pid;
|
|
506
|
+
this._updateWeights = this._updateWeights.bind(this);
|
|
507
|
+
this._thresholdsUpdated = this._thresholdsUpdated.bind(this);
|
|
508
|
+
this._updateWeights();
|
|
509
|
+
this._thresholdsUpdated();
|
|
510
|
+
this.clear = true;
|
|
511
|
+
}
|
|
512
|
+
_thresholdsUpdated() {
|
|
513
|
+
this.prefilter.x = this.threshold;
|
|
514
|
+
this.prefilter.y = this.softThreshold;
|
|
515
|
+
this.prefilter.z = 2 * this.prefilter.x * this.prefilter.y;
|
|
516
|
+
this.prefilter.w = this.uniforms?.prefilter ? .125 / (this.uniforms.prefilter.value.z + 1e-5) : 0;
|
|
517
|
+
this.setDirty();
|
|
518
|
+
}
|
|
519
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
520
|
+
const renderManager = renderer.renderManager;
|
|
521
|
+
this.material.defines.PASS_STEP = 0;
|
|
522
|
+
this.clear = true;
|
|
523
|
+
this.needsSwap = false;
|
|
524
|
+
const source = readBuffer;
|
|
525
|
+
if (!source) {
|
|
526
|
+
console.warn("BloomPluginPass: No source to read from");
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
this.needsSwap = true;
|
|
530
|
+
let sizeMultiplier = .5;
|
|
531
|
+
let width = source.width * sizeMultiplier;
|
|
532
|
+
let height = source.height * sizeMultiplier;
|
|
533
|
+
const textures = [];
|
|
534
|
+
let currentDestination = renderManager.getTempTarget({
|
|
535
|
+
sizeMultiplier: 1,
|
|
536
|
+
type: threepipe.HalfFloatType
|
|
537
|
+
});
|
|
538
|
+
textures.push(currentDestination);
|
|
539
|
+
let currentSource = source;
|
|
540
|
+
this.material.needsUpdate = true;
|
|
541
|
+
this.material.uniforms.weight.value = this._weights[0];
|
|
542
|
+
super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
|
|
543
|
+
currentSource = currentDestination;
|
|
544
|
+
const ci = this._currentIterations;
|
|
545
|
+
let i = 1;
|
|
546
|
+
const iter = Math.max(2, this.bloomIterations);
|
|
547
|
+
for (; i < iter; i++) {
|
|
548
|
+
width /= 2;
|
|
549
|
+
height /= 2;
|
|
550
|
+
sizeMultiplier /= 2;
|
|
551
|
+
if (height < 2 || width < 2) break;
|
|
552
|
+
currentDestination = renderManager.getTempTarget({
|
|
553
|
+
sizeMultiplier,
|
|
554
|
+
type: threepipe.HalfFloatType
|
|
555
|
+
});
|
|
556
|
+
textures.push(currentDestination);
|
|
557
|
+
this.material.defines.PASS_STEP = 1;
|
|
558
|
+
let modifiedWeight = this._weights[i];
|
|
559
|
+
modifiedWeight = this._weights[i - 1] !== 0 ? this._weights[i] / this._weights[i - 1] : this._weights[i];
|
|
560
|
+
this.material.uniforms.weight.value = modifiedWeight;
|
|
561
|
+
this.material.needsUpdate = true;
|
|
562
|
+
super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
|
|
563
|
+
currentSource = currentDestination;
|
|
564
|
+
this._currentIterations = i + 1;
|
|
565
|
+
}
|
|
566
|
+
if (ci !== this._currentIterations) this._updateWeights(false);
|
|
567
|
+
this.clear = false;
|
|
568
|
+
const oldAutoClear = renderer.autoClear;
|
|
569
|
+
renderer.autoClear = false;
|
|
570
|
+
for (i -= 2; i >= 0; i--) {
|
|
571
|
+
currentDestination = textures[i];
|
|
572
|
+
textures[i] = void 0;
|
|
573
|
+
this.material.defines.PASS_STEP = 2;
|
|
574
|
+
this.material.transparent = true;
|
|
575
|
+
this.material.blending = threepipe.AdditiveBlending;
|
|
576
|
+
this.material.needsUpdate = true;
|
|
577
|
+
renderer.autoClear = false;
|
|
578
|
+
super.render(renderer, currentDestination, currentSource, deltaTime, maskActive);
|
|
579
|
+
this.material.blending = threepipe.NoBlending;
|
|
580
|
+
renderManager.releaseTempTarget(currentSource);
|
|
581
|
+
currentSource = currentDestination;
|
|
582
|
+
}
|
|
583
|
+
this.clear = true;
|
|
584
|
+
renderer.autoClear = oldAutoClear;
|
|
585
|
+
renderer.autoClear = true;
|
|
586
|
+
if (this.bloomDebug) {
|
|
587
|
+
this.material.defines.PASS_STEP = 4;
|
|
588
|
+
this.material.needsUpdate = true;
|
|
589
|
+
super.render(renderer, writeBuffer, currentSource, deltaTime, maskActive);
|
|
590
|
+
} else {
|
|
591
|
+
this.uniforms.tSource.value = source.texture;
|
|
592
|
+
this.material.defines.PASS_STEP = 3;
|
|
593
|
+
this.material.needsUpdate = true;
|
|
594
|
+
super.render(renderer, writeBuffer, currentSource, deltaTime, maskActive);
|
|
595
|
+
this.uniforms.tSource.value = null;
|
|
596
|
+
}
|
|
597
|
+
renderManager.releaseTempTarget(currentSource);
|
|
598
|
+
}
|
|
599
|
+
_updateWeights(setDirty = true) {
|
|
600
|
+
if (!this._weights) return;
|
|
601
|
+
const radius = Math.max(Math.min(this.radius, 1), 0);
|
|
602
|
+
const iter = Math.max(2, this._currentIterations || this.bloomIterations);
|
|
603
|
+
const delta = 1 / (iter - 1);
|
|
604
|
+
for (let i = 0; i < iter; i++) {
|
|
605
|
+
let f = i * delta + .1;
|
|
606
|
+
let oneMinusF = 1.2 - f;
|
|
607
|
+
f = Math.pow(f, this.power);
|
|
608
|
+
oneMinusF = Math.pow(oneMinusF, this.power);
|
|
609
|
+
this._weights[i] = oneMinusF * (1 - radius) + f * radius;
|
|
610
|
+
}
|
|
611
|
+
if (setDirty !== false) this.setDirty();
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
__decorate([(0, threepipe.uniform)()], BloomPluginPass.prototype, "prefilter", void 0);
|
|
615
|
+
__decorate([
|
|
616
|
+
(0, threepipe.uiSlider)("Threshold", [0, 2]),
|
|
617
|
+
(0, threepipe.onChange)(BloomPluginPass.prototype._thresholdsUpdated),
|
|
618
|
+
(0, threepipe.serialize)()
|
|
619
|
+
], BloomPluginPass.prototype, "threshold", void 0);
|
|
620
|
+
__decorate([
|
|
621
|
+
(0, threepipe.uiSlider)("Soft Threshold", [0, 1]),
|
|
622
|
+
(0, threepipe.onChange)(BloomPluginPass.prototype._thresholdsUpdated),
|
|
623
|
+
(0, threepipe.serialize)()
|
|
624
|
+
], BloomPluginPass.prototype, "softThreshold", void 0);
|
|
625
|
+
__decorate([
|
|
626
|
+
(0, threepipe.uiSlider)("Intensity", [0, 3]),
|
|
627
|
+
(0, threepipe.serialize)(),
|
|
628
|
+
(0, threepipe.uniform)({ onChange: BloomPluginPass.prototype.setDirty })
|
|
629
|
+
], BloomPluginPass.prototype, "intensity", void 0);
|
|
630
|
+
__decorate([
|
|
631
|
+
(0, threepipe.uiToggle)("Background Bloom"),
|
|
632
|
+
(0, threepipe.serialize)(),
|
|
633
|
+
(0, threepipe.matDefineBool)("BACKGROUND_BLOOM", void 0, void 0, BloomPluginPass.prototype.setDirty)
|
|
634
|
+
], BloomPluginPass.prototype, "backgroundBloom", void 0);
|
|
635
|
+
__decorate([
|
|
636
|
+
(0, threepipe.uiSlider)("Iterations", [2, 7], 1),
|
|
637
|
+
(0, threepipe.onChange2)(BloomPluginPass.prototype._updateWeights),
|
|
638
|
+
(0, threepipe.serialize)()
|
|
639
|
+
], BloomPluginPass.prototype, "bloomIterations", void 0);
|
|
640
|
+
__decorate([
|
|
641
|
+
(0, threepipe.uiSlider)("Radius", [0, 1], .01),
|
|
642
|
+
(0, threepipe.onChange2)(BloomPluginPass.prototype._updateWeights),
|
|
643
|
+
(0, threepipe.serialize)()
|
|
644
|
+
], BloomPluginPass.prototype, "radius", void 0);
|
|
645
|
+
__decorate([
|
|
646
|
+
(0, threepipe.uiSlider)("Power", [.2, 10], .01),
|
|
647
|
+
(0, threepipe.onChange2)(BloomPluginPass.prototype._updateWeights),
|
|
648
|
+
(0, threepipe.serialize)()
|
|
649
|
+
], BloomPluginPass.prototype, "power", void 0);
|
|
650
|
+
__decorate([(0, threepipe.uiToggle)("Debug"), (0, threepipe.onChange2)(BloomPluginPass.prototype.setDirty)], BloomPluginPass.prototype, "bloomDebug", void 0);
|
|
651
|
+
BloomPluginPass = __decorate([(0, threepipe.uiFolderContainer)("Bloom Pass")], BloomPluginPass);
|
|
652
|
+
// src/plugins/postprocessing/shaders/dofCombine.glsl
|
|
653
|
+
var dofCombine_default = "#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}";
|
|
654
|
+
// src/plugins/postprocessing/shaders/dofPoissonBox.glsl
|
|
655
|
+
var dofPoissonBox_default = "#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}";
|
|
656
|
+
// src/plugins/postprocessing/shaders/poissonDiskSamples.glsl
|
|
657
|
+
var poissonDiskSamples_default$1 = "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);}";
|
|
658
|
+
// src/plugins/postprocessing/shaders/dofComputeCoC.glsl
|
|
659
|
+
var dofComputeCoC_default = "#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}";
|
|
660
|
+
// src/plugins/postprocessing/shaders/dofExpandCoC.glsl
|
|
661
|
+
var dofExpandCoC_default = "#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}";
|
|
662
|
+
// src/plugins/postprocessing/DepthOfFieldPlugin.ts
|
|
663
|
+
var passId$2 = "depthOfField";
|
|
664
|
+
/**
|
|
665
|
+
* Depth Of Field Plugin
|
|
666
|
+
*
|
|
667
|
+
* Adds a depth of field effect with configurable focal point.
|
|
668
|
+
* @category Plugins
|
|
669
|
+
*/
|
|
670
|
+
var DepthOfFieldPlugin = class extends threepipe.PipelinePassPlugin {
|
|
671
|
+
static {
|
|
672
|
+
this.PluginType = "DepthOfField";
|
|
673
|
+
}
|
|
674
|
+
static {
|
|
675
|
+
this.OldPluginType = "DepthOfFieldPlugin";
|
|
676
|
+
}
|
|
677
|
+
get _frameFadeTime() {
|
|
678
|
+
return this.crossFadeTime * 2.5;
|
|
679
|
+
}
|
|
680
|
+
constructor(enabled = true, enableEdit = false) {
|
|
681
|
+
super();
|
|
682
|
+
this.passId = passId$2;
|
|
683
|
+
this.enableEdit = false;
|
|
684
|
+
this._focalPointHit = new threepipe.Vector3(0, 0, 0);
|
|
685
|
+
this.crossFadeTime = 200;
|
|
686
|
+
this._focalPointHitTime = 0;
|
|
687
|
+
this.dependencies = [threepipe.GBufferPlugin];
|
|
688
|
+
this._onPluginAdd = (e) => {
|
|
689
|
+
const plugin = e.plugin;
|
|
690
|
+
if (!plugin) return;
|
|
691
|
+
if (plugin.constructor?.PluginType === threepipe.GBufferPlugin.PluginType) {
|
|
692
|
+
const gbuffer = plugin;
|
|
693
|
+
this._pass?.material.registerMaterialExtensions([gbuffer.unpackExtension]);
|
|
694
|
+
this._pass?.computeCocMaterial.registerMaterialExtensions([gbuffer.unpackExtension]);
|
|
695
|
+
this._pass?.expandCocMaterial.registerMaterialExtensions([gbuffer.unpackExtension]);
|
|
696
|
+
}
|
|
697
|
+
if (plugin.constructor?.PluginType === threepipe.PickingPlugin.PluginType) plugin.addEventListener("hitObject", this._onObjectHit);
|
|
698
|
+
};
|
|
699
|
+
this._onPluginRemove = (e) => {
|
|
700
|
+
const plugin = e.plugin;
|
|
701
|
+
if (!plugin) return;
|
|
702
|
+
if (plugin.constructor?.PluginType === threepipe.GBufferPlugin.PluginType) {
|
|
703
|
+
const gbuffer = e.plugin;
|
|
704
|
+
this._pass?.material.unregisterMaterialExtensions([gbuffer.unpackExtension]);
|
|
705
|
+
this._pass?.computeCocMaterial.unregisterMaterialExtensions([gbuffer.unpackExtension]);
|
|
706
|
+
this._pass?.expandCocMaterial.unregisterMaterialExtensions([gbuffer.unpackExtension]);
|
|
707
|
+
}
|
|
708
|
+
if (plugin.constructor?.PluginType === threepipe.PickingPlugin.PluginType) e.plugin.removeEventListener("hitObject", this._onObjectHit);
|
|
709
|
+
};
|
|
710
|
+
this.uiConfig = {
|
|
711
|
+
type: "folder",
|
|
712
|
+
label: "DepthOfField",
|
|
713
|
+
onChange: this.setDirty.bind(this),
|
|
714
|
+
children: [...(0, threepipe.generateUiConfig)(this) || [], () => this._pass?.uiConfig]
|
|
715
|
+
};
|
|
716
|
+
this._tempVec = new threepipe.Vector3();
|
|
717
|
+
this.enabled = enabled;
|
|
718
|
+
this.enableEdit = enableEdit;
|
|
719
|
+
this._onObjectHit = this._onObjectHit.bind(this);
|
|
720
|
+
this.setDirty = this.setDirty.bind(this);
|
|
721
|
+
}
|
|
722
|
+
setFocalPoint(p, fade = true, showGizmo = false) {
|
|
723
|
+
this._focalPointHit.copy(p);
|
|
724
|
+
if (fade) this._viewer?.getPlugin("FrameFadePlugin")?.startTransition(this._frameFadeTime);
|
|
725
|
+
if (showGizmo) this._focalPointHitTime = (0, threepipe.now)();
|
|
726
|
+
this.setDirty();
|
|
727
|
+
}
|
|
728
|
+
getFocalPoint() {
|
|
729
|
+
return this._focalPointHit;
|
|
730
|
+
}
|
|
731
|
+
_onObjectHit(e) {
|
|
732
|
+
if (!this._pass || !e.intersects.intersect || this.isDisabled() || !this.enableEdit) return;
|
|
733
|
+
this._focalPointHit.copy(e.intersects.intersect.point);
|
|
734
|
+
this._focalPointHitTime = e.time;
|
|
735
|
+
e.intersects.selectedObject = null;
|
|
736
|
+
this._viewer?.getPlugin(threepipe.FrameFadePlugin)?.startTransition(this._frameFadeTime);
|
|
737
|
+
this.setDirty();
|
|
738
|
+
}
|
|
739
|
+
_createPass() {
|
|
740
|
+
return new DepthOfFieldPluginPass(this.passId);
|
|
741
|
+
}
|
|
742
|
+
onAdded(viewer) {
|
|
743
|
+
super.onAdded(viewer);
|
|
744
|
+
viewer.addEventListener("addPlugin", this._onPluginAdd);
|
|
745
|
+
viewer.addEventListener("removePlugin", this._onPluginRemove);
|
|
746
|
+
this._onPluginAdd({ plugin: viewer.getPlugin(threepipe.GBufferPlugin) });
|
|
747
|
+
this._onPluginAdd({ plugin: viewer.getPlugin(threepipe.PickingPlugin) });
|
|
748
|
+
}
|
|
749
|
+
onRemove(viewer) {
|
|
750
|
+
viewer.removeEventListener("addPlugin", this._onPluginAdd);
|
|
751
|
+
viewer.removeEventListener("removePlugin", this._onPluginRemove);
|
|
752
|
+
this._onPluginRemove({ plugin: viewer.getPlugin(threepipe.GBufferPlugin) });
|
|
753
|
+
this._onPluginRemove({ plugin: viewer.getPlugin(threepipe.PickingPlugin) });
|
|
754
|
+
super.onRemove(viewer);
|
|
755
|
+
}
|
|
756
|
+
_beforeRender(scene, camera, renderManager) {
|
|
757
|
+
if (!super._beforeRender(scene, camera, renderManager)) return false;
|
|
758
|
+
const pass = this.pass;
|
|
759
|
+
if (!pass) return false;
|
|
760
|
+
if (pass.dofBlurMaterial.uniforms.frameCount) renderManager?.updateShaderProperties(pass.dofBlurMaterial);
|
|
761
|
+
const cam = camera;
|
|
762
|
+
if (!cam) return false;
|
|
763
|
+
cam.updateMatrixWorld(true);
|
|
764
|
+
cam.updateShaderProperties(pass.material);
|
|
765
|
+
cam.getWorldPosition(this._tempVec);
|
|
766
|
+
this._tempVec.subVectors(this._focalPointHit, this._tempVec);
|
|
767
|
+
pass.focalDepthRange.x = this._tempVec.length();
|
|
768
|
+
pass.focalDepthRange.x *= cam.getWorldDirection(new threepipe.Vector3()).dot(this._tempVec.normalize());
|
|
769
|
+
let crossAlpha = ((0, threepipe.now)() - this._focalPointHitTime) / this.crossFadeTime;
|
|
770
|
+
crossAlpha = 1 - Math.min(1, Math.max(0, crossAlpha));
|
|
771
|
+
if (Math.abs(crossAlpha - pass.crossAlpha) > .01) {
|
|
772
|
+
pass.crossAlpha = crossAlpha;
|
|
773
|
+
this.setDirty();
|
|
774
|
+
}
|
|
775
|
+
if (crossAlpha > 0) {
|
|
776
|
+
const projectedPoint = this._tempVec.copy(this._focalPointHit).project(cam).addScalar(1).divideScalar(2);
|
|
777
|
+
pass.crossCenter.set(projectedPoint.x, projectedPoint.y);
|
|
778
|
+
pass.computeCocMaterial.uniformsNeedUpdate = true;
|
|
779
|
+
pass.expandCocMaterial.uniformsNeedUpdate = true;
|
|
780
|
+
}
|
|
781
|
+
return true;
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.uiToggle)()], DepthOfFieldPlugin.prototype, "enableEdit", void 0);
|
|
785
|
+
__decorate([(0, threepipe.serialize)("focalPoint")], DepthOfFieldPlugin.prototype, "_focalPointHit", void 0);
|
|
786
|
+
__decorate([(0, threepipe.serialize)()], DepthOfFieldPlugin.prototype, "crossFadeTime", void 0);
|
|
787
|
+
var dofBlurMaterialPoisson = new threepipe.ExtendedShaderMaterial({
|
|
788
|
+
uniforms: {
|
|
789
|
+
colorTexture: { value: null },
|
|
790
|
+
colorTextureSize: { value: new threepipe.Vector2() },
|
|
791
|
+
direction: { value: new threepipe.Vector2() },
|
|
792
|
+
frameCount: { value: 0 },
|
|
793
|
+
blurRadius: { value: 16 }
|
|
794
|
+
},
|
|
795
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
796
|
+
fragmentShader: poissonDiskSamples_default$1 + "\n" + dofPoissonBox_default,
|
|
797
|
+
defines: { ["DOF_MODE"]: 1 }
|
|
798
|
+
}, ["colorTexture"]);
|
|
799
|
+
var DepthOfFieldPluginPass = class DepthOfFieldPluginPass extends threepipe.ExtendedShaderPass {
|
|
800
|
+
constructor(pid) {
|
|
801
|
+
super({
|
|
802
|
+
uniforms: {
|
|
803
|
+
colorTexture: { value: null },
|
|
804
|
+
blurTexture: { value: null },
|
|
805
|
+
cocTexture: { value: null },
|
|
806
|
+
cocTextureSize: { value: new threepipe.Vector2() },
|
|
807
|
+
cameraNearFar: { value: new threepipe.Vector2() }
|
|
808
|
+
},
|
|
809
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
810
|
+
fragmentShader: dofCombine_default
|
|
811
|
+
}, "colorTexture", "cocTexture", "blurTexture");
|
|
812
|
+
this.uiConfig = void 0;
|
|
813
|
+
this.before = ["progressive", "screen"];
|
|
814
|
+
this.after = ["render"];
|
|
815
|
+
this.required = ["render"];
|
|
816
|
+
this.dofBlurMaterial = dofBlurMaterialPoisson;
|
|
817
|
+
this.nearFarBlurScale = new threepipe.Vector2(.25, .25);
|
|
818
|
+
this.focalDepthRange = new threepipe.Vector2(.5, 1.5);
|
|
819
|
+
this.crossCenter = new threepipe.Vector2(.5, .5);
|
|
820
|
+
this.crossRadius = .04;
|
|
821
|
+
this.crossAlpha = 1;
|
|
822
|
+
this.crossColor = new threepipe.Color(16750848);
|
|
823
|
+
this.passId = pid;
|
|
824
|
+
this.computeCocMaterial = new threepipe.ExtendedShaderMaterial({
|
|
825
|
+
uniforms: {
|
|
826
|
+
colorTexture: { value: null },
|
|
827
|
+
cameraNearFar: this.uniforms.cameraNearFar,
|
|
828
|
+
nearFarBlurScale: this.uniforms.nearFarBlurScale,
|
|
829
|
+
focalDepthRange: this.uniforms.focalDepthRange
|
|
830
|
+
},
|
|
831
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
832
|
+
fragmentShader: dofComputeCoC_default
|
|
833
|
+
}, ["colorTexture"]);
|
|
834
|
+
this.expandCocMaterial = new threepipe.ExtendedShaderMaterial({
|
|
835
|
+
uniforms: {
|
|
836
|
+
colorTexture: { value: null },
|
|
837
|
+
colorTextureSize: { value: new threepipe.Vector2() },
|
|
838
|
+
direction: { value: new threepipe.Vector2() },
|
|
839
|
+
nearFarBlurScale: this.uniforms.nearFarBlurScale
|
|
840
|
+
},
|
|
841
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
842
|
+
fragmentShader: dofExpandCoC_default
|
|
843
|
+
}, ["colorTexture"]);
|
|
844
|
+
}
|
|
845
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
846
|
+
if (!this.enabled) return;
|
|
847
|
+
if (!readBuffer) {
|
|
848
|
+
console.error("DepthOfFieldPluginPass: No readBuffer");
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
const renderManager = renderer.renderManager;
|
|
852
|
+
const halfPars = {
|
|
853
|
+
minFilter: threepipe.NearestFilter,
|
|
854
|
+
magFilter: threepipe.NearestFilter,
|
|
855
|
+
type: threepipe.HalfFloatType,
|
|
856
|
+
colorSpace: threepipe.LinearSRGBColorSpace,
|
|
857
|
+
sizeMultiplier: .5,
|
|
858
|
+
format: threepipe.RGBAFormat,
|
|
859
|
+
depthBuffer: false,
|
|
860
|
+
generateMipmaps: false
|
|
861
|
+
};
|
|
862
|
+
const cocRt = renderManager.getTempTarget(halfPars);
|
|
863
|
+
const renderTargetBlurTemp = renderManager.getTempTarget(halfPars);
|
|
864
|
+
this.computeCocMaterial.uniforms.colorTexture.value = readBuffer.texture;
|
|
865
|
+
renderManager.blit(cocRt, { material: this.computeCocMaterial });
|
|
866
|
+
this.expandCocMaterial.uniforms.colorTexture.value = cocRt.texture;
|
|
867
|
+
this.expandCocMaterial.uniforms.direction.value.set(1, 0);
|
|
868
|
+
renderManager.blit(renderTargetBlurTemp, { material: this.expandCocMaterial });
|
|
869
|
+
this.expandCocMaterial.uniforms.colorTexture.value = renderTargetBlurTemp.texture;
|
|
870
|
+
this.expandCocMaterial.uniforms.direction.value.set(0, 1);
|
|
871
|
+
renderManager.blit(cocRt, { material: this.expandCocMaterial });
|
|
872
|
+
if (this.dofBlurMaterial.uniforms.frameCount) {
|
|
873
|
+
this.dofBlurMaterial.uniforms.colorTexture.value = cocRt.texture;
|
|
874
|
+
renderManager.blit(renderTargetBlurTemp, { material: this.dofBlurMaterial });
|
|
875
|
+
} else {
|
|
876
|
+
const renderTargetBlurTemp2 = renderManager.getTempTarget(halfPars);
|
|
877
|
+
this.dofBlurMaterial.uniforms.cocTexture.value = cocRt.texture;
|
|
878
|
+
this.dofBlurMaterial.uniforms.colorTexture.value = cocRt.texture;
|
|
879
|
+
this.dofBlurMaterial.uniforms.direction.value.set(1, 0);
|
|
880
|
+
renderManager.blit(renderTargetBlurTemp2, { material: this.dofBlurMaterial });
|
|
881
|
+
this.dofBlurMaterial.uniforms.colorTexture.value = renderTargetBlurTemp2.texture;
|
|
882
|
+
this.dofBlurMaterial.uniforms.direction.value.set(0, 1);
|
|
883
|
+
renderManager.blit(renderTargetBlurTemp, { material: this.dofBlurMaterial });
|
|
884
|
+
renderManager.releaseTempTarget(renderTargetBlurTemp2);
|
|
885
|
+
}
|
|
886
|
+
this.material.uniforms.blurTexture.value = renderTargetBlurTemp.texture;
|
|
887
|
+
this.material.uniforms.cocTexture.value = cocRt.texture;
|
|
888
|
+
super.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
|
|
889
|
+
renderManager.releaseTempTarget(cocRt);
|
|
890
|
+
renderManager.releaseTempTarget(renderTargetBlurTemp);
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
__decorate([(0, threepipe.bindToValue)({
|
|
894
|
+
obj: "focalDepthRange",
|
|
895
|
+
key: "y",
|
|
896
|
+
onChange: "setDirty"
|
|
897
|
+
}), (0, threepipe.uiSlider)("Depth Range", [.25, 3])], DepthOfFieldPluginPass.prototype, "depthRange", void 0);
|
|
898
|
+
__decorate([(0, threepipe.bindToValue)({
|
|
899
|
+
obj: "nearFarBlurScale",
|
|
900
|
+
key: "x",
|
|
901
|
+
onChange: "setDirty"
|
|
902
|
+
}), (0, threepipe.uiSlider)("Near Blur Scale", [0, 1])], DepthOfFieldPluginPass.prototype, "nearBlurScale", void 0);
|
|
903
|
+
__decorate([(0, threepipe.bindToValue)({
|
|
904
|
+
obj: "nearFarBlurScale",
|
|
905
|
+
key: "y",
|
|
906
|
+
onChange: "setDirty"
|
|
907
|
+
}), (0, threepipe.uiSlider)("Far Blur Scale", [0, 1])], DepthOfFieldPluginPass.prototype, "farBlurScale", void 0);
|
|
908
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "nearFarBlurScale", void 0);
|
|
909
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "focalDepthRange", void 0);
|
|
910
|
+
__decorate([(0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "crossCenter", void 0);
|
|
911
|
+
__decorate([(0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "crossRadius", void 0);
|
|
912
|
+
__decorate([(0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "crossAlpha", void 0);
|
|
913
|
+
__decorate([(0, threepipe.uniform)()], DepthOfFieldPluginPass.prototype, "crossColor", void 0);
|
|
914
|
+
DepthOfFieldPluginPass = __decorate([(0, threepipe.uiFolderContainer)("DepthOfField Pass")], DepthOfFieldPluginPass);
|
|
915
|
+
// src/plugins/postprocessing/shaders/ssrt.glsl
|
|
916
|
+
var ssrt_default = "#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";
|
|
917
|
+
// src/plugins/postprocessing/SSContactShadowsPlugin.ts
|
|
918
|
+
var _SSContactShadowsPlugin;
|
|
919
|
+
var ShaderChunk$2 = threepipe.RenderManager.ShaderChunk;
|
|
920
|
+
var SSContactShadowsPlugin = class SSContactShadowsPlugin extends threepipe.AViewerPluginSync {
|
|
921
|
+
static {
|
|
922
|
+
_SSContactShadowsPlugin = this;
|
|
923
|
+
}
|
|
924
|
+
static {
|
|
925
|
+
this.PluginType = "SSContactShadows";
|
|
926
|
+
}
|
|
927
|
+
static {
|
|
928
|
+
this.OldPluginType = "SSContactShadowsPlugin";
|
|
929
|
+
}
|
|
930
|
+
setDirty() {
|
|
931
|
+
this.materialExtension?.setDirty?.();
|
|
932
|
+
this._viewer?.setDirty();
|
|
933
|
+
}
|
|
934
|
+
constructor(enabled = true) {
|
|
935
|
+
super();
|
|
936
|
+
this.enabled = true;
|
|
937
|
+
this._uniforms = {
|
|
938
|
+
sscsRadius: { value: .03 },
|
|
939
|
+
sscsIntensity: { value: 1 },
|
|
940
|
+
sscsTolerance: { value: 1.5 },
|
|
941
|
+
frameCount: { value: 0 },
|
|
942
|
+
projection: { value: new threepipe.Matrix4() },
|
|
943
|
+
cameraPositionWorld: { value: new threepipe.Vector3() },
|
|
944
|
+
cameraNearFar: { value: new threepipe.Vector2(.1, 1e3) },
|
|
945
|
+
sceneBoundingRadius: { value: 0 }
|
|
946
|
+
};
|
|
947
|
+
this.radius = .015;
|
|
948
|
+
this.intensity = 1;
|
|
949
|
+
this.tolerance = 1.5;
|
|
950
|
+
this._defines = { ["PERSPECTIVE_CAMERA"]: 1 };
|
|
951
|
+
this.onlySSCSDebug = false;
|
|
952
|
+
this.stepCount = 2;
|
|
953
|
+
this.dependencies = [threepipe.GBufferPlugin];
|
|
954
|
+
this.materialExtension = {
|
|
955
|
+
uuid: _SSContactShadowsPlugin.PluginType,
|
|
956
|
+
priority: 5,
|
|
957
|
+
shaderExtender: (shader, _material, _renderer) => {
|
|
958
|
+
if (!shader.defines.SSCS_ENABLED) return;
|
|
959
|
+
const rsS = "float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {";
|
|
960
|
+
const lsS = threepipe.glsl`
|
|
2
961
|
#ifndef D_sceneBoundingRadius
|
|
3
962
|
#define D_sceneBoundingRadius
|
|
4
963
|
uniform float sceneBoundingRadius;
|
|
@@ -19,7 +978,368 @@
|
|
|
19
978
|
#if defined(SSCS_DEBUG) && SSCS_DEBUG > 0
|
|
20
979
|
return state.z;
|
|
21
980
|
#endif
|
|
22
|
-
`,n=`\n#if SSCS_ENABLED\n\n uniform float sscsIntensity;\n uniform float sscsRadius;\n uniform float sscsTolerance;\n\n #define THREE_PACKING_INCLUDED // by threejs\n #include <cameraHelpers>\n #include <randomHelpers>\n ${C}\n \n#endif\n `+t.shaderReplaceString(B.shadowmap_pars_fragment,"float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {",`${a}\n`).replace("return mix( 1.0, shadow, shadowIntensity );","return mix( 1.0, min(shadow, state.z), shadowIntensity );");e.fragmentShader=t.shaderReplaceString(e.fragmentShader,"#include <shadowmap_pars_fragment>",n),e.fragmentShader=e.fragmentShader.replace("#include <lights_fragment_begin>",B.lights_fragment_begin),e.fragmentShader=t.shaderReplaceString(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;"),e.fragmentShader=t.shaderReplaceString(e.fragmentShader,"directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;","directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;"),this._gbufferUnpackExtension?.shaderExtender?.(e,i,r)},onObjectRender:(e,i,r)=>{const a=!this.enabled||!1===r.userData.screenSpaceRendering||i.userData?.pluginsDisabled||i.userData?.sscsDisabled?0:1;t.updateMaterialDefines({...this._defines,SSCS_ENABLED:a},i)},extraUniforms:{...this._uniforms},extraDefines:{},computeCacheKey:e=>this.isDisabled()?"0":"1",isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.getPlugin(t.ProgressivePlugin),this._viewer?.scene.renderCamera,this._viewer?.renderManager,this._viewer?.scene]},this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._viewer)throw new Error("SSContactShadowPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed"))},this.enabled=i}setDirty(){this.materialExtension?.setDirty?.(),this._viewer?.setDirty()}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.getPlugin(t.BaseGroundPlugin)&&(e.getPlugin(t.BaseGroundPlugin).material.userData.sscsDisabled=!1),this._gbufferUnpackExtensionChanged(),e.renderManager.addEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.renderManager.removeEventListener("gbufferUnpackExtensionChanged",this._gbufferUnpackExtensionChanged),super.onRemove(e)}setGBufferUnpackExtension(e){this._gbufferUnpackExtension=e,this._gbufferUnpackExtension&&(Object.assign(this.materialExtension.extraUniforms,this._gbufferUnpackExtension.extraUniforms),Object.assign(this.materialExtension.extraDefines,this._gbufferUnpackExtension.extraDefines))}},e.SSContactShadowsPlugin.PluginType="SSContactShadows",e.SSContactShadowsPlugin.OldPluginType="SSContactShadowsPlugin",E([t.uiToggle("Enabled"),t.serialize(),t.onChange(e.SSContactShadowsPlugin.prototype.setDirty)],e.SSContactShadowsPlugin.prototype,"enabled",2),E([t.uniform({propKey:"sscsRadius",onChange:e.SSContactShadowsPlugin.prototype.setDirty}),t.uiSlider("Radius",[1e-4,.1],1e-4),t.serialize()],e.SSContactShadowsPlugin.prototype,"radius",2),E([t.uniform({propKey:"sscsIntensity",onChange:e.SSContactShadowsPlugin.prototype.setDirty}),t.uiSlider("Intensity",[1e-4,1],1e-4),t.serialize()],e.SSContactShadowsPlugin.prototype,"intensity",2),E([t.uniform({propKey:"sscsTolerance",onChange:e.SSContactShadowsPlugin.prototype.setDirty}),t.uiSlider("Tolerance",[.1,5]),t.serialize()],e.SSContactShadowsPlugin.prototype,"tolerance",2),E([t.matDefine("SSCS_DEBUG",void 0,!0,e.SSContactShadowsPlugin.prototype.setDirty),t.uiToggle("Debug only SSCS"),t.serialize()],e.SSContactShadowsPlugin.prototype,"onlySSCSDebug",2),E([t.matDefine("SSCS_STEP_COUNT",void 0,!0,e.SSContactShadowsPlugin.prototype.setDirty),t.uiSlider("Step count",[1,8],1),t.serialize()],e.SSContactShadowsPlugin.prototype,"stepCount",2),e.SSContactShadowsPlugin=E([t.uiFolderContainer("SS Contact Shadows")],e.SSContactShadowsPlugin);const A="#define PI 3.141592653589793\nmat3 GetTangentBasis(vec3 TangentZ){vec3 up=vec3(0.0,0.0,1.0);vec3 TangentX=normalize(cross(dot(TangentZ,up)<0.8 ? up : vec3(1.0,0.0,0.0),TangentZ));vec3 TangentY=cross(TangentZ,TangentX);return mat3(TangentX,TangentY,TangentZ);}vec4 CosineSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=sqrt(E.y);float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=CosTheta*(1.0/PI);return vec4(H,PDF);}vec4 UniformSampleHemisphere(vec2 E){float Phi=2.*PI*E.x;float CosTheta=E.y;float SinTheta=sqrt(1.-CosTheta*CosTheta);vec3 H;H.x=SinTheta*cos(Phi);H.y=SinTheta*sin(Phi);H.z=CosTheta;float PDF=1.0/(2.*PI);return vec4(H,PDF);}vec2 UniformSampleDiskConcentric(vec2 E){vec2 p=2.*E-1.;float Radius;float Phi;if(abs(p.x)>abs(p.y)){Radius=p.x;Phi=(PI/4.)*(p.y/p.x);}else{Radius=p.y;Phi=(PI/2.)-(PI/4.)*(p.x/p.y);}return vec2(Radius*cos(Phi),Radius*sin(Phi));}vec2 UniformSampleDiskConcentricApprox(vec2 E){vec2 sf=E*sqrt(2.0)-sqrt(0.5);vec2 sq=sf*sf;float root=sqrt(2.0*max(sq.x,sq.y)-min(sq.x,sq.y));if(sq.x>sq.y){sf.x=sf.x>0. ? root :-root;}else{sf.y=sf.y>0. ? root :-root;}return sf;}";var O=Object.defineProperty,U=Object.getOwnPropertyDescriptor,L=(e,t,i,r)=>{for(var a,n=r>1?void 0:r?U(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&&O(t,i,n),n};e.SSReflectionPlugin=class extends t.PipelinePassPlugin{constructor(e=!0,i=t.UnsignedByteType,r=1,a=!0){super(),this.inlineShaderRayTrace=e,this.passId="ssrefl",this.dependencies=[t.GBufferPlugin,t.SSAAPlugin],this._gbufferUnpackExtension=void 0,this._gbufferUnpackExtensionChanged=()=>{if(!this._pass||!this._viewer)throw new Error("SSReflectionPlugin: pass/viewer not created yet");const e=this._viewer.renderManager.gbufferUnpackExtension;this._gbufferUnpackExtension!==e&&(this._gbufferUnpackExtension&&this._pass.setGBufferUnpackExtension(void 0),this._gbufferUnpackExtension=e,this._gbufferUnpackExtension?this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension):this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed"))},this._viewerListeners={preRender:()=>{if(!this._viewer||this.isDisabled())return;if(!this._pass)return;const e=this._viewer.scene.renderCamera;this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._pass.uniforms.inverseViewMatrix.value.copy(e.matrixWorld)},postRender:()=>{this._viewer&&!this.isDisabled()&&this._pass&&this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value)}},this.enabled=a,this.bufferType=i,this.sizeMultiplier=r}_createTarget(e=!0){this._viewer&&(e&&this._disposeTarget(),this.inlineShaderRayTrace||(this.target||(this.target=this._viewer.renderManager.createTarget({depthBuffer:!1,type:this.bufferType,sizeMultiplier:this.sizeMultiplier})),this.texture=this.target.texture,this.texture.name="ssreflBuffer"))}_disposeTarget(){this._viewer&&(this.target&&(this._viewer.renderManager.disposeTarget(this.target),this.target=void 0),this.texture=void 0)}_createPass(){if(!this._viewer)throw new Error("SSReflectionPlugin: viewer not set");if(!this._viewer.renderManager.gbufferTarget||!this._viewer.renderManager.gbufferUnpackExtension)throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");return this._createTarget(!0),new e.SSReflectionPluginPass(this.passId,()=>this.target,this.inlineShaderRayTrace)}onAdded(t){super.onAdded(t),(t.getPlugin("Ground")||t.getPlugin("BaseGroundPlugin"))&&console.warn("GroundPlugin must be added after SSReflectionPlugin"),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)}_beforeRender(e,i,r){if(!this._viewer)return!1;const a=super._beforeRender(e,i,r);if(!a)return a;const n=this._viewer.getPlugin(t.ProgressivePlugin);return this._pass?.updateShaderProperties([n]),a}get ssrTarget(){return console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead"),this.target}fromJSON(e,t){return e.passes?.ssr&&((e={...e}).pass=e.passes.ssr,delete e.passes,void 0!==e.pass.enabled&&(e.enabled=e.pass.enabled)),super.fromJSON(e,t)}},e.SSReflectionPlugin.PluginType="SSReflectionPlugin",e.SSReflectionPlugin.OldPluginType="SSReflection",L([t.uiImage("SSReflection Buffer",{readOnly:!0,hideOnEmpty:!0})],e.SSReflectionPlugin.prototype,"texture",2),L([t.uiConfig(void 0,{unwrapContents:!0})],e.SSReflectionPlugin.prototype,"_pass",2),e.SSReflectionPlugin=L([t.uiFolderContainer("SSReflection Plugin")],e.SSReflectionPlugin),e.SSReflectionPluginPass=class extends t.ExtendedShaderPass{constructor(i,r,a=!0){super({defines:{SSR_STEP_COUNT:16,SSR_RAY_COUNT:4,SSR_RAY_BLEND_MAX:0,SSR_LOW_QUALITY_FRAMES:0,SSR_INLINE:a?"1":"0",SSR_MASK_FRONT_RAYS:!0,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},boost:{value:new t.Vector3(0,0,0)},objectRadius:{value:0},autoRadius:{value:!1},power:{value:0},maskFrontFactor:{value:-.1},tolerance:{value:0},ssrRoughnessFactor:{value:1},sceneBoundingRadius:{value:0},currentProjectionViewMatrix:{value:new t.Matrix4},lastProjectionViewMatrix:{value:new t.Matrix4},inverseViewMatrix:{value:new t.Matrix4},ssrSplitX:{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().ssReflection}\n\nvoid main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}\n `},"tDiffuse","tLastThis","tLastFrame"),this.target=r,this.inlineShaderRayTrace=a,this.before=["render"],this.after=["gbuffer","depth"],this.required=["render","progressive"],this.intensity=1,this.boost=new t.Vector3(1,1,1),this.objectRadius=1,this.autoRadius=!0,this.power=1.1,this.tolerance=.5,this.roughnessFactor=1,this.stepCount=16,this.rayCount=1,this.rayBlendMax=!1,this.lowQualityFrames=0,this.maskFrontRays=!0,this.maskFrontFactor=-.2,this.split=0,this.materialExtension={extraUniforms:{tSSReflMap:()=>({value:t.getOrCall(this.target)?.texture??null}),ssrPower:this.material.uniforms.power,ssrIntensity:this.material.uniforms.intensity,ssrMaskFrontFactor:this.material.uniforms.maskFrontFactor,ssrBoost:this.material.uniforms.boost},extraDefines:{SSR_STEP_COUNT:()=>this.material.defines.SSR_STEP_COUNT,SSR_RAY_COUNT:()=>this.material.defines.SSR_RAY_COUNT,SSR_RAY_BLEND_MAX:()=>this.material.defines.SSR_RAY_BLEND_MAX,SSR_LOW_QUALITY_FRAMES:()=>this.material.defines.SSR_LOW_QUALITY_FRAMES,SSR_INLINE:()=>this.material.defines.SSR_INLINE,SSR_MASK_FRONT_RAYS:()=>this.material.defines.SSR_MASK_FRONT_RAYS,PERSPECTIVE_CAMERA:()=>this.material.defines.PERSPECTIVE_CAMERA},shaderExtender:(e,i,r)=>{if(!e.defines?.SSREFL_ENABLED)return;e.fragmentShader=t.shaderReplaceString(e.fragmentShader,"#glMarker beforeModulation","\n \n \n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n\n \n // reflectedLight.directDiffuse = vec3(0.);\n // reflectedLight.indirectDiffuse = vec3(0.);\n // reflectedLight.directSpecular = vec3(0.);\n // reflectedLight.indirectSpecular = vec3(0.);\n \n ",{prepend:!0}),this._gbufferUnpackExtension?.shaderExtender?.(e,i,r)},onObjectRender:(e,t,i)=>{let r=!this.enabled||!1===i.userData.screenSpaceRendering||t.userData?.pluginsDisabled||t.userData?.ssreflDisabled?0:this.split>0?2:1;t.defines.SSREFL_ENABLED!==r&&(t.defines.SSREFL_ENABLED=r,t.needsUpdate=!0),r=t.userData?.ssreflNonPhysical?1:0,t.defines.SSR_NON_PHYSICAL!==r&&(t.defines.SSR_NON_PHYSICAL=r,t.needsUpdate=!0)},parsFragmentSnippet:()=>t.glsl`
|
|
981
|
+
`;
|
|
982
|
+
const shadowChunk = `
|
|
983
|
+
#if SSCS_ENABLED
|
|
984
|
+
|
|
985
|
+
uniform float sscsIntensity;
|
|
986
|
+
uniform float sscsRadius;
|
|
987
|
+
uniform float sscsTolerance;
|
|
988
|
+
|
|
989
|
+
#define THREE_PACKING_INCLUDED // by threejs
|
|
990
|
+
#include <cameraHelpers>
|
|
991
|
+
#include <randomHelpers>
|
|
992
|
+
${ssrt_default}
|
|
993
|
+
|
|
994
|
+
#endif
|
|
995
|
+
` + (0, threepipe.shaderReplaceString)(ShaderChunk$2.shadowmap_pars_fragment, rsS, `${lsS}\n`).replace("return mix( 1.0, shadow, shadowIntensity );", "return mix( 1.0, min(shadow, state.z), shadowIntensity );");
|
|
996
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <shadowmap_pars_fragment>", shadowChunk);
|
|
997
|
+
shader.fragmentShader = shader.fragmentShader.replace("#include <lights_fragment_begin>", ShaderChunk$2.lights_fragment_begin);
|
|
998
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;", "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;");
|
|
999
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;", "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;");
|
|
1000
|
+
this._gbufferUnpackExtension?.shaderExtender?.(shader, _material, _renderer);
|
|
1001
|
+
},
|
|
1002
|
+
onObjectRender: (_, material, renderer) => {
|
|
1003
|
+
const enabled = this.enabled && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.sscsDisabled ? 1 : 0;
|
|
1004
|
+
(0, threepipe.updateMaterialDefines)({
|
|
1005
|
+
...this._defines,
|
|
1006
|
+
["SSCS_ENABLED"]: enabled
|
|
1007
|
+
}, material);
|
|
1008
|
+
},
|
|
1009
|
+
extraUniforms: { ...this._uniforms },
|
|
1010
|
+
extraDefines: {},
|
|
1011
|
+
computeCacheKey: (_) => {
|
|
1012
|
+
return this.isDisabled() ? "0" : "1";
|
|
1013
|
+
},
|
|
1014
|
+
isCompatible: (material1) => {
|
|
1015
|
+
return material1.isPhysicalMaterial;
|
|
1016
|
+
},
|
|
1017
|
+
updaters: () => [
|
|
1018
|
+
this._viewer?.getPlugin(threepipe.ProgressivePlugin),
|
|
1019
|
+
this._viewer?.scene.renderCamera,
|
|
1020
|
+
this._viewer?.renderManager,
|
|
1021
|
+
this._viewer?.scene
|
|
1022
|
+
]
|
|
1023
|
+
};
|
|
1024
|
+
this._gbufferUnpackExtension = void 0;
|
|
1025
|
+
this._gbufferUnpackExtensionChanged = () => {
|
|
1026
|
+
if (!this._viewer) throw new Error("SSContactShadowPlugin: pass/viewer not created yet");
|
|
1027
|
+
const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
|
|
1028
|
+
if (this._gbufferUnpackExtension === newExtension) return;
|
|
1029
|
+
if (this._gbufferUnpackExtension) this.setGBufferUnpackExtension(void 0);
|
|
1030
|
+
this._gbufferUnpackExtension = newExtension;
|
|
1031
|
+
if (this._gbufferUnpackExtension) this.setGBufferUnpackExtension(this._gbufferUnpackExtension);
|
|
1032
|
+
else this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed");
|
|
1033
|
+
};
|
|
1034
|
+
this.enabled = enabled;
|
|
1035
|
+
}
|
|
1036
|
+
onAdded(v) {
|
|
1037
|
+
super.onAdded(v);
|
|
1038
|
+
v.assetManager.materials.registerMaterialExtension(this.materialExtension);
|
|
1039
|
+
if (v.getPlugin(threepipe.BaseGroundPlugin)) v.getPlugin(threepipe.BaseGroundPlugin).material.userData.sscsDisabled = false;
|
|
1040
|
+
this._gbufferUnpackExtensionChanged();
|
|
1041
|
+
v.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1042
|
+
}
|
|
1043
|
+
onRemove(v) {
|
|
1044
|
+
v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension);
|
|
1045
|
+
v.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1046
|
+
return super.onRemove(v);
|
|
1047
|
+
}
|
|
1048
|
+
setGBufferUnpackExtension(extension) {
|
|
1049
|
+
this._gbufferUnpackExtension = extension;
|
|
1050
|
+
if (!this._gbufferUnpackExtension) return;
|
|
1051
|
+
Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms);
|
|
1052
|
+
Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines);
|
|
1053
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
__decorate([
|
|
1056
|
+
(0, threepipe.uiToggle)("Enabled"),
|
|
1057
|
+
(0, threepipe.serialize)(),
|
|
1058
|
+
(0, threepipe.onChange)(SSContactShadowsPlugin.prototype.setDirty)
|
|
1059
|
+
], SSContactShadowsPlugin.prototype, "enabled", void 0);
|
|
1060
|
+
__decorate([
|
|
1061
|
+
(0, threepipe.uniform)({
|
|
1062
|
+
propKey: "sscsRadius",
|
|
1063
|
+
onChange: SSContactShadowsPlugin.prototype.setDirty
|
|
1064
|
+
}),
|
|
1065
|
+
(0, threepipe.uiSlider)("Radius", [1e-4, .1], 1e-4),
|
|
1066
|
+
(0, threepipe.serialize)()
|
|
1067
|
+
], SSContactShadowsPlugin.prototype, "radius", void 0);
|
|
1068
|
+
__decorate([
|
|
1069
|
+
(0, threepipe.uniform)({
|
|
1070
|
+
propKey: "sscsIntensity",
|
|
1071
|
+
onChange: SSContactShadowsPlugin.prototype.setDirty
|
|
1072
|
+
}),
|
|
1073
|
+
(0, threepipe.uiSlider)("Intensity", [1e-4, 1], 1e-4),
|
|
1074
|
+
(0, threepipe.serialize)()
|
|
1075
|
+
], SSContactShadowsPlugin.prototype, "intensity", void 0);
|
|
1076
|
+
__decorate([
|
|
1077
|
+
(0, threepipe.uniform)({
|
|
1078
|
+
propKey: "sscsTolerance",
|
|
1079
|
+
onChange: SSContactShadowsPlugin.prototype.setDirty
|
|
1080
|
+
}),
|
|
1081
|
+
(0, threepipe.uiSlider)("Tolerance", [.1, 5]),
|
|
1082
|
+
(0, threepipe.serialize)()
|
|
1083
|
+
], SSContactShadowsPlugin.prototype, "tolerance", void 0);
|
|
1084
|
+
__decorate([
|
|
1085
|
+
(0, threepipe.matDefine)("SSCS_DEBUG", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
|
|
1086
|
+
(0, threepipe.uiToggle)("Debug only SSCS"),
|
|
1087
|
+
(0, threepipe.serialize)()
|
|
1088
|
+
], SSContactShadowsPlugin.prototype, "onlySSCSDebug", void 0);
|
|
1089
|
+
__decorate([
|
|
1090
|
+
(0, threepipe.matDefine)("SSCS_STEP_COUNT", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
|
|
1091
|
+
(0, threepipe.uiSlider)("Step count", [1, 8], 1),
|
|
1092
|
+
(0, threepipe.serialize)()
|
|
1093
|
+
], SSContactShadowsPlugin.prototype, "stepCount", void 0);
|
|
1094
|
+
SSContactShadowsPlugin = _SSContactShadowsPlugin = __decorate([(0, threepipe.uiFolderContainer)("SS Contact Shadows")], SSContactShadowsPlugin);
|
|
1095
|
+
/**
|
|
1096
|
+
* SSContactShadows Materials Extension
|
|
1097
|
+
*
|
|
1098
|
+
* Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_clearcoat_tint.html
|
|
1099
|
+
*/
|
|
1100
|
+
// src/plugins/postprocessing/shaders/samplePointHelpers.glsl
|
|
1101
|
+
var samplePointHelpers_default = "\n#define PI 3.141592653589793\n";
|
|
1102
|
+
// src/plugins/postprocessing/shaders/ssrPatch.glsl
|
|
1103
|
+
var ssrPatch_default = "\n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometryPosition);\n#if SSREFL_ENABLED == 2\nif(screenPos.x>ssrSplitX){\n#endif\nvec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;\n#if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0\nalphaModifier*=clamp(-4.0*dot(geometryViewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);\n#endif\n#ifdef USE_TRANSMISSION\nalphaModifier*=1.-transmission;\n#endif\nfloat vignette=1.;if(true){float fadeStrength=0.1;float dist=max(0.,min(min(1.-screenPos.x,1.-screenPos.y),min(screenPos.x,screenPos.y)));float fade=dist*dist/(fadeStrength+0.001);fade=clamp(fade,0.0,1.0);fade=pow(fade,0.3);vignette=fade;}alphaModifier*=vignette;vec3 specularColor=EnvironmentBRDF(geometryNormal,geometryViewDir,material.specularColor.rgb,material.specularF90,material.roughness);if(length(specularColor.rgb)*alphaModifier>0.01&&roughnessFactor<0.9){\n#if defined(SSR_INLINE) && SSR_INLINE > 0\nvec3 scPos=vec3(screenPos.xy,geometryPosition.z);vec4 scol=vec4(0,0,0,0);\n#pragma unroll_loop_start\nfor(int i=0;i<8;i++){if(SSR_RAY_COUNT>UNROLLED_LOOP_INDEX){scol=calculateSSR(float(UNROLLED_LOOP_INDEX),scPos,geometryNormal,UNROLLED_LOOP_INDEX%3==0?1.:UNROLLED_LOOP_INDEX%3==1?0.5:1.5,material.roughness);\n#ifdef SSR_RAY_BLEND_MAX\nssrColor=max(ssrColor,scol);\n#else\nssrColor+=scol;\n#endif\n}}\n#pragma unroll_loop_end\n#ifndef SSR_RAY_BLEND_MAX\nssrColor*=ssrColor.a>0.001 ? 1.0/ssrColor.a : 1.0;\n#endif\n#else\nssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));\n#endif\n}ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(max(vec3(0.),ssrColor.rgb),vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);\n#if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0\ndiffuseColor.a=max(ssrColor.a,diffuseColor.a*diffuseColor.a);reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,saturate(diffuseColor.rgb*ssrColor.rgb),1.0);reflectedLight.indirectDiffuse=diffuseColor.rgb*(1.0-ssrColor.a);reflectedLight.directDiffuse=vec3(0.0);reflectedLight.directSpecular=vec3(0.0);\n#else\nreflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);\n#endif\n#if SSREFL_ENABLED == 2\n}\n#endif\n#endif\n";
|
|
1104
|
+
// src/plugins/postprocessing/shaders/ssreflectionMain.glsl
|
|
1105
|
+
var ssreflectionMain_default = "void main(){vec4 texel=tDiffuseTexelToLinear(texture2D(tDiffuse,vUv));vec4 lastAO=tLastThisTexelToLinear(texture2D(tLastThis,vUv));float depth;vec3 normal;getDepthNormal(vUv,depth,normal);if(depth>=0.999){discard;}float viewZ=depthToViewZ(depth);vec3 screenPos=vec3(vUv.x,vUv.y,viewZ);vec3 viewPos=screenToView3(screenPos.xy,screenPos.z);viewPos.z=viewZ/viewPos.z;vec4 ao=vec4(0.);ao+=calculateSSR(8.,screenPos,normal,1.,0.1);ao.rgb=min(vec3(3.),ao.rgb);ao.rgb=max(vec3(0.),ao.rgb);if(currentFrameCount<2.){gl_FragColor=ao;return;}if(ao.a<0.01){gl_FragColor.rgb=lastAO.rgb;gl_FragColor.a=(((lastAO.a)*currentFrameCount)/(currentFrameCount+1.));}else{gl_FragColor=((ao+(lastAO)*currentFrameCount)/(currentFrameCount+1.));}\n#include <colorspace_fragment>\n}";
|
|
1106
|
+
// src/plugins/postprocessing/SSReflectionPlugin.ts
|
|
1107
|
+
var passId$1 = "ssrefl";
|
|
1108
|
+
var SSReflectionPlugin = class SSReflectionPlugin extends threepipe.PipelinePassPlugin {
|
|
1109
|
+
static {
|
|
1110
|
+
this.PluginType = "SSReflectionPlugin";
|
|
1111
|
+
}
|
|
1112
|
+
static {
|
|
1113
|
+
this.OldPluginType = "SSReflection";
|
|
1114
|
+
}
|
|
1115
|
+
constructor(inlineShaderRayTrace = true, bufferType = threepipe.UnsignedByteType, sizeMultiplier = 1, enabled = true) {
|
|
1116
|
+
super();
|
|
1117
|
+
this.inlineShaderRayTrace = inlineShaderRayTrace;
|
|
1118
|
+
this.passId = passId$1;
|
|
1119
|
+
this.dependencies = [threepipe.GBufferPlugin, threepipe.SSAAPlugin];
|
|
1120
|
+
this._gbufferUnpackExtension = void 0;
|
|
1121
|
+
this._gbufferUnpackExtensionChanged = () => {
|
|
1122
|
+
if (!this._pass || !this._viewer) throw new Error("SSReflectionPlugin: pass/viewer not created yet");
|
|
1123
|
+
const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
|
|
1124
|
+
if (this._gbufferUnpackExtension === newExtension) return;
|
|
1125
|
+
if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(void 0);
|
|
1126
|
+
this._gbufferUnpackExtension = newExtension;
|
|
1127
|
+
if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension);
|
|
1128
|
+
else this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed");
|
|
1129
|
+
};
|
|
1130
|
+
this._viewerListeners = {
|
|
1131
|
+
preRender: () => {
|
|
1132
|
+
if (!this._viewer || this.isDisabled()) return;
|
|
1133
|
+
if (!this._pass) return;
|
|
1134
|
+
const renderCamera = this._viewer.scene.renderCamera;
|
|
1135
|
+
this._pass.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(renderCamera.projectionMatrix, renderCamera.matrixWorldInverse);
|
|
1136
|
+
this._pass.uniforms.inverseViewMatrix.value.copy(renderCamera.matrixWorld);
|
|
1137
|
+
},
|
|
1138
|
+
postRender: () => {
|
|
1139
|
+
if (!this._viewer || this.isDisabled()) return;
|
|
1140
|
+
if (!this._pass) return;
|
|
1141
|
+
this._pass.uniforms.lastProjectionViewMatrix.value.copy(this._pass.uniforms.currentProjectionViewMatrix.value);
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
this.enabled = enabled;
|
|
1145
|
+
this.bufferType = bufferType;
|
|
1146
|
+
this.sizeMultiplier = sizeMultiplier;
|
|
1147
|
+
}
|
|
1148
|
+
_createTarget(recreate = true) {
|
|
1149
|
+
if (!this._viewer) return;
|
|
1150
|
+
if (recreate) this._disposeTarget();
|
|
1151
|
+
if (this.inlineShaderRayTrace) return;
|
|
1152
|
+
if (!this.target) this.target = this._viewer.renderManager.createTarget({
|
|
1153
|
+
depthBuffer: false,
|
|
1154
|
+
type: this.bufferType,
|
|
1155
|
+
sizeMultiplier: this.sizeMultiplier
|
|
1156
|
+
});
|
|
1157
|
+
this.texture = this.target.texture;
|
|
1158
|
+
this.texture.name = "ssreflBuffer";
|
|
1159
|
+
}
|
|
1160
|
+
_disposeTarget() {
|
|
1161
|
+
if (!this._viewer) return;
|
|
1162
|
+
if (this.target) {
|
|
1163
|
+
this._viewer.renderManager.disposeTarget(this.target);
|
|
1164
|
+
this.target = void 0;
|
|
1165
|
+
}
|
|
1166
|
+
this.texture = void 0;
|
|
1167
|
+
}
|
|
1168
|
+
_createPass() {
|
|
1169
|
+
if (!this._viewer) throw new Error("SSReflectionPlugin: viewer not set");
|
|
1170
|
+
if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");
|
|
1171
|
+
this._createTarget(true);
|
|
1172
|
+
return new SSReflectionPluginPass(this.passId, () => this.target, this.inlineShaderRayTrace);
|
|
1173
|
+
}
|
|
1174
|
+
onAdded(viewer) {
|
|
1175
|
+
super.onAdded(viewer);
|
|
1176
|
+
if (viewer.getPlugin("Ground") || viewer.getPlugin("BaseGroundPlugin")) console.warn("GroundPlugin must be added after SSReflectionPlugin");
|
|
1177
|
+
this._gbufferUnpackExtensionChanged();
|
|
1178
|
+
viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1179
|
+
viewer.forPlugin(VelocityBufferPlugin, (vbp) => {
|
|
1180
|
+
this._pass?.material.registerMaterialExtensions([vbp.unpackExtension]);
|
|
1181
|
+
}, (vbp) => {
|
|
1182
|
+
this._pass?.material?.unregisterMaterialExtensions([vbp.unpackExtension]);
|
|
1183
|
+
}, this);
|
|
1184
|
+
}
|
|
1185
|
+
onRemove(viewer) {
|
|
1186
|
+
this._disposeTarget();
|
|
1187
|
+
viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1188
|
+
return super.onRemove(viewer);
|
|
1189
|
+
}
|
|
1190
|
+
_beforeRender(_, _1, _2) {
|
|
1191
|
+
if (!this._viewer) return false;
|
|
1192
|
+
const e = super._beforeRender(_, _1, _2);
|
|
1193
|
+
if (!e) return e;
|
|
1194
|
+
const progressive = this._viewer.getPlugin(threepipe.ProgressivePlugin);
|
|
1195
|
+
this._pass?.updateShaderProperties([progressive]);
|
|
1196
|
+
return e;
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* @deprecated use {@link target} instead
|
|
1200
|
+
*/
|
|
1201
|
+
get ssrTarget() {
|
|
1202
|
+
console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead");
|
|
1203
|
+
return this.target;
|
|
1204
|
+
}
|
|
1205
|
+
fromJSON(data, meta) {
|
|
1206
|
+
if (data.passes?.ssr) {
|
|
1207
|
+
data = { ...data };
|
|
1208
|
+
data.pass = data.passes.ssr;
|
|
1209
|
+
delete data.passes;
|
|
1210
|
+
if (data.pass.enabled !== void 0) data.enabled = data.pass.enabled;
|
|
1211
|
+
}
|
|
1212
|
+
return super.fromJSON(data, meta);
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
__decorate([(0, threepipe.uiImage)("SSReflection Buffer", {
|
|
1216
|
+
readOnly: true,
|
|
1217
|
+
hideOnEmpty: true
|
|
1218
|
+
})], SSReflectionPlugin.prototype, "texture", void 0);
|
|
1219
|
+
__decorate([(0, threepipe.uiConfig)(void 0, { unwrapContents: true })], SSReflectionPlugin.prototype, "_pass", void 0);
|
|
1220
|
+
SSReflectionPlugin = __decorate([(0, threepipe.uiFolderContainer)("SSReflection Plugin")], SSReflectionPlugin);
|
|
1221
|
+
var SSReflectionPluginPass = class SSReflectionPluginPass extends threepipe.ExtendedShaderPass {
|
|
1222
|
+
setDirty() {
|
|
1223
|
+
this.materialExtension?.setDirty?.();
|
|
1224
|
+
super.setDirty();
|
|
1225
|
+
}
|
|
1226
|
+
constructor(pid, target, inlineShaderRayTrace = true) {
|
|
1227
|
+
super({
|
|
1228
|
+
defines: {
|
|
1229
|
+
["SSR_STEP_COUNT"]: 16,
|
|
1230
|
+
["SSR_RAY_COUNT"]: 4,
|
|
1231
|
+
["SSR_RAY_BLEND_MAX"]: 0,
|
|
1232
|
+
["SSR_LOW_QUALITY_FRAMES"]: 0,
|
|
1233
|
+
["SSR_INLINE"]: inlineShaderRayTrace ? "1" : "0",
|
|
1234
|
+
["SSR_MASK_FRONT_RAYS"]: true,
|
|
1235
|
+
["PERSPECTIVE_CAMERA"]: 1
|
|
1236
|
+
},
|
|
1237
|
+
uniforms: {
|
|
1238
|
+
tLastThis: { value: null },
|
|
1239
|
+
tLastFrame: { value: null },
|
|
1240
|
+
screenSize: { value: new threepipe.Vector2(0, 0) },
|
|
1241
|
+
currentFrameCount: { value: 0 },
|
|
1242
|
+
frameCount: { value: 0 },
|
|
1243
|
+
cameraNearFar: { value: new threepipe.Vector2(.1, 1e3) },
|
|
1244
|
+
cameraPositionWorld: { value: new threepipe.Vector3() },
|
|
1245
|
+
projection: { value: new threepipe.Matrix4() },
|
|
1246
|
+
opacity: { value: 1 },
|
|
1247
|
+
intensity: { value: 0 },
|
|
1248
|
+
boost: { value: new threepipe.Vector3(0, 0, 0) },
|
|
1249
|
+
objectRadius: { value: 0 },
|
|
1250
|
+
autoRadius: { value: false },
|
|
1251
|
+
power: { value: 0 },
|
|
1252
|
+
maskFrontFactor: { value: -.1 },
|
|
1253
|
+
tolerance: { value: 0 },
|
|
1254
|
+
ssrRoughnessFactor: { value: 1 },
|
|
1255
|
+
sceneBoundingRadius: { value: 0 },
|
|
1256
|
+
currentProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
1257
|
+
lastProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
1258
|
+
inverseViewMatrix: { value: new threepipe.Matrix4() },
|
|
1259
|
+
ssrSplitX: { value: .5 }
|
|
1260
|
+
},
|
|
1261
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
1262
|
+
fragmentShader: `
|
|
1263
|
+
varying vec2 vUv;
|
|
1264
|
+
|
|
1265
|
+
// for gbuffer
|
|
1266
|
+
#include <packing>
|
|
1267
|
+
#define THREE_PACKING_INCLUDED
|
|
1268
|
+
#include <cameraHelpers>
|
|
1269
|
+
#include <randomHelpers>
|
|
1270
|
+
${samplePointHelpers_default}
|
|
1271
|
+
|
|
1272
|
+
${ssrt_default}
|
|
1273
|
+
|
|
1274
|
+
${getShaders().ssReflection}
|
|
1275
|
+
|
|
1276
|
+
${ssreflectionMain_default}
|
|
1277
|
+
`
|
|
1278
|
+
}, "tDiffuse", "tLastThis", "tLastFrame");
|
|
1279
|
+
this.target = target;
|
|
1280
|
+
this.inlineShaderRayTrace = inlineShaderRayTrace;
|
|
1281
|
+
this.before = ["render"];
|
|
1282
|
+
this.after = ["gbuffer", "depth"];
|
|
1283
|
+
this.required = ["render", "progressive"];
|
|
1284
|
+
this.intensity = 1;
|
|
1285
|
+
this.boost = new threepipe.Vector3(1, 1, 1);
|
|
1286
|
+
this.objectRadius = 1;
|
|
1287
|
+
this.autoRadius = true;
|
|
1288
|
+
this.power = 1.1;
|
|
1289
|
+
this.tolerance = .5;
|
|
1290
|
+
this.roughnessFactor = 1;
|
|
1291
|
+
this.stepCount = 16;
|
|
1292
|
+
this.rayCount = 1;
|
|
1293
|
+
this.rayBlendMax = false;
|
|
1294
|
+
this.lowQualityFrames = 0;
|
|
1295
|
+
this.maskFrontRays = true;
|
|
1296
|
+
this.maskFrontFactor = -.2;
|
|
1297
|
+
this.split = 0;
|
|
1298
|
+
this.materialExtension = {
|
|
1299
|
+
extraUniforms: {
|
|
1300
|
+
tSSReflMap: () => ({ value: (0, threepipe.getOrCall)(this.target)?.texture ?? null }),
|
|
1301
|
+
ssrPower: this.material.uniforms.power,
|
|
1302
|
+
ssrIntensity: this.material.uniforms.intensity,
|
|
1303
|
+
ssrMaskFrontFactor: this.material.uniforms.maskFrontFactor,
|
|
1304
|
+
ssrBoost: this.material.uniforms.boost
|
|
1305
|
+
},
|
|
1306
|
+
extraDefines: {
|
|
1307
|
+
["SSR_STEP_COUNT"]: () => this.material.defines.SSR_STEP_COUNT,
|
|
1308
|
+
["SSR_RAY_COUNT"]: () => this.material.defines.SSR_RAY_COUNT,
|
|
1309
|
+
["SSR_RAY_BLEND_MAX"]: () => this.material.defines.SSR_RAY_BLEND_MAX,
|
|
1310
|
+
["SSR_LOW_QUALITY_FRAMES"]: () => this.material.defines.SSR_LOW_QUALITY_FRAMES,
|
|
1311
|
+
["SSR_INLINE"]: () => this.material.defines.SSR_INLINE,
|
|
1312
|
+
["SSR_MASK_FRONT_RAYS"]: () => this.material.defines.SSR_MASK_FRONT_RAYS,
|
|
1313
|
+
["PERSPECTIVE_CAMERA"]: () => this.material.defines.PERSPECTIVE_CAMERA
|
|
1314
|
+
},
|
|
1315
|
+
shaderExtender: (shader, _material, _renderer) => {
|
|
1316
|
+
if (!shader.defines?.SSREFL_ENABLED) return;
|
|
1317
|
+
const ls = `
|
|
1318
|
+
|
|
1319
|
+
${ssrPatch_default}
|
|
1320
|
+
|
|
1321
|
+
// reflectedLight.directDiffuse = vec3(0.);
|
|
1322
|
+
// reflectedLight.indirectDiffuse = vec3(0.);
|
|
1323
|
+
// reflectedLight.directSpecular = vec3(0.);
|
|
1324
|
+
// reflectedLight.indirectSpecular = vec3(0.);
|
|
1325
|
+
|
|
1326
|
+
`;
|
|
1327
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#glMarker beforeModulation", ls, { prepend: true });
|
|
1328
|
+
this._gbufferUnpackExtension?.shaderExtender?.(shader, _material, _renderer);
|
|
1329
|
+
},
|
|
1330
|
+
onObjectRender: (_object, material, renderer) => {
|
|
1331
|
+
let x = this.enabled && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.ssreflDisabled ? this.split > 0 ? 2 : 1 : 0;
|
|
1332
|
+
if (material.defines.SSREFL_ENABLED !== x) {
|
|
1333
|
+
material.defines.SSREFL_ENABLED = x;
|
|
1334
|
+
material.needsUpdate = true;
|
|
1335
|
+
}
|
|
1336
|
+
x = material.userData?.ssreflNonPhysical ? 1 : 0;
|
|
1337
|
+
if (material.defines.SSR_NON_PHYSICAL !== x) {
|
|
1338
|
+
material.defines.SSR_NON_PHYSICAL = x;
|
|
1339
|
+
material.needsUpdate = true;
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
parsFragmentSnippet: () => threepipe.glsl`
|
|
23
1343
|
#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0
|
|
24
1344
|
uniform float ssrPower;
|
|
25
1345
|
uniform float ssrIntensity;
|
|
@@ -27,14 +1347,765 @@
|
|
|
27
1347
|
uniform vec3 ssrBoost;
|
|
28
1348
|
uniform sampler2D tSSReflMap;
|
|
29
1349
|
uniform sampler2D tLastFrame;
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
${this.inlineShaderRayTrace
|
|
1350
|
+
${(0, threepipe.getTexelDecoding)("tSSReflMap", (0, threepipe.getOrCall)(this.target)?.texture.colorSpace)}
|
|
1351
|
+
${(0, threepipe.getTexelDecoding)("tLastFrame", this.material.uniforms.tLastFrame.value?.colorSpace)}
|
|
1352
|
+
${!this.inlineShaderRayTrace ? "" : `
|
|
1353
|
+
#define THREE_PACKING_INCLUDED // by threejs
|
|
1354
|
+
#include <cameraHelpers>
|
|
1355
|
+
#include <randomHelpers>
|
|
1356
|
+
${samplePointHelpers_default}
|
|
1357
|
+
${ssrt_default}
|
|
1358
|
+
${getShaders().ssReflection}
|
|
1359
|
+
`}
|
|
33
1360
|
#include <simpleCameraHelpers>
|
|
34
1361
|
#endif
|
|
35
|
-
`,
|
|
36
|
-
|
|
37
|
-
`,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}const i=e?e.getSelectedObjects?e.getSelectedObjects():[e.getSelectedObject()||null]:null;return i&&i.length>0?1===i.length?i[0]:i: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.warn("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`
|
|
1362
|
+
`,
|
|
1363
|
+
computeCacheKey: () => {
|
|
1364
|
+
return (this.enabled ? "1" : "0") + (0, threepipe.getOrCall)(this.target)?.texture?.colorSpace + Object.values(this.material.defines).map((v) => v + "").join(",");
|
|
1365
|
+
},
|
|
1366
|
+
uuid: SSReflectionPlugin.PluginType,
|
|
1367
|
+
...(0, threepipe.uiConfigMaterialExtension)(this._getUiConfig.bind(this), SSReflectionPlugin.PluginType),
|
|
1368
|
+
isCompatible: (material) => {
|
|
1369
|
+
return material.isPhysicalMaterial;
|
|
1370
|
+
}
|
|
1371
|
+
};
|
|
1372
|
+
this.passId = pid;
|
|
1373
|
+
this.needsSwap = false;
|
|
1374
|
+
this.clear = true;
|
|
1375
|
+
if (inlineShaderRayTrace) Object.assign(this.materialExtension.extraUniforms, {
|
|
1376
|
+
tNormalDepth: this.material.uniforms.tNormalDepth,
|
|
1377
|
+
tLastFrame: this.material.uniforms.tLastFrame,
|
|
1378
|
+
objectRadius: this.material.uniforms.objectRadius,
|
|
1379
|
+
autoRadius: this.material.uniforms.autoRadius,
|
|
1380
|
+
tolerance: this.material.uniforms.tolerance,
|
|
1381
|
+
ssrRoughnessFactor: this.material.uniforms.ssrRoughnessFactor,
|
|
1382
|
+
frameCount: this.material.uniforms.frameCount,
|
|
1383
|
+
currentFrameCount: this.material.uniforms.currentFrameCount,
|
|
1384
|
+
projection: this.material.uniforms.projection,
|
|
1385
|
+
cameraPositionWorld: this.material.uniforms.cameraPositionWorld,
|
|
1386
|
+
cameraNearFar: this.material.uniforms.cameraNearFar,
|
|
1387
|
+
sceneBoundingRadius: this.material.uniforms.sceneBoundingRadius,
|
|
1388
|
+
currentProjectionViewMatrix: this.material.uniforms.currentProjectionViewMatrix,
|
|
1389
|
+
lastProjectionViewMatrix: this.material.uniforms.lastProjectionViewMatrix,
|
|
1390
|
+
inverseViewMatrix: this.material.uniforms.inverseViewMatrix,
|
|
1391
|
+
ssrSplitX: this.material.uniforms.ssrSplitX
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
1395
|
+
if (!this.enabled) return;
|
|
1396
|
+
if (this.inlineShaderRayTrace) {
|
|
1397
|
+
this.needsSwap = false;
|
|
1398
|
+
return;
|
|
1399
|
+
}
|
|
1400
|
+
const target = (0, threepipe.getOrCall)(this.target);
|
|
1401
|
+
if (!target) {
|
|
1402
|
+
console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false");
|
|
1403
|
+
return;
|
|
1404
|
+
}
|
|
1405
|
+
if (!this.material.defines.HAS_GBUFFER) console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl");
|
|
1406
|
+
renderer.renderManager.blit(writeBuffer, { source: target.texture });
|
|
1407
|
+
this.uniforms.tLastThis.value = writeBuffer.texture;
|
|
1408
|
+
super.render(renderer, target, readBuffer, deltaTime, maskActive);
|
|
1409
|
+
this.needsSwap = false;
|
|
1410
|
+
}
|
|
1411
|
+
beforeRender(scene, camera, renderManager) {
|
|
1412
|
+
if (!this.enabled) return;
|
|
1413
|
+
this.updateShaderProperties([
|
|
1414
|
+
scene,
|
|
1415
|
+
camera,
|
|
1416
|
+
renderManager
|
|
1417
|
+
]);
|
|
1418
|
+
}
|
|
1419
|
+
/**
|
|
1420
|
+
* Returns a uiConfig to toggle SSReflection on a material.
|
|
1421
|
+
* This uiConfig is added to each material by extension
|
|
1422
|
+
* @param material
|
|
1423
|
+
* @private
|
|
1424
|
+
*/
|
|
1425
|
+
_getUiConfig(material) {
|
|
1426
|
+
return {
|
|
1427
|
+
type: "folder",
|
|
1428
|
+
label: "SSReflection",
|
|
1429
|
+
children: [{
|
|
1430
|
+
type: "checkbox",
|
|
1431
|
+
label: "Enabled",
|
|
1432
|
+
get value() {
|
|
1433
|
+
return !(material.userData.ssreflDisabled ?? false);
|
|
1434
|
+
},
|
|
1435
|
+
set value(v) {
|
|
1436
|
+
if (v === !(material.userData.ssreflDisabled ?? false)) return;
|
|
1437
|
+
material.userData.ssreflDisabled = !v;
|
|
1438
|
+
material.setDirty();
|
|
1439
|
+
},
|
|
1440
|
+
onChange: this.setDirty
|
|
1441
|
+
}, {
|
|
1442
|
+
type: "checkbox",
|
|
1443
|
+
label: "Non Physical",
|
|
1444
|
+
get value() {
|
|
1445
|
+
return material.userData.ssreflNonPhysical ?? false;
|
|
1446
|
+
},
|
|
1447
|
+
set value(v) {
|
|
1448
|
+
if (v === (material.userData.ssreflNonPhysical ?? false)) return;
|
|
1449
|
+
material.userData.ssreflNonPhysical = v;
|
|
1450
|
+
material.setDirty();
|
|
1451
|
+
},
|
|
1452
|
+
onChange: this.setDirty
|
|
1453
|
+
}]
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
set uniformsNeedUpdate(value) {
|
|
1457
|
+
this.material.uniformsNeedUpdate = value;
|
|
1458
|
+
this.setDirty();
|
|
1459
|
+
}
|
|
1460
|
+
setGBufferUnpackExtension(extension) {
|
|
1461
|
+
if (this._gbufferUnpackExtension === extension) return;
|
|
1462
|
+
if (this._gbufferUnpackExtension) this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
|
|
1463
|
+
this._gbufferUnpackExtension = extension;
|
|
1464
|
+
if (this._gbufferUnpackExtension) this.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
|
|
1465
|
+
if (!this._gbufferUnpackExtension) return;
|
|
1466
|
+
Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms);
|
|
1467
|
+
Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines);
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
__decorate([
|
|
1471
|
+
(0, threepipe.uiSlider)("Intensity", [0, 4]),
|
|
1472
|
+
(0, threepipe.serialize)(),
|
|
1473
|
+
(0, threepipe.uniform)()
|
|
1474
|
+
], SSReflectionPluginPass.prototype, "intensity", void 0);
|
|
1475
|
+
__decorate([
|
|
1476
|
+
(0, threepipe.uiVector)("Boost"),
|
|
1477
|
+
(0, threepipe.serialize)(),
|
|
1478
|
+
(0, threepipe.uniform)()
|
|
1479
|
+
], SSReflectionPluginPass.prototype, "boost", void 0);
|
|
1480
|
+
__decorate([
|
|
1481
|
+
(0, threepipe.uiSlider)("Object Radius", [.01, 2]),
|
|
1482
|
+
(0, threepipe.serialize)(),
|
|
1483
|
+
(0, threepipe.uniform)()
|
|
1484
|
+
], SSReflectionPluginPass.prototype, "objectRadius", void 0);
|
|
1485
|
+
__decorate([
|
|
1486
|
+
(0, threepipe.uiToggle)("Auto radius"),
|
|
1487
|
+
(0, threepipe.serialize)(),
|
|
1488
|
+
(0, threepipe.uniform)()
|
|
1489
|
+
], SSReflectionPluginPass.prototype, "autoRadius", void 0);
|
|
1490
|
+
__decorate([
|
|
1491
|
+
(0, threepipe.uiSlider)("Power", [0, 3]),
|
|
1492
|
+
(0, threepipe.serialize)(),
|
|
1493
|
+
(0, threepipe.uniform)()
|
|
1494
|
+
], SSReflectionPluginPass.prototype, "power", void 0);
|
|
1495
|
+
__decorate([
|
|
1496
|
+
(0, threepipe.uiSlider)("Tolerance", [.1, 5]),
|
|
1497
|
+
(0, threepipe.serialize)(),
|
|
1498
|
+
(0, threepipe.uniform)()
|
|
1499
|
+
], SSReflectionPluginPass.prototype, "tolerance", void 0);
|
|
1500
|
+
__decorate([
|
|
1501
|
+
(0, threepipe.uiSlider)("Roughness Factor", [.1, 1.25]),
|
|
1502
|
+
(0, threepipe.serialize)(),
|
|
1503
|
+
(0, threepipe.uniform)({ propKey: "ssrRoughnessFactor" })
|
|
1504
|
+
], SSReflectionPluginPass.prototype, "roughnessFactor", void 0);
|
|
1505
|
+
__decorate([
|
|
1506
|
+
(0, threepipe.uiSlider)("Step count", [1, 32], 1, { tags: ["performance"] }),
|
|
1507
|
+
(0, threepipe.serialize)(),
|
|
1508
|
+
(0, threepipe.matDefine)("SSR_STEP_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
|
|
1509
|
+
], SSReflectionPluginPass.prototype, "stepCount", void 0);
|
|
1510
|
+
__decorate([
|
|
1511
|
+
(0, threepipe.uiSlider)("Ray count", [1, 8], 1, { tags: ["performance"] }),
|
|
1512
|
+
(0, threepipe.serialize)(),
|
|
1513
|
+
(0, threepipe.matDefine)("SSR_RAY_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
|
|
1514
|
+
], SSReflectionPluginPass.prototype, "rayCount", void 0);
|
|
1515
|
+
__decorate([
|
|
1516
|
+
(0, threepipe.uiToggle)("Ray Blend MAX"),
|
|
1517
|
+
(0, threepipe.serialize)(),
|
|
1518
|
+
(0, threepipe.matDefineBool)("SSR_RAY_BLEND_MAX", void 0, void 0, SSReflectionPluginPass.prototype.setDirty, true)
|
|
1519
|
+
], SSReflectionPluginPass.prototype, "rayBlendMax", void 0);
|
|
1520
|
+
__decorate([
|
|
1521
|
+
(0, threepipe.uiSlider)("Low Quality Frames", [0, 4], 1),
|
|
1522
|
+
(0, threepipe.serialize)(),
|
|
1523
|
+
(0, threepipe.matDefine)("SSR_LOW_QUALITY_FRAMES", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
|
|
1524
|
+
], SSReflectionPluginPass.prototype, "lowQualityFrames", void 0);
|
|
1525
|
+
__decorate([
|
|
1526
|
+
(0, threepipe.uiToggle)("Ignore front rays"),
|
|
1527
|
+
(0, threepipe.serialize)(),
|
|
1528
|
+
(0, threepipe.matDefineBool)("SSR_MASK_FRONT_RAYS", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
|
|
1529
|
+
], SSReflectionPluginPass.prototype, "maskFrontRays", void 0);
|
|
1530
|
+
__decorate([
|
|
1531
|
+
(0, threepipe.uiSlider)("Mask front rays factor", [-1, 1], .01, (that) => ({ hidden: () => !that.maskFrontRays })),
|
|
1532
|
+
(0, threepipe.serialize)(),
|
|
1533
|
+
(0, threepipe.uniform)()
|
|
1534
|
+
], SSReflectionPluginPass.prototype, "maskFrontFactor", void 0);
|
|
1535
|
+
__decorate([
|
|
1536
|
+
(0, threepipe.uiSlider)("Split", [0, 1], .01, { tags: ["debug"] }),
|
|
1537
|
+
(0, threepipe.serialize)(),
|
|
1538
|
+
(0, threepipe.uniform)({
|
|
1539
|
+
propKey: "ssrSplitX",
|
|
1540
|
+
onChange: SSReflectionPluginPass.prototype.setDirty
|
|
1541
|
+
})
|
|
1542
|
+
], SSReflectionPluginPass.prototype, "split", void 0);
|
|
1543
|
+
SSReflectionPluginPass = __decorate([(0, threepipe.uiFolderContainer)("SSReflection Pass")], SSReflectionPluginPass);
|
|
1544
|
+
// src/plugins/postprocessing/shaders/outline.glsl
|
|
1545
|
+
var outline_default = "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);}";
|
|
1546
|
+
// src/plugins/postprocessing/shaders/outlineDepthVert.glsl
|
|
1547
|
+
var outlineDepthVert_default = "#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;}";
|
|
1548
|
+
// src/plugins/postprocessing/shaders/outlineDepthFrag.glsl
|
|
1549
|
+
var outlineDepthFrag_default = "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.);}";
|
|
1550
|
+
// src/plugins/postprocessing/OutlinePlugin.ts
|
|
1551
|
+
var OutlinePlugin = class OutlinePlugin extends threepipe.AScreenPassExtensionPlugin {
|
|
1552
|
+
static {
|
|
1553
|
+
this.PluginType = "OutlinePlugin";
|
|
1554
|
+
}
|
|
1555
|
+
static {
|
|
1556
|
+
this.OldPluginType = "Outline";
|
|
1557
|
+
}
|
|
1558
|
+
constructor(enabled = true, bufferType = threepipe.UnsignedByteType) {
|
|
1559
|
+
super();
|
|
1560
|
+
this.passId = "outline";
|
|
1561
|
+
this.extraUniforms = {
|
|
1562
|
+
outlineIntensity: { value: 1 },
|
|
1563
|
+
outlineThickness: { value: 2 },
|
|
1564
|
+
highlightTransparency: { value: 1 },
|
|
1565
|
+
outlineColor: { value: new threepipe.Color(15305317) },
|
|
1566
|
+
enableHighlight: { value: true },
|
|
1567
|
+
dpr: { value: 1 },
|
|
1568
|
+
outlineBuffer: { value: null },
|
|
1569
|
+
tDiffuseSize: { value: new threepipe.Vector2(1024, 1024) }
|
|
1570
|
+
};
|
|
1571
|
+
this.extraDefines = { ["DEBUG_OUTLINE"]: "0" };
|
|
1572
|
+
this.priority = -101;
|
|
1573
|
+
this.enableHighlight = false;
|
|
1574
|
+
this.enableDynamicSelection = true;
|
|
1575
|
+
this.intensity = 2;
|
|
1576
|
+
this.highlightTransparency = .84;
|
|
1577
|
+
this.color = new threepipe.Color(15305317);
|
|
1578
|
+
this.thickness = 2;
|
|
1579
|
+
this.debugOutline = false;
|
|
1580
|
+
this.highlightSelectedMaterials = false;
|
|
1581
|
+
this.highlightMaterialSameNames = false;
|
|
1582
|
+
this.transparency = 0;
|
|
1583
|
+
this.parsFragmentSnippet = () => {
|
|
1584
|
+
if (this.isDisabled()) return "";
|
|
1585
|
+
return threepipe.glsl`
|
|
1586
|
+
${outline_default}
|
|
1587
|
+
`;
|
|
1588
|
+
};
|
|
1589
|
+
this._shaderPatch = "diffuseColor = outline(diffuseColor);";
|
|
1590
|
+
this.dependencies = [threepipe.PickingPlugin, threepipe.GBufferPlugin];
|
|
1591
|
+
this._pickingWidgetDisabled = false;
|
|
1592
|
+
this.material = new threepipe.ShaderMaterial({
|
|
1593
|
+
uniforms: { "cameraNearFar": { value: new threepipe.Vector2(.1, 100) } },
|
|
1594
|
+
vertexShader: outlineDepthVert_default,
|
|
1595
|
+
fragmentShader: outlineDepthFrag_default,
|
|
1596
|
+
side: threepipe.DoubleSide
|
|
1597
|
+
});
|
|
1598
|
+
this._getSelectedObject = () => {
|
|
1599
|
+
if (!this._viewer) return null;
|
|
1600
|
+
const picking = this._viewer.getPlugin(threepipe.PickingPlugin);
|
|
1601
|
+
if (this.highlightSelectedMaterials) {
|
|
1602
|
+
const mat = picking?.getSelectedObject()?.material || null;
|
|
1603
|
+
if (this.highlightMaterialSameNames && mat) {
|
|
1604
|
+
const names = Array.isArray(mat) ? mat.map((m) => m.name) : [mat.name];
|
|
1605
|
+
const mats = /* @__PURE__ */ new Set();
|
|
1606
|
+
for (const name of names) (this._viewer?.assetManager?.materials?.findMaterialsByName(name))?.forEach((m) => mats.add(m));
|
|
1607
|
+
return [...mats];
|
|
1608
|
+
}
|
|
1609
|
+
return mat;
|
|
1610
|
+
}
|
|
1611
|
+
const objects = picking ? picking.getSelectedObjects ? picking.getSelectedObjects() : [picking.getSelectedObject() || null] : null;
|
|
1612
|
+
return objects && objects.length > 0 ? objects.length === 1 ? objects[0] : objects : null;
|
|
1613
|
+
};
|
|
1614
|
+
this._viewerListeners = { preRender: () => {
|
|
1615
|
+
if (this.isDisabled() || !this._viewer) return;
|
|
1616
|
+
this.extraUniforms.dpr.value = this._viewer.renderManager.renderScale * 2;
|
|
1617
|
+
} };
|
|
1618
|
+
this.mouseInOutAnimationEnabled = true;
|
|
1619
|
+
this._state = "in";
|
|
1620
|
+
this.enabled = enabled;
|
|
1621
|
+
this.bufferType = bufferType;
|
|
1622
|
+
}
|
|
1623
|
+
setDirty() {
|
|
1624
|
+
super.setDirty();
|
|
1625
|
+
if (!this._viewer) return;
|
|
1626
|
+
const picking = this._viewer.getPlugin(threepipe.PickingPlugin);
|
|
1627
|
+
let enabled = !this.isDisabled();
|
|
1628
|
+
if (enabled) {
|
|
1629
|
+
const selected = picking?.getSelectedObject();
|
|
1630
|
+
if (typeof selected?.type === "string" && selected?.type?.includes("Line")) enabled = false;
|
|
1631
|
+
}
|
|
1632
|
+
if (picking) {
|
|
1633
|
+
if (enabled && picking.widgetEnabled) {
|
|
1634
|
+
picking.widgetEnabled = false;
|
|
1635
|
+
this._pickingWidgetDisabled = true;
|
|
1636
|
+
} else if (!enabled && this._pickingWidgetDisabled) {
|
|
1637
|
+
picking.widgetEnabled = true;
|
|
1638
|
+
this._pickingWidgetDisabled = false;
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
this._viewer.setDirty();
|
|
1642
|
+
}
|
|
1643
|
+
onAdded(viewer) {
|
|
1644
|
+
super.onAdded(viewer);
|
|
1645
|
+
this.setDirty();
|
|
1646
|
+
this._pass = this._createPass();
|
|
1647
|
+
this._pass.onDirty?.push(viewer.setDirty);
|
|
1648
|
+
viewer.renderManager.registerPass(this._pass);
|
|
1649
|
+
const pickingPlugin = viewer.getPlugin(threepipe.PickingPlugin);
|
|
1650
|
+
pickingPlugin?.addEventListener("selectedObjectChanged", () => {
|
|
1651
|
+
if (!this._animationCallBack && this) {
|
|
1652
|
+
if (pickingPlugin?.getSelectedObject()) {
|
|
1653
|
+
if (this.enableDynamicSelection) {
|
|
1654
|
+
this.transparency = 1;
|
|
1655
|
+
this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 400);
|
|
1656
|
+
} else this.transparency = this.highlightTransparency;
|
|
1657
|
+
} else this.transparency = 1;
|
|
1658
|
+
}
|
|
1659
|
+
});
|
|
1660
|
+
document.addEventListener("mousemove", (e) => {
|
|
1661
|
+
if (!this) return;
|
|
1662
|
+
if (!this.mouseInOutAnimationEnabled) return;
|
|
1663
|
+
if (!this.enableHighlight) return;
|
|
1664
|
+
const selectedObject = pickingPlugin?.getSelectedObject();
|
|
1665
|
+
if (selectedObject && this.enableDynamicSelection) {
|
|
1666
|
+
if (e.target !== viewer.canvas) {
|
|
1667
|
+
if (!this._animationCallBack && this._state === "in") {
|
|
1668
|
+
this._animationCallBack = this._startTransparencyAnimation(this.highlightTransparency, 1, 600);
|
|
1669
|
+
this._state = "out";
|
|
1670
|
+
}
|
|
1671
|
+
} else if (!this._animationCallBack && this._state === "out") {
|
|
1672
|
+
this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 600);
|
|
1673
|
+
this._state = "in";
|
|
1674
|
+
}
|
|
1675
|
+
} else this.transparency = selectedObject ? this.highlightTransparency : 1;
|
|
1676
|
+
});
|
|
1677
|
+
}
|
|
1678
|
+
onRemove(viewer) {
|
|
1679
|
+
this._disposeTarget();
|
|
1680
|
+
if (this._pass) {
|
|
1681
|
+
viewer.renderManager.unregisterPass(this._pass);
|
|
1682
|
+
if (this._pass.dispose) this._pass.dispose();
|
|
1683
|
+
}
|
|
1684
|
+
this._pass = void 0;
|
|
1685
|
+
return super.onRemove(viewer);
|
|
1686
|
+
}
|
|
1687
|
+
_createTarget(recreate = true) {
|
|
1688
|
+
if (!this._viewer) return;
|
|
1689
|
+
if (recreate) this._disposeTarget();
|
|
1690
|
+
if (!this.target) this.target = this._viewer.renderManager.createTarget({
|
|
1691
|
+
sizeMultiplier: 1,
|
|
1692
|
+
type: this.bufferType
|
|
1693
|
+
});
|
|
1694
|
+
this.texture = this.target.texture;
|
|
1695
|
+
this.texture.name = "normalBuffer";
|
|
1696
|
+
}
|
|
1697
|
+
_disposeTarget() {
|
|
1698
|
+
if (!this._viewer) return;
|
|
1699
|
+
if (this.target) {
|
|
1700
|
+
this._viewer.renderManager.disposeTarget(this.target);
|
|
1701
|
+
this.target = void 0;
|
|
1702
|
+
}
|
|
1703
|
+
this.texture = void 0;
|
|
1704
|
+
}
|
|
1705
|
+
_createPass() {
|
|
1706
|
+
this._createTarget(true);
|
|
1707
|
+
if (!this.target) throw new Error("OutlinePlugin: target not created");
|
|
1708
|
+
this.material.userData.isOutlinePluginMaterial = true;
|
|
1709
|
+
return new OutlineRenderPass(this.passId, this._getSelectedObject, () => this.target, this.material);
|
|
1710
|
+
}
|
|
1711
|
+
async _startTransparencyAnimation(from, to, duration) {
|
|
1712
|
+
return (0, threepipe.animateTarget)(this, "transparency", {
|
|
1713
|
+
from,
|
|
1714
|
+
to,
|
|
1715
|
+
duration,
|
|
1716
|
+
onComplete: () => {
|
|
1717
|
+
this._animationCallBack = void 0;
|
|
1718
|
+
}
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1721
|
+
get outlineIntensity() {
|
|
1722
|
+
console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
|
|
1723
|
+
return this.intensity;
|
|
1724
|
+
}
|
|
1725
|
+
set outlineIntensity(v) {
|
|
1726
|
+
console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
|
|
1727
|
+
this.intensity = v;
|
|
1728
|
+
}
|
|
1729
|
+
get outlineColor() {
|
|
1730
|
+
console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
|
|
1731
|
+
return this.intensity;
|
|
1732
|
+
}
|
|
1733
|
+
set outlineColor(v) {
|
|
1734
|
+
console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
|
|
1735
|
+
this.intensity = v;
|
|
1736
|
+
}
|
|
1737
|
+
};
|
|
1738
|
+
__decorate([
|
|
1739
|
+
(0, threepipe.onChange)(OutlinePlugin.prototype.setDirty),
|
|
1740
|
+
(0, threepipe.uiToggle)("Enable"),
|
|
1741
|
+
(0, threepipe.serialize)()
|
|
1742
|
+
], OutlinePlugin.prototype, "enabled", void 0);
|
|
1743
|
+
__decorate([
|
|
1744
|
+
(0, threepipe.uiToggle)("Highlight"),
|
|
1745
|
+
(0, threepipe.uniform)({ propKey: "enableHighlight" }),
|
|
1746
|
+
(0, threepipe.serialize)()
|
|
1747
|
+
], OutlinePlugin.prototype, "enableHighlight", void 0);
|
|
1748
|
+
__decorate([
|
|
1749
|
+
(0, threepipe.onChange)(OutlinePlugin.prototype.setDirty),
|
|
1750
|
+
(0, threepipe.uiToggle)("DynamicSelection"),
|
|
1751
|
+
(0, threepipe.serialize)()
|
|
1752
|
+
], OutlinePlugin.prototype, "enableDynamicSelection", void 0);
|
|
1753
|
+
__decorate([
|
|
1754
|
+
(0, threepipe.uiSlider)("Intensity", [0, 4], .001),
|
|
1755
|
+
(0, threepipe.uniform)({ propKey: "outlineIntensity" }),
|
|
1756
|
+
(0, threepipe.serialize)("outlineIntensity")
|
|
1757
|
+
], OutlinePlugin.prototype, "intensity", void 0);
|
|
1758
|
+
__decorate([
|
|
1759
|
+
(0, threepipe.onChange)(OutlinePlugin.prototype.setDirty),
|
|
1760
|
+
(0, threepipe.uiSlider)("Transparency", [0, 1], .01),
|
|
1761
|
+
(0, threepipe.serialize)()
|
|
1762
|
+
], OutlinePlugin.prototype, "highlightTransparency", void 0);
|
|
1763
|
+
__decorate([
|
|
1764
|
+
(0, threepipe.uiColor)("Color"),
|
|
1765
|
+
(0, threepipe.uniform)({ propKey: "outlineColor" }),
|
|
1766
|
+
(0, threepipe.serialize)("outlineColor")
|
|
1767
|
+
], OutlinePlugin.prototype, "color", void 0);
|
|
1768
|
+
__decorate([
|
|
1769
|
+
(0, threepipe.uiSlider)("Thickness", [0, 10], .01),
|
|
1770
|
+
(0, threepipe.uniform)({ propKey: "outlineThickness" }),
|
|
1771
|
+
(0, threepipe.serialize)("outlineThickness")
|
|
1772
|
+
], OutlinePlugin.prototype, "thickness", void 0);
|
|
1773
|
+
__decorate([(0, threepipe.uiToggle)("Debug"), (0, threepipe.matDefineBool)("DEBUG_OUTLINE", void 0, true)], OutlinePlugin.prototype, "debugOutline", void 0);
|
|
1774
|
+
__decorate([(0, threepipe.onChange)(OutlinePlugin.prototype.setDirty), (0, threepipe.uiToggle)("Highlight Selected Materials")], OutlinePlugin.prototype, "highlightSelectedMaterials", void 0);
|
|
1775
|
+
__decorate([(0, threepipe.onChange)(OutlinePlugin.prototype.setDirty), (0, threepipe.uiToggle)("Highlight Materials (same name)")], OutlinePlugin.prototype, "highlightMaterialSameNames", void 0);
|
|
1776
|
+
__decorate([(0, threepipe.uniform)({ propKey: "highlightTransparency" })], OutlinePlugin.prototype, "transparency", void 0);
|
|
1777
|
+
__decorate([(0, threepipe.uniform)({ propKey: "outlineBuffer" }), (0, threepipe.uiImage)("Outline Buffer", { readOnly: true })], OutlinePlugin.prototype, "texture", void 0);
|
|
1778
|
+
OutlinePlugin = __decorate([(0, threepipe.uiFolderContainer)("Selection Outline")], OutlinePlugin);
|
|
1779
|
+
var OutlineRenderPass = class OutlineRenderPass extends threepipe.RenderPass {
|
|
1780
|
+
constructor(passId, _getSelectedObjectOrMaterial, target, overrideMaterial) {
|
|
1781
|
+
super(void 0, void 0, overrideMaterial, new threepipe.Color(1, 1, 1), 1);
|
|
1782
|
+
this.passId = passId;
|
|
1783
|
+
this._getSelectedObjectOrMaterial = _getSelectedObjectOrMaterial;
|
|
1784
|
+
this.target = target;
|
|
1785
|
+
this.isOutlineRenderPass = true;
|
|
1786
|
+
this.enabled = true;
|
|
1787
|
+
this.before = ["render"];
|
|
1788
|
+
this.after = ["gbuffer"];
|
|
1789
|
+
this.required = ["render", "gbuffer"];
|
|
1790
|
+
this.onDirty = [];
|
|
1791
|
+
}
|
|
1792
|
+
/**
|
|
1793
|
+
* Renders to {@link target}
|
|
1794
|
+
* @param renderer
|
|
1795
|
+
* @param writeBuffer - this is ignored? or used as transmissionRenderTarget?
|
|
1796
|
+
* @param _1 - this is ignored
|
|
1797
|
+
* @param deltaTime
|
|
1798
|
+
* @param maskActive
|
|
1799
|
+
*/
|
|
1800
|
+
render(renderer, writeBuffer, _1, deltaTime, maskActive) {
|
|
1801
|
+
if (!this.scene || !this.camera || !this.enabled) return;
|
|
1802
|
+
const t = renderer.getRenderTarget();
|
|
1803
|
+
const activeCubeFace = renderer.getActiveCubeFace();
|
|
1804
|
+
const activeMipLevel = renderer.getActiveMipmapLevel();
|
|
1805
|
+
const selectedObject = this._getSelectedObjectOrMaterial();
|
|
1806
|
+
if (selectedObject) this._renderSelectedObject(renderer, selectedObject, writeBuffer || null, deltaTime, maskActive);
|
|
1807
|
+
else {
|
|
1808
|
+
renderer.setRenderTarget((0, threepipe.getOrCall)(this.target) || null);
|
|
1809
|
+
const color = new threepipe.Color();
|
|
1810
|
+
renderer.getClearColor(color);
|
|
1811
|
+
renderer.setClearColor(new threepipe.Color(16777215));
|
|
1812
|
+
renderer.clear(true, true);
|
|
1813
|
+
renderer.setClearColor(color);
|
|
1814
|
+
}
|
|
1815
|
+
renderer.setRenderTarget(t, activeCubeFace, activeMipLevel);
|
|
1816
|
+
}
|
|
1817
|
+
_renderSelectedObject(renderer, selectedObject, writeBuffer, deltaTime, maskActive) {
|
|
1818
|
+
if (!this.camera || !selectedObject) return;
|
|
1819
|
+
const selectionLayer = 6;
|
|
1820
|
+
const objs = (Array.isArray(selectedObject) ? selectedObject : [selectedObject]).flatMap((o) => o?.isTexture ? [...o.appliedObjects?.values() || []] : o).flatMap((o) => o?.isMaterial ? [...o.appliedMeshes?.values() || []] : o?.isBufferGeometry ? [...o.appliedMeshes?.values() || []] : o);
|
|
1821
|
+
for (const o1 of objs) o1 && o1.traverse((o) => {
|
|
1822
|
+
o.layers.enable(selectionLayer);
|
|
1823
|
+
});
|
|
1824
|
+
const mask = this.camera.layers.mask;
|
|
1825
|
+
this.camera.layers.set(selectionLayer);
|
|
1826
|
+
const ud = renderer.userData;
|
|
1827
|
+
if (!ud) console.error("threejs is not patched?");
|
|
1828
|
+
ud.transmissionRenderTarget = writeBuffer;
|
|
1829
|
+
renderer.renderWithModes({
|
|
1830
|
+
shadowMapRender: false,
|
|
1831
|
+
backgroundRender: false,
|
|
1832
|
+
opaqueRender: true,
|
|
1833
|
+
transparentRender: true,
|
|
1834
|
+
transmissionRender: true,
|
|
1835
|
+
mainRenderPass: false
|
|
1836
|
+
}, () => super.render(renderer, writeBuffer, (0, threepipe.getOrCall)(this.target), deltaTime, maskActive));
|
|
1837
|
+
ud.transmissionRenderTarget = void 0;
|
|
1838
|
+
objs.forEach((o1) => o1.traverse((o) => {
|
|
1839
|
+
o.layers.disable(selectionLayer);
|
|
1840
|
+
}));
|
|
1841
|
+
this.camera.layers.mask = mask;
|
|
1842
|
+
}
|
|
1843
|
+
dispose() {
|
|
1844
|
+
this.onDirty = [];
|
|
1845
|
+
this.scene = void 0;
|
|
1846
|
+
this.camera = void 0;
|
|
1847
|
+
super.dispose?.();
|
|
1848
|
+
}
|
|
1849
|
+
setDirty() {
|
|
1850
|
+
this.onDirty.forEach((v) => v());
|
|
1851
|
+
}
|
|
1852
|
+
beforeRender(scene, camera, _) {
|
|
1853
|
+
this.scene = scene;
|
|
1854
|
+
this.camera = camera;
|
|
1855
|
+
camera.updateShaderProperties(this.overrideMaterial);
|
|
1856
|
+
}
|
|
1857
|
+
};
|
|
1858
|
+
__decorate([(0, threepipe.uiToggle)("Enabled")], OutlineRenderPass.prototype, "enabled", void 0);
|
|
1859
|
+
OutlineRenderPass = __decorate([(0, threepipe.uiFolderContainer)((c) => c.passId + " Render Pass")], OutlineRenderPass);
|
|
1860
|
+
// src/plugins/postprocessing/shaders/giPatch.glsl
|
|
1861
|
+
var giPatch_default = "\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";
|
|
1862
|
+
// src/passes/shaders/ssaoBilateral.glsl
|
|
1863
|
+
var ssaoBilateral_default = "uniform 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;}";
|
|
1864
|
+
// src/passes/BilateralFilterPass.ts
|
|
1865
|
+
var BilateralFilterPass = class extends threepipe.ExtendedShaderPass {
|
|
1866
|
+
constructor(target, sourceAccessor = "rgba") {
|
|
1867
|
+
super({
|
|
1868
|
+
vertexShader: threepipe.CopyShader.vertexShader,
|
|
1869
|
+
fragmentShader: `
|
|
1870
|
+
// for gbuffer
|
|
1871
|
+
#include <packing>
|
|
1872
|
+
#define THREE_PACKING_INCLUDED
|
|
1873
|
+
` + ssaoBilateral_default,
|
|
1874
|
+
uniforms: {
|
|
1875
|
+
bilDirection: { value: new threepipe.Vector2(1, 0) },
|
|
1876
|
+
tDiffuse: { value: null },
|
|
1877
|
+
tDiffuseSize: { value: new threepipe.Vector2() }
|
|
1878
|
+
},
|
|
1879
|
+
defines: { ["B_SRC_ACCESSOR"]: sourceAccessor }
|
|
1880
|
+
}, "tDiffuse");
|
|
1881
|
+
this.target = target;
|
|
1882
|
+
this.smoothEnabled = true;
|
|
1883
|
+
this.edgeSharpness = .1;
|
|
1884
|
+
this.clear = false;
|
|
1885
|
+
this.needsSwap = false;
|
|
1886
|
+
}
|
|
1887
|
+
render(renderer, writeBuffer, _readBuffer, deltaTime, maskActive) {
|
|
1888
|
+
if (!this.enabled) return;
|
|
1889
|
+
const target = (0, threepipe.getOrCall)(this.target);
|
|
1890
|
+
if (!target) return;
|
|
1891
|
+
this.uniforms.bilDirection.value.set(1, 0);
|
|
1892
|
+
this.uniforms.tDiffuse.value = target.texture;
|
|
1893
|
+
this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width || 0, this.uniforms.tDiffuse.value?.image.height || 0);
|
|
1894
|
+
super.render(renderer, writeBuffer, target, deltaTime, maskActive);
|
|
1895
|
+
this.uniforms.bilDirection.value.set(0, 1);
|
|
1896
|
+
this.uniforms.tDiffuse.value = writeBuffer.texture;
|
|
1897
|
+
this.uniforms.tDiffuseSize.value.set(this.uniforms.tDiffuse.value?.image.width || 0, this.uniforms.tDiffuse.value?.image.height || 0);
|
|
1898
|
+
super.render(renderer, target, writeBuffer, deltaTime, maskActive);
|
|
1899
|
+
}
|
|
1900
|
+
};
|
|
1901
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.uniform)()], BilateralFilterPass.prototype, "smoothEnabled", void 0);
|
|
1902
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.uniform)()], BilateralFilterPass.prototype, "edgeSharpness", void 0);
|
|
1903
|
+
// src/plugins/postprocessing/SSGIPlugin.ts
|
|
1904
|
+
var _SSGIPlugin;
|
|
1905
|
+
var passId = "ssrtgi";
|
|
1906
|
+
var SSGIPlugin = class SSGIPlugin extends threepipe.PipelinePassPlugin {
|
|
1907
|
+
static {
|
|
1908
|
+
_SSGIPlugin = this;
|
|
1909
|
+
}
|
|
1910
|
+
static {
|
|
1911
|
+
this.PluginType = "SSGIPlugin";
|
|
1912
|
+
}
|
|
1913
|
+
static {
|
|
1914
|
+
this.OldPluginType = "SSGI";
|
|
1915
|
+
}
|
|
1916
|
+
constructor(bufferType = threepipe.UnsignedByteType, sizeMultiplier = 1, enabled = true) {
|
|
1917
|
+
super();
|
|
1918
|
+
this.passId = passId;
|
|
1919
|
+
this.dependencies = [threepipe.GBufferPlugin, threepipe.SSAAPlugin];
|
|
1920
|
+
this._gbufferUnpackExtension = void 0;
|
|
1921
|
+
this._gbufferUnpackExtensionChanged = () => {
|
|
1922
|
+
if (!this._pass || !this._viewer) throw new Error("SSGIPlugin: pass/viewer not created yet");
|
|
1923
|
+
const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
|
|
1924
|
+
if (this._gbufferUnpackExtension === newExtension) return;
|
|
1925
|
+
if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(void 0);
|
|
1926
|
+
this._gbufferUnpackExtension = newExtension;
|
|
1927
|
+
if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension);
|
|
1928
|
+
else this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed");
|
|
1929
|
+
};
|
|
1930
|
+
this._releaseSsao = () => {
|
|
1931
|
+
if (this.isDisabled()) this._viewer?.getPlugin("SSAOPlugin")?.enable(_SSGIPlugin.PluginType);
|
|
1932
|
+
};
|
|
1933
|
+
this.enabled = enabled;
|
|
1934
|
+
this.bufferType = bufferType;
|
|
1935
|
+
this.sizeMultiplier = sizeMultiplier;
|
|
1936
|
+
}
|
|
1937
|
+
_createTarget(recreate = true) {
|
|
1938
|
+
if (!this._viewer) return;
|
|
1939
|
+
if (recreate) this._disposeTarget();
|
|
1940
|
+
if (!this.target) this.target = this._viewer.renderManager.createTarget({
|
|
1941
|
+
depthBuffer: false,
|
|
1942
|
+
type: this.bufferType,
|
|
1943
|
+
sizeMultiplier: this.sizeMultiplier
|
|
1944
|
+
});
|
|
1945
|
+
this.texture = this.target.texture;
|
|
1946
|
+
this.texture.name = "ssgiBuffer";
|
|
1947
|
+
}
|
|
1948
|
+
_disposeTarget() {
|
|
1949
|
+
if (!this._viewer) return;
|
|
1950
|
+
if (this.target) {
|
|
1951
|
+
this._viewer.renderManager.disposeTarget(this.target);
|
|
1952
|
+
this.target = void 0;
|
|
1953
|
+
}
|
|
1954
|
+
this.texture = void 0;
|
|
1955
|
+
}
|
|
1956
|
+
_createPass() {
|
|
1957
|
+
if (!this._viewer) throw new Error("SSGIPlugin: viewer not set");
|
|
1958
|
+
if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension) throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");
|
|
1959
|
+
this._createTarget(true);
|
|
1960
|
+
return new SSGIPluginPass(this.passId, () => this.target);
|
|
1961
|
+
}
|
|
1962
|
+
onAdded(viewer) {
|
|
1963
|
+
super.onAdded(viewer);
|
|
1964
|
+
if (viewer.getPlugin("Ground") || viewer.getPlugin("BaseGroundPlugin")) console.warn("GroundPlugin must be added after SSGIPlugin");
|
|
1965
|
+
this._gbufferUnpackExtensionChanged();
|
|
1966
|
+
viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1967
|
+
viewer.addEventListener("preFrame", this._releaseSsao);
|
|
1968
|
+
viewer.forPlugin(VelocityBufferPlugin, (vbp) => {
|
|
1969
|
+
this._pass?.material.registerMaterialExtensions([vbp.unpackExtension]);
|
|
1970
|
+
}, (vbp) => {
|
|
1971
|
+
this._pass?.material?.unregisterMaterialExtensions([vbp.unpackExtension]);
|
|
1972
|
+
}, this);
|
|
1973
|
+
}
|
|
1974
|
+
onRemove(viewer) {
|
|
1975
|
+
this._disposeTarget();
|
|
1976
|
+
viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
|
|
1977
|
+
viewer.removeEventListener("preFrame", this._releaseSsao);
|
|
1978
|
+
viewer.getPlugin("SSAOPlugin")?.enable(_SSGIPlugin.PluginType);
|
|
1979
|
+
return super.onRemove(viewer);
|
|
1980
|
+
}
|
|
1981
|
+
fromJSON(data, meta) {
|
|
1982
|
+
if (data.passes?.ssrtgi) {
|
|
1983
|
+
data = { ...data };
|
|
1984
|
+
data.pass = data.passes.ssrtgi;
|
|
1985
|
+
delete data.passes;
|
|
1986
|
+
if (data.pass.enabled !== void 0) data.enabled = data.pass.enabled;
|
|
1987
|
+
}
|
|
1988
|
+
return super.fromJSON(data, meta);
|
|
1989
|
+
}
|
|
1990
|
+
_beforeRender(_, _1, _2) {
|
|
1991
|
+
if (!this._viewer) return false;
|
|
1992
|
+
const e = super._beforeRender(_, _1, _2);
|
|
1993
|
+
if (e) {
|
|
1994
|
+
const ssao = this._viewer?.getPlugin("SSAOPlugin");
|
|
1995
|
+
if (ssao && !ssao.isDisabled()) ssao.disable(_SSGIPlugin.PluginType);
|
|
1996
|
+
}
|
|
1997
|
+
if (!e) return e;
|
|
1998
|
+
const progressive = this._viewer.getPlugin(threepipe.ProgressivePlugin);
|
|
1999
|
+
this._pass?.updateShaderProperties([progressive]);
|
|
2000
|
+
return e;
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* @deprecated use {@link target} instead
|
|
2004
|
+
*/
|
|
2005
|
+
get rtgiTarget() {
|
|
2006
|
+
console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead");
|
|
2007
|
+
return this.target;
|
|
2008
|
+
}
|
|
2009
|
+
};
|
|
2010
|
+
__decorate([(0, threepipe.uiImage)("SSGI Buffer", { readOnly: true })], SSGIPlugin.prototype, "texture", void 0);
|
|
2011
|
+
__decorate([(0, threepipe.uiConfig)(void 0, { unwrapContents: true })], SSGIPlugin.prototype, "_pass", void 0);
|
|
2012
|
+
SSGIPlugin = _SSGIPlugin = __decorate([(0, threepipe.uiFolderContainer)("SSGI Plugin")], SSGIPlugin);
|
|
2013
|
+
var SSGIPluginPass = class SSGIPluginPass extends threepipe.ExtendedShaderPass {
|
|
2014
|
+
constructor(pid, target, giEnabled = true) {
|
|
2015
|
+
super({
|
|
2016
|
+
defines: {
|
|
2017
|
+
["RTAO_STEP_COUNT"]: 16,
|
|
2018
|
+
["PERSPECTIVE_CAMERA"]: 1
|
|
2019
|
+
},
|
|
2020
|
+
uniforms: {
|
|
2021
|
+
tLastThis: { value: null },
|
|
2022
|
+
tLastFrame: { value: null },
|
|
2023
|
+
screenSize: { value: new threepipe.Vector2(0, 0) },
|
|
2024
|
+
currentFrameCount: { value: 0 },
|
|
2025
|
+
frameCount: { value: 0 },
|
|
2026
|
+
cameraNearFar: { value: new threepipe.Vector2(.1, 1e3) },
|
|
2027
|
+
cameraPositionWorld: { value: new threepipe.Vector3() },
|
|
2028
|
+
projection: { value: new threepipe.Matrix4() },
|
|
2029
|
+
opacity: { value: 1 },
|
|
2030
|
+
intensity: { value: 0 },
|
|
2031
|
+
objectRadius: { value: 0 },
|
|
2032
|
+
autoRadius: { value: giEnabled ? false : true },
|
|
2033
|
+
rayCount: { value: .1 },
|
|
2034
|
+
bias: { value: .015 },
|
|
2035
|
+
falloff: { value: .7 },
|
|
2036
|
+
power: { value: 1.1 },
|
|
2037
|
+
tolerance: { value: 0 },
|
|
2038
|
+
sceneBoundingRadius: { value: 0 },
|
|
2039
|
+
currentProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
2040
|
+
lastProjectionViewMatrix: { value: new threepipe.Matrix4() },
|
|
2041
|
+
inverseViewMatrix: { value: new threepipe.Matrix4() },
|
|
2042
|
+
ssrtaoSplitX: { value: .5 }
|
|
2043
|
+
},
|
|
2044
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
2045
|
+
fragmentShader: `
|
|
2046
|
+
varying vec2 vUv;
|
|
2047
|
+
|
|
2048
|
+
// for gbuffer
|
|
2049
|
+
#include <packing>
|
|
2050
|
+
#define THREE_PACKING_INCLUDED
|
|
2051
|
+
#include <cameraHelpers>
|
|
2052
|
+
#include <randomHelpers>
|
|
2053
|
+
${samplePointHelpers_default}
|
|
2054
|
+
|
|
2055
|
+
${ssrt_default}
|
|
2056
|
+
|
|
2057
|
+
${getShaders().calculateGI}
|
|
2058
|
+
`
|
|
2059
|
+
}, "tDiffuse", "tLastThis", "tLastFrame");
|
|
2060
|
+
this.target = target;
|
|
2061
|
+
this.before = ["render"];
|
|
2062
|
+
this.after = ["gbuffer", "depth"];
|
|
2063
|
+
this.required = ["render", "progressive"];
|
|
2064
|
+
this.giEnabled = true;
|
|
2065
|
+
this.intensity = 2;
|
|
2066
|
+
this.power = 1.1;
|
|
2067
|
+
this.autoRadius = true;
|
|
2068
|
+
this.objectRadius = 1;
|
|
2069
|
+
this.tolerance = 1;
|
|
2070
|
+
this.bias = .001;
|
|
2071
|
+
this.falloff = .7;
|
|
2072
|
+
this.rayCount = 4;
|
|
2073
|
+
this.stepCount = 8;
|
|
2074
|
+
this.smoothEnabled = true;
|
|
2075
|
+
this.renderWithCamera = true;
|
|
2076
|
+
this.split = 0;
|
|
2077
|
+
this.materialExtension = {
|
|
2078
|
+
extraUniforms: {
|
|
2079
|
+
tSSGIMap: () => ({ value: (0, threepipe.getOrCall)(this.target)?.texture ?? null }),
|
|
2080
|
+
ssaoPower: this.material.uniforms.power,
|
|
2081
|
+
ssgiIntensity: this.material.uniforms.intensity,
|
|
2082
|
+
ssrtaoSplitX: this.material.uniforms.ssrtaoSplitX
|
|
2083
|
+
},
|
|
2084
|
+
extraDefines: { ["SSGI_ENABLED"]: () => this.material.defines.SSGI_ENABLED },
|
|
2085
|
+
shaderExtender: (shader, _material, _renderer) => {
|
|
2086
|
+
if (!shader.defines?.SSRTAO_ENABLED) return;
|
|
2087
|
+
const ls = `
|
|
2088
|
+
|
|
2089
|
+
${giPatch_default}
|
|
2090
|
+
|
|
2091
|
+
#if defined(SSGI_ENABLED) && SSGI_ENABLED > 0
|
|
2092
|
+
// reflectedLight.directDiffuse = vec3(0.);
|
|
2093
|
+
// reflectedLight.indirectDiffuse = vec3(0.);
|
|
2094
|
+
// reflectedLight.directSpecular = vec3(0.);
|
|
2095
|
+
// reflectedLight.indirectSpecular = vec3(0.);
|
|
2096
|
+
#endif
|
|
2097
|
+
`;
|
|
2098
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "vec3 totalDiffuse =", ls, { prepend: true });
|
|
2099
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <aomap_fragment>", "");
|
|
2100
|
+
},
|
|
2101
|
+
onObjectRender: (_object, material, renderer) => {
|
|
2102
|
+
let x = this.enabled && (this.renderWithCamera || renderer.renderManager.frameCount > 1) && renderer.userData.screenSpaceRendering !== false && !material.userData?.pluginsDisabled && !material.userData?.ssgiDisabled && !material.userData?.ssrtaoDisabled && !material.userData?.ssaoDisabled ? this.split > 0 ? 2 : 1 : 0;
|
|
2103
|
+
if (material.defines.SSRTAO_ENABLED !== x) {
|
|
2104
|
+
material.defines.SSRTAO_ENABLED = x;
|
|
2105
|
+
material.needsUpdate = true;
|
|
2106
|
+
}
|
|
2107
|
+
},
|
|
2108
|
+
parsFragmentSnippet: (_renderer) => threepipe.glsl`
|
|
38
2109
|
#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0
|
|
39
2110
|
uniform float ssaoPower;
|
|
40
2111
|
uniform float ssgiIntensity;
|
|
@@ -42,23 +2113,976 @@
|
|
|
42
2113
|
#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED == 2
|
|
43
2114
|
uniform float ssrtaoSplitX;
|
|
44
2115
|
#endif
|
|
45
|
-
${
|
|
2116
|
+
${(0, threepipe.getTexelDecoding)("tSSGIMap", (0, threepipe.getOrCall)(this.target)?.texture.colorSpace)}
|
|
46
2117
|
${""}
|
|
47
2118
|
#include <simpleCameraHelpers>
|
|
48
2119
|
#endif
|
|
49
|
-
`,
|
|
2120
|
+
`,
|
|
2121
|
+
computeCacheKey: () => {
|
|
2122
|
+
const tex = (0, threepipe.getOrCall)(this.target)?.texture;
|
|
2123
|
+
return (this.enabled ? "1" : "0") + tex?.colorSpace + tex?.uuid + Object.values(this.material.defines).map((v) => v + "").join(",");
|
|
2124
|
+
},
|
|
2125
|
+
uuid: SSGIPlugin.PluginType,
|
|
2126
|
+
...(0, threepipe.uiConfigMaterialExtension)(this._getUiConfig.bind(this), SSGIPlugin.PluginType),
|
|
2127
|
+
isCompatible: (material) => {
|
|
2128
|
+
return material.isPhysicalMaterial;
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
this.passId = pid;
|
|
2132
|
+
this.needsSwap = true;
|
|
2133
|
+
this.clear = true;
|
|
2134
|
+
this.giEnabled = giEnabled;
|
|
2135
|
+
this.bilateralPass = new BilateralFilterPass(this.target, "rgba");
|
|
2136
|
+
}
|
|
2137
|
+
render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
|
|
2138
|
+
if (!this.enabled) return;
|
|
2139
|
+
this.needsSwap = false;
|
|
2140
|
+
if (!this.renderWithCamera && renderer.renderManager.frameCount < 2) return;
|
|
2141
|
+
const target = (0, threepipe.getOrCall)(this.target);
|
|
2142
|
+
if (!target) {
|
|
2143
|
+
console.warn("SSGIPluginPass: target not defined.");
|
|
2144
|
+
return;
|
|
2145
|
+
}
|
|
2146
|
+
renderer.renderManager.blit(writeBuffer, { source: target.texture });
|
|
2147
|
+
if (!this.material.defines.HAS_GBUFFER) console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi");
|
|
2148
|
+
this.uniforms.tLastThis.value = writeBuffer.texture;
|
|
2149
|
+
super.render(renderer, target, readBuffer, deltaTime, maskActive);
|
|
2150
|
+
if (this.smoothEnabled) this.bilateralPass.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
|
|
2151
|
+
this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value);
|
|
2152
|
+
}
|
|
2153
|
+
beforeRender(scene, camera, renderManager) {
|
|
2154
|
+
if (!this.enabled) return;
|
|
2155
|
+
this.updateShaderProperties([
|
|
2156
|
+
scene,
|
|
2157
|
+
camera,
|
|
2158
|
+
renderManager
|
|
2159
|
+
]);
|
|
2160
|
+
this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
|
|
2161
|
+
this.uniforms.inverseViewMatrix.value.copy(camera.matrixWorld);
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Returns a uiConfig to toggle SSGI on a material.
|
|
2165
|
+
* This uiConfig is added to each material by extension
|
|
2166
|
+
* @param material
|
|
2167
|
+
* @private
|
|
2168
|
+
*/
|
|
2169
|
+
_getUiConfig(material) {
|
|
2170
|
+
return {
|
|
2171
|
+
type: "folder",
|
|
2172
|
+
label: "SSGI",
|
|
2173
|
+
children: [{
|
|
2174
|
+
type: "checkbox",
|
|
2175
|
+
label: "Enabled",
|
|
2176
|
+
get value() {
|
|
2177
|
+
return !(material.userData.ssgiDisabled ?? false);
|
|
2178
|
+
},
|
|
2179
|
+
set value(v) {
|
|
2180
|
+
if (v === !(material.userData.ssgiDisabled ?? false)) return;
|
|
2181
|
+
material.userData.ssgiDisabled = !v;
|
|
2182
|
+
material.setDirty();
|
|
2183
|
+
},
|
|
2184
|
+
onChange: this.setDirty
|
|
2185
|
+
}]
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
set uniformsNeedUpdate(value) {
|
|
2189
|
+
this.material.uniformsNeedUpdate = value;
|
|
2190
|
+
this.setDirty();
|
|
2191
|
+
}
|
|
2192
|
+
setGBufferUnpackExtension(extension) {
|
|
2193
|
+
if (this._gbufferUnpackExtension === extension) return;
|
|
2194
|
+
if (this._gbufferUnpackExtension) {
|
|
2195
|
+
this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
|
|
2196
|
+
this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
|
|
2197
|
+
}
|
|
2198
|
+
this._gbufferUnpackExtension = extension;
|
|
2199
|
+
if (this._gbufferUnpackExtension) {
|
|
2200
|
+
this.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
|
|
2201
|
+
this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
|
|
2202
|
+
}
|
|
2203
|
+
if (!this._gbufferUnpackExtension) return;
|
|
2204
|
+
}
|
|
2205
|
+
setDirty() {
|
|
2206
|
+
this.materialExtension?.setDirty?.();
|
|
2207
|
+
super.setDirty();
|
|
2208
|
+
}
|
|
2209
|
+
};
|
|
2210
|
+
__decorate([(0, threepipe.serialize)()], SSGIPluginPass.prototype, "bilateralPass", void 0);
|
|
2211
|
+
__decorate([
|
|
2212
|
+
(0, threepipe.uiToggle)("GI Enabled"),
|
|
2213
|
+
(0, threepipe.serialize)(),
|
|
2214
|
+
(0, threepipe.matDefineBool)("SSGI_ENABLED", void 0, void 0, SSGIPluginPass.prototype.setDirty, false)
|
|
2215
|
+
], SSGIPluginPass.prototype, "giEnabled", void 0);
|
|
2216
|
+
__decorate([
|
|
2217
|
+
(0, threepipe.uiSlider)("Intensity", [0, 4]),
|
|
2218
|
+
(0, threepipe.serialize)(),
|
|
2219
|
+
(0, threepipe.uniform)()
|
|
2220
|
+
], SSGIPluginPass.prototype, "intensity", void 0);
|
|
2221
|
+
__decorate([
|
|
2222
|
+
(0, threepipe.uiSlider)("Power", [0, 3]),
|
|
2223
|
+
(0, threepipe.serialize)(),
|
|
2224
|
+
(0, threepipe.uniform)()
|
|
2225
|
+
], SSGIPluginPass.prototype, "power", void 0);
|
|
2226
|
+
__decorate([
|
|
2227
|
+
(0, threepipe.uiToggle)("Auto radius"),
|
|
2228
|
+
(0, threepipe.serialize)(),
|
|
2229
|
+
(0, threepipe.uniform)()
|
|
2230
|
+
], SSGIPluginPass.prototype, "autoRadius", void 0);
|
|
2231
|
+
__decorate([
|
|
2232
|
+
(0, threepipe.uiSlider)("Object Radius", [.01, 10]),
|
|
2233
|
+
(0, threepipe.serialize)(),
|
|
2234
|
+
(0, threepipe.uniform)()
|
|
2235
|
+
], SSGIPluginPass.prototype, "objectRadius", void 0);
|
|
2236
|
+
__decorate([
|
|
2237
|
+
(0, threepipe.uiSlider)("Tolerance", [.1, 5]),
|
|
2238
|
+
(0, threepipe.serialize)(),
|
|
2239
|
+
(0, threepipe.uniform)()
|
|
2240
|
+
], SSGIPluginPass.prototype, "tolerance", void 0);
|
|
2241
|
+
__decorate([
|
|
2242
|
+
(0, threepipe.uiSlider)("Bias", [-.3, .3]),
|
|
2243
|
+
(0, threepipe.serialize)(),
|
|
2244
|
+
(0, threepipe.uniform)()
|
|
2245
|
+
], SSGIPluginPass.prototype, "bias", void 0);
|
|
2246
|
+
__decorate([
|
|
2247
|
+
(0, threepipe.uiSlider)("Falloff", [1e-4, 4]),
|
|
2248
|
+
(0, threepipe.serialize)(),
|
|
2249
|
+
(0, threepipe.uniform)()
|
|
2250
|
+
], SSGIPluginPass.prototype, "falloff", void 0);
|
|
2251
|
+
__decorate([
|
|
2252
|
+
(0, threepipe.uiSlider)("Ray Count", [1, 5], 1, { tags: ["performance"] }),
|
|
2253
|
+
(0, threepipe.serialize)(),
|
|
2254
|
+
(0, threepipe.uniform)()
|
|
2255
|
+
], SSGIPluginPass.prototype, "rayCount", void 0);
|
|
2256
|
+
__decorate([
|
|
2257
|
+
(0, threepipe.uiSlider)("Step count", [1, 16], 1, { tags: ["performance"] }),
|
|
2258
|
+
(0, threepipe.serialize)(),
|
|
2259
|
+
(0, threepipe.matDefine)("RTAO_STEP_COUNT", void 0, void 0, SSGIPluginPass.prototype.setDirty)
|
|
2260
|
+
], SSGIPluginPass.prototype, "stepCount", void 0);
|
|
2261
|
+
__decorate([(0, threepipe.uiToggle)("Smooth Enabled"), (0, threepipe.serialize)()], SSGIPluginPass.prototype, "smoothEnabled", void 0);
|
|
2262
|
+
__decorate([(0, threepipe.uiToggle)("Render with Camera")], SSGIPluginPass.prototype, "renderWithCamera", void 0);
|
|
2263
|
+
__decorate([
|
|
2264
|
+
(0, threepipe.uiSlider)("Split", [0, 1], .01, { tags: ["debug"] }),
|
|
2265
|
+
(0, threepipe.serialize)(),
|
|
2266
|
+
(0, threepipe.uniform)({
|
|
2267
|
+
propKey: "ssrtaoSplitX",
|
|
2268
|
+
onChange: SSGIPluginPass.prototype.setDirty
|
|
2269
|
+
})
|
|
2270
|
+
], SSGIPluginPass.prototype, "split", void 0);
|
|
2271
|
+
SSGIPluginPass = __decorate([(0, threepipe.uiFolderContainer)("SSGI Pass")], SSGIPluginPass);
|
|
2272
|
+
// src/plugins/extras/shaders/anisotropyBsdf.glsl
|
|
2273
|
+
var anisotropyBsdf_default = "uniform float anisotropyFactor;uniform float anisotropyNoise;\n#if ANISOTROPY_TEX_MODE == 0\nuniform float anisotropyDirection;\n#else\nuniform sampler2D anisotropyDirectionMap;varying vec2 vAnisotropy2MapUv;\n#endif\nconst float MIN_ROUGHNESS=0.05;vec3 indirectAnisotropyBentNormal(const in vec3 normal,const in vec3 viewDir,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){vec3 aDirection=anisotropyFactor>=0.0 ? anisotropicB : anisotropicT;vec3 aTangent=cross(aDirection,viewDir);vec3 aNormal=cross(aTangent,aDirection);float bendFactor=abs(anisotropyFactor)*saturate(5.0*max(roughness,MIN_ROUGHNESS));return normalize(mix(normal,aNormal,bendFactor));}vec3 BRDF_GGX_Anisotropy(const in vec3 lightDir,const in vec3 viewDir,const in vec3 normal,const in vec3 f0,const in float f90,const in float roughness,const in vec3 anisotropicT,const in vec3 anisotropicB){float alpha=pow2(roughness);vec3 halfDir=normalize(lightDir+viewDir);float dotNL=saturate(dot(normal,lightDir));float dotNV=saturate(dot(normal,viewDir));float dotNH=saturate(dot(normal,halfDir));float dotVH=saturate(dot(viewDir,halfDir));float dotTV=dot(anisotropicT,viewDir);float dotBV=dot(anisotropicB,viewDir);float dotTL=dot(anisotropicT,lightDir);float dotBL=dot(anisotropicB,lightDir);float dotTH=dot(anisotropicT,halfDir);float dotBH=dot(anisotropicB,halfDir);float aspect=sqrt(1.0-min(1.-MIN_ROUGHNESS,abs(anisotropyFactor)*0.9));if(anisotropyFactor>0.0)aspect=1.0/aspect;float at=roughness*aspect;float ab=roughness/aspect;vec3 F=F_Schlick(f0,f90,dotVH);float V=V_GGX_SmithCorrelated_Anisotropic(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropic(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}";
|
|
2274
|
+
// src/plugins/extras/shaders/anisotropyTBN.glsl
|
|
2275
|
+
var anisotropyTBN_default = "float rnd=(random2(vUv.xy,frameCount)-0.5)*anisotropyNoise*material.roughness;\n#if ANISOTROPY_TEX_MODE < 2\n#if ANISOTROPY_TEX_MODE == 0\nfloat rot=saturate(anisotropyDirection);\n#else\nfloat rot=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).r);\n#endif\nrot=rot*2.*PI+rnd;vec2 rot2=vec2(sin(rot),cos(rot));\n#else\nvec2 rot2=(anisotropyDirectionMapTexelToLinear(texture2D(anisotropyDirectionMap,vAnisotropy2MapUv)).rg*2.-1.)+vec2(rnd,rnd);rot2=normalize(rot2);const float anisoSpecMultiplier=0.25;float matSpecAniso=(length(material.specularColor.rgb))*2.*PI;rot2=mix(rot2,vec2(sin(matSpecAniso),cos(matSpecAniso)),anisoSpecMultiplier);rot2=normalize(rot2);\n#endif\nvec3 anisotropicT=(tbn[0]*rot2.x+tbn[1]*rot2.y);anisotropicT=normalize(anisotropicT-normal*dot(anisotropicT,normal));vec3 anisotropicB=normalize(cross(normal,anisotropicT));";
|
|
2276
|
+
// src/plugins/extras/AnisotropyPlugin.ts
|
|
2277
|
+
var _AnisotropyPlugin;
|
|
2278
|
+
var ShaderChunk$1 = threepipe.RenderManager.ShaderChunk;
|
|
2279
|
+
var AnisotropyPlugin = class AnisotropyPlugin extends threepipe.AViewerPluginSync {
|
|
2280
|
+
static {
|
|
2281
|
+
_AnisotropyPlugin = this;
|
|
2282
|
+
}
|
|
2283
|
+
static {
|
|
2284
|
+
this.PluginType = "AnisotropyPlugin";
|
|
2285
|
+
}
|
|
2286
|
+
enableAnisotropy(material, map, factor, noise, directionMode) {
|
|
2287
|
+
const ud = material?.userData;
|
|
2288
|
+
if (!ud) return false;
|
|
2289
|
+
if (ud._isAnisotropic === void 0) {
|
|
2290
|
+
const meshes = material.appliedMeshes;
|
|
2291
|
+
let possible = true;
|
|
2292
|
+
if (meshes) for (const { geometry } of meshes) {
|
|
2293
|
+
if (geometry && (!geometry.attributes.position || !geometry.attributes.normal || !geometry.attributes.uv)) possible = false;
|
|
2294
|
+
if (possible && geometry && !geometry.attributes.tangent) geometry.computeTangents();
|
|
2295
|
+
}
|
|
2296
|
+
if (!possible) return false;
|
|
2297
|
+
}
|
|
2298
|
+
ud._isAnisotropic = true;
|
|
2299
|
+
ud._anisotropyFactor = factor ?? ud._anisotropyFactor ?? 1;
|
|
2300
|
+
ud._anisotropyNoise = noise ?? ud._anisotropyNoise ?? 0;
|
|
2301
|
+
ud._anisotropyDirection = ud._anisotropyDirection ?? 1;
|
|
2302
|
+
ud._anisotropyDirectionMode = directionMode ?? ud._anisotropyDirectionMode ?? "DIRECTION";
|
|
2303
|
+
ud._anisotropyDirectionMap = map ?? ud._anisotropyDirectionMap ?? null;
|
|
2304
|
+
if (material.setDirty) material.setDirty();
|
|
2305
|
+
return true;
|
|
2306
|
+
}
|
|
2307
|
+
tryComputeTangents(m, mats) {
|
|
2308
|
+
if (m.geometry && !m.geometry.attributes.tangent) {
|
|
2309
|
+
let possible = true;
|
|
2310
|
+
if (!m.geometry.index || !m.geometry.attributes.position || !m.geometry.attributes.normal || !m.geometry.attributes.uv) possible = false;
|
|
2311
|
+
if (possible) m.geometry.computeTangents();
|
|
2312
|
+
else mats.map((m1) => {
|
|
2313
|
+
if (m1?.userData?._isAnisotropic) m1.userData._isAnisotropic = false;
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
constructor() {
|
|
2318
|
+
super();
|
|
2319
|
+
this.enabled = true;
|
|
2320
|
+
this._defines = {};
|
|
2321
|
+
this._uniforms = {
|
|
2322
|
+
anisotropyFactor: { value: 1 },
|
|
2323
|
+
anisotropyNoise: { value: 1 },
|
|
2324
|
+
anisotropyDirection: { value: 1 },
|
|
2325
|
+
anisotropyDirectionMap: { value: null },
|
|
2326
|
+
anisotropy2MapUvTransform: { value: new threepipe.Matrix3() },
|
|
2327
|
+
frameCount: { value: 0 }
|
|
2328
|
+
};
|
|
2329
|
+
this.materialExtension = {
|
|
2330
|
+
uuid: _AnisotropyPlugin.PluginType,
|
|
2331
|
+
priority: 10,
|
|
2332
|
+
shaderExtender: (shader, material, _renderer) => {
|
|
2333
|
+
if (this.isDisabled() || !material?.userData._isAnisotropic) return;
|
|
2334
|
+
const rotMap = material.userData?._anisotropyDirectionMap;
|
|
2335
|
+
const bsdfs = threepipe.glsl`
|
|
50
2336
|
//#if ANISOTROPY_ENABLED
|
|
51
2337
|
#include <randomHelpers>
|
|
52
2338
|
#ifndef D_frameCount
|
|
53
2339
|
#define D_frameCount
|
|
54
2340
|
uniform float frameCount;
|
|
55
2341
|
#endif
|
|
56
|
-
${
|
|
57
|
-
`;
|
|
2342
|
+
${rotMap ? (0, threepipe.getTexelDecoding)("anisotropyDirectionMap", rotMap?.colorSpace) : ""}\n
|
|
2343
|
+
`;
|
|
2344
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <common>", bsdfs, { append: true });
|
|
2345
|
+
shader.fragmentShader = shader.fragmentShader.replace("#include <lights_fragment_begin>", ShaderChunk$1.lights_fragment_begin);
|
|
2346
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)((0, threepipe.shaderReplaceString)(shader.fragmentShader, "IncidentLight directLight;", anisotropyTBN_default, { prepend: true }), "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight )", "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight, anisotropicT, anisotropicB )", { replaceAll: true });
|
|
2347
|
+
let lights_physical_pars_fragment = (0, threepipe.shaderReplaceString)(ShaderChunk$1.lights_physical_pars_fragment, "void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {", "void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight, const in vec3 anisotropicT, const in vec3 anisotropicB ) {");
|
|
2348
|
+
lights_physical_pars_fragment = (0, threepipe.shaderReplaceString)(lights_physical_pars_fragment, "vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {", anisotropyBsdf_default + "\n", { prepend: true });
|
|
2349
|
+
lights_physical_pars_fragment = (0, threepipe.shaderReplaceString)(lights_physical_pars_fragment, "BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material )", "BRDF_GGX_Anisotropy( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )");
|
|
2350
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <lights_physical_pars_fragment>", lights_physical_pars_fragment);
|
|
2351
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <normal_fragment_begin>", ShaderChunk$1.normal_fragment_begin);
|
|
2352
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )", "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )");
|
|
2353
|
+
let lights_fragment_maps = threepipe.glsl`
|
|
58
2354
|
#if defined( USE_ENVMAP )
|
|
59
2355
|
vec3 anisotropyBentNormal = indirectAnisotropyBentNormal(geometryNormal, geometryViewDir, material.roughness, anisotropicT, anisotropicB);
|
|
60
2356
|
#endif
|
|
61
|
-
`+K.lights_fragment_maps;o=t.shaderReplaceString(o,"getIBLIrradiance( geometryNormal )","getIBLIrradiance( anisotropyBentNormal )"),o=t.shaderReplaceString(o,"getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )","getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )"),e.fragmentShader=t.shaderReplaceString(e.fragmentShader,"#include <lights_fragment_maps>",o),e.vertexShader=t.shaderReplaceString(e.vertexShader,"#include <uv_pars_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n varying vec2 vAnisotropy2MapUv;\n uniform mat3 anisotropy2MapUvTransform;\n#endif\n ",{prepend:!0}),e.vertexShader=t.shaderReplaceString(e.vertexShader,"#include <uv_vertex>","\n#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0\n vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;\n#endif\n ",{prepend:!0}),e.defines||(e.defines={}),e.defines.USE_ANISOTROPY_BRDF="",e.defines.USE_UV="",e.vertexTangents=!0},onObjectRender:(e,i)=>{const r=i.userData;if(!r?._isAnisotropic)return;if(!e.isMesh||!e.geometry)return;e.geometry.attributes.tangent||this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.",e),this._uniforms.anisotropyFactor.value=r._anisotropyFactor??1,this._uniforms.anisotropyNoise.value=r._anisotropyNoise??0,this._uniforms.anisotropyDirection.value=r._anisotropyDirection??1;const a=r._anisotropyDirectionMap?.isTexture?r._anisotropyDirectionMap:null;this._uniforms.anisotropyDirectionMap.value=a,a&&(a.updateMatrix(),this._uniforms.anisotropy2MapUvTransform.value.copy(a.matrix)),t.updateMaterialDefines({...this._defines,ANISOTROPY_ENABLED:+this.enabled,ANISOTROPY_TEX_MODE:a?"DIRECTION"===r._anisotropyDirectionMode?2:"ROTATION"===r._anisotropyDirectionMode?1:0:0},i)},extraUniforms:{},computeCacheKey:e=>(this.enabled?"1":"0")+(e.userData?._isAnisotropic?"1":"0")+e.userData?._anisotropyDirectionMap?.uuid,isCompatible:e=>e.isPhysicalMaterial,updaters:()=>[this._viewer?.renderManager],getUiConfig:e=>{const i=this._viewer,r=this.enableAnisotropy.bind(this),a=e.userData,n={type:"folder",label:"Anisotropy",onChange:e=>{e.config&&this.setDirty()},children:[{type:"checkbox",label:"Enabled",get value(){return a._isAnisotropic||!1},set value(t){t!==a._isAnisotropic&&(t?r(e)||i.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic."):(a._isAnisotropic=!1,e.setDirty&&e.setDirty()),n.uiRefresh?.(!0,"postFrame"))}},{type:"slider",label:"Factor",bounds:[-2,2],hidden:()=>!a._isAnisotropic,property:[a,"_anisotropyFactor"]},{type:"slider",label:"Noise",bounds:[0,2],hidden:()=>!a._isAnisotropic,property:[a,"_anisotropyNoise"]},{type:"dropdown",label:"Mode",hidden:()=>!a._isAnisotropic,property:[a,"_anisotropyDirectionMode"],children:["CONSTANT","ROTATION","DIRECTION"].map(e=>({label:e})),onChange:()=>{e.setDirty&&e.setDirty(),n.uiRefresh?.(!0,"postFrame")}},{type:"slider",label:"Direction",bounds:[0,5],hidden:()=>"CONSTANT"===a._anisotropyDirectionMode||!a._isAnisotropic,property:[a,"_anisotropicDirection"]},{type:"image",label:"Texture",hidden:()=>!a._isAnisotropic||"CONSTANT"===a._anisotropyDirectionMode,property:[a,"_anisotropyDirectionMap"],onChange:()=>{e.setDirty&&e.setDirty()}},t.makeSamplerUi(a,"_anisotropyDirectionMap","Sampler",()=>!a._isAnisotropic||"CONSTANT"===a._anisotropyDirectionMode,()=>e.setDirty&&e.setDirty())]};return n},onMaterialUpdate:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onRegister:e=>{e.userData?._isAnisotropic&&e.userData.__appliedMeshes?.forEach(t=>this.tryComputeTangents(t,[e]))},onAddToMesh:e=>{if(!e.isMesh)return;const t=e,i=Array.isArray(t.material)?t.material:[t.material];i.find(e=>e?.userData?._isAnisotropic)&&this.tryComputeTangents(t,i)}},this.setDirty=()=>{this.materialExtension.setDirty?.(),this._viewer?.setDirty()},Object.assign(this.materialExtension.extraUniforms,this._uniforms)}enableAnisotropy(e,t,i,r,a){const n=e?.userData;if(!n)return!1;if(void 0===n._isAnisotropic){const t=e.appliedMeshes;let i=!0;if(t)for(const{geometry:e}of t)!e||e.attributes.position&&e.attributes.normal&&e.attributes.uv||(i=!1),i&&e&&!e.attributes.tangent&&e.computeTangents();if(!i)return!1}return n._isAnisotropic=!0,n._anisotropyFactor=i??n._anisotropyFactor??1,n._anisotropyNoise=r??n._anisotropyNoise??0,n._anisotropyDirection=n._anisotropyDirection??1,n._anisotropyDirectionMode=a??n._anisotropyDirectionMode??"DIRECTION",n._anisotropyDirectionMap=t??n._anisotropyDirectionMap??null,e.setDirty&&e.setDirty(),!0}tryComputeTangents(e,t){if(e.geometry&&!e.geometry.attributes.tangent){let i=!0;e.geometry.index&&e.geometry.attributes.position&&e.geometry.attributes.normal&&e.geometry.attributes.uv||(i=!1),i?e.geometry.computeTangents():t.map(e=>{e?.userData?._isAnisotropic&&(e.userData._isAnisotropic=!1)})}}onAdded(e){super.onAdded(e),e.assetManager.materials.registerMaterialExtension(this.materialExtension),e.assetManager.registerGltfExtension(Z)}onRemove(e){return e.assetManager.materials?.unregisterMaterialExtension(this.materialExtension),e.assetManager.unregisterGltfExtension(Z.name),super.onRemove(e)}makeAnisotropic(e){return this.enableAnisotropy(e)}},e.AnisotropyPlugin.PluginType="AnisotropyPlugin",e.AnisotropyPlugin.ANISOTROPY_GLTF_EXTENSION="WEBGI_materials_anisotropy",X([t.uiToggle("Enabled",e=>({onChange:e.setDirty})),t.serialize()],e.AnisotropyPlugin.prototype,"enabled",2),e.AnisotropyPlugin=X([t.uiFolderContainer("Anisotropy (MatExt)")],e.AnisotropyPlugin);class q{constructor(e){this.parser=e,this.name=Z.name}async extendMaterialParams(e,i){const r=this.parser,a=r.json.materials[e];if(!a.extensions||!a.extensions[this.name])return Promise.resolve();const n=[],s=a.extensions[this.name];i.userData||(i.userData={}),i.userData._isAnisotropic=!0,i.userData._anisotropyFactor=s.anisotropyFactor??0,i.userData._anisotropyNoise=s.anisotropyNoiseFactor??s.anisotropyNoise??0;let{anisotropyDirectionMode:o,anisotropyDirection:l}=s;return o||(o=s.anisotropyTextureMode),l||(l=s.anisotropyRotation),i.userData._anisotropyDirectionMode=o&&"number"==typeof l?.index?o:"CONSTANT","ROTATION"===o||"DIRECTION"===o?n.push(r.assignTexture(i.userData,"_anisotropyDirectionMap",l).then(e=>{e.colorSpace=t.SRGBColorSpace})):i.userData._anisotropyDirection=l??0,Promise.all(n)}afterRoot(e){return e.scene?.traverse(e=>{const t=e.material?.userData?._isAnisotropic;if(!t)return;const i=e.geometry;i.attributes.tangent||(i.computeTangents(),i.attributes.tangent.needsUpdate=!0)}),null}}const Z={name:"WEBGI_materials_anisotropy",import:e=>new q(e),export:e=>({writeMaterial:(t,i)=>{if(!t.isMeshStandardMaterial||!t.userData._isAnisotropic)return;if((t.userData._anisotropyFactor||0)<.001)return;i.extensions=i.extensions||{};const r={};if(r.anisotropyFactor=t.userData._anisotropyFactor||1,r.anisotropyNoiseFactor=t.userData._anisotropyNoise||0,r.anisotropyDirectionMode=t.userData._anisotropyDirectionMode||"CONSTANT",e.checkEmptyMap(t.userData._anisotropyDirectionMap)&&"CONSTANT"!==r.anisotropyDirectionMode){const i={index:e.processTexture(t.userData._anisotropyDirectionMap)};e.applyTextureTransform(i,t.userData._anisotropyDirectionMap),r.anisotropyDirection=i}else r.anisotropyDirectionMode="CONSTANT",r.anisotropyDirection=t.userData._anisotropyDirection||0;i.extensions[Z.name]=r,e.extensionsUsed[Z.name]=!0}}),textures:{anisotropyDirection:"RGB"}};var J=Object.defineProperty,$=(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&&J(t,i,n),n};const Q=class extends t.Mesh2{constructor(e,i,r=0,a){super(e,a),this.type="Reflector",this.isReflector2=!0,this.enabled=!0,this.reflectorModePhysical=!0,this.reflectionTargetNeedsUpdate=!0,this.transparentReflectionBackground=!0,this.materialExtension={extraUniforms:{tRefDiffuse:{value:null},tRefDiffuseSize:{value:new t.Vector2},refTextureMatrix:{value:new t.Matrix4},frameCount:{value:0},sceneBoundingRadius:{value:0}},extraDefines:{USE_UV:""},updaters:[],shaderExtender:(e,i,r)=>{if(this.enabled){e.vertexShader=t.shaderReplaceString(e.vertexShader,"void main() {","void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");const i="#glMarker beforeModulation";e.fragmentShader=t.shaderReplaceString(e.fragmentShader,i,"\n if(roughnessFactor < 0.95) {\n float d = 0.;//textureProj(tRefDepth, vRefUv).r;\n // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));\n vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);\n // refBaseColor.rgb = vec3(refBaseColor.a);\n // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);\n "+(this.reflectorModePhysical?"\n #if !defined(SSR_ENABLED) || SSR_ENABLED < 1 \n vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);\n #endif\n reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);\n ":"\n reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);\n diffuseColor.a *= refBaseColor.a;\n ")+"}\n"+i)}},parsVertexSnippet:()=>this.enabled?"\n\t\tuniform mat4 refTextureMatrix;\n\t\tvarying vec4 vRefUv;\n":"",parsFragmentSnippet:()=>this.enabled?"vec2 poisson_disk_samples[16];void setPds(){poisson_disk_samples[0]=vec2(-0.399691779231,0.728591545584);poisson_disk_samples[1]=vec2(-0.48622557676,-0.84016533712);poisson_disk_samples[2]=vec2(0.770309468987,-0.24906070432);poisson_disk_samples[3]=vec2(0.556596796154,0.820359876432);poisson_disk_samples[4]=vec2(-0.933902004071,0.0600539051593);poisson_disk_samples[5]=vec2(0.330144964342,0.207477293384);poisson_disk_samples[6]=vec2(0.289013230975,-0.686749271417);poisson_disk_samples[7]=vec2(-0.0832470893559,-0.187351643125);poisson_disk_samples[8]=vec2(-0.296314525615,0.254474834305);poisson_disk_samples[9]=vec2(-0.850977666059,0.484642744689);poisson_disk_samples[10]=vec2(0.829287915319,0.2345063545);poisson_disk_samples[11]=vec2(-0.773042143899,-0.543741521254);poisson_disk_samples[12]=vec2(0.0561133030864,0.928419742597);poisson_disk_samples[13]=vec2(-0.205799249508,-0.562072714492);poisson_disk_samples[14]=vec2(-0.526991665882,-0.193690188118);poisson_disk_samples[15]=vec2(-0.051789270667,-0.935374050821);}\n\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}":"",computeCacheKey:e=>this.enabled+" "+e.transparent+" "+this.reflectorModePhysical+" ",onObjectRender:(e,t)=>{t.userData.__lastTransparent!==t.transparent&&(t.needsUpdate=!0,t.userData.__lastTransparent=t.transparent)},isCompatible:e=>e.isPhysicalMaterial,setDirty:()=>this.materialExtension.__setDirty?.()},this._renderTarget=i;const n=new t.Plane,s=new t.Vector3,o=new t.Vector3,l=new t.Vector3,c=new t.Matrix4,u=new t.Vector3(0,0,-1),d=new t.Vector4,h=new t.Vector3,p=new t.Vector3,f=new t.Vector4,g=new t.Matrix4,m=new t.PerspectiveCamera;this.onBeforeRender=(e,t,i)=>{if(!this.enabled||!e.userData.mainRenderPass)return;if(!this.reflectionTargetNeedsUpdate)return;const a=this._getRenderTarget();if(!a)return void console.warn("Reflector2: No render target set.");const v=i.view?Object.assign({},i.view):null;if(v&&i.clearViewOffset&&i.clearViewOffset(),o.setFromMatrixPosition(this.matrixWorld),l.setFromMatrixPosition(i.matrixWorld),c.extractRotation(this.matrixWorld),s.set(0,0,1),s.applyMatrix4(c),h.subVectors(o,l),h.dot(s)>0)return;h.reflect(s).negate(),h.add(o),c.extractRotation(i.matrixWorld),u.set(0,0,-1),u.applyMatrix4(c),u.add(l),p.subVectors(o,u),p.reflect(s).negate(),p.add(o),m.position.copy(h),m.up.set(0,1,0),m.up.applyMatrix4(c),m.up.reflect(s),m.lookAt(p),m.far=2,m.near=0,m.updateMatrixWorld(),m.projectionMatrix.copy(i.projectionMatrix),g.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),g.multiply(m.projectionMatrix),g.multiply(m.matrixWorldInverse),g.multiply(this.matrixWorld),n.setFromNormalAndCoplanarPoint(s,o),n.applyMatrix4(m.matrixWorldInverse),d.set(n.normal.x,n.normal.y,n.normal.z,n.constant);const _=m.projectionMatrix;f.x=(Math.sign(d.x)+_.elements[8])/_.elements[0],f.y=(Math.sign(d.y)+_.elements[9])/_.elements[5],f.z=-1,f.w=(1+_.elements[10])/_.elements[14],d.multiplyScalar(2/d.dot(f)),_.elements[2]=d.x,_.elements[6]=d.y,_.elements[10]=d.z+1-r,_.elements[14]=d.w,this.visible=!1;const S=e.getRenderTarget(),y=e.xr.enabled,x=e.shadowMap.autoUpdate;e.xr.enabled=!1,e.shadowMap.autoUpdate=!1,e.setRenderTarget(a),e.state.buffers.depth.setMask(!0),!1===e.autoClear&&e.clear();const P=t.background;this.transparentReflectionBackground&&(t.background=null);const b=!this.transparentReflectionBackground;P?.isTexture&&b&&(P.userData||(P.userData={}),P.userData.flipX=!P.userData.flipX),e.renderWithModes({shadowMapRender:!1,backgroundRender:b,opaqueRender:!0,transparentRender:!0,transmissionRender:!1,screenSpaceRendering:!1},()=>e.render(t,m)),P?.isTexture&&b&&(P.userData.flipX=!P.userData.flipX||void 0),this.transparentReflectionBackground&&(t.background=P),e.xr.enabled=y,e.shadowMap.autoUpdate=x,e.setRenderTarget(S),v?.enabled&&i.setViewOffset&&i.setViewOffset(v.fullWidth,v.fullHeight,v.offsetX,v.offsetY,v.width,v.height);const w=i.viewport;void 0!==w&&e.state.viewport(w),this.visible=!0,this.reflectionTargetNeedsUpdate=!1},this.textureMatrix=g,this.materialExtension.extraUniforms.refTextureMatrix.value=g}_getRenderTarget(){const e=t.getOrCall(this._renderTarget);return e&&(!e.texture.generateMipmaps||t.MathUtils.isPowerOfTwo(e.texture.image.width)&&t.MathUtils.isPowerOfTwo(e.texture.image.height)||(e.texture.generateMipmaps=!1),this.materialExtension.extraUniforms.tRefDiffuse.value=e.texture,this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(e.width,e.height)),e}_updateExtension(){this.transparentReflectionBackground=this.reflectorModePhysical,this.materialExtension?.setDirty?.()}getRenderTarget(){return this._renderTarget}};$([t.onChange(Q.prototype._updateExtension)],Q.prototype,"enabled"),$([t.onChange(Q.prototype._updateExtension)],Q.prototype,"reflectorModePhysical");let ee=Q;ee.prototype.isReflector=!0;class te{static _xfnv1a(e){let t=2166136261;for(let i=0;i<e.length;i++)t=Math.imul(t^e.charCodeAt(i),16777619);return()=>(t+=t<<13,t^=t>>>7,t+=t<<3,t^=t>>>17,(t+=t<<5)>>>0)}}class ie extends te{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.a=ie._xfnv1a(e)()}next(){let e=this.a+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}class re extends te{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=re._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){this.a>>>=0,this.b>>>=0,this.c>>>=0,this.d>>>=0;let e=this.a+this.b|0;return this.a=this.b^this.b>>>9,this.b=this.c+(this.c<<3)|0,this.c=this.c<<21|this.c>>>11,this.d=this.d+1|0,e=e+this.d|0,this.c=this.c+e|0,(e>>>0)/4294967296}}class ae extends te{constructor(e){super(),Object.defineProperty(this,"a",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"b",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"c",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"d",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const t=ae._xfnv1a(e);this.a=t(),this.b=t(),this.c=t(),this.d=t()}next(){const e=this.b<<9;let t=5*this.b;return t=9*(t<<7|t>>>25),this.c^=this.a,this.d^=this.b,this.b^=this.c,this.a^=this.d,this.c^=e,this.d=this.d<<11|this.d>>>21,(t>>>0)/4294967296}}var ne,se;(se=ne||(ne={})).sfc32="sfc32",se.mulberry32="mulberry32",se.xoshiro128ss="xoshiro128ss";class oe{constructor(e,t=ne.sfc32){Object.defineProperty(this,"str",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"prng",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.str=e,this.prng=t,this.generator=this._initializeGenerator()}next(){return this.generator.next()}_initializeGenerator(){if((e=>null===e)(e=this.str)||(e=>void 0===e)(e))return this.wrap();var e;switch(this.prng){case"sfc32":return new re(this.str);case"mulberry32":return new ie(this.str);case"xoshiro128ss":return new ae(this.str);default:return this.wrap()}}wrap(){return{next:()=>Math.random()}}}var le=Object.defineProperty,ce=(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&&le(t,i,n),n};class ue extends t.DirectionalLight2{constructor(e,i,r,a){super(e,i),this._shadowParams={enabled:!0,radius:2,width:1024,height:1024,bias:-.001,normalBias:0,near:1.5,far:4,frustumSize:4},this._randomParams={focus:1,spread:.01,distanceScale:50,minDistanceScale:new t.Vector3(10,10,10),normalDirection:new t.Vector3(.01,.98,.01).normalize(),direction:new t.Vector3(-.9,.5,-1)},this.isRandomizedDirectionalLight=!0,this.shadowParams=r??{},this.randomParams=a??{},this.updateShadowParams=this.updateShadowParams.bind(this)}get shadowParams(){return this._shadowParams}set shadowParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this._shadowParams={...this._shadowParams,...e},this.updateShadowParams()}get randomParams(){return this._randomParams}set randomParams(e){Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),Object.assign(this._randomParams,e)}updateShadowParams(){this.castShadow=this._shadowParams.enabled,this.shadow.mapSize.x=this._shadowParams.width,this.shadow.mapSize.y=this._shadowParams.height,this.shadow.bias=this._shadowParams.bias,this.shadow.normalBias=this._shadowParams.normalBias,this.refreshShadowCamNearFar(),this.shadow.radius=this._shadowParams.radius,this.shadow.camera.right=this._shadowParams.frustumSize/2,this.shadow.camera.left=-this._shadowParams.frustumSize/2,this.shadow.camera.top=this._shadowParams.frustumSize/2,this.shadow.camera.bottom=-this._shadowParams.frustumSize/2,this.shadow.camera.updateProjectionMatrix(),this.matrixWorldNeedsUpdate=!0}randomizePosition(e,i=null,r=null){const a=new oe(e.toString()),n=new t.Vector2(a.next()*Math.PI*2,Math.asin(2*a.next()-1));let s=new t.Vector3(Math.cos(n.x)*Math.cos(n.y),Math.sin(n.y),Math.sin(n.x)*Math.cos(n.y));const o=new t.Vector2;for(let t=0;t<5;t++){o.set(a.next(),a.next()),s=de(o,this._randomParams.normalDirection,.4),a.next()<Math.sqrt(i??this._randomParams.focus)&&(o.set(a.next(),a.next()),s=de(o,this._randomParams.direction,Math.pow((r??this._randomParams.spread)/2,2)));const e=s.dot(this._randomParams.normalDirection);if(e>0&&e<.4)break}s.normalize(),s.multiplyScalar(this._randomParams.distanceScale),this.position.set(0,0,0),this.target.position.copy(s.normalize().negate()),this.target.updateMatrixWorld(),this.refreshShadowCamNearFar(),this.updateMatrixWorld()}refreshShadowCamNearFar(){const e=(new t.Vector3).subVectors(this.target.position,this.shadow.camera.position).length();this.shadow.camera.near=e-this._shadowParams.near*this._shadowParams.frustumSize/2,this.shadow.camera.far=e+this._shadowParams.far*this._shadowParams.frustumSize/2}dispose(){}toJSON(e,i=!1){const{userData:r,children:a}=this;this.userData={},this.children=[];const n=super.toJSON(e),s=t.copyObject3DUserData({},r);return n.userData=t.Serialization.Serialize(s),this.userData=r,this.children=a,n.type="DirectionalLight2",n.target=this.target.position.toArray(),{...n,...t.ThreeSerialization.Serialize(this,e,!0)}}fromJSON(e,i,r=!1){if("DirectionalLight2"!==e.type)return null;const a=e.target,n=e.object;return e.target&&(this.target.position.fromArray(e.target),this.target.updateMatrixWorld(),delete e.target),e.object&&delete e.object,t.ThreeSerialization.Deserialize(e,this,i,!0),a&&(e.target=a),n&&(void 0!==n.color&&this.color.set(n.color),void 0!==n.intensity&&(this.intensity=n.intensity),e.object=n),this.updateShadowParams(),this}}function de(e,i,r){i=i.clone().normalize();const a=new t.Vector3(0,-i.z,i.y).normalize(),n=(new t.Vector3).crossVectors(i,a).normalize(),s=e;s.x=2*s.x*Math.PI,s.y=1-s.y*r;const o=Math.sqrt(1-s.y*s.y);return a.multiplyScalar(Math.cos(s.x)*o).add(n.multiplyScalar(Math.sin(s.x)*o)).add(i.multiplyScalar(s.y))}ce([t.serialize("shadowParams")],ue.prototype,"_shadowParams"),ce([t.serialize("randomParams")],ue.prototype,"_randomParams");var he=Object.defineProperty;class pe extends t.ShadowMaterial{constructor(){super(...arguments),this.typeSlug="fsShadow",this.assetType="material",this._uniforms={},this.lastFrameTexture=null}get materialObject(){return this}onBeforeCompile(e,i){e.vertexShader=e.vertexShader.replace("#include <project_vertex>","\n#include <project_vertex>\ngl_Position = vec4(uv*2.-1., 0, 1.); \n "),e.vertexShader=e.vertexShader.replace("void main() {","\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n "),e.fragmentShader=e.fragmentShader.replace("void main() {","\nvarying vec2 vUv;\nuniform sampler2D tLastThis;\nvoid main() {\n "),e.fragmentShader=e.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );",t.glsl`
|
|
2357
|
+
` + ShaderChunk$1.lights_fragment_maps;
|
|
2358
|
+
lights_fragment_maps = (0, threepipe.shaderReplaceString)(lights_fragment_maps, "getIBLIrradiance( geometryNormal )", "getIBLIrradiance( anisotropyBentNormal )");
|
|
2359
|
+
lights_fragment_maps = (0, threepipe.shaderReplaceString)(lights_fragment_maps, "getIBLRadiance( geometryViewDir, geometryNormal, material.roughness )", "getIBLRadiance( geometryViewDir, anisotropyBentNormal, material.roughness )");
|
|
2360
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <lights_fragment_maps>", lights_fragment_maps);
|
|
2361
|
+
shader.vertexShader = (0, threepipe.shaderReplaceString)(shader.vertexShader, "#include <uv_pars_vertex>", `
|
|
2362
|
+
#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
|
|
2363
|
+
varying vec2 vAnisotropy2MapUv;
|
|
2364
|
+
uniform mat3 anisotropy2MapUvTransform;
|
|
2365
|
+
#endif
|
|
2366
|
+
`, { prepend: true });
|
|
2367
|
+
shader.vertexShader = (0, threepipe.shaderReplaceString)(shader.vertexShader, "#include <uv_vertex>", `
|
|
2368
|
+
#if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
|
|
2369
|
+
vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;
|
|
2370
|
+
#endif
|
|
2371
|
+
`, { prepend: true });
|
|
2372
|
+
if (!shader.defines) shader.defines = {};
|
|
2373
|
+
shader.defines.USE_ANISOTROPY_BRDF = "";
|
|
2374
|
+
shader.defines.USE_UV = "";
|
|
2375
|
+
shader.vertexTangents = true;
|
|
2376
|
+
},
|
|
2377
|
+
onObjectRender: (object, material) => {
|
|
2378
|
+
const userData = material.userData;
|
|
2379
|
+
if (!userData?._isAnisotropic) return;
|
|
2380
|
+
if (!object.isMesh || !object.geometry) return;
|
|
2381
|
+
if (!object.geometry.attributes.tangent) this._viewer?.console.error("AnisotropyPlugin - No tangents on the geometry, cannot use anisotropy. Make sure the tangents are computed before rendering the model. The model will render as black.", object);
|
|
2382
|
+
this._uniforms.anisotropyFactor.value = userData._anisotropyFactor ?? 1;
|
|
2383
|
+
this._uniforms.anisotropyNoise.value = userData._anisotropyNoise ?? 0;
|
|
2384
|
+
this._uniforms.anisotropyDirection.value = userData._anisotropyDirection ?? 1;
|
|
2385
|
+
const tex = userData._anisotropyDirectionMap?.isTexture ? userData._anisotropyDirectionMap : null;
|
|
2386
|
+
this._uniforms.anisotropyDirectionMap.value = tex;
|
|
2387
|
+
if (tex) {
|
|
2388
|
+
tex.updateMatrix();
|
|
2389
|
+
this._uniforms.anisotropy2MapUvTransform.value.copy(tex.matrix);
|
|
2390
|
+
}
|
|
2391
|
+
(0, threepipe.updateMaterialDefines)({
|
|
2392
|
+
...this._defines,
|
|
2393
|
+
["ANISOTROPY_ENABLED"]: +this.enabled,
|
|
2394
|
+
["ANISOTROPY_TEX_MODE"]: !tex ? 0 : userData._anisotropyDirectionMode === "DIRECTION" ? 2 : userData._anisotropyDirectionMode === "ROTATION" ? 1 : 0
|
|
2395
|
+
}, material);
|
|
2396
|
+
},
|
|
2397
|
+
extraUniforms: {},
|
|
2398
|
+
computeCacheKey: (material1) => {
|
|
2399
|
+
return (this.enabled ? "1" : "0") + (material1.userData?._isAnisotropic ? "1" : "0") + material1.userData?._anisotropyDirectionMap?.uuid;
|
|
2400
|
+
},
|
|
2401
|
+
isCompatible: (material1) => material1.isPhysicalMaterial,
|
|
2402
|
+
updaters: () => [this._viewer?.renderManager],
|
|
2403
|
+
getUiConfig: (material) => {
|
|
2404
|
+
const viewer = this._viewer;
|
|
2405
|
+
const enableAnisotropy = this.enableAnisotropy.bind(this);
|
|
2406
|
+
const state = material.userData;
|
|
2407
|
+
const config = {
|
|
2408
|
+
type: "folder",
|
|
2409
|
+
label: "Anisotropy",
|
|
2410
|
+
onChange: (ev) => {
|
|
2411
|
+
if (!ev.config) return;
|
|
2412
|
+
this.setDirty();
|
|
2413
|
+
},
|
|
2414
|
+
children: [
|
|
2415
|
+
{
|
|
2416
|
+
type: "checkbox",
|
|
2417
|
+
label: "Enabled",
|
|
2418
|
+
get value() {
|
|
2419
|
+
return state._isAnisotropic || false;
|
|
2420
|
+
},
|
|
2421
|
+
set value(v) {
|
|
2422
|
+
if (v === state._isAnisotropic) return;
|
|
2423
|
+
if (v) {
|
|
2424
|
+
if (!enableAnisotropy(material)) viewer.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic.");
|
|
2425
|
+
} else {
|
|
2426
|
+
state._isAnisotropic = false;
|
|
2427
|
+
if (material.setDirty) material.setDirty();
|
|
2428
|
+
}
|
|
2429
|
+
config.uiRefresh?.(true, "postFrame");
|
|
2430
|
+
}
|
|
2431
|
+
},
|
|
2432
|
+
{
|
|
2433
|
+
type: "slider",
|
|
2434
|
+
label: "Factor",
|
|
2435
|
+
bounds: [-2, 2],
|
|
2436
|
+
hidden: () => !state._isAnisotropic,
|
|
2437
|
+
property: [state, "_anisotropyFactor"]
|
|
2438
|
+
},
|
|
2439
|
+
{
|
|
2440
|
+
type: "slider",
|
|
2441
|
+
label: "Noise",
|
|
2442
|
+
bounds: [0, 2],
|
|
2443
|
+
hidden: () => !state._isAnisotropic,
|
|
2444
|
+
property: [state, "_anisotropyNoise"]
|
|
2445
|
+
},
|
|
2446
|
+
{
|
|
2447
|
+
type: "dropdown",
|
|
2448
|
+
label: "Mode",
|
|
2449
|
+
hidden: () => !state._isAnisotropic,
|
|
2450
|
+
property: [state, "_anisotropyDirectionMode"],
|
|
2451
|
+
children: [
|
|
2452
|
+
"CONSTANT",
|
|
2453
|
+
"ROTATION",
|
|
2454
|
+
"DIRECTION"
|
|
2455
|
+
].map((value) => ({ label: value })),
|
|
2456
|
+
onChange: () => {
|
|
2457
|
+
if (material.setDirty) material.setDirty();
|
|
2458
|
+
config.uiRefresh?.(true, "postFrame");
|
|
2459
|
+
}
|
|
2460
|
+
},
|
|
2461
|
+
{
|
|
2462
|
+
type: "slider",
|
|
2463
|
+
label: "Direction",
|
|
2464
|
+
bounds: [0, 5],
|
|
2465
|
+
hidden: () => state._anisotropyDirectionMode === "CONSTANT" || !state._isAnisotropic,
|
|
2466
|
+
property: [state, "_anisotropicDirection"]
|
|
2467
|
+
},
|
|
2468
|
+
{
|
|
2469
|
+
type: "image",
|
|
2470
|
+
label: "Texture",
|
|
2471
|
+
hidden: () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT",
|
|
2472
|
+
property: [state, "_anisotropyDirectionMap"],
|
|
2473
|
+
onChange: () => {
|
|
2474
|
+
if (material.setDirty) material.setDirty();
|
|
2475
|
+
}
|
|
2476
|
+
},
|
|
2477
|
+
(0, threepipe.makeSamplerUi)(state, "_anisotropyDirectionMap", "Sampler", () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT", () => material.setDirty && material.setDirty())
|
|
2478
|
+
]
|
|
2479
|
+
};
|
|
2480
|
+
return config;
|
|
2481
|
+
},
|
|
2482
|
+
onMaterialUpdate: (material) => {
|
|
2483
|
+
if (!material.userData?._isAnisotropic) return;
|
|
2484
|
+
material.userData.__appliedMeshes?.forEach((m) => this.tryComputeTangents(m, [material]));
|
|
2485
|
+
},
|
|
2486
|
+
onRegister: (material) => {
|
|
2487
|
+
if (!material.userData?._isAnisotropic) return;
|
|
2488
|
+
material.userData.__appliedMeshes?.forEach((m) => this.tryComputeTangents(m, [material]));
|
|
2489
|
+
},
|
|
2490
|
+
onAddToMesh: (mesh) => {
|
|
2491
|
+
if (!mesh.isMesh) return;
|
|
2492
|
+
const m = mesh;
|
|
2493
|
+
const mats = Array.isArray(m.material) ? m.material : [m.material];
|
|
2494
|
+
if (!mats.find((m1) => m1?.userData?._isAnisotropic)) return;
|
|
2495
|
+
this.tryComputeTangents(m, mats);
|
|
2496
|
+
}
|
|
2497
|
+
};
|
|
2498
|
+
this.setDirty = () => {
|
|
2499
|
+
this.materialExtension.setDirty?.();
|
|
2500
|
+
this._viewer?.setDirty();
|
|
2501
|
+
};
|
|
2502
|
+
Object.assign(this.materialExtension.extraUniforms, this._uniforms);
|
|
2503
|
+
}
|
|
2504
|
+
onAdded(v) {
|
|
2505
|
+
super.onAdded(v);
|
|
2506
|
+
v.assetManager.materials.registerMaterialExtension(this.materialExtension);
|
|
2507
|
+
v.assetManager.registerGltfExtension(anisotropyGLTFExtension);
|
|
2508
|
+
}
|
|
2509
|
+
onRemove(v) {
|
|
2510
|
+
v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension);
|
|
2511
|
+
v.assetManager.unregisterGltfExtension(anisotropyGLTFExtension.name);
|
|
2512
|
+
return super.onRemove(v);
|
|
2513
|
+
}
|
|
2514
|
+
static {
|
|
2515
|
+
this.ANISOTROPY_GLTF_EXTENSION = "WEBGI_materials_anisotropy";
|
|
2516
|
+
}
|
|
2517
|
+
/**
|
|
2518
|
+
* @deprecated - use {@link enableAnisotropy} instead
|
|
2519
|
+
* @param material
|
|
2520
|
+
*/
|
|
2521
|
+
makeAnisotropic(material) {
|
|
2522
|
+
return this.enableAnisotropy(material);
|
|
2523
|
+
}
|
|
2524
|
+
};
|
|
2525
|
+
__decorate([(0, threepipe.uiToggle)("Enabled", (that) => ({ onChange: that.setDirty })), (0, threepipe.serialize)()], AnisotropyPlugin.prototype, "enabled", void 0);
|
|
2526
|
+
AnisotropyPlugin = _AnisotropyPlugin = __decorate([(0, threepipe.uiFolderContainer)("Anisotropy (MatExt)")], AnisotropyPlugin);
|
|
2527
|
+
/**
|
|
2528
|
+
* Anisotropy Materials Extension
|
|
2529
|
+
*
|
|
2530
|
+
* Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_anisotropy.html
|
|
2531
|
+
*/
|
|
2532
|
+
var GLTFMaterialsAnisotropyExtensionImport = class {
|
|
2533
|
+
constructor(parser) {
|
|
2534
|
+
this.parser = parser;
|
|
2535
|
+
this.name = anisotropyGLTFExtension.name;
|
|
2536
|
+
}
|
|
2537
|
+
async extendMaterialParams(materialIndex, materialParams) {
|
|
2538
|
+
const parser = this.parser;
|
|
2539
|
+
const materialDef = parser.json.materials[materialIndex];
|
|
2540
|
+
if (!materialDef.extensions || !materialDef.extensions[this.name]) return Promise.resolve();
|
|
2541
|
+
const pending = [];
|
|
2542
|
+
const extension = materialDef.extensions[this.name];
|
|
2543
|
+
if (!materialParams.userData) materialParams.userData = {};
|
|
2544
|
+
materialParams.userData._isAnisotropic = true;
|
|
2545
|
+
materialParams.userData._anisotropyFactor = extension.anisotropyFactor ?? 0;
|
|
2546
|
+
materialParams.userData._anisotropyNoise = extension.anisotropyNoiseFactor ?? extension.anisotropyNoise ?? 0;
|
|
2547
|
+
let { anisotropyDirectionMode, anisotropyDirection } = extension;
|
|
2548
|
+
if (!anisotropyDirectionMode) anisotropyDirectionMode = extension.anisotropyTextureMode;
|
|
2549
|
+
if (!anisotropyDirection) anisotropyDirection = extension.anisotropyRotation;
|
|
2550
|
+
materialParams.userData._anisotropyDirectionMode = anisotropyDirectionMode && typeof anisotropyDirection?.index === "number" ? anisotropyDirectionMode : "CONSTANT";
|
|
2551
|
+
if (anisotropyDirectionMode === "ROTATION" || anisotropyDirectionMode === "DIRECTION") pending.push(parser.assignTexture(materialParams.userData, "_anisotropyDirectionMap", anisotropyDirection).then((t) => {
|
|
2552
|
+
t.colorSpace = threepipe.SRGBColorSpace;
|
|
2553
|
+
}));
|
|
2554
|
+
else materialParams.userData._anisotropyDirection = anisotropyDirection ?? 0;
|
|
2555
|
+
return Promise.all(pending);
|
|
2556
|
+
}
|
|
2557
|
+
afterRoot(result) {
|
|
2558
|
+
result.scene?.traverse((object) => {
|
|
2559
|
+
if (!object.material?.userData?._isAnisotropic) return;
|
|
2560
|
+
const geom = object.geometry;
|
|
2561
|
+
if (!geom.attributes.tangent) {
|
|
2562
|
+
geom.computeTangents();
|
|
2563
|
+
geom.attributes.tangent.needsUpdate = true;
|
|
2564
|
+
}
|
|
2565
|
+
});
|
|
2566
|
+
return null;
|
|
2567
|
+
}
|
|
2568
|
+
};
|
|
2569
|
+
var glTFMaterialsAnisotropyExtensionExport = (w) => ({ writeMaterial: (material, materialDef) => {
|
|
2570
|
+
if (!material.isMeshStandardMaterial || !material.userData._isAnisotropic) return;
|
|
2571
|
+
if ((material.userData._anisotropyFactor || 0) < .001) return;
|
|
2572
|
+
materialDef.extensions = materialDef.extensions || {};
|
|
2573
|
+
const extensionDef = {};
|
|
2574
|
+
extensionDef.anisotropyFactor = material.userData._anisotropyFactor || 1;
|
|
2575
|
+
extensionDef.anisotropyNoiseFactor = material.userData._anisotropyNoise || 0;
|
|
2576
|
+
extensionDef.anisotropyDirectionMode = material.userData._anisotropyDirectionMode || "CONSTANT";
|
|
2577
|
+
if (w.checkEmptyMap(material.userData._anisotropyDirectionMap) && extensionDef.anisotropyDirectionMode !== "CONSTANT") {
|
|
2578
|
+
const anisotropyDirectionMapDef = { index: w.processTexture(material.userData._anisotropyDirectionMap) };
|
|
2579
|
+
w.applyTextureTransform(anisotropyDirectionMapDef, material.userData._anisotropyDirectionMap);
|
|
2580
|
+
extensionDef.anisotropyDirection = anisotropyDirectionMapDef;
|
|
2581
|
+
} else {
|
|
2582
|
+
extensionDef.anisotropyDirectionMode = "CONSTANT";
|
|
2583
|
+
extensionDef.anisotropyDirection = material.userData._anisotropyDirection || 0;
|
|
2584
|
+
}
|
|
2585
|
+
materialDef.extensions[anisotropyGLTFExtension.name] = extensionDef;
|
|
2586
|
+
w.extensionsUsed[anisotropyGLTFExtension.name] = true;
|
|
2587
|
+
} });
|
|
2588
|
+
var anisotropyGLTFExtension = {
|
|
2589
|
+
name: "WEBGI_materials_anisotropy",
|
|
2590
|
+
import: (p) => new GLTFMaterialsAnisotropyExtensionImport(p),
|
|
2591
|
+
export: glTFMaterialsAnisotropyExtensionExport,
|
|
2592
|
+
textures: { anisotropyDirection: "RGB" }
|
|
2593
|
+
};
|
|
2594
|
+
// src/utils/shaders/poissonDiskSamples.glsl
|
|
2595
|
+
var poissonDiskSamples_default = "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);}";
|
|
2596
|
+
// src/utils/shaders/reflectorSample.glsl
|
|
2597
|
+
var reflectorSample_default = "\n#include <randomHelpers>\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\n#endif\n#ifndef D_frameCount\n#define D_frameCount\nuniform float frameCount;\n#endif\nvarying vec4 vRefUv;uniform sampler2D tRefDiffuse;uniform vec2 tRefDiffuseSize;float getSpecularMIPLevel(const in float roughness,const in float maxMIPLevel){float sigma=PI*roughness*roughness/(1.0+roughness);float desiredMIPLevel=maxMIPLevel+log2(sigma);return clamp(desiredMIPLevel,0.0,maxMIPLevel);}vec4 getReflectionColor(const in float roughness,const in float depthModifier){float mip=getSpecularMIPLevel(roughness+depthModifier,4.0);vec4 color=texture2D(tRefDiffuse,vRefUv.xy/vRefUv.w,mip);float blurDist=saturate(2.0/(1.+pow(abs(vViewPosition.z),0.25)))*roughness*64.*color.a;float rnd=PI2*interleavedGradientNoise(vUv.xy,frameCount);vec4 rotationMatrix=vec4(cos(rnd),-sin(rnd),0.,0.);rotationMatrix.z=-rotationMatrix.y;rotationMatrix.w=rotationMatrix.x;vec3 colorSum=color.rgb*color.a;float weightSum=0.001+color.a;vec2 ofs;setPds();\n#pragma unroll_loop_start\nfor(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));ofs=vRefUv.xy+vRefUv.w*blurDist*ofs/tRefDiffuseSize.xy;color=texture2D(tRefDiffuse,ofs/vRefUv.w,mip);colorSum+=color.rgb*color.a;weightSum+=color.a;}\n#pragma unroll_loop_end\nreturn vec4(colorSum/weightSum,1.0);}";
|
|
2598
|
+
// src/utils/Reflector2.ts
|
|
2599
|
+
var Reflector2 = class extends threepipe.Mesh2 {
|
|
2600
|
+
_getRenderTarget() {
|
|
2601
|
+
const target = (0, threepipe.getOrCall)(this._renderTarget);
|
|
2602
|
+
if (target) {
|
|
2603
|
+
if (target.texture.generateMipmaps && (!threepipe.MathUtils.isPowerOfTwo(target.texture.image.width) || !threepipe.MathUtils.isPowerOfTwo(target.texture.image.height))) target.texture.generateMipmaps = false;
|
|
2604
|
+
this.materialExtension.extraUniforms.tRefDiffuse.value = target.texture;
|
|
2605
|
+
this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(target.width, target.height);
|
|
2606
|
+
}
|
|
2607
|
+
return target;
|
|
2608
|
+
}
|
|
2609
|
+
_updateExtension() {
|
|
2610
|
+
this.transparentReflectionBackground = this.reflectorModePhysical;
|
|
2611
|
+
this.materialExtension?.setDirty?.();
|
|
2612
|
+
}
|
|
2613
|
+
constructor(geometry, renderTarget, clipBias = 0, material) {
|
|
2614
|
+
super(geometry, material);
|
|
2615
|
+
this.type = "Reflector";
|
|
2616
|
+
this.isReflector2 = true;
|
|
2617
|
+
this.enabled = true;
|
|
2618
|
+
this.reflectorModePhysical = true;
|
|
2619
|
+
this.reflectionTargetNeedsUpdate = true;
|
|
2620
|
+
this.transparentReflectionBackground = true;
|
|
2621
|
+
this.materialExtension = {
|
|
2622
|
+
extraUniforms: {
|
|
2623
|
+
tRefDiffuse: { value: null },
|
|
2624
|
+
tRefDiffuseSize: { value: new threepipe.Vector2() },
|
|
2625
|
+
refTextureMatrix: { value: new threepipe.Matrix4() },
|
|
2626
|
+
frameCount: { value: 0 },
|
|
2627
|
+
sceneBoundingRadius: { value: 0 }
|
|
2628
|
+
},
|
|
2629
|
+
extraDefines: { USE_UV: "" },
|
|
2630
|
+
updaters: [],
|
|
2631
|
+
shaderExtender: (shader, _material, _renderer) => {
|
|
2632
|
+
if (this.enabled) {
|
|
2633
|
+
shader.vertexShader = (0, threepipe.shaderReplaceString)(shader.vertexShader, "void main() {", "void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );");
|
|
2634
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#glMarker beforeModulation", `
|
|
2635
|
+
if(roughnessFactor < 0.95) {
|
|
2636
|
+
float d = 0.;//textureProj(tRefDepth, vRefUv).r;
|
|
2637
|
+
// d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));
|
|
2638
|
+
vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);
|
|
2639
|
+
// refBaseColor.rgb = vec3(refBaseColor.a);
|
|
2640
|
+
// refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);
|
|
2641
|
+
` + (this.reflectorModePhysical ? `
|
|
2642
|
+
#if !defined(SSR_ENABLED) || SSR_ENABLED < 1
|
|
2643
|
+
vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);
|
|
2644
|
+
#endif
|
|
2645
|
+
reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);
|
|
2646
|
+
` : `
|
|
2647
|
+
reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);
|
|
2648
|
+
diffuseColor.a *= refBaseColor.a;
|
|
2649
|
+
`) + "}\n#glMarker beforeModulation");
|
|
2650
|
+
}
|
|
2651
|
+
},
|
|
2652
|
+
parsVertexSnippet: () => !this.enabled ? "" : `
|
|
2653
|
+
uniform mat4 refTextureMatrix;
|
|
2654
|
+
varying vec4 vRefUv;
|
|
2655
|
+
`,
|
|
2656
|
+
parsFragmentSnippet: () => this.enabled ? poissonDiskSamples_default + "\n" + reflectorSample_default : "",
|
|
2657
|
+
computeCacheKey: (material) => {
|
|
2658
|
+
return this.enabled + " " + material.transparent + " " + this.reflectorModePhysical + " ";
|
|
2659
|
+
},
|
|
2660
|
+
onObjectRender: (_object, material) => {
|
|
2661
|
+
if (material.userData.__lastTransparent !== material.transparent) {
|
|
2662
|
+
material.needsUpdate = true;
|
|
2663
|
+
material.userData.__lastTransparent = material.transparent;
|
|
2664
|
+
}
|
|
2665
|
+
},
|
|
2666
|
+
isCompatible: (material) => {
|
|
2667
|
+
return material.isPhysicalMaterial;
|
|
2668
|
+
},
|
|
2669
|
+
setDirty: () => this.materialExtension.__setDirty?.()
|
|
2670
|
+
};
|
|
2671
|
+
this._renderTarget = renderTarget;
|
|
2672
|
+
const reflectorPlane = new threepipe.Plane();
|
|
2673
|
+
const normal = new threepipe.Vector3();
|
|
2674
|
+
const reflectorWorldPosition = new threepipe.Vector3();
|
|
2675
|
+
const cameraWorldPosition = new threepipe.Vector3();
|
|
2676
|
+
const rotationMatrix = new threepipe.Matrix4();
|
|
2677
|
+
const lookAtPosition = new threepipe.Vector3(0, 0, -1);
|
|
2678
|
+
const clipPlane = new threepipe.Vector4();
|
|
2679
|
+
const view = new threepipe.Vector3();
|
|
2680
|
+
const target = new threepipe.Vector3();
|
|
2681
|
+
const q = new threepipe.Vector4();
|
|
2682
|
+
const textureMatrix = new threepipe.Matrix4();
|
|
2683
|
+
const virtualCamera = new threepipe.PerspectiveCamera();
|
|
2684
|
+
this.onBeforeRender = (renderer, scene, camera) => {
|
|
2685
|
+
if (!this.enabled || !renderer.userData.mainRenderPass) return;
|
|
2686
|
+
if (!this.reflectionTargetNeedsUpdate) return;
|
|
2687
|
+
const thisRenderTarget = this._getRenderTarget();
|
|
2688
|
+
if (!thisRenderTarget) {
|
|
2689
|
+
console.warn("Reflector2: No render target set.");
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
const viewOffset = camera.view ? Object.assign({}, camera.view) : null;
|
|
2693
|
+
viewOffset && camera.clearViewOffset && camera.clearViewOffset();
|
|
2694
|
+
reflectorWorldPosition.setFromMatrixPosition(this.matrixWorld);
|
|
2695
|
+
cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
|
|
2696
|
+
rotationMatrix.extractRotation(this.matrixWorld);
|
|
2697
|
+
normal.set(0, 0, 1);
|
|
2698
|
+
normal.applyMatrix4(rotationMatrix);
|
|
2699
|
+
view.subVectors(reflectorWorldPosition, cameraWorldPosition);
|
|
2700
|
+
if (view.dot(normal) > 0) return;
|
|
2701
|
+
view.reflect(normal).negate();
|
|
2702
|
+
view.add(reflectorWorldPosition);
|
|
2703
|
+
rotationMatrix.extractRotation(camera.matrixWorld);
|
|
2704
|
+
lookAtPosition.set(0, 0, -1);
|
|
2705
|
+
lookAtPosition.applyMatrix4(rotationMatrix);
|
|
2706
|
+
lookAtPosition.add(cameraWorldPosition);
|
|
2707
|
+
target.subVectors(reflectorWorldPosition, lookAtPosition);
|
|
2708
|
+
target.reflect(normal).negate();
|
|
2709
|
+
target.add(reflectorWorldPosition);
|
|
2710
|
+
virtualCamera.position.copy(view);
|
|
2711
|
+
virtualCamera.up.set(0, 1, 0);
|
|
2712
|
+
virtualCamera.up.applyMatrix4(rotationMatrix);
|
|
2713
|
+
virtualCamera.up.reflect(normal);
|
|
2714
|
+
virtualCamera.lookAt(target);
|
|
2715
|
+
virtualCamera.far = 2;
|
|
2716
|
+
virtualCamera.near = 0;
|
|
2717
|
+
virtualCamera.updateMatrixWorld();
|
|
2718
|
+
virtualCamera.projectionMatrix.copy(camera.projectionMatrix);
|
|
2719
|
+
textureMatrix.set(.5, 0, 0, .5, 0, .5, 0, .5, 0, 0, .5, .5, 0, 0, 0, 1);
|
|
2720
|
+
textureMatrix.multiply(virtualCamera.projectionMatrix);
|
|
2721
|
+
textureMatrix.multiply(virtualCamera.matrixWorldInverse);
|
|
2722
|
+
textureMatrix.multiply(this.matrixWorld);
|
|
2723
|
+
reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition);
|
|
2724
|
+
reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse);
|
|
2725
|
+
clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant);
|
|
2726
|
+
const projectionMatrix = virtualCamera.projectionMatrix;
|
|
2727
|
+
q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0];
|
|
2728
|
+
q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5];
|
|
2729
|
+
q.z = -1;
|
|
2730
|
+
q.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14];
|
|
2731
|
+
clipPlane.multiplyScalar(2 / clipPlane.dot(q));
|
|
2732
|
+
projectionMatrix.elements[2] = clipPlane.x;
|
|
2733
|
+
projectionMatrix.elements[6] = clipPlane.y;
|
|
2734
|
+
projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias;
|
|
2735
|
+
projectionMatrix.elements[14] = clipPlane.w;
|
|
2736
|
+
this.visible = false;
|
|
2737
|
+
const currentRenderTarget = renderer.getRenderTarget();
|
|
2738
|
+
const currentXrEnabled = renderer.xr.enabled;
|
|
2739
|
+
const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
|
|
2740
|
+
renderer.xr.enabled = false;
|
|
2741
|
+
renderer.shadowMap.autoUpdate = false;
|
|
2742
|
+
renderer.setRenderTarget(thisRenderTarget);
|
|
2743
|
+
renderer.state.buffers.depth.setMask(true);
|
|
2744
|
+
if (renderer.autoClear === false) renderer.clear();
|
|
2745
|
+
const sceneBackground = scene.background;
|
|
2746
|
+
if (this.transparentReflectionBackground) scene.background = null;
|
|
2747
|
+
const renderBackground = !this.transparentReflectionBackground;
|
|
2748
|
+
if (sceneBackground?.isTexture && renderBackground) {
|
|
2749
|
+
if (!sceneBackground.userData) sceneBackground.userData = {};
|
|
2750
|
+
sceneBackground.userData.flipX = !sceneBackground.userData.flipX;
|
|
2751
|
+
}
|
|
2752
|
+
renderer.renderWithModes({
|
|
2753
|
+
shadowMapRender: false,
|
|
2754
|
+
backgroundRender: renderBackground,
|
|
2755
|
+
opaqueRender: true,
|
|
2756
|
+
transparentRender: true,
|
|
2757
|
+
transmissionRender: false,
|
|
2758
|
+
screenSpaceRendering: false
|
|
2759
|
+
}, () => renderer.render(scene, virtualCamera));
|
|
2760
|
+
if (sceneBackground?.isTexture && renderBackground) sceneBackground.userData.flipX = !sceneBackground.userData.flipX || void 0;
|
|
2761
|
+
if (this.transparentReflectionBackground) scene.background = sceneBackground;
|
|
2762
|
+
renderer.xr.enabled = currentXrEnabled;
|
|
2763
|
+
renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
|
|
2764
|
+
renderer.setRenderTarget(currentRenderTarget);
|
|
2765
|
+
if (viewOffset?.enabled && camera.setViewOffset) camera.setViewOffset(viewOffset.fullWidth, viewOffset.fullHeight, viewOffset.offsetX, viewOffset.offsetY, viewOffset.width, viewOffset.height);
|
|
2766
|
+
const viewport = camera.viewport;
|
|
2767
|
+
if (viewport !== void 0) renderer.state.viewport(viewport);
|
|
2768
|
+
this.visible = true;
|
|
2769
|
+
this.reflectionTargetNeedsUpdate = false;
|
|
2770
|
+
};
|
|
2771
|
+
this.textureMatrix = textureMatrix;
|
|
2772
|
+
this.materialExtension.extraUniforms.refTextureMatrix.value = textureMatrix;
|
|
2773
|
+
}
|
|
2774
|
+
getRenderTarget() {
|
|
2775
|
+
return this._renderTarget;
|
|
2776
|
+
}
|
|
2777
|
+
};
|
|
2778
|
+
__decorate([(0, threepipe.onChange)(Reflector2.prototype._updateExtension)], Reflector2.prototype, "enabled", void 0);
|
|
2779
|
+
__decorate([(0, threepipe.onChange)(Reflector2.prototype._updateExtension)], Reflector2.prototype, "reflectorModePhysical", void 0);
|
|
2780
|
+
Reflector2.prototype.isReflector = true;
|
|
2781
|
+
// ../../node_modules/rand-seed/dist/es/index.js
|
|
2782
|
+
var e = class {
|
|
2783
|
+
static _xfnv1a(e) {
|
|
2784
|
+
let t = 2166136261;
|
|
2785
|
+
for (let i = 0; i < e.length; i++) t = Math.imul(t ^ e.charCodeAt(i), 16777619);
|
|
2786
|
+
return () => (t += t << 13, t ^= t >>> 7, t += t << 3, t ^= t >>> 17, (t += t << 5) >>> 0);
|
|
2787
|
+
}
|
|
2788
|
+
};
|
|
2789
|
+
var t = class t extends e {
|
|
2790
|
+
constructor(e) {
|
|
2791
|
+
super(), Object.defineProperty(this, "a", {
|
|
2792
|
+
enumerable: !0,
|
|
2793
|
+
configurable: !0,
|
|
2794
|
+
writable: !0,
|
|
2795
|
+
value: void 0
|
|
2796
|
+
}), this.a = t._xfnv1a(e)();
|
|
2797
|
+
}
|
|
2798
|
+
next() {
|
|
2799
|
+
let e = this.a += 1831565813;
|
|
2800
|
+
return e = Math.imul(e ^ e >>> 15, 1 | e), e ^= e + Math.imul(e ^ e >>> 7, 61 | e), ((e ^ e >>> 14) >>> 0) / 4294967296;
|
|
2801
|
+
}
|
|
2802
|
+
};
|
|
2803
|
+
var i = class i extends e {
|
|
2804
|
+
constructor(e) {
|
|
2805
|
+
super(), Object.defineProperty(this, "a", {
|
|
2806
|
+
enumerable: !0,
|
|
2807
|
+
configurable: !0,
|
|
2808
|
+
writable: !0,
|
|
2809
|
+
value: void 0
|
|
2810
|
+
}), Object.defineProperty(this, "b", {
|
|
2811
|
+
enumerable: !0,
|
|
2812
|
+
configurable: !0,
|
|
2813
|
+
writable: !0,
|
|
2814
|
+
value: void 0
|
|
2815
|
+
}), Object.defineProperty(this, "c", {
|
|
2816
|
+
enumerable: !0,
|
|
2817
|
+
configurable: !0,
|
|
2818
|
+
writable: !0,
|
|
2819
|
+
value: void 0
|
|
2820
|
+
}), Object.defineProperty(this, "d", {
|
|
2821
|
+
enumerable: !0,
|
|
2822
|
+
configurable: !0,
|
|
2823
|
+
writable: !0,
|
|
2824
|
+
value: void 0
|
|
2825
|
+
});
|
|
2826
|
+
const t = i._xfnv1a(e);
|
|
2827
|
+
this.a = t(), this.b = t(), this.c = t(), this.d = t();
|
|
2828
|
+
}
|
|
2829
|
+
next() {
|
|
2830
|
+
this.a >>>= 0, this.b >>>= 0, this.c >>>= 0, this.d >>>= 0;
|
|
2831
|
+
let e = this.a + this.b | 0;
|
|
2832
|
+
return this.a = this.b ^ this.b >>> 9, this.b = this.c + (this.c << 3) | 0, this.c = this.c << 21 | this.c >>> 11, this.d = this.d + 1 | 0, e = e + this.d | 0, this.c = this.c + e | 0, (e >>> 0) / 4294967296;
|
|
2833
|
+
}
|
|
2834
|
+
};
|
|
2835
|
+
var r = class r extends e {
|
|
2836
|
+
constructor(e) {
|
|
2837
|
+
super(), Object.defineProperty(this, "a", {
|
|
2838
|
+
enumerable: !0,
|
|
2839
|
+
configurable: !0,
|
|
2840
|
+
writable: !0,
|
|
2841
|
+
value: void 0
|
|
2842
|
+
}), Object.defineProperty(this, "b", {
|
|
2843
|
+
enumerable: !0,
|
|
2844
|
+
configurable: !0,
|
|
2845
|
+
writable: !0,
|
|
2846
|
+
value: void 0
|
|
2847
|
+
}), Object.defineProperty(this, "c", {
|
|
2848
|
+
enumerable: !0,
|
|
2849
|
+
configurable: !0,
|
|
2850
|
+
writable: !0,
|
|
2851
|
+
value: void 0
|
|
2852
|
+
}), Object.defineProperty(this, "d", {
|
|
2853
|
+
enumerable: !0,
|
|
2854
|
+
configurable: !0,
|
|
2855
|
+
writable: !0,
|
|
2856
|
+
value: void 0
|
|
2857
|
+
});
|
|
2858
|
+
const t = r._xfnv1a(e);
|
|
2859
|
+
this.a = t(), this.b = t(), this.c = t(), this.d = t();
|
|
2860
|
+
}
|
|
2861
|
+
next() {
|
|
2862
|
+
const e = this.b << 9;
|
|
2863
|
+
let t = 5 * this.b;
|
|
2864
|
+
return t = 9 * (t << 7 | t >>> 25), this.c ^= this.a, this.d ^= this.b, this.b ^= this.c, this.a ^= this.d, this.c ^= e, this.d = this.d << 11 | this.d >>> 21, (t >>> 0) / 4294967296;
|
|
2865
|
+
}
|
|
2866
|
+
};
|
|
2867
|
+
var s;
|
|
2868
|
+
(function(e) {
|
|
2869
|
+
e.sfc32 = "sfc32", e.mulberry32 = "mulberry32", e.xoshiro128ss = "xoshiro128ss";
|
|
2870
|
+
})(s || (s = {}));
|
|
2871
|
+
var a = class {
|
|
2872
|
+
constructor(e, t = s.sfc32) {
|
|
2873
|
+
Object.defineProperty(this, "str", {
|
|
2874
|
+
enumerable: !0,
|
|
2875
|
+
configurable: !0,
|
|
2876
|
+
writable: !0,
|
|
2877
|
+
value: void 0
|
|
2878
|
+
}), Object.defineProperty(this, "prng", {
|
|
2879
|
+
enumerable: !0,
|
|
2880
|
+
configurable: !0,
|
|
2881
|
+
writable: !0,
|
|
2882
|
+
value: void 0
|
|
2883
|
+
}), Object.defineProperty(this, "generator", {
|
|
2884
|
+
enumerable: !0,
|
|
2885
|
+
configurable: !0,
|
|
2886
|
+
writable: !0,
|
|
2887
|
+
value: void 0
|
|
2888
|
+
}), this.str = e, this.prng = t, this.generator = this._initializeGenerator();
|
|
2889
|
+
}
|
|
2890
|
+
next() {
|
|
2891
|
+
return this.generator.next();
|
|
2892
|
+
}
|
|
2893
|
+
_initializeGenerator() {
|
|
2894
|
+
if (((e) => null === e)(e = this.str) || ((e) => void 0 === e)(e)) return this.wrap();
|
|
2895
|
+
var e;
|
|
2896
|
+
switch (this.prng) {
|
|
2897
|
+
case "sfc32": return new i(this.str);
|
|
2898
|
+
case "mulberry32": return new t(this.str);
|
|
2899
|
+
case "xoshiro128ss": return new r(this.str);
|
|
2900
|
+
default: return this.wrap();
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
wrap() {
|
|
2904
|
+
return { next: () => Math.random() };
|
|
2905
|
+
}
|
|
2906
|
+
};
|
|
2907
|
+
// src/utils/RandomizedDirectionalLight.ts
|
|
2908
|
+
var RandomizedDirectionalLight = class extends threepipe.DirectionalLight2 {
|
|
2909
|
+
constructor(color, intensity, shadow, random) {
|
|
2910
|
+
super(color, intensity);
|
|
2911
|
+
this._shadowParams = {
|
|
2912
|
+
enabled: true,
|
|
2913
|
+
radius: 2,
|
|
2914
|
+
width: 1024,
|
|
2915
|
+
height: 1024,
|
|
2916
|
+
bias: -.001,
|
|
2917
|
+
normalBias: 0,
|
|
2918
|
+
near: 1.5,
|
|
2919
|
+
far: 4,
|
|
2920
|
+
frustumSize: 4
|
|
2921
|
+
};
|
|
2922
|
+
this._randomParams = {
|
|
2923
|
+
focus: 1,
|
|
2924
|
+
spread: .01,
|
|
2925
|
+
distanceScale: 50,
|
|
2926
|
+
minDistanceScale: new threepipe.Vector3(10, 10, 10),
|
|
2927
|
+
normalDirection: new threepipe.Vector3(.01, .98, .01).normalize(),
|
|
2928
|
+
direction: new threepipe.Vector3(-.9, .5, -1)
|
|
2929
|
+
};
|
|
2930
|
+
this.isRandomizedDirectionalLight = true;
|
|
2931
|
+
this.shadowParams = shadow ?? {};
|
|
2932
|
+
this.randomParams = random ?? {};
|
|
2933
|
+
this.updateShadowParams = this.updateShadowParams.bind(this);
|
|
2934
|
+
}
|
|
2935
|
+
/**
|
|
2936
|
+
* call setter to change. or call updateShadowParams after changing
|
|
2937
|
+
*/
|
|
2938
|
+
get shadowParams() {
|
|
2939
|
+
return this._shadowParams;
|
|
2940
|
+
}
|
|
2941
|
+
set shadowParams(value) {
|
|
2942
|
+
Object.keys(value).forEach((key) => value[key] === void 0 && delete value[key]);
|
|
2943
|
+
this._shadowParams = {
|
|
2944
|
+
...this._shadowParams,
|
|
2945
|
+
...value
|
|
2946
|
+
};
|
|
2947
|
+
this.updateShadowParams();
|
|
2948
|
+
}
|
|
2949
|
+
get randomParams() {
|
|
2950
|
+
return this._randomParams;
|
|
2951
|
+
}
|
|
2952
|
+
set randomParams(value) {
|
|
2953
|
+
Object.keys(value).forEach((key) => value[key] === void 0 && delete value[key]);
|
|
2954
|
+
Object.assign(this._randomParams, value);
|
|
2955
|
+
}
|
|
2956
|
+
updateShadowParams() {
|
|
2957
|
+
this.castShadow = this._shadowParams.enabled;
|
|
2958
|
+
this.shadow.mapSize.x = this._shadowParams.width;
|
|
2959
|
+
this.shadow.mapSize.y = this._shadowParams.height;
|
|
2960
|
+
this.shadow.bias = this._shadowParams.bias;
|
|
2961
|
+
this.shadow.normalBias = this._shadowParams.normalBias;
|
|
2962
|
+
this.refreshShadowCamNearFar();
|
|
2963
|
+
this.shadow.radius = this._shadowParams.radius;
|
|
2964
|
+
this.shadow.camera.right = this._shadowParams.frustumSize / 2;
|
|
2965
|
+
this.shadow.camera.left = -this._shadowParams.frustumSize / 2;
|
|
2966
|
+
this.shadow.camera.top = this._shadowParams.frustumSize / 2;
|
|
2967
|
+
this.shadow.camera.bottom = -this._shadowParams.frustumSize / 2;
|
|
2968
|
+
this.shadow.camera.updateProjectionMatrix();
|
|
2969
|
+
this.matrixWorldNeedsUpdate = true;
|
|
2970
|
+
}
|
|
2971
|
+
randomizePosition(seed, focus = null, spread = null) {
|
|
2972
|
+
const rand = new a(seed.toString());
|
|
2973
|
+
const rnd = new threepipe.Vector2(rand.next() * Math.PI * 2, Math.asin(rand.next() * 2 - 1));
|
|
2974
|
+
let dir = new threepipe.Vector3(Math.cos(rnd.x) * Math.cos(rnd.y), Math.sin(rnd.y), Math.sin(rnd.x) * Math.cos(rnd.y));
|
|
2975
|
+
/**
|
|
2976
|
+
* @type {string}
|
|
2977
|
+
*/
|
|
2978
|
+
const v2 = new threepipe.Vector2();
|
|
2979
|
+
for (let kk = 0; kk < 5; kk++) {
|
|
2980
|
+
v2.set(rand.next(), rand.next());
|
|
2981
|
+
dir = getSample(v2, this._randomParams.normalDirection, .4);
|
|
2982
|
+
if (rand.next() < Math.sqrt(focus ?? this._randomParams.focus)) {
|
|
2983
|
+
v2.set(rand.next(), rand.next());
|
|
2984
|
+
dir = getSample(v2, this._randomParams.direction, Math.pow((spread ?? this._randomParams.spread) / 2, 2));
|
|
2985
|
+
}
|
|
2986
|
+
const cd = dir.dot(this._randomParams.normalDirection);
|
|
2987
|
+
if (cd > 0 && cd < .4) break;
|
|
2988
|
+
}
|
|
2989
|
+
dir.normalize();
|
|
2990
|
+
dir.multiplyScalar(this._randomParams.distanceScale);
|
|
2991
|
+
this.position.set(0, 0, 0);
|
|
2992
|
+
this.target.position.copy(dir.normalize().negate());
|
|
2993
|
+
this.target.updateMatrixWorld();
|
|
2994
|
+
this.refreshShadowCamNearFar();
|
|
2995
|
+
this.updateMatrixWorld();
|
|
2996
|
+
}
|
|
2997
|
+
refreshShadowCamNearFar() {
|
|
2998
|
+
const dist = new threepipe.Vector3().subVectors(this.target.position, this.shadow.camera.position).length();
|
|
2999
|
+
this.shadow.camera.near = dist - this._shadowParams.near * this._shadowParams.frustumSize / 2;
|
|
3000
|
+
this.shadow.camera.far = dist + this._shadowParams.far * this._shadowParams.frustumSize / 2;
|
|
3001
|
+
}
|
|
3002
|
+
dispose() {
|
|
3003
|
+
super.dispose();
|
|
3004
|
+
}
|
|
3005
|
+
toJSON(meta, _internal = false) {
|
|
3006
|
+
const { userData, children } = this;
|
|
3007
|
+
this.userData = {};
|
|
3008
|
+
this.children = [];
|
|
3009
|
+
const data = super.toJSON(meta);
|
|
3010
|
+
const copiedData = (0, threepipe.copyObject3DUserData)({}, userData);
|
|
3011
|
+
data.userData = threepipe.Serialization.Serialize(copiedData);
|
|
3012
|
+
this.userData = userData;
|
|
3013
|
+
this.children = children;
|
|
3014
|
+
data.type = "DirectionalLight2";
|
|
3015
|
+
data.target = this.target.position.toArray();
|
|
3016
|
+
return {
|
|
3017
|
+
...data,
|
|
3018
|
+
...threepipe.ThreeSerialization.Serialize(this, meta, true)
|
|
3019
|
+
};
|
|
3020
|
+
}
|
|
3021
|
+
fromJSON(data, meta, _internal = false) {
|
|
3022
|
+
if (data.type !== "DirectionalLight2") return null;
|
|
3023
|
+
const target = data.target;
|
|
3024
|
+
const object = data.object;
|
|
3025
|
+
if (data.target) {
|
|
3026
|
+
this.target.position.fromArray(data.target);
|
|
3027
|
+
this.target.updateMatrixWorld();
|
|
3028
|
+
delete data.target;
|
|
3029
|
+
}
|
|
3030
|
+
if (data.object) delete data.object;
|
|
3031
|
+
threepipe.ThreeSerialization.Deserialize(data, this, meta, true);
|
|
3032
|
+
if (target) data.target = target;
|
|
3033
|
+
if (object) {
|
|
3034
|
+
if (object.color !== void 0) this.color.set(object.color);
|
|
3035
|
+
if (object.intensity !== void 0) this.intensity = object.intensity;
|
|
3036
|
+
data.object = object;
|
|
3037
|
+
}
|
|
3038
|
+
this.updateShadowParams();
|
|
3039
|
+
return this;
|
|
3040
|
+
}
|
|
3041
|
+
};
|
|
3042
|
+
__decorate([(0, threepipe.serialize)("shadowParams")], RandomizedDirectionalLight.prototype, "_shadowParams", void 0);
|
|
3043
|
+
__decorate([(0, threepipe.serialize)("randomParams")], RandomizedDirectionalLight.prototype, "_randomParams", void 0);
|
|
3044
|
+
/**
|
|
3045
|
+
* Random direction, uniformly distributed over the cone around `dir` in which cos(angle to dir)
|
|
3046
|
+
* is between 1 - extent and 1: phi = 2 pi u, cos(theta) = 1 - v extent, with (u, v) = rand in [0, 1).
|
|
3047
|
+
* Basis: b1 = (0, -dir.z, dir.y) and b2 = dir x b1, both zero when dir is along x.
|
|
3048
|
+
*/
|
|
3049
|
+
function getSample(rand, dir, extent) {
|
|
3050
|
+
const w = dir.clone().normalize();
|
|
3051
|
+
const b1 = new threepipe.Vector3(0, -w.z, w.y).normalize();
|
|
3052
|
+
const b2 = new threepipe.Vector3().crossVectors(w, b1).normalize();
|
|
3053
|
+
const phi = rand.x * 2 * Math.PI;
|
|
3054
|
+
const cosTheta = 1 - rand.y * extent;
|
|
3055
|
+
const sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
|
|
3056
|
+
return b1.multiplyScalar(Math.cos(phi) * sinTheta).add(b2.multiplyScalar(Math.sin(phi) * sinTheta)).add(w.multiplyScalar(cosTheta));
|
|
3057
|
+
}
|
|
3058
|
+
// src/utils/FSShadowMaterial.ts
|
|
3059
|
+
var FSShadowMaterial = class extends threepipe.ShadowMaterial {
|
|
3060
|
+
constructor(..._args) {
|
|
3061
|
+
super(..._args);
|
|
3062
|
+
this.typeSlug = "fsShadow";
|
|
3063
|
+
this.assetType = "material";
|
|
3064
|
+
this._uniforms = {};
|
|
3065
|
+
this.lastFrameTexture = null;
|
|
3066
|
+
}
|
|
3067
|
+
get materialObject() {
|
|
3068
|
+
return this;
|
|
3069
|
+
}
|
|
3070
|
+
onBeforeCompile(shader, renderer) {
|
|
3071
|
+
shader.vertexShader = shader.vertexShader.replace("#include <project_vertex>", `
|
|
3072
|
+
#include <project_vertex>
|
|
3073
|
+
gl_Position = vec4(uv*2.-1., 0, 1.);
|
|
3074
|
+
`);
|
|
3075
|
+
shader.vertexShader = shader.vertexShader.replace("void main() {", `
|
|
3076
|
+
varying vec2 vUv;
|
|
3077
|
+
void main() {
|
|
3078
|
+
vUv = uv;
|
|
3079
|
+
`);
|
|
3080
|
+
shader.fragmentShader = shader.fragmentShader.replace("void main() {", `
|
|
3081
|
+
varying vec2 vUv;
|
|
3082
|
+
uniform sampler2D tLastThis;
|
|
3083
|
+
void main() {
|
|
3084
|
+
`);
|
|
3085
|
+
shader.fragmentShader = shader.fragmentShader.replace("gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );", threepipe.glsl`
|
|
62
3086
|
float shadow = getShadowMask();
|
|
63
3087
|
|
|
64
3088
|
//shift the color by dither_shift
|
|
@@ -68,9 +3092,78 @@ float last = unpackRGBAToDepth(texture2D(tLastThis, vUv));
|
|
|
68
3092
|
gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
|
|
69
3093
|
//if not useMovingAverage:
|
|
70
3094
|
//gl_FragColor = packDepthToRGBA(shadow * opacity + last);
|
|
71
|
-
`)
|
|
3095
|
+
`);
|
|
3096
|
+
Object.assign(shader.uniforms, this._uniforms);
|
|
3097
|
+
super.onBeforeCompile(shader, renderer);
|
|
3098
|
+
}
|
|
3099
|
+
customProgramCacheKey() {
|
|
3100
|
+
return super.customProgramCacheKey();
|
|
3101
|
+
}
|
|
3102
|
+
toJSON() {
|
|
3103
|
+
throw new Error("Method not supported for this material.");
|
|
3104
|
+
}
|
|
3105
|
+
fromJSON() {
|
|
3106
|
+
throw new Error("Method not supported for this material.");
|
|
3107
|
+
}
|
|
3108
|
+
copyProps() {
|
|
3109
|
+
throw new Error("Method not supported for this material.");
|
|
3110
|
+
}
|
|
3111
|
+
setDirty(options) {
|
|
3112
|
+
this.needsUpdate = true;
|
|
3113
|
+
this.dispatchEvent({
|
|
3114
|
+
...options,
|
|
3115
|
+
type: "materialUpdate"
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
};
|
|
3119
|
+
__decorate([(0, threepipe.uniform)({ propKey: "tLastThis" })], FSShadowMaterial.prototype, "lastFrameTexture", void 0);
|
|
3120
|
+
// src/utils/shaders/seperableShadowBlur.glsl
|
|
3121
|
+
var seperableShadowBlur_default = "#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);}";
|
|
3122
|
+
// src/utils/ShadowMapBaker.ts
|
|
3123
|
+
var ShaderChunk = threepipe.RenderManager.ShaderChunk;
|
|
3124
|
+
var ShadowMapBaker = class extends threepipe.SimpleEventDispatcher {
|
|
3125
|
+
get attachedMesh() {
|
|
3126
|
+
return this._attachedMesh;
|
|
3127
|
+
}
|
|
3128
|
+
set attachedMesh(value) {
|
|
3129
|
+
if (this._attachedMesh !== value) {
|
|
3130
|
+
this._attachedMesh && this.cleanupMaterial();
|
|
3131
|
+
this._attachedMesh = value;
|
|
3132
|
+
this._attachedMesh && this._updateMaterial();
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
get target() {
|
|
3136
|
+
return this._target;
|
|
3137
|
+
}
|
|
3138
|
+
get light() {
|
|
3139
|
+
return this._light;
|
|
3140
|
+
}
|
|
3141
|
+
constructor(viewer) {
|
|
3142
|
+
super();
|
|
3143
|
+
this.enabled = true;
|
|
3144
|
+
this._lightLayer = 5;
|
|
3145
|
+
this._frameNumber = 0;
|
|
3146
|
+
this.maxFrameNumber = 400;
|
|
3147
|
+
this.smoothShadow = false;
|
|
3148
|
+
this.shadowMapType = threepipe.BasicShadowMap;
|
|
3149
|
+
this.groundMapMode = "aoMap";
|
|
3150
|
+
this.alphaVignette = true;
|
|
3151
|
+
this.alphaVignetteAxis = "xy";
|
|
3152
|
+
this.shadowAutoUpdate = true;
|
|
3153
|
+
this._bakeCounter = 0;
|
|
3154
|
+
this.maxBakeCount = Infinity;
|
|
3155
|
+
this.materialExtension = {
|
|
3156
|
+
parsFragmentSnippet: (_renderer, _material) => {
|
|
3157
|
+
return threepipe.glsl`
|
|
72
3158
|
uniform float transitionOpacity;
|
|
73
|
-
|
|
3159
|
+
`;
|
|
3160
|
+
},
|
|
3161
|
+
extraUniforms: { transitionOpacity: { value: 1 } },
|
|
3162
|
+
shaderExtender: (shader, _material, renderer) => {
|
|
3163
|
+
if (this.groundMapMode === "aoMap") shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <aomap_fragment>", (0, threepipe.shaderReplaceString)(ShaderChunk.aomap_fragment, "float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;", "float ambientOcclusion = ( mix(1., unpackRGBAToDepth(texture2D( aoMap, vAoMapUv ) ), transitionOpacity) - 1.0) * aoMapIntensity + 1.0;"));
|
|
3164
|
+
else if (this.groundMapMode === "map") shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <map_fragment>", (0, threepipe.shaderReplaceString)(ShaderChunk.map_fragment, "diffuseColor *= sampledDiffuseColor", "float groundShadow = mix(1., unpackRGBAToDepth(sampledDiffuseColor), transitionOpacity); diffuseColor.rgb *= groundShadow; diffuseColor.a *= max(0., 1.-groundShadow) * transitionOpacity;"));
|
|
3165
|
+
else if (this.groundMapMode === "alphaMap") shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <alphamap_fragment>", (0, threepipe.shaderReplaceString)(ShaderChunk.alphamap_fragment, "texture2D( alphaMap, vAlphaMapUv ).g", "1. - unpackRGBAToDepth( texture2D( alphaMap, vAlphaMapUv ) )", { replaceAll: true }));
|
|
3166
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <opaque_fragment>", threepipe.glsl`#include <opaque_fragment>
|
|
74
3167
|
#ifndef OPAQUE
|
|
75
3168
|
#ifdef USE_AOMAP
|
|
76
3169
|
#if NUM_DIR_LIGHT_SHADOWS > 0
|
|
@@ -85,7 +3178,10 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
|
|
|
85
3178
|
gl_FragColor.a *= max(t, 0.);
|
|
86
3179
|
#endif
|
|
87
3180
|
#endif
|
|
88
|
-
`)
|
|
3181
|
+
`);
|
|
3182
|
+
if (this.alphaVignette && renderer.capabilities.isWebGL2) {
|
|
3183
|
+
shader.defines.USE_UV = "";
|
|
3184
|
+
shader.fragmentShader = (0, threepipe.shaderReplaceString)(shader.fragmentShader, "#include <opaque_fragment>", threepipe.glsl`#include <opaque_fragment>
|
|
89
3185
|
#ifndef OPAQUE
|
|
90
3186
|
float weight = 0.;
|
|
91
3187
|
#ifdef USE_UV // why are we checking for this? this is always supposed to be true
|
|
@@ -102,5 +3198,798 @@ gl_FragColor = packDepthToRGBA(mix(last, shadow, opacity));
|
|
|
102
3198
|
gl_FragColor = saturate(gl_FragColor);
|
|
103
3199
|
//gl_FragColor.a = 0.5;
|
|
104
3200
|
#endif
|
|
105
|
-
`))},computeCacheKey:()=>this.groundMapMode+"."+this.alphaVignette+"."+this.alphaVignetteAxis,onObjectRender:(e,t)=>{t.userData.gMapMode!==this.groundMapMode&&(t.userData.gMapMode=this.groundMapMode,t.needsUpdate=!0)},isCompatible:e=>e.isPhysicalMaterial},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),"widget"===e?.object?.assetType||e?.object?.userData?.isWidgetRoot||!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"})});
|
|
106
|
-
|
|
3201
|
+
`);
|
|
3202
|
+
}
|
|
3203
|
+
},
|
|
3204
|
+
computeCacheKey: () => {
|
|
3205
|
+
return this.groundMapMode + "." + this.alphaVignette + "." + this.alphaVignetteAxis;
|
|
3206
|
+
},
|
|
3207
|
+
onObjectRender: (_object, material) => {
|
|
3208
|
+
if (material.userData.gMapMode !== this.groundMapMode) {
|
|
3209
|
+
material.userData.gMapMode = this.groundMapMode;
|
|
3210
|
+
material.needsUpdate = true;
|
|
3211
|
+
}
|
|
3212
|
+
},
|
|
3213
|
+
isCompatible: (material) => {
|
|
3214
|
+
return material.isPhysicalMaterial;
|
|
3215
|
+
}
|
|
3216
|
+
};
|
|
3217
|
+
this._viewer = viewer;
|
|
3218
|
+
const light = new RandomizedDirectionalLight(16777215, 10, {
|
|
3219
|
+
near: 1.5,
|
|
3220
|
+
far: 20,
|
|
3221
|
+
bias: 0,
|
|
3222
|
+
frustumSize: 4,
|
|
3223
|
+
width: 1024,
|
|
3224
|
+
height: 1024,
|
|
3225
|
+
enabled: true,
|
|
3226
|
+
radius: 10,
|
|
3227
|
+
normalBias: 0
|
|
3228
|
+
}, {
|
|
3229
|
+
direction: new threepipe.Vector3(.2, 1, .2).normalize(),
|
|
3230
|
+
spread: .9,
|
|
3231
|
+
focus: 1,
|
|
3232
|
+
distanceScale: 20,
|
|
3233
|
+
minDistanceScale: new threepipe.Vector3(10, 10, 10),
|
|
3234
|
+
normalDirection: new threepipe.Vector3(0, 1, 0)
|
|
3235
|
+
});
|
|
3236
|
+
light.shadow.camera.updateProjectionMatrix();
|
|
3237
|
+
light.layers.disableAll();
|
|
3238
|
+
light.layers.set(this._lightLayer);
|
|
3239
|
+
this._light = light;
|
|
3240
|
+
viewer.scene.addObject(this._light, { addToRoot: true });
|
|
3241
|
+
this._shadowMat = new FSShadowMaterial({
|
|
3242
|
+
color: "#ffffff",
|
|
3243
|
+
toneMapped: false,
|
|
3244
|
+
depthWrite: false,
|
|
3245
|
+
depthTest: false,
|
|
3246
|
+
premultipliedAlpha: false,
|
|
3247
|
+
opacity: 1,
|
|
3248
|
+
transparent: false,
|
|
3249
|
+
blending: threepipe.NoBlending
|
|
3250
|
+
});
|
|
3251
|
+
this._shadowBlurMat = new threepipe.ShaderMaterial2({
|
|
3252
|
+
uniforms: {
|
|
3253
|
+
"colorTexture": { value: null },
|
|
3254
|
+
"step": { value: .1 },
|
|
3255
|
+
"size": { value: new threepipe.Vector2(.5, .5) },
|
|
3256
|
+
"direction": { value: new threepipe.Vector2(.5, .5) }
|
|
3257
|
+
},
|
|
3258
|
+
vertexShader: threepipe.shaderUtils.defaultVertex,
|
|
3259
|
+
fragmentShader: seperableShadowBlur_default
|
|
3260
|
+
});
|
|
3261
|
+
}
|
|
3262
|
+
dispose() {
|
|
3263
|
+
this._shadowMat.dispose();
|
|
3264
|
+
this._shadowBlurMat.dispose();
|
|
3265
|
+
if (this._target) this._viewer.renderManager.disposeTarget(this._target);
|
|
3266
|
+
this._target = void 0;
|
|
3267
|
+
this._light.dispose();
|
|
3268
|
+
this.reset();
|
|
3269
|
+
}
|
|
3270
|
+
cleanupMaterial() {
|
|
3271
|
+
this._updateMaterial(true);
|
|
3272
|
+
}
|
|
3273
|
+
_groundMapModeChanged() {
|
|
3274
|
+
if (this._attachedMesh) {
|
|
3275
|
+
this.cleanupMaterial();
|
|
3276
|
+
this._updateMaterial();
|
|
3277
|
+
if (this.groundMapMode === "alphaMap") this._attachedMesh.material.transparent = true;
|
|
3278
|
+
else this._attachedMesh.material.transparent = false;
|
|
3279
|
+
}
|
|
3280
|
+
this.reset();
|
|
3281
|
+
}
|
|
3282
|
+
_alphaVignetteChanged() {
|
|
3283
|
+
this.materialExtension?.setDirty?.();
|
|
3284
|
+
this._viewer?.setDirty();
|
|
3285
|
+
}
|
|
3286
|
+
fromJSON(data, meta, _internal = false) {
|
|
3287
|
+
if (!_internal) return threepipe.ThreeSerialization.Deserialize(data, this, meta, false);
|
|
3288
|
+
else {
|
|
3289
|
+
threepipe.ThreeSerialization.Deserialize(data, this, meta, true);
|
|
3290
|
+
this.reset();
|
|
3291
|
+
}
|
|
3292
|
+
return this;
|
|
3293
|
+
}
|
|
3294
|
+
reset() {
|
|
3295
|
+
this._frameNumber = 0;
|
|
3296
|
+
}
|
|
3297
|
+
get frameNumber() {
|
|
3298
|
+
return this._frameNumber;
|
|
3299
|
+
}
|
|
3300
|
+
autoUpdateShadow() {
|
|
3301
|
+
if (this.shadowAutoUpdate) {
|
|
3302
|
+
if (this._bakeCounter >= this.maxBakeCount) return false;
|
|
3303
|
+
if (!this.updateShadow()) return false;
|
|
3304
|
+
if (this._frameNumber === this.maxFrameNumber) this.dispatchEvent({
|
|
3305
|
+
type: "shadowBaked",
|
|
3306
|
+
bakeCount: ++this._bakeCounter
|
|
3307
|
+
});
|
|
3308
|
+
else if (this._frameNumber > 0 && this._frameNumber < this.maxFrameNumber) this.dispatchEvent({
|
|
3309
|
+
type: "shadowBaking",
|
|
3310
|
+
progress: this._frameNumber / this.maxFrameNumber,
|
|
3311
|
+
bakeCount: this._bakeCounter
|
|
3312
|
+
});
|
|
3313
|
+
return true;
|
|
3314
|
+
}
|
|
3315
|
+
return false;
|
|
3316
|
+
}
|
|
3317
|
+
updateShadow() {
|
|
3318
|
+
if (!this.enabled) return false;
|
|
3319
|
+
const mesh = this._attachedMesh;
|
|
3320
|
+
if (!mesh) return false;
|
|
3321
|
+
if (++this._frameNumber > this.maxFrameNumber) return false;
|
|
3322
|
+
const customSize = 1024;
|
|
3323
|
+
if (!this._target) this._target = this._viewer.renderManager.createTarget({
|
|
3324
|
+
type: threepipe.UnsignedByteType,
|
|
3325
|
+
depthBuffer: false,
|
|
3326
|
+
size: new threepipe.Vector2(customSize, customSize),
|
|
3327
|
+
sizeMultiplier: void 0,
|
|
3328
|
+
colorSpace: threepipe.NoColorSpace,
|
|
3329
|
+
format: threepipe.RGBAFormat
|
|
3330
|
+
});
|
|
3331
|
+
if (this._frameNumber < 3) this._light.randomizePosition(0, 1, 0);
|
|
3332
|
+
else this._light.randomizePosition(this._frameNumber);
|
|
3333
|
+
mesh.castShadow = false;
|
|
3334
|
+
const renderer = this._viewer.renderManager.renderer;
|
|
3335
|
+
const shadowMap = renderer.shadowMap;
|
|
3336
|
+
const shadowMapType = shadowMap.type;
|
|
3337
|
+
const shadowMapNeedsUpdate = shadowMap.needsUpdate;
|
|
3338
|
+
const shadowMapAutoUpdate = shadowMap.autoUpdate;
|
|
3339
|
+
shadowMap.type = this.shadowMapType;
|
|
3340
|
+
shadowMap.needsUpdate = true;
|
|
3341
|
+
shadowMap.autoUpdate = false;
|
|
3342
|
+
const scene = this._viewer.scene;
|
|
3343
|
+
const sceneLightLayer = new threepipe.Layers();
|
|
3344
|
+
sceneLightLayer.disableAll();
|
|
3345
|
+
scene.traverse((o) => {
|
|
3346
|
+
if (o.isLight && o !== this._light) {
|
|
3347
|
+
o.userData.__gp_layers = o.layers;
|
|
3348
|
+
o.layers = sceneLightLayer;
|
|
3349
|
+
}
|
|
3350
|
+
});
|
|
3351
|
+
const cam = scene.mainCamera;
|
|
3352
|
+
if ((cam.layers.mask & 1 << this._lightLayer) !== 0) throw "Camera can render pseudo directional light, check layers";
|
|
3353
|
+
cam.layers.enable(this._lightLayer);
|
|
3354
|
+
mesh.layers.disable(this._lightLayer);
|
|
3355
|
+
renderer.renderWithModes({
|
|
3356
|
+
shadowMapRender: true,
|
|
3357
|
+
backgroundRender: false,
|
|
3358
|
+
sceneRender: false
|
|
3359
|
+
}, () => renderer.render(scene, scene.mainCamera));
|
|
3360
|
+
cam.layers.disable(this._lightLayer);
|
|
3361
|
+
const camLayers = cam.layers.mask;
|
|
3362
|
+
cam.layers.set(this._lightLayer);
|
|
3363
|
+
mesh.layers.enable(this._lightLayer);
|
|
3364
|
+
const lastThisTarget = this._viewer.renderManager.getTempTarget({
|
|
3365
|
+
type: threepipe.UnsignedByteType,
|
|
3366
|
+
depthBuffer: false,
|
|
3367
|
+
size: new threepipe.Vector2(customSize, customSize),
|
|
3368
|
+
colorSpace: threepipe.NoColorSpace,
|
|
3369
|
+
format: threepipe.RGBAFormat
|
|
3370
|
+
});
|
|
3371
|
+
const texture = lastThisTarget.texture;
|
|
3372
|
+
const lastThisTargetColorSpace = texture.colorSpace;
|
|
3373
|
+
texture.colorSpace = threepipe.NoColorSpace;
|
|
3374
|
+
this._viewer.renderManager.blit(lastThisTarget, {
|
|
3375
|
+
clear: true,
|
|
3376
|
+
source: this._target.texture
|
|
3377
|
+
});
|
|
3378
|
+
{
|
|
3379
|
+
const currentMaterial = mesh.material;
|
|
3380
|
+
const currentFrustumCulled = mesh.frustumCulled;
|
|
3381
|
+
const currentRt = renderer.getRenderTarget();
|
|
3382
|
+
const activeCubeFace = renderer.getActiveCubeFace();
|
|
3383
|
+
const activeMipLevel = renderer.getActiveMipmapLevel();
|
|
3384
|
+
mesh.material = this._shadowMat;
|
|
3385
|
+
mesh.frustumCulled = false;
|
|
3386
|
+
renderer.setRenderTarget(this._target);
|
|
3387
|
+
this._shadowMat.opacity = Math.max(1 / this.maxFrameNumber, 1 / this._frameNumber);
|
|
3388
|
+
this._shadowMat.lastFrameTexture = lastThisTarget.texture;
|
|
3389
|
+
this._shadowMat.needsUpdate = true;
|
|
3390
|
+
renderer.renderWithModes({
|
|
3391
|
+
shadowMapRender: false,
|
|
3392
|
+
backgroundRender: false,
|
|
3393
|
+
opaqueRender: true,
|
|
3394
|
+
transparentRender: false,
|
|
3395
|
+
transmissionRender: false
|
|
3396
|
+
}, () => renderer.render(scene, scene.mainCamera));
|
|
3397
|
+
renderer.setRenderTarget(currentRt, activeCubeFace, activeMipLevel);
|
|
3398
|
+
mesh.frustumCulled = currentFrustumCulled;
|
|
3399
|
+
mesh.material = currentMaterial;
|
|
3400
|
+
if (this.smoothShadow) this._applySmoothFilter(this._target, lastThisTarget);
|
|
3401
|
+
}
|
|
3402
|
+
lastThisTarget.texture.colorSpace = lastThisTargetColorSpace;
|
|
3403
|
+
this._viewer.renderManager.releaseTempTarget(lastThisTarget);
|
|
3404
|
+
mesh.layers.disable(this._lightLayer);
|
|
3405
|
+
cam.layers.mask = camLayers;
|
|
3406
|
+
scene.modelObject.traverse((o) => {
|
|
3407
|
+
if (o.isLight && o !== this._light.lightObject) {
|
|
3408
|
+
o.layers = o.userData.__gp_layers;
|
|
3409
|
+
delete o.userData.__gp_layers;
|
|
3410
|
+
}
|
|
3411
|
+
});
|
|
3412
|
+
shadowMap.type = shadowMapType;
|
|
3413
|
+
shadowMap.needsUpdate = shadowMapNeedsUpdate;
|
|
3414
|
+
shadowMap.autoUpdate = shadowMapAutoUpdate;
|
|
3415
|
+
mesh.castShadow = true;
|
|
3416
|
+
if (this._frameNumber < 3 || this._frameNumber > Math.min(100, this.maxFrameNumber) && this._frameNumber % 4 === 0) {
|
|
3417
|
+
this._updateMaterial();
|
|
3418
|
+
mesh.material.setDirty();
|
|
3419
|
+
}
|
|
3420
|
+
return true;
|
|
3421
|
+
}
|
|
3422
|
+
_updateMaterial(isNull = false) {
|
|
3423
|
+
if (!this._attachedMesh) return;
|
|
3424
|
+
if (isNull) {
|
|
3425
|
+
if (this._attachedMesh.material.alphaMap === this._target?.texture) this._attachedMesh.material.alphaMap = null;
|
|
3426
|
+
if (this._attachedMesh.material.aoMap === this._target?.texture) this._attachedMesh.material.aoMap = null;
|
|
3427
|
+
if (this._attachedMesh.material.map === this._target?.texture) this._attachedMesh.material.map = null;
|
|
3428
|
+
} else if (this._target) {
|
|
3429
|
+
if (this.groundMapMode === "alphaMap") this._attachedMesh.material.alphaMap = this._target.texture;
|
|
3430
|
+
if (this.groundMapMode === "aoMap") this._attachedMesh.material.aoMap = this._target.texture;
|
|
3431
|
+
if (this.groundMapMode === "map") this._attachedMesh.material.map = this._target.texture;
|
|
3432
|
+
}
|
|
3433
|
+
if (this._attachedMesh.material) {
|
|
3434
|
+
this._attachedMesh.material.userData.ALPHA_I_RGBA_PACKING = !isNull && this.groundMapMode === "alphaMap";
|
|
3435
|
+
this._attachedMesh.material.alphaTest = !isNull && this.groundMapMode === "alphaMap" ? .01 : 0;
|
|
3436
|
+
this._attachedMesh.material.needsUpdate = true;
|
|
3437
|
+
}
|
|
3438
|
+
}
|
|
3439
|
+
_applySmoothFilter(shadowReadBuffer, shadowWriteBuffer) {
|
|
3440
|
+
this._shadowBlurMat.uniforms.colorTexture.value = shadowReadBuffer.texture;
|
|
3441
|
+
this._shadowBlurMat.uniforms.direction.value.set(1, 0);
|
|
3442
|
+
this._shadowBlurMat.uniforms.size.value.set(shadowReadBuffer.width, shadowReadBuffer.height);
|
|
3443
|
+
this._viewer.renderManager.blit(shadowWriteBuffer, { material: this._shadowBlurMat });
|
|
3444
|
+
this._shadowBlurMat.uniforms.colorTexture.value = shadowWriteBuffer.texture;
|
|
3445
|
+
this._shadowBlurMat.uniforms.direction.value.set(0, 1);
|
|
3446
|
+
this._shadowBlurMat.uniforms.size.value.set(shadowWriteBuffer.width, shadowWriteBuffer.height);
|
|
3447
|
+
this._viewer.renderManager.blit(shadowReadBuffer, { material: this._shadowBlurMat });
|
|
3448
|
+
}
|
|
3449
|
+
};
|
|
3450
|
+
__decorate([(0, threepipe.serialize)("randomizedLight")], ShadowMapBaker.prototype, "_light", void 0);
|
|
3451
|
+
__decorate([(0, threepipe.onChange)(ShadowMapBaker.prototype.reset), (0, threepipe.serialize)()], ShadowMapBaker.prototype, "maxFrameNumber", void 0);
|
|
3452
|
+
__decorate([(0, threepipe.onChange)(ShadowMapBaker.prototype.reset), (0, threepipe.serialize)()], ShadowMapBaker.prototype, "smoothShadow", void 0);
|
|
3453
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.onChange)(ShadowMapBaker.prototype.reset)], ShadowMapBaker.prototype, "shadowMapType", void 0);
|
|
3454
|
+
__decorate([(0, threepipe.onChange)(ShadowMapBaker.prototype._groundMapModeChanged), (0, threepipe.serialize)()], ShadowMapBaker.prototype, "groundMapMode", void 0);
|
|
3455
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.onChange)(ShadowMapBaker.prototype._alphaVignetteChanged)], ShadowMapBaker.prototype, "alphaVignette", void 0);
|
|
3456
|
+
__decorate([(0, threepipe.serialize)(), (0, threepipe.onChange)(ShadowMapBaker.prototype._alphaVignetteChanged)], ShadowMapBaker.prototype, "alphaVignetteAxis", void 0);
|
|
3457
|
+
__decorate([(0, threepipe.serialize)()], ShadowMapBaker.prototype, "maxBakeCount", void 0);
|
|
3458
|
+
// src/plugins/extras/AdvancedGroundPlugin.ts
|
|
3459
|
+
var AdvancedGroundPlugin = class extends threepipe.BaseGroundPlugin {
|
|
3460
|
+
static {
|
|
3461
|
+
this.PluginType = "AdvancedGroundPlugin";
|
|
3462
|
+
}
|
|
3463
|
+
get shadowBaker() {
|
|
3464
|
+
return this._shadowBaker;
|
|
3465
|
+
}
|
|
3466
|
+
_refresh3() {
|
|
3467
|
+
this.refresh();
|
|
3468
|
+
}
|
|
3469
|
+
/**
|
|
3470
|
+
* bake shadows manually, to be used with {@see autoBakeShadows} set to false
|
|
3471
|
+
*/
|
|
3472
|
+
bakeShadows() {
|
|
3473
|
+
this._shadowBaker?.reset();
|
|
3474
|
+
}
|
|
3475
|
+
constructor() {
|
|
3476
|
+
super();
|
|
3477
|
+
this.bakedShadows = true;
|
|
3478
|
+
this.groundReflection = false;
|
|
3479
|
+
this.physicalReflections = false;
|
|
3480
|
+
this.autoFrustumSize = true;
|
|
3481
|
+
this.autoBakeShadows = true;
|
|
3482
|
+
this.autoResetShadows = () => {
|
|
3483
|
+
if (this.autoBakeShadows) this._shadowBaker?.reset();
|
|
3484
|
+
};
|
|
3485
|
+
this._onSceneUpdate = this._onSceneUpdate.bind(this);
|
|
3486
|
+
const generatedUi = (0, threepipe.generateUiConfig)(this);
|
|
3487
|
+
const matUI = generatedUi.find((f) => typeof f === "function");
|
|
3488
|
+
this.uiConfig = {
|
|
3489
|
+
label: "Ground",
|
|
3490
|
+
type: "folder",
|
|
3491
|
+
children: [
|
|
3492
|
+
...generatedUi.filter((f) => f !== matUI),
|
|
3493
|
+
...this._extraUiConfig(),
|
|
3494
|
+
matUI
|
|
3495
|
+
]
|
|
3496
|
+
};
|
|
3497
|
+
}
|
|
3498
|
+
_createMesh(mesh) {
|
|
3499
|
+
if (mesh) throw new Error("AdvancedGroundPlugin - mesh should not be provided");
|
|
3500
|
+
const reflector = new Reflector2(this._geometry, () => this._reflectionTarget ??= this._viewer?.renderManager.createTarget({
|
|
3501
|
+
type: threepipe.UnsignedByteType,
|
|
3502
|
+
format: threepipe.RGBAFormat,
|
|
3503
|
+
colorSpace: threepipe.NoColorSpace,
|
|
3504
|
+
size: {
|
|
3505
|
+
width: 1024,
|
|
3506
|
+
height: 1024
|
|
3507
|
+
},
|
|
3508
|
+
generateMipmaps: true,
|
|
3509
|
+
depthBuffer: true,
|
|
3510
|
+
minFilter: threepipe.LinearMipmapLinearFilter,
|
|
3511
|
+
magFilter: threepipe.LinearFilter
|
|
3512
|
+
}), 0, this._createMaterial());
|
|
3513
|
+
const superOnBeforeRender = reflector.onBeforeRender;
|
|
3514
|
+
reflector.onBeforeRender = (...params) => {
|
|
3515
|
+
let ssr = this._viewer?.getPluginByType("SSReflectionPlugin");
|
|
3516
|
+
if (ssr && ssr.isDisabled()) ssr = void 0;
|
|
3517
|
+
if (ssr) ssr.disable(reflector.uuid, false);
|
|
3518
|
+
superOnBeforeRender(...params);
|
|
3519
|
+
if (ssr) ssr.enable(reflector.uuid, false);
|
|
3520
|
+
};
|
|
3521
|
+
return reflector;
|
|
3522
|
+
}
|
|
3523
|
+
onAdded(viewer) {
|
|
3524
|
+
super.onAdded(viewer);
|
|
3525
|
+
}
|
|
3526
|
+
_postFrame() {
|
|
3527
|
+
super._postFrame();
|
|
3528
|
+
if (!this._viewer) return;
|
|
3529
|
+
if (!this.enabled) return;
|
|
3530
|
+
if (this._shadowBaker && this.bakedShadows) this._shadowBaker.autoUpdateShadow();
|
|
3531
|
+
}
|
|
3532
|
+
_preRender() {
|
|
3533
|
+
super._preRender();
|
|
3534
|
+
if (!this._viewer) return;
|
|
3535
|
+
this._mesh.reflectionTargetNeedsUpdate = this._viewer.renderManager.frameCount < 1;
|
|
3536
|
+
}
|
|
3537
|
+
onRemove(viewer) {
|
|
3538
|
+
if (this._reflectionTarget) {
|
|
3539
|
+
viewer.renderManager.disposeTarget(this._reflectionTarget);
|
|
3540
|
+
this._reflectionTarget = void 0;
|
|
3541
|
+
}
|
|
3542
|
+
super.onRemove(viewer);
|
|
3543
|
+
this._shadowBaker?.dispose();
|
|
3544
|
+
this._shadowBaker = void 0;
|
|
3545
|
+
}
|
|
3546
|
+
_removeMaterial() {
|
|
3547
|
+
if (!this._material) return;
|
|
3548
|
+
if (this._shadowBaker && this._material.groundMatExtension) {
|
|
3549
|
+
this._material.unregisterMaterialExtensions?.([this._shadowBaker.materialExtension]);
|
|
3550
|
+
delete this._material.groundMatExtension;
|
|
3551
|
+
}
|
|
3552
|
+
if (this._material.reflectorMatExtension) {
|
|
3553
|
+
const ext = this._mesh.materialExtension;
|
|
3554
|
+
if (!ext) this._viewer?.console.warn("AdavancedGroundPlugin: unable to find the extension to unregister");
|
|
3555
|
+
this._material.unregisterMaterialExtensions?.([ext]);
|
|
3556
|
+
delete this._material.reflectorMatExtension;
|
|
3557
|
+
}
|
|
3558
|
+
super._removeMaterial();
|
|
3559
|
+
}
|
|
3560
|
+
_onSceneUpdate(event) {
|
|
3561
|
+
super._onSceneUpdate(event);
|
|
3562
|
+
if (event?.object?.assetType === "widget" || event?.object?.userData?.isWidgetRoot) return;
|
|
3563
|
+
if (event.geometryChanged === false) return;
|
|
3564
|
+
this.autoResetShadows();
|
|
3565
|
+
}
|
|
3566
|
+
refresh() {
|
|
3567
|
+
if (!this._viewer) return;
|
|
3568
|
+
if (!this.isDisabled()) {
|
|
3569
|
+
if (this.bakedShadows && !this._shadowBaker) {
|
|
3570
|
+
this._shadowBaker = new ShadowMapBaker(this._viewer);
|
|
3571
|
+
this._shadowBaker.attachedMesh = this._mesh;
|
|
3572
|
+
} else if (!this.bakedShadows && this._shadowBaker) {
|
|
3573
|
+
this._shadowBaker.reset();
|
|
3574
|
+
this._shadowBaker.cleanupMaterial();
|
|
3575
|
+
}
|
|
3576
|
+
const ref = this._mesh;
|
|
3577
|
+
if (ref.isReflector2) {
|
|
3578
|
+
ref.enabled = this.groundReflection;
|
|
3579
|
+
ref.reflectorModePhysical = this.physicalReflections;
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
super.refresh();
|
|
3583
|
+
}
|
|
3584
|
+
_refreshTransform() {
|
|
3585
|
+
if (!super._refreshTransform()) return false;
|
|
3586
|
+
if (this.autoFrustumSize) {
|
|
3587
|
+
const baker = this.shadowBaker;
|
|
3588
|
+
if (baker) {
|
|
3589
|
+
const fs = this.size / 2;
|
|
3590
|
+
if (fs !== baker.light.shadowParams.frustumSize) {
|
|
3591
|
+
baker.light.shadowParams.frustumSize = fs;
|
|
3592
|
+
baker.light.updateShadowParams();
|
|
3593
|
+
baker.reset();
|
|
3594
|
+
}
|
|
3595
|
+
}
|
|
3596
|
+
}
|
|
3597
|
+
return true;
|
|
3598
|
+
}
|
|
3599
|
+
fromJSON(data, meta) {
|
|
3600
|
+
if (!super.fromJSON(data, meta)) return null;
|
|
3601
|
+
if (data.autoFrustumSize === void 0) this.autoFrustumSize = false;
|
|
3602
|
+
return this;
|
|
3603
|
+
}
|
|
3604
|
+
_refreshMaterial() {
|
|
3605
|
+
if (!this._viewer) return false;
|
|
3606
|
+
super._refreshMaterial();
|
|
3607
|
+
if (!this._material) return;
|
|
3608
|
+
if (this.groundReflection && this._mesh.isReflector2 && !this._material.reflectorMatExtension) {
|
|
3609
|
+
const ext = this._mesh.materialExtension;
|
|
3610
|
+
ext.updaters = [this._viewer.scene, this._viewer.renderManager];
|
|
3611
|
+
this._material.registerMaterialExtensions?.([ext]);
|
|
3612
|
+
this._material.reflectorMatExtension = true;
|
|
3613
|
+
}
|
|
3614
|
+
if (this.bakedShadows && this._shadowBaker && !this._material.groundMatExtension) {
|
|
3615
|
+
this._material.registerMaterialExtensions?.([this._shadowBaker.materialExtension]);
|
|
3616
|
+
this._material.groundMatExtension = true;
|
|
3617
|
+
}
|
|
3618
|
+
this._material.userData.ssreflDisabled = this.groundReflection;
|
|
3619
|
+
this._material.userData.ssreflNonPhysical = !this.physicalReflections;
|
|
3620
|
+
this._material.userData.ssaoDisabled = true;
|
|
3621
|
+
this._material.userData.sscsDisabled = true;
|
|
3622
|
+
this._viewer.setDirty(this);
|
|
3623
|
+
}
|
|
3624
|
+
_extraUiConfig() {
|
|
3625
|
+
return [
|
|
3626
|
+
{
|
|
3627
|
+
label: "Shadow Frames",
|
|
3628
|
+
type: "input",
|
|
3629
|
+
hidden: () => !this._shadowBaker,
|
|
3630
|
+
stepSize: 1,
|
|
3631
|
+
bounds: [1, 1e3],
|
|
3632
|
+
property: () => [this._shadowBaker, "maxFrameNumber"]
|
|
3633
|
+
},
|
|
3634
|
+
{
|
|
3635
|
+
label: "Alpha Vignette",
|
|
3636
|
+
type: "checkbox",
|
|
3637
|
+
hidden: () => !this._material || (this._material.transmission || 0) < 1e-4 && !this._material.transparent,
|
|
3638
|
+
property: () => [this._shadowBaker, "alphaVignette"],
|
|
3639
|
+
limitedUi: true,
|
|
3640
|
+
onChange: () => this.uiConfig?.uiRefresh?.(true, "postFrame")
|
|
3641
|
+
},
|
|
3642
|
+
{
|
|
3643
|
+
label: "Alpha Vignette Axis",
|
|
3644
|
+
type: "dropdown",
|
|
3645
|
+
hidden: () => !this._shadowBaker?.alphaVignette || !this._material || (this._material.transmission || 0) < 1e-4 && !this._material.transparent,
|
|
3646
|
+
property: () => [this._shadowBaker, "alphaVignetteAxis"],
|
|
3647
|
+
children: [
|
|
3648
|
+
"x",
|
|
3649
|
+
"y",
|
|
3650
|
+
"xy"
|
|
3651
|
+
].map((v) => ({
|
|
3652
|
+
label: v,
|
|
3653
|
+
value: v
|
|
3654
|
+
})),
|
|
3655
|
+
limitedUi: true
|
|
3656
|
+
},
|
|
3657
|
+
{
|
|
3658
|
+
label: "Shadow type",
|
|
3659
|
+
type: "dropdown",
|
|
3660
|
+
hidden: () => !this._shadowBaker,
|
|
3661
|
+
property: () => [this._shadowBaker, "groundMapMode"],
|
|
3662
|
+
children: [
|
|
3663
|
+
{ label: "aoMap" },
|
|
3664
|
+
{ label: "map" },
|
|
3665
|
+
{ label: "alphaMap" }
|
|
3666
|
+
],
|
|
3667
|
+
limitedUi: true
|
|
3668
|
+
},
|
|
3669
|
+
{
|
|
3670
|
+
label: "Smooth Shadow",
|
|
3671
|
+
type: "checkbox",
|
|
3672
|
+
property: () => [this._shadowBaker, "smoothShadow"]
|
|
3673
|
+
},
|
|
3674
|
+
{
|
|
3675
|
+
label: "Baked shadow type",
|
|
3676
|
+
type: "dropdown",
|
|
3677
|
+
children: [
|
|
3678
|
+
["Basic", threepipe.BasicShadowMap],
|
|
3679
|
+
["PCF", threepipe.PCFShadowMap],
|
|
3680
|
+
["PCFSoft", threepipe.PCFSoftShadowMap],
|
|
3681
|
+
["VSM", threepipe.VSMShadowMap]
|
|
3682
|
+
].map((v) => ({
|
|
3683
|
+
label: v[0].toString(),
|
|
3684
|
+
value: v[1]
|
|
3685
|
+
})),
|
|
3686
|
+
property: () => [this._shadowBaker, "shadowMapType"]
|
|
3687
|
+
},
|
|
3688
|
+
{
|
|
3689
|
+
type: "folder",
|
|
3690
|
+
label: "Randomized Light",
|
|
3691
|
+
hidden: () => !this._shadowBaker,
|
|
3692
|
+
limitedUi: true,
|
|
3693
|
+
children: [
|
|
3694
|
+
{
|
|
3695
|
+
type: "color",
|
|
3696
|
+
label: "Color",
|
|
3697
|
+
property: () => [this._shadowBaker?.light, "color"]
|
|
3698
|
+
},
|
|
3699
|
+
{
|
|
3700
|
+
type: "slider",
|
|
3701
|
+
bounds: [0, 1],
|
|
3702
|
+
property: () => [this._shadowBaker?.light?.randomParams, "focus"],
|
|
3703
|
+
onChange: this.autoResetShadows
|
|
3704
|
+
},
|
|
3705
|
+
{
|
|
3706
|
+
type: "slider",
|
|
3707
|
+
bounds: [0, 1],
|
|
3708
|
+
property: () => [this._shadowBaker?.light?.randomParams, "spread"],
|
|
3709
|
+
onChange: this.autoResetShadows,
|
|
3710
|
+
limitedUi: true
|
|
3711
|
+
},
|
|
3712
|
+
{
|
|
3713
|
+
type: "slider",
|
|
3714
|
+
bounds: [.01, 60],
|
|
3715
|
+
property: () => [this._shadowBaker?.light?.randomParams, "distanceScale"],
|
|
3716
|
+
onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
|
|
3717
|
+
},
|
|
3718
|
+
{
|
|
3719
|
+
type: "vec3",
|
|
3720
|
+
bounds: [-1, 1],
|
|
3721
|
+
property: () => [this._shadowBaker?.light?.randomParams, "direction"],
|
|
3722
|
+
onChange: this.autoResetShadows,
|
|
3723
|
+
limitedUi: true
|
|
3724
|
+
},
|
|
3725
|
+
{
|
|
3726
|
+
type: "vec3",
|
|
3727
|
+
bounds: [-1, 1],
|
|
3728
|
+
property: () => [this._shadowBaker?.light?.randomParams, "normalDirection"],
|
|
3729
|
+
onChange: this.autoResetShadows,
|
|
3730
|
+
limitedUi: true
|
|
3731
|
+
},
|
|
3732
|
+
{
|
|
3733
|
+
type: "slider",
|
|
3734
|
+
bounds: [.01, 10],
|
|
3735
|
+
property: () => [this._shadowBaker?.light?.shadowParams, "radius"],
|
|
3736
|
+
onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
|
|
3737
|
+
},
|
|
3738
|
+
{
|
|
3739
|
+
type: "input",
|
|
3740
|
+
property: () => [this._shadowBaker?.light?.shadowParams, "frustumSize"],
|
|
3741
|
+
hidden: () => this.autoFrustumSize,
|
|
3742
|
+
onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
|
|
3743
|
+
},
|
|
3744
|
+
{
|
|
3745
|
+
type: "slider",
|
|
3746
|
+
bounds: [-.1, .1],
|
|
3747
|
+
property: () => [this._shadowBaker?.light?.shadowParams, "bias"],
|
|
3748
|
+
onChange: [this._shadowBaker?.light?.updateShadowParams, this.autoResetShadows]
|
|
3749
|
+
}
|
|
3750
|
+
]
|
|
3751
|
+
}
|
|
3752
|
+
];
|
|
3753
|
+
}
|
|
3754
|
+
};
|
|
3755
|
+
__decorate([
|
|
3756
|
+
(0, threepipe.onChange)(AdvancedGroundPlugin.prototype._refresh3),
|
|
3757
|
+
(0, threepipe.uiToggle)("Baked Shadows"),
|
|
3758
|
+
(0, threepipe.serialize)()
|
|
3759
|
+
], AdvancedGroundPlugin.prototype, "bakedShadows", void 0);
|
|
3760
|
+
__decorate([
|
|
3761
|
+
(0, threepipe.onChange)(AdvancedGroundPlugin.prototype._refresh3),
|
|
3762
|
+
(0, threepipe.uiToggle)("Planar Reflections"),
|
|
3763
|
+
(0, threepipe.serialize)()
|
|
3764
|
+
], AdvancedGroundPlugin.prototype, "groundReflection", void 0);
|
|
3765
|
+
__decorate([
|
|
3766
|
+
(0, threepipe.onChange)(AdvancedGroundPlugin.prototype._refresh3),
|
|
3767
|
+
(0, threepipe.uiToggle)("Physical Reflections"),
|
|
3768
|
+
(0, threepipe.serialize)()
|
|
3769
|
+
], AdvancedGroundPlugin.prototype, "physicalReflections", void 0);
|
|
3770
|
+
__decorate([
|
|
3771
|
+
(0, threepipe.onChange)(AdvancedGroundPlugin.prototype._refresh3),
|
|
3772
|
+
(0, threepipe.uiToggle)("Auto Shadow Frustum Size"),
|
|
3773
|
+
(0, threepipe.serialize)()
|
|
3774
|
+
], AdvancedGroundPlugin.prototype, "autoFrustumSize", void 0);
|
|
3775
|
+
__decorate([(0, threepipe.serialize)("shadowBaker")], AdvancedGroundPlugin.prototype, "_shadowBaker", void 0);
|
|
3776
|
+
__decorate([(0, threepipe.bindToValue)({ key: "groundReflection" })], AdvancedGroundPlugin.prototype, "planarReflections", void 0);
|
|
3777
|
+
// src/plugins/extras/WatchHandsPlugin.ts
|
|
3778
|
+
var WatchHandsPlugin = class WatchHandsPlugin extends threepipe.AViewerPluginSync {
|
|
3779
|
+
constructor(..._args) {
|
|
3780
|
+
super(..._args);
|
|
3781
|
+
this.enabled = true;
|
|
3782
|
+
this.dependencies = [];
|
|
3783
|
+
this.axis = "y";
|
|
3784
|
+
this.invertAxis = false;
|
|
3785
|
+
this.analog = true;
|
|
3786
|
+
this.hourOffset = 0;
|
|
3787
|
+
this.minuteOffset = 0;
|
|
3788
|
+
this.secondOffset = 0;
|
|
3789
|
+
this.hour = ".*hour.*";
|
|
3790
|
+
this.minute = ".*minute.*";
|
|
3791
|
+
this.second = ".*second.*";
|
|
3792
|
+
this.regex = true;
|
|
3793
|
+
this.hands = [];
|
|
3794
|
+
this._lastEnabled = true;
|
|
3795
|
+
this._preFrame = () => {
|
|
3796
|
+
if (!this.enabled) {
|
|
3797
|
+
if (this._lastEnabled) {
|
|
3798
|
+
this._lastEnabled = false;
|
|
3799
|
+
if (!this.hands.length) return;
|
|
3800
|
+
for (const h of this.hands) {
|
|
3801
|
+
h.object.rotation.fromArray(h.object.userData.initRotation);
|
|
3802
|
+
h.object.updateMatrixWorld();
|
|
3803
|
+
}
|
|
3804
|
+
this._viewer?.renderManager.resetShadows();
|
|
3805
|
+
this._viewer?.setDirty();
|
|
3806
|
+
}
|
|
3807
|
+
return;
|
|
3808
|
+
}
|
|
3809
|
+
this._lastEnabled = true;
|
|
3810
|
+
if (!this.hands.length) return;
|
|
3811
|
+
if (this._viewer?.getPlugin("ProgressivePlugin")?.postFrameConvergedRecordingDelta() === 0) return;
|
|
3812
|
+
const time = /* @__PURE__ */ new Date();
|
|
3813
|
+
const invert = this.invertAxis ? -1 : 1;
|
|
3814
|
+
const secondHandRotation = invert * (time.getSeconds() + (this.analog ? time.getMilliseconds() / 1e3 : 0) - this.secondOffset) * (Math.PI * 2) / 60;
|
|
3815
|
+
const minuteHandRotation = invert * (time.getMinutes() - this.minuteOffset) * (Math.PI * 2) / 60 + secondHandRotation / 60;
|
|
3816
|
+
const targetRotation = {
|
|
3817
|
+
second: secondHandRotation,
|
|
3818
|
+
minute: minuteHandRotation,
|
|
3819
|
+
hour: invert * (time.getHours() - this.hourOffset) * (Math.PI * 2) / 12 + minuteHandRotation / 12
|
|
3820
|
+
};
|
|
3821
|
+
if (this.hands.some((h) => Math.abs(targetRotation[h.type] - h.object.rotation[this.axis]) > .001)) {
|
|
3822
|
+
for (const hand of this.hands) hand.object.rotation[this.axis] = targetRotation[hand.type];
|
|
3823
|
+
this._viewer?.renderManager.resetShadows();
|
|
3824
|
+
this._viewer?.setDirty();
|
|
3825
|
+
}
|
|
3826
|
+
};
|
|
3827
|
+
this._addSceneObject = async (e) => {
|
|
3828
|
+
if (!e.object) return;
|
|
3829
|
+
this.refresh();
|
|
3830
|
+
};
|
|
3831
|
+
}
|
|
3832
|
+
static {
|
|
3833
|
+
this.PluginType = "WatchHandsPlugin";
|
|
3834
|
+
}
|
|
3835
|
+
onAdded(viewer) {
|
|
3836
|
+
super.onAdded(viewer);
|
|
3837
|
+
viewer.scene.addEventListener("addSceneObject", this._addSceneObject);
|
|
3838
|
+
viewer.addEventListener("preFrame", this._preFrame);
|
|
3839
|
+
}
|
|
3840
|
+
onRemove(viewer) {
|
|
3841
|
+
viewer.scene.removeEventListener("addSceneObject", this._addSceneObject);
|
|
3842
|
+
viewer.removeEventListener("preFrame", this._preFrame);
|
|
3843
|
+
super.onRemove(viewer);
|
|
3844
|
+
}
|
|
3845
|
+
refresh() {
|
|
3846
|
+
this.hands = [];
|
|
3847
|
+
this._viewer?.scene.modelRoot.traverse((o) => {
|
|
3848
|
+
let isChild = false;
|
|
3849
|
+
o.traverseAncestors((oa) => {
|
|
3850
|
+
if (isChild) return;
|
|
3851
|
+
if (this.hands.find((h) => h.object === oa)) isChild = true;
|
|
3852
|
+
});
|
|
3853
|
+
if (isChild) return;
|
|
3854
|
+
if (o.name.match(this.regex ? new RegExp(this.hour) : this.hour)) {
|
|
3855
|
+
if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
|
|
3856
|
+
this.hands.push({
|
|
3857
|
+
type: "hour",
|
|
3858
|
+
object: o
|
|
3859
|
+
});
|
|
3860
|
+
}
|
|
3861
|
+
if (o.name.match(this.regex ? new RegExp(this.minute) : this.minute)) {
|
|
3862
|
+
if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
|
|
3863
|
+
this.hands.push({
|
|
3864
|
+
type: "minute",
|
|
3865
|
+
object: o
|
|
3866
|
+
});
|
|
3867
|
+
}
|
|
3868
|
+
if (o.name.match(this.regex ? new RegExp(this.second) : this.second)) {
|
|
3869
|
+
if (!o.userData.initRotation) o.userData.initRotation = o.rotation.toArray();
|
|
3870
|
+
this.hands.push({
|
|
3871
|
+
type: "second",
|
|
3872
|
+
object: o
|
|
3873
|
+
});
|
|
3874
|
+
}
|
|
3875
|
+
});
|
|
3876
|
+
}
|
|
3877
|
+
};
|
|
3878
|
+
__decorate([(0, threepipe.uiToggle)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "enabled", void 0);
|
|
3879
|
+
__decorate([(0, threepipe.uiDropdown)(void 0, [
|
|
3880
|
+
"x",
|
|
3881
|
+
"y",
|
|
3882
|
+
"z"
|
|
3883
|
+
].map((label) => ({ label }))), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "axis", void 0);
|
|
3884
|
+
__decorate([(0, threepipe.uiToggle)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "invertAxis", void 0);
|
|
3885
|
+
__decorate([(0, threepipe.uiToggle)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "analog", void 0);
|
|
3886
|
+
__decorate([(0, threepipe.uiSlider)(void 0, [0, 12], .001), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "hourOffset", void 0);
|
|
3887
|
+
__decorate([(0, threepipe.uiSlider)(void 0, [0, 60], .001), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "minuteOffset", void 0);
|
|
3888
|
+
__decorate([(0, threepipe.uiSlider)(void 0, [0, 60], .001), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "secondOffset", void 0);
|
|
3889
|
+
__decorate([(0, threepipe.uiInput)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "hour", void 0);
|
|
3890
|
+
__decorate([(0, threepipe.uiInput)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "minute", void 0);
|
|
3891
|
+
__decorate([(0, threepipe.uiInput)(), (0, threepipe.serialize)()], WatchHandsPlugin.prototype, "second", void 0);
|
|
3892
|
+
__decorate([
|
|
3893
|
+
(0, threepipe.uiToggle)(),
|
|
3894
|
+
(0, threepipe.onChange)("refresh"),
|
|
3895
|
+
(0, threepipe.serialize)()
|
|
3896
|
+
], WatchHandsPlugin.prototype, "regex", void 0);
|
|
3897
|
+
__decorate([(0, threepipe.uiButton)()], WatchHandsPlugin.prototype, "refresh", null);
|
|
3898
|
+
WatchHandsPlugin = __decorate([(0, threepipe.uiFolderContainer)("Watch Hands Time")], WatchHandsPlugin);
|
|
3899
|
+
// src/plugins/index.ts
|
|
3900
|
+
var webgiPlugins = [
|
|
3901
|
+
TemporalAAPlugin,
|
|
3902
|
+
VelocityBufferPlugin,
|
|
3903
|
+
BloomPlugin,
|
|
3904
|
+
SSReflectionPlugin,
|
|
3905
|
+
SSContactShadowsPlugin,
|
|
3906
|
+
DepthOfFieldPlugin,
|
|
3907
|
+
OutlinePlugin,
|
|
3908
|
+
SSGIPlugin,
|
|
3909
|
+
AnisotropyPlugin,
|
|
3910
|
+
AdvancedGroundPlugin,
|
|
3911
|
+
WatchHandsPlugin
|
|
3912
|
+
];
|
|
3913
|
+
exports.AdvancedGroundPlugin = AdvancedGroundPlugin;
|
|
3914
|
+
Object.defineProperty(exports, "AnisotropyPlugin", {
|
|
3915
|
+
enumerable: true,
|
|
3916
|
+
get: function() {
|
|
3917
|
+
return AnisotropyPlugin;
|
|
3918
|
+
}
|
|
3919
|
+
});
|
|
3920
|
+
exports.BloomPlugin = BloomPlugin;
|
|
3921
|
+
Object.defineProperty(exports, "BloomPluginPass", {
|
|
3922
|
+
enumerable: true,
|
|
3923
|
+
get: function() {
|
|
3924
|
+
return BloomPluginPass;
|
|
3925
|
+
}
|
|
3926
|
+
});
|
|
3927
|
+
exports.DepthOfFieldPlugin = DepthOfFieldPlugin;
|
|
3928
|
+
Object.defineProperty(exports, "DepthOfFieldPluginPass", {
|
|
3929
|
+
enumerable: true,
|
|
3930
|
+
get: function() {
|
|
3931
|
+
return DepthOfFieldPluginPass;
|
|
3932
|
+
}
|
|
3933
|
+
});
|
|
3934
|
+
Object.defineProperty(exports, "OutlinePlugin", {
|
|
3935
|
+
enumerable: true,
|
|
3936
|
+
get: function() {
|
|
3937
|
+
return OutlinePlugin;
|
|
3938
|
+
}
|
|
3939
|
+
});
|
|
3940
|
+
Object.defineProperty(exports, "OutlineRenderPass", {
|
|
3941
|
+
enumerable: true,
|
|
3942
|
+
get: function() {
|
|
3943
|
+
return OutlineRenderPass;
|
|
3944
|
+
}
|
|
3945
|
+
});
|
|
3946
|
+
Object.defineProperty(exports, "SSContactShadowsPlugin", {
|
|
3947
|
+
enumerable: true,
|
|
3948
|
+
get: function() {
|
|
3949
|
+
return SSContactShadowsPlugin;
|
|
3950
|
+
}
|
|
3951
|
+
});
|
|
3952
|
+
Object.defineProperty(exports, "SSGIPlugin", {
|
|
3953
|
+
enumerable: true,
|
|
3954
|
+
get: function() {
|
|
3955
|
+
return SSGIPlugin;
|
|
3956
|
+
}
|
|
3957
|
+
});
|
|
3958
|
+
Object.defineProperty(exports, "SSGIPluginPass", {
|
|
3959
|
+
enumerable: true,
|
|
3960
|
+
get: function() {
|
|
3961
|
+
return SSGIPluginPass;
|
|
3962
|
+
}
|
|
3963
|
+
});
|
|
3964
|
+
Object.defineProperty(exports, "SSReflectionPlugin", {
|
|
3965
|
+
enumerable: true,
|
|
3966
|
+
get: function() {
|
|
3967
|
+
return SSReflectionPlugin;
|
|
3968
|
+
}
|
|
3969
|
+
});
|
|
3970
|
+
Object.defineProperty(exports, "SSReflectionPluginPass", {
|
|
3971
|
+
enumerable: true,
|
|
3972
|
+
get: function() {
|
|
3973
|
+
return SSReflectionPluginPass;
|
|
3974
|
+
}
|
|
3975
|
+
});
|
|
3976
|
+
exports.SSVelocityMaterial = SSVelocityMaterial;
|
|
3977
|
+
exports.TemporalAAPlugin = TemporalAAPlugin;
|
|
3978
|
+
exports.TemporalAAPluginPass = TemporalAAPluginPass;
|
|
3979
|
+
Object.defineProperty(exports, "VelocityBufferPlugin", {
|
|
3980
|
+
enumerable: true,
|
|
3981
|
+
get: function() {
|
|
3982
|
+
return VelocityBufferPlugin;
|
|
3983
|
+
}
|
|
3984
|
+
});
|
|
3985
|
+
Object.defineProperty(exports, "WatchHandsPlugin", {
|
|
3986
|
+
enumerable: true,
|
|
3987
|
+
get: function() {
|
|
3988
|
+
return WatchHandsPlugin;
|
|
3989
|
+
}
|
|
3990
|
+
});
|
|
3991
|
+
exports.anisotropyGLTFExtension = anisotropyGLTFExtension;
|
|
3992
|
+
exports.webgiPlugins = webgiPlugins;
|
|
3993
|
+
});
|
|
3994
|
+
|
|
3995
|
+
//# sourceMappingURL=index.js.map
|