@threepipe/webgi-plugins 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,31 +1,31 @@
1
1
  /**
2
2
  * @license
3
- * @threepipe/webgi-plugins v0.2.1
3
+ * @threepipe/webgi-plugins v0.3.0
4
4
  * Copyright 2022-2025 repalash <palash@shaders.app>
5
5
  * GPL-3.0-only License
6
6
  */
7
7
  var _a;
8
- import { PipelinePassPlugin, GBufferPlugin, ProgressivePlugin, generateUiConfig, uiToggle, uiConfig, ExtendedShaderPass, CopyShader, Vector2, Matrix4, getOrCall, serialize, uniform, uiVector, matDefineBool, shaderReplaceString, UnsignedByteType, LinearSRGBColorSpace, GBufferRenderPass, Color, uiImage, uiFolderContainer, ShaderMaterial, Matrix3, NoBlending, DoubleSide, uiConfigMaterialExtension, updateBit, Vector4, HalfFloatType, AdditiveBlending, uiSlider, onChange, onChange2, Vector3, PickingPlugin, now, FrameFadePlugin, ExtendedShaderMaterial, shaderUtils, bindToValue, NearestFilter, RGBAFormat, AViewerPluginSync, glsl, ShaderChunk, updateMaterialDefines, BaseGroundPlugin, matDefine, SSAAPlugin, getTexelDecoding } from "threepipe";
8
+ import { PipelinePassPlugin, GBufferPlugin, ProgressivePlugin, generateUiConfig, uiToggle, uiConfig, ExtendedShaderPass, CopyShader, Vector2, Matrix4, getOrCall, serialize, uniform, uiVector, matDefineBool, shaderReplaceString, UnsignedByteType, LinearSRGBColorSpace, GBufferRenderPass, Color, uiImage, uiFolderContainer, ShaderMaterial, Matrix3, NoBlending, DoubleSide, uiConfigMaterialExtension, updateBit, Vector4, HalfFloatType, AdditiveBlending, uiSlider, onChange, onChange2, Vector3, PickingPlugin, now, FrameFadePlugin, ExtendedShaderMaterial, shaderUtils, bindToValue, NearestFilter, RGBAFormat, AViewerPluginSync, glsl, ShaderChunk, updateMaterialDefines, BaseGroundPlugin, matDefine, SSAAPlugin, getTexelDecoding, AScreenPassExtensionPlugin, animateTarget, uiColor, RenderPass, makeSamplerUi, SRGBColorSpace } from "threepipe";
9
9
  const VelocityBufferUnpack = "#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";
10
10
  const ssVelocityVert = "#ifdef USE_ALPHAMAP\n#define USE_UV\n#endif\n#include <uv_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 <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}";
11
11
  const ssVelocityFrag = "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.);}";
12
12
  const taaShader = "#include <common>\n#include <gbuffer_unpack>\n#ifdef HAS_VELOCITY_BUFFER\n#pragma <velocity_unpack>\n#endif\n#include <cameraHelpers>\nvarying vec2 vUv;uniform vec2 previousRTSize;uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;uniform mat4 inverseViewMatrix;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;\n#ifndef HAS_VELOCITY_BUFFER\n#define HAS_VELOCITY_BUFFER 0\n#endif\nvec3 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\nvec2 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);}\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.));}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;}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(firstFrame){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 <encodings_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}";
13
- var __defProp$5 = Object.defineProperty;
14
- var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
15
- var __decorateClass$5 = (decorators, target, key, kind) => {
16
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
13
+ var __defProp$9 = Object.defineProperty;
14
+ var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
15
+ var __decorateClass$9 = (decorators, target, key, kind) => {
16
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
17
17
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
18
18
  if (decorator = decorators[i])
19
19
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
20
- if (kind && result) __defProp$5(target, key, result);
20
+ if (kind && result) __defProp$9(target, key, result);
21
21
  return result;
22
22
  };
23
- const passId$3 = "taa";
23
+ const passId$4 = "taa";
24
24
  const _TemporalAAPlugin = class _TemporalAAPlugin extends PipelinePassPlugin {
25
25
  // readonly materialExtension: MaterialExtension = uiConfigMaterialExtension(this._getUiConfig.bind(this), TemporalAAPlugin.PluginType)
26
26
  constructor(enabled = true) {
27
27
  super();
28
- this.passId = passId$3;
28
+ this.passId = passId$4;
29
29
  this._stableNoise = true;
30
30
  this._gbufferUnpackExtension = void 0;
31
31
  this._gbufferUnpackExtensionChanged = () => {
@@ -144,10 +144,10 @@ const _TemporalAAPlugin = class _TemporalAAPlugin extends PipelinePassPlugin {
144
144
  _TemporalAAPlugin.PluginType = "TAA";
145
145
  _TemporalAAPlugin.OldPluginType = "TemporalAAPlugin";
146
146
  let TemporalAAPlugin = _TemporalAAPlugin;
147
- __decorateClass$5([
147
+ __decorateClass$9([
148
148
  uiToggle("Stable Noise (Total frame count)")
149
149
  ], TemporalAAPlugin.prototype, "stableNoise", 1);
150
- __decorateClass$5([
150
+ __decorateClass$9([
151
151
  uiConfig()
152
152
  ], TemporalAAPlugin.prototype, "_pass", 2);
153
153
  class TemporalAAPluginPass extends ExtendedShaderPass {
@@ -226,23 +226,23 @@ class TemporalAAPluginPass extends ExtendedShaderPass {
226
226
  this.onSizeUpdate();
227
227
  }
228
228
  }
229
- __decorateClass$5([
229
+ __decorateClass$9([
230
230
  serialize(),
231
231
  uniform(),
232
232
  uiVector("Feedback", void 0, 1e-4)
233
233
  ], TemporalAAPluginPass.prototype, "feedBack", 2);
234
- __decorateClass$5([
234
+ __decorateClass$9([
235
235
  uiToggle(),
236
236
  matDefineBool("DEBUG_VELOCITY", void 0, false, void 0, true)
237
237
  ], TemporalAAPluginPass.prototype, "debugVelocity", 2);
238
- var __defProp$4 = Object.defineProperty;
239
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
240
- var __decorateClass$4 = (decorators, target, key, kind) => {
241
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
238
+ var __defProp$8 = Object.defineProperty;
239
+ var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
240
+ var __decorateClass$8 = (decorators, target, key, kind) => {
241
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$7(target, key) : target;
242
242
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
243
243
  if (decorator = decorators[i])
244
244
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
245
- if (kind && result) __defProp$4(target, key, result);
245
+ if (kind && result) __defProp$8(target, key, result);
246
246
  return result;
247
247
  };
248
248
  let VelocityBufferPlugin = class extends PipelinePassPlugin {
@@ -373,13 +373,13 @@ let VelocityBufferPlugin = class extends PipelinePassPlugin {
373
373
  };
374
374
  VelocityBufferPlugin.PluginType = "VelocityBuffer";
375
375
  VelocityBufferPlugin.OldPluginType = "VelocityBufferPlugin";
376
- __decorateClass$4([
376
+ __decorateClass$8([
377
377
  uiImage(
378
378
  "Velocity Buffer"
379
379
  /* {readOnly: true}*/
380
380
  )
381
381
  ], VelocityBufferPlugin.prototype, "texture", 2);
382
- VelocityBufferPlugin = __decorateClass$4([
382
+ VelocityBufferPlugin = __decorateClass$8([
383
383
  uiFolderContainer("Velocity Buffer Plugin (for TAA)")
384
384
  ], VelocityBufferPlugin);
385
385
  class SSVelocityMaterial extends ShaderMaterial {
@@ -434,21 +434,21 @@ class SSVelocityMaterial extends ShaderMaterial {
434
434
  }
435
435
  }
436
436
  const hdrBloom = "#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 <encodings_fragment>\n}";
437
- var __defProp$3 = Object.defineProperty;
438
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
439
- var __decorateClass$3 = (decorators, target, key, kind) => {
440
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
437
+ var __defProp$7 = Object.defineProperty;
438
+ var __getOwnPropDesc$6 = Object.getOwnPropertyDescriptor;
439
+ var __decorateClass$7 = (decorators, target, key, kind) => {
440
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$6(target, key) : target;
441
441
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
442
442
  if (decorator = decorators[i])
443
443
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
444
- if (kind && result) __defProp$3(target, key, result);
444
+ if (kind && result) __defProp$7(target, key, result);
445
445
  return result;
446
446
  };
447
- const passId$2 = "bloom";
447
+ const passId$3 = "bloom";
448
448
  const _BloomPlugin = (_a = class extends PipelinePassPlugin {
449
449
  constructor() {
450
450
  super(...arguments);
451
- this.passId = passId$2;
451
+ this.passId = passId$3;
452
452
  this.materialExtension = uiConfigMaterialExtension(this._getUiConfig.bind(this), _a.PluginType);
453
453
  this.dependencies = [GBufferPlugin];
454
454
  this._onPluginAdd = (e) => {
@@ -543,7 +543,7 @@ const _BloomPlugin = (_a = class extends PipelinePassPlugin {
543
543
  return config;
544
544
  }
545
545
  }, _a.PluginType = "Bloom", _a.OldPluginType = "BloomPlugin", _a);
546
- __decorateClass$3([
546
+ __decorateClass$7([
547
547
  uiConfig()
548
548
  ], _BloomPlugin.prototype, "_pass", 2);
549
549
  let BloomPlugin = _BloomPlugin;
@@ -691,48 +691,48 @@ let BloomPluginPass = class extends ExtendedShaderPass {
691
691
  if (setDirty !== false) this.setDirty();
692
692
  }
693
693
  };
694
- __decorateClass$3([
694
+ __decorateClass$7([
695
695
  uniform()
696
696
  ], BloomPluginPass.prototype, "prefilter", 2);
697
- __decorateClass$3([
697
+ __decorateClass$7([
698
698
  uiSlider("Threshold", [0, 2]),
699
699
  onChange(BloomPluginPass.prototype._thresholdsUpdated),
700
700
  serialize()
701
701
  ], BloomPluginPass.prototype, "threshold", 2);
702
- __decorateClass$3([
702
+ __decorateClass$7([
703
703
  uiSlider("Soft Threshold", [0, 1]),
704
704
  onChange(BloomPluginPass.prototype._thresholdsUpdated),
705
705
  serialize()
706
706
  ], BloomPluginPass.prototype, "softThreshold", 2);
707
- __decorateClass$3([
707
+ __decorateClass$7([
708
708
  uiSlider("Intensity", [0, 3]),
709
709
  serialize(),
710
710
  uniform()
711
711
  ], BloomPluginPass.prototype, "intensity", 2);
712
- __decorateClass$3([
712
+ __decorateClass$7([
713
713
  uiToggle("Background Bloom"),
714
714
  serialize(),
715
715
  matDefineBool("BACKGROUND_BLOOM")
716
716
  ], BloomPluginPass.prototype, "backgroundBloom", 2);
717
- __decorateClass$3([
717
+ __decorateClass$7([
718
718
  uiSlider("Iterations", [2, 7], 1),
719
719
  onChange2(BloomPluginPass.prototype._updateWeights),
720
720
  serialize()
721
721
  ], BloomPluginPass.prototype, "bloomIterations", 2);
722
- __decorateClass$3([
722
+ __decorateClass$7([
723
723
  uiSlider("Radius", [0, 1], 0.01),
724
724
  onChange2(BloomPluginPass.prototype._updateWeights),
725
725
  serialize()
726
726
  ], BloomPluginPass.prototype, "radius", 2);
727
- __decorateClass$3([
727
+ __decorateClass$7([
728
728
  uiSlider("Power", [0.2, 10], 0.01),
729
729
  onChange2(BloomPluginPass.prototype._updateWeights),
730
730
  serialize()
731
731
  ], BloomPluginPass.prototype, "power", 2);
732
- __decorateClass$3([
732
+ __decorateClass$7([
733
733
  uiToggle("Debug")
734
734
  ], BloomPluginPass.prototype, "bloomDebug", 2);
735
- BloomPluginPass = __decorateClass$3([
735
+ BloomPluginPass = __decorateClass$7([
736
736
  uiFolderContainer("Bloom Pass")
737
737
  ], BloomPluginPass);
738
738
  const dofCombine = "#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 <encodings_fragment>\n}";
@@ -740,22 +740,22 @@ const dofPoissonBox = "#include <randomHelpers>\n#include <common>\nvarying vec2
740
740
  const poissonDiskSamples = "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);}";
741
741
  const dofComputeCoC = "#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 <encodings_fragment>\n}";
742
742
  const dofExpandCoC = "#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 <encodings_fragment>\n}";
743
- var __defProp$2 = Object.defineProperty;
744
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
745
- var __decorateClass$2 = (decorators, target, key, kind) => {
746
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
743
+ var __defProp$6 = Object.defineProperty;
744
+ var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
745
+ var __decorateClass$6 = (decorators, target, key, kind) => {
746
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
747
747
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
748
748
  if (decorator = decorators[i])
749
749
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
750
- if (kind && result) __defProp$2(target, key, result);
750
+ if (kind && result) __defProp$6(target, key, result);
751
751
  return result;
752
752
  };
753
- const passId$1 = "depthOfField";
753
+ const passId$2 = "depthOfField";
754
754
  const _DepthOfFieldPlugin = class _DepthOfFieldPlugin extends PipelinePassPlugin {
755
755
  // ms
756
756
  constructor(enabled = true, enableEdit = false) {
757
757
  super();
758
- this.passId = passId$1;
758
+ this.passId = passId$2;
759
759
  this.enableEdit = false;
760
760
  this._focalPointHit = new Vector3(0, 0, 0);
761
761
  this.crossFadeTime = 200;
@@ -960,14 +960,14 @@ const _DepthOfFieldPlugin = class _DepthOfFieldPlugin extends PipelinePassPlugin
960
960
  _DepthOfFieldPlugin.PluginType = "DepthOfField";
961
961
  _DepthOfFieldPlugin.OldPluginType = "DepthOfFieldPlugin";
962
962
  let DepthOfFieldPlugin = _DepthOfFieldPlugin;
963
- __decorateClass$2([
963
+ __decorateClass$6([
964
964
  serialize(),
965
965
  uiToggle()
966
966
  ], DepthOfFieldPlugin.prototype, "enableEdit", 2);
967
- __decorateClass$2([
967
+ __decorateClass$6([
968
968
  serialize("focalPoint")
969
969
  ], DepthOfFieldPlugin.prototype, "_focalPointHit", 2);
970
- __decorateClass$2([
970
+ __decorateClass$6([
971
971
  serialize()
972
972
  ], DepthOfFieldPlugin.prototype, "crossFadeTime", 2);
973
973
  const dofBlurMaterialPoisson = new ExtendedShaderMaterial({
@@ -1082,50 +1082,50 @@ let DepthOfFieldPluginPass = class extends ExtendedShaderPass {
1082
1082
  renderManager.releaseTempTarget(renderTargetBlurTemp);
1083
1083
  }
1084
1084
  };
1085
- __decorateClass$2([
1085
+ __decorateClass$6([
1086
1086
  bindToValue({ obj: "focalDepthRange", key: "y" }),
1087
1087
  uiSlider("Depth Range", [0.25, 3])
1088
1088
  ], DepthOfFieldPluginPass.prototype, "depthRange", 2);
1089
- __decorateClass$2([
1089
+ __decorateClass$6([
1090
1090
  bindToValue({ obj: "nearFarBlurScale", key: "x" }),
1091
1091
  uiSlider("Near Blur Scale", [0, 1])
1092
1092
  ], DepthOfFieldPluginPass.prototype, "nearBlurScale", 2);
1093
- __decorateClass$2([
1093
+ __decorateClass$6([
1094
1094
  bindToValue({ obj: "nearFarBlurScale", key: "y" }),
1095
1095
  uiSlider("Far Blur Scale", [0, 1])
1096
1096
  ], DepthOfFieldPluginPass.prototype, "farBlurScale", 2);
1097
- __decorateClass$2([
1097
+ __decorateClass$6([
1098
1098
  serialize(),
1099
1099
  uniform()
1100
1100
  ], DepthOfFieldPluginPass.prototype, "nearFarBlurScale", 2);
1101
- __decorateClass$2([
1101
+ __decorateClass$6([
1102
1102
  serialize(),
1103
1103
  uniform()
1104
1104
  ], DepthOfFieldPluginPass.prototype, "focalDepthRange", 2);
1105
- __decorateClass$2([
1105
+ __decorateClass$6([
1106
1106
  uniform()
1107
1107
  ], DepthOfFieldPluginPass.prototype, "crossCenter", 2);
1108
- __decorateClass$2([
1108
+ __decorateClass$6([
1109
1109
  uniform()
1110
1110
  ], DepthOfFieldPluginPass.prototype, "crossRadius", 2);
1111
- __decorateClass$2([
1111
+ __decorateClass$6([
1112
1112
  uniform()
1113
1113
  ], DepthOfFieldPluginPass.prototype, "crossAlpha", 2);
1114
- __decorateClass$2([
1114
+ __decorateClass$6([
1115
1115
  uniform()
1116
1116
  ], DepthOfFieldPluginPass.prototype, "crossColor", 2);
1117
- DepthOfFieldPluginPass = __decorateClass$2([
1117
+ DepthOfFieldPluginPass = __decorateClass$6([
1118
1118
  uiFolderContainer("DepthOfField Pass")
1119
1119
  ], DepthOfFieldPluginPass);
1120
1120
  const ssrtShader = "#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";
1121
- var __defProp$1 = Object.defineProperty;
1122
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
1123
- var __decorateClass$1 = (decorators, target, key, kind) => {
1124
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
1121
+ var __defProp$5 = Object.defineProperty;
1122
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
1123
+ var __decorateClass$5 = (decorators, target, key, kind) => {
1124
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
1125
1125
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
1126
1126
  if (decorator = decorators[i])
1127
1127
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1128
- if (kind && result) __defProp$1(target, key, result);
1128
+ if (kind && result) __defProp$5(target, key, result);
1129
1129
  return result;
1130
1130
  };
1131
1131
  let SSContactShadowsPlugin = class extends AViewerPluginSync {
@@ -1159,6 +1159,7 @@ let SSContactShadowsPlugin = class extends AViewerPluginSync {
1159
1159
  this.dependencies = [GBufferPlugin];
1160
1160
  this.materialExtension = {
1161
1161
  uuid: SSContactShadowsPlugin.PluginType,
1162
+ priority: 5,
1162
1163
  shaderExtender: (shader, _material, _renderer) => {
1163
1164
  var _a2, _b;
1164
1165
  if (!shader.defines.SSCS_ENABLED) return;
@@ -1168,12 +1169,15 @@ let SSContactShadowsPlugin = class extends AViewerPluginSync {
1168
1169
  #define D_sceneBoundingRadius
1169
1170
  uniform float sceneBoundingRadius;
1170
1171
  #endif
1172
+ #ifndef D_frameCount
1173
+ #define D_frameCount
1171
1174
  uniform float frameCount;
1175
+ #endif
1172
1176
  float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, vec3 lightDirection ) {
1173
1177
  vec3 ray_origin_view = -vViewPosition;
1174
1178
  float rnd = interleavedGradientNoise(gl_FragCoord.xy, frameCount+34.);
1175
1179
  float cameraDist = length(cameraPositionWorld);
1176
- // float radius = mix((cameraNearFar.y) + ray_origin_view.z, -ray_origin_view.z - cameraNearFar.x, rnd * 0.5 + 0.5)*sscsRadius;
1180
+ // float radius = mix((cameraNearFar.y) + ray_origin_view.z, -ray_origin_view.z - cameraNearFar.x, rnd * 0.5 + 0.5)*sscsRadius;
1177
1181
  float radius = mix((cameraDist + sceneBoundingRadius) + ray_origin_view.z, -ray_origin_view.z - max(0.0, cameraDist - sceneBoundingRadius), rnd * 0.5 + 0.5)*sscsRadius;
1178
1182
  vec3 state = vec3(1.,(rnd+0.5)/float(SSCS_STEP_COUNT),2.);
1179
1183
  traceRay(ray_origin_view, normalize(lightDirection) * radius, sscsTolerance * radius * 2., state, SSCS_STEP_COUNT);
@@ -1334,60 +1338,60 @@ let SSContactShadowsPlugin = class extends AViewerPluginSync {
1334
1338
  };
1335
1339
  SSContactShadowsPlugin.PluginType = "SSContactShadows";
1336
1340
  SSContactShadowsPlugin.OldPluginType = "SSContactShadowsPlugin";
1337
- __decorateClass$1([
1341
+ __decorateClass$5([
1338
1342
  uiToggle("Enabled"),
1339
1343
  serialize(),
1340
1344
  onChange(SSContactShadowsPlugin.prototype.setDirty)
1341
1345
  ], SSContactShadowsPlugin.prototype, "enabled", 2);
1342
- __decorateClass$1([
1346
+ __decorateClass$5([
1343
1347
  uniform({ propKey: "sscsRadius", onChange: SSContactShadowsPlugin.prototype.setDirty }),
1344
1348
  uiSlider("Radius", [1e-4, 0.1], 1e-4),
1345
1349
  serialize()
1346
1350
  ], SSContactShadowsPlugin.prototype, "radius", 2);
1347
- __decorateClass$1([
1351
+ __decorateClass$5([
1348
1352
  uniform({ propKey: "sscsIntensity", onChange: SSContactShadowsPlugin.prototype.setDirty }),
1349
1353
  uiSlider("Intensity", [1e-4, 1], 1e-4),
1350
1354
  serialize()
1351
1355
  ], SSContactShadowsPlugin.prototype, "intensity", 2);
1352
- __decorateClass$1([
1356
+ __decorateClass$5([
1353
1357
  uniform({ propKey: "sscsTolerance", onChange: SSContactShadowsPlugin.prototype.setDirty }),
1354
1358
  uiSlider("Tolerance", [0.1, 5]),
1355
1359
  serialize()
1356
1360
  ], SSContactShadowsPlugin.prototype, "tolerance", 2);
1357
- __decorateClass$1([
1361
+ __decorateClass$5([
1358
1362
  matDefine("SSCS_DEBUG", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
1359
1363
  uiToggle("Debug only SSCS"),
1360
1364
  serialize()
1361
1365
  ], SSContactShadowsPlugin.prototype, "onlySSCSDebug", 2);
1362
- __decorateClass$1([
1366
+ __decorateClass$5([
1363
1367
  matDefine("SSCS_STEP_COUNT", void 0, true, SSContactShadowsPlugin.prototype.setDirty),
1364
1368
  uiSlider("Step count", [1, 8], 1),
1365
1369
  serialize()
1366
1370
  ], SSContactShadowsPlugin.prototype, "stepCount", 2);
1367
- SSContactShadowsPlugin = __decorateClass$1([
1371
+ SSContactShadowsPlugin = __decorateClass$5([
1368
1372
  uiFolderContainer("SS Contact Shadows")
1369
1373
  ], SSContactShadowsPlugin);
1370
1374
  const samplePointHelpers = "#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;}";
1371
- const ssrShader = "uniform float currentFrameCount;uniform float frameCount;uniform float objectRadius;uniform float radius;uniform float tolerance;uniform bool autoRadius;\n#ifndef D_sceneBoundingRadius\n#define D_sceneBoundingRadius\nuniform float sceneBoundingRadius;\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*117.);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);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){vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}";
1372
- const ssreflPatch = "\n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometry.position);vec4 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(geometry.viewDir,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(geometry.normal,geometry.viewDir,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\nssrColor=calculateSSR(8.,vec3(screenPos.xy,geometry.position.z),geometry.normal,1.,material.roughness);\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#endif\n";
1375
+ const ssrShader = "uniform float currentFrameCount;uniform float frameCount;uniform 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\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){vec3 hitColor=(tLastFrameTexelToLinear(texture2D(tLastFrame,screenHitP.xy))).rgb;float ssrWeight=1.;return vec4(hitColor*ssrWeight,1.);}return vec4(0.);}";
1376
+ const ssreflPatch = "\n#if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0\nvec3 screenPos=viewToScreen(geometry.position);vec4 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(geometry.viewDir,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(geometry.normal,geometry.viewDir,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,geometry.position.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,geometry.normal,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#endif\n";
1373
1377
  const ssrShaderMain = "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 <encodings_fragment>\n}";
1374
- var __defProp = Object.defineProperty;
1375
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1376
- var __decorateClass = (decorators, target, key, kind) => {
1377
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
1378
+ var __defProp$4 = Object.defineProperty;
1379
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
1380
+ var __decorateClass$4 = (decorators, target, key, kind) => {
1381
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
1378
1382
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
1379
1383
  if (decorator = decorators[i])
1380
1384
  result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1381
- if (kind && result) __defProp(target, key, result);
1385
+ if (kind && result) __defProp$4(target, key, result);
1382
1386
  return result;
1383
1387
  };
1384
- const passId = "ssrefl";
1388
+ const passId$1 = "ssrefl";
1385
1389
  let SSReflectionPlugin = class extends PipelinePassPlugin {
1386
1390
  // cannot be changed after creation (for now)
1387
1391
  constructor(inlineShaderRayTrace = true, bufferType = UnsignedByteType, sizeMultiplier = 1, enabled = true) {
1388
1392
  super();
1389
1393
  this.inlineShaderRayTrace = inlineShaderRayTrace;
1390
- this.passId = passId;
1394
+ this.passId = passId$1;
1391
1395
  this.dependencies = [GBufferPlugin, SSAAPlugin];
1392
1396
  this._gbufferUnpackExtension = void 0;
1393
1397
  this._gbufferUnpackExtensionChanged = () => {
@@ -1421,7 +1425,6 @@ let SSReflectionPlugin = class extends PipelinePassPlugin {
1421
1425
  );
1422
1426
  this.texture = this.target.texture;
1423
1427
  this.texture.name = "ssreflBuffer";
1424
- if (this._pass) this._pass.target = this.target;
1425
1428
  }
1426
1429
  _disposeTarget() {
1427
1430
  if (!this._viewer) return;
@@ -1436,7 +1439,7 @@ let SSReflectionPlugin = class extends PipelinePassPlugin {
1436
1439
  if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension)
1437
1440
  throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");
1438
1441
  this._createTarget(true);
1439
- return new SSReflectionPluginPass(this.passId, this.target, this.inlineShaderRayTrace);
1442
+ return new SSReflectionPluginPass(this.passId, () => this.target, this.inlineShaderRayTrace);
1440
1443
  }
1441
1444
  onAdded(viewer) {
1442
1445
  super.onAdded(viewer);
@@ -1452,8 +1455,11 @@ let SSReflectionPlugin = class extends PipelinePassPlugin {
1452
1455
  _beforeRender(_, _1, _2) {
1453
1456
  var _a2;
1454
1457
  if (!this._viewer) return false;
1455
- (_a2 = this._pass) == null ? void 0 : _a2.updateShaderProperties([this._viewer.getPlugin(ProgressivePlugin)]);
1456
- return super._beforeRender(_, _1, _2);
1458
+ const e = super._beforeRender(_, _1, _2);
1459
+ if (!e) return e;
1460
+ const progressive = this._viewer.getPlugin(ProgressivePlugin);
1461
+ (_a2 = this._pass) == null ? void 0 : _a2.updateShaderProperties([progressive]);
1462
+ return e;
1457
1463
  }
1458
1464
  /**
1459
1465
  * @deprecated use {@link target} instead
@@ -1463,18 +1469,18 @@ let SSReflectionPlugin = class extends PipelinePassPlugin {
1463
1469
  return this.target;
1464
1470
  }
1465
1471
  };
1466
- SSReflectionPlugin.PluginType = "SSReflection";
1467
- SSReflectionPlugin.OldPluginType = "SSReflectionPlugin";
1468
- __decorateClass([
1472
+ SSReflectionPlugin.PluginType = "SSReflectionPlugin";
1473
+ SSReflectionPlugin.OldPluginType = "SSReflection";
1474
+ __decorateClass$4([
1469
1475
  uiImage(
1470
1476
  "SSReflection Buffer"
1471
1477
  /* {readOnly: true}*/
1472
1478
  )
1473
1479
  ], SSReflectionPlugin.prototype, "texture", 2);
1474
- __decorateClass([
1480
+ __decorateClass$4([
1475
1481
  uiConfig()
1476
1482
  ], SSReflectionPlugin.prototype, "_pass", 2);
1477
- SSReflectionPlugin = __decorateClass([
1483
+ SSReflectionPlugin = __decorateClass$4([
1478
1484
  uiFolderContainer("SSReflection Plugin")
1479
1485
  ], SSReflectionPlugin);
1480
1486
  let SSReflectionPluginPass = class extends ExtendedShaderPass {
@@ -1482,7 +1488,9 @@ let SSReflectionPluginPass = class extends ExtendedShaderPass {
1482
1488
  super({
1483
1489
  defines: {
1484
1490
  ["SSR_STEP_COUNT"]: 16,
1485
- ["SSR_LOW_QUALITY_FRAMES"]: 2,
1491
+ ["SSR_RAY_COUNT"]: 4,
1492
+ ["SSR_RAY_BLEND_MAX"]: 0,
1493
+ ["SSR_LOW_QUALITY_FRAMES"]: 0,
1486
1494
  // todo: only on mobile
1487
1495
  ["SSR_INLINE"]: inlineShaderRayTrace ? "1" : "0",
1488
1496
  // ['SSR_NON_PHYSICAL']: '0', only in inline, so it should not be here
@@ -1508,7 +1516,7 @@ let SSReflectionPluginPass = class extends ExtendedShaderPass {
1508
1516
  // set in PerspectiveCamera2
1509
1517
  projection: { value: new Matrix4() },
1510
1518
  // set in PerspectiveCamera2
1511
- saoBiasEpsilon: { value: new Vector3(1, 1, 1) },
1519
+ // saoBiasEpsilon: {value: new Vector3(1, 1, 1)},
1512
1520
  opacity: { value: 1 },
1513
1521
  // todo?
1514
1522
  intensity: { value: 0 },
@@ -1518,6 +1526,7 @@ let SSReflectionPluginPass = class extends ExtendedShaderPass {
1518
1526
  power: { value: 0 },
1519
1527
  maskFrontFactor: { value: -0.1 },
1520
1528
  tolerance: { value: 0 },
1529
+ ssrRoughnessFactor: { value: 1 },
1521
1530
  sceneBoundingRadius: { value: 0 }
1522
1531
  // todo do same in SSAO
1523
1532
  },
@@ -1550,7 +1559,10 @@ ${ssrShaderMain}
1550
1559
  this.autoRadius = true;
1551
1560
  this.power = 1.1;
1552
1561
  this.tolerance = 0.5;
1562
+ this.roughnessFactor = 1;
1553
1563
  this.stepCount = 16;
1564
+ this.rayCount = 1;
1565
+ this.rayBlendMax = false;
1554
1566
  this.lowQualityFrames = 0;
1555
1567
  this.maskFrontRays = true;
1556
1568
  this.maskFrontFactor = -0.2;
@@ -1567,6 +1579,8 @@ ${ssrShaderMain}
1567
1579
  },
1568
1580
  extraDefines: {
1569
1581
  ["SSR_STEP_COUNT"]: () => this.material.defines.SSR_STEP_COUNT,
1582
+ ["SSR_RAY_COUNT"]: () => this.material.defines.SSR_RAY_COUNT,
1583
+ ["SSR_RAY_BLEND_MAX"]: () => this.material.defines.SSR_RAY_BLEND_MAX,
1570
1584
  ["SSR_LOW_QUALITY_FRAMES"]: () => this.material.defines.SSR_LOW_QUALITY_FRAMES,
1571
1585
  ["SSR_INLINE"]: () => this.material.defines.SSR_INLINE,
1572
1586
  ["SSR_MASK_FRONT_RAYS"]: () => this.material.defines.SSR_MASK_FRONT_RAYS,
@@ -1633,7 +1647,7 @@ ${ssrShader}
1633
1647
  },
1634
1648
  computeCacheKey: () => {
1635
1649
  var _a2, _b;
1636
- return this.enabled ? "1" : "0" + ((_b = (_a2 = getOrCall(this.target)) == null ? void 0 : _a2.texture) == null ? void 0 : _b.colorSpace) + Object.values(this.material.defines).map((v) => v + "").join(",");
1650
+ return (this.enabled ? "1" : "0") + ((_b = (_a2 = getOrCall(this.target)) == null ? void 0 : _a2.texture) == null ? void 0 : _b.colorSpace) + Object.values(this.material.defines).map((v) => v + "").join(",");
1637
1651
  },
1638
1652
  uuid: SSReflectionPlugin.PluginType,
1639
1653
  ...uiConfigMaterialExtension(this._getUiConfig.bind(this), SSReflectionPlugin.PluginType),
@@ -1651,8 +1665,9 @@ ${ssrShader}
1651
1665
  objectRadius: this.material.uniforms.objectRadius,
1652
1666
  autoRadius: this.material.uniforms.autoRadius,
1653
1667
  tolerance: this.material.uniforms.tolerance,
1668
+ ssrRoughnessFactor: this.material.uniforms.ssrRoughnessFactor,
1654
1669
  frameCount: this.material.uniforms.frameCount,
1655
- // currentFrameCount: this.material.uniforms.currentFrameCount, // todo required?
1670
+ currentFrameCount: this.material.uniforms.currentFrameCount,
1656
1671
  projection: this.material.uniforms.projection,
1657
1672
  cameraPositionWorld: this.material.uniforms.cameraPositionWorld,
1658
1673
  cameraNearFar: this.material.uniforms.cameraNearFar,
@@ -1660,6 +1675,11 @@ ${ssrShader}
1660
1675
  });
1661
1676
  }
1662
1677
  }
1678
+ setDirty() {
1679
+ var _a2, _b;
1680
+ (_b = (_a2 = this.materialExtension) == null ? void 0 : _a2.setDirty) == null ? void 0 : _b.call(_a2);
1681
+ super.setDirty();
1682
+ }
1663
1683
  render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
1664
1684
  if (!this.enabled) return;
1665
1685
  if (this.inlineShaderRayTrace) {
@@ -1739,79 +1759,1349 @@ ${ssrShader}
1739
1759
  Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines);
1740
1760
  }
1741
1761
  };
1742
- __decorateClass([
1762
+ __decorateClass$4([
1743
1763
  uiSlider("Intensity", [0, 4]),
1744
1764
  serialize(),
1745
1765
  uniform()
1746
1766
  ], SSReflectionPluginPass.prototype, "intensity", 2);
1747
- __decorateClass([
1767
+ __decorateClass$4([
1748
1768
  uiVector("Boost"),
1749
1769
  serialize(),
1750
1770
  uniform()
1751
1771
  ], SSReflectionPluginPass.prototype, "boost", 2);
1752
- __decorateClass([
1772
+ __decorateClass$4([
1753
1773
  uiSlider("Object Radius", [0.01, 2]),
1754
1774
  serialize(),
1755
1775
  uniform()
1756
1776
  ], SSReflectionPluginPass.prototype, "objectRadius", 2);
1757
- __decorateClass([
1777
+ __decorateClass$4([
1758
1778
  uiToggle("Auto radius"),
1759
1779
  serialize(),
1760
1780
  uniform()
1761
1781
  ], SSReflectionPluginPass.prototype, "autoRadius", 2);
1762
- __decorateClass([
1782
+ __decorateClass$4([
1763
1783
  uiSlider("Power", [0, 3]),
1764
1784
  serialize(),
1765
1785
  uniform()
1766
1786
  ], SSReflectionPluginPass.prototype, "power", 2);
1767
- __decorateClass([
1787
+ __decorateClass$4([
1768
1788
  uiSlider("Tolerance", [0.1, 5]),
1769
1789
  serialize(),
1770
1790
  uniform()
1771
1791
  ], SSReflectionPluginPass.prototype, "tolerance", 2);
1772
- __decorateClass([
1792
+ __decorateClass$4([
1793
+ uiSlider("Roughness Factor", [0.1, 1.25]),
1794
+ serialize(),
1795
+ uniform({ propKey: "ssrRoughnessFactor" })
1796
+ ], SSReflectionPluginPass.prototype, "roughnessFactor", 2);
1797
+ __decorateClass$4([
1773
1798
  uiSlider("Step count", [1, 32], 1),
1774
1799
  serialize(),
1775
1800
  matDefine("SSR_STEP_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1776
1801
  ], SSReflectionPluginPass.prototype, "stepCount", 2);
1777
- __decorateClass([
1802
+ __decorateClass$4([
1803
+ uiSlider("Ray count", [1, 8], 1),
1804
+ serialize(),
1805
+ matDefine("SSR_RAY_COUNT", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1806
+ ], SSReflectionPluginPass.prototype, "rayCount", 2);
1807
+ __decorateClass$4([
1808
+ uiToggle("Ray Blend MAX"),
1809
+ serialize(),
1810
+ matDefineBool("SSR_RAY_BLEND_MAX", void 0, void 0, SSReflectionPluginPass.prototype.setDirty, true)
1811
+ ], SSReflectionPluginPass.prototype, "rayBlendMax", 2);
1812
+ __decorateClass$4([
1778
1813
  uiSlider("Low Quality Frames", [0, 4], 1),
1779
1814
  serialize(),
1780
1815
  matDefine("SSR_LOW_QUALITY_FRAMES", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1781
1816
  ], SSReflectionPluginPass.prototype, "lowQualityFrames", 2);
1782
- __decorateClass([
1817
+ __decorateClass$4([
1783
1818
  uiToggle("Ignore front rays"),
1784
1819
  serialize(),
1785
1820
  matDefineBool("SSR_MASK_FRONT_RAYS", void 0, void 0, SSReflectionPluginPass.prototype.setDirty)
1786
1821
  ], SSReflectionPluginPass.prototype, "maskFrontRays", 2);
1787
- __decorateClass([
1822
+ __decorateClass$4([
1788
1823
  uiSlider("Mask front rays factor", [-1, 1], 0.01, (that) => ({ hidden: () => !that.maskFrontRays })),
1789
1824
  serialize(),
1790
1825
  uniform()
1791
1826
  ], SSReflectionPluginPass.prototype, "maskFrontFactor", 2);
1792
- SSReflectionPluginPass = __decorateClass([
1827
+ SSReflectionPluginPass = __decorateClass$4([
1793
1828
  uiFolderContainer("SSReflection Pass")
1794
1829
  ], SSReflectionPluginPass);
1795
- const webgiPlugins = [
1796
- TemporalAAPlugin,
1797
- VelocityBufferPlugin,
1798
- BloomPlugin,
1799
- SSReflectionPlugin,
1800
- SSContactShadowsPlugin,
1801
- DepthOfFieldPlugin
1830
+ const outlineShader = "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);}";
1831
+ const outlineDepthVertex = "#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;}";
1832
+ const outlineDepthFrag = "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.);}";
1833
+ var __defProp$3 = Object.defineProperty;
1834
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
1835
+ var __decorateClass$3 = (decorators, target, key, kind) => {
1836
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
1837
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
1838
+ if (decorator = decorators[i])
1839
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1840
+ if (kind && result) __defProp$3(target, key, result);
1841
+ return result;
1842
+ };
1843
+ let OutlinePlugin = class extends AScreenPassExtensionPlugin {
1844
+ constructor(enabled = true, bufferType = UnsignedByteType) {
1845
+ super();
1846
+ this.passId = "outline";
1847
+ this.extraUniforms = {
1848
+ outlineIntensity: { value: 1 },
1849
+ outlineThickness: { value: 2 },
1850
+ highlightTransparency: { value: 1 },
1851
+ outlineColor: { value: new Color(15305317) },
1852
+ enableHighlight: { value: true },
1853
+ dpr: { value: 1 },
1854
+ outlineBuffer: { value: null },
1855
+ tDiffuseSize: { value: new Vector2(1024, 1024) }
1856
+ };
1857
+ this.extraDefines = {
1858
+ ["DEBUG_OUTLINE"]: "0"
1859
+ };
1860
+ this.priority = -101;
1861
+ this.enableHighlight = false;
1862
+ this.enableDynamicSelection = true;
1863
+ this.intensity = 2;
1864
+ this.highlightTransparency = 0.84;
1865
+ this.color = new Color(15305317);
1866
+ this.thickness = 2;
1867
+ this.debugOutline = false;
1868
+ this.highlightSelectedMaterials = false;
1869
+ this.highlightMaterialSameNames = false;
1870
+ this.transparency = 0;
1871
+ this.parsFragmentSnippet = () => {
1872
+ if (this.isDisabled()) return "";
1873
+ return glsl`
1874
+ ${outlineShader}
1875
+ `;
1876
+ };
1877
+ this._shaderPatch = "diffuseColor = outline(diffuseColor);";
1878
+ this.dependencies = [PickingPlugin, GBufferPlugin];
1879
+ this._pickingWidgetDisabled = false;
1880
+ this.material = new ShaderMaterial({
1881
+ uniforms: {
1882
+ "cameraNearFar": { value: new Vector2(0.1, 100) }
1883
+ },
1884
+ vertexShader: outlineDepthVertex,
1885
+ fragmentShader: outlineDepthFrag,
1886
+ side: DoubleSide
1887
+ });
1888
+ this._getSelectedObject = () => {
1889
+ var _a2, _b, _c, _d;
1890
+ if (!this._viewer) return;
1891
+ const picking = this._viewer.getPlugin(PickingPlugin);
1892
+ if (this.highlightSelectedMaterials) {
1893
+ const mat = (_a2 = picking == null ? void 0 : picking.getSelectedObject()) == null ? void 0 : _a2.material;
1894
+ if (this.highlightMaterialSameNames && mat) {
1895
+ const names = Array.isArray(mat) ? mat.map((m) => m.name) : [mat.name];
1896
+ const mats = /* @__PURE__ */ new Set();
1897
+ for (const name of names) {
1898
+ const mats1 = (_d = (_c = (_b = this._viewer) == null ? void 0 : _b.assetManager) == null ? void 0 : _c.materials) == null ? void 0 : _d.findMaterialsByName(name);
1899
+ mats1 == null ? void 0 : mats1.forEach((m) => mats.add(m));
1900
+ }
1901
+ return [...mats];
1902
+ }
1903
+ return mat;
1904
+ }
1905
+ return picking == null ? void 0 : picking.getSelectedObject();
1906
+ };
1907
+ this._viewerListeners = {
1908
+ preRender: () => {
1909
+ if (this.isDisabled() || !this._viewer) return;
1910
+ this.extraUniforms.dpr.value = this._viewer.renderManager.renderScale * 2;
1911
+ }
1912
+ };
1913
+ this.mouseInOutAnimationEnabled = true;
1914
+ this._state = "in";
1915
+ this.enabled = enabled;
1916
+ this.bufferType = bufferType;
1917
+ }
1918
+ setDirty() {
1919
+ super.setDirty();
1920
+ if (!this._viewer) return;
1921
+ const picking = this._viewer.getPlugin(PickingPlugin);
1922
+ const enabled = !this.isDisabled();
1923
+ if (enabled && picking.widgetEnabled) {
1924
+ picking.widgetEnabled = false;
1925
+ this._pickingWidgetDisabled = true;
1926
+ } else if (!enabled && this._pickingWidgetDisabled) {
1927
+ picking.widgetEnabled = true;
1928
+ this._pickingWidgetDisabled = false;
1929
+ }
1930
+ this._viewer.setDirty();
1931
+ }
1932
+ onAdded(viewer) {
1933
+ var _a2;
1934
+ super.onAdded(viewer);
1935
+ this.setDirty();
1936
+ this._pass = this._createPass();
1937
+ (_a2 = this._pass.onDirty) == null ? void 0 : _a2.push(viewer.setDirty);
1938
+ viewer.renderManager.registerPass(this._pass);
1939
+ const pickingPlugin = viewer.getPlugin(PickingPlugin);
1940
+ pickingPlugin == null ? void 0 : pickingPlugin.addEventListener("selectedObjectChanged", () => {
1941
+ if (!this._animationCallBack && this) {
1942
+ if (pickingPlugin == null ? void 0 : pickingPlugin.getSelectedObject()) {
1943
+ if (this.enableDynamicSelection) {
1944
+ this.transparency = 1;
1945
+ this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 400);
1946
+ } else {
1947
+ this.transparency = this.highlightTransparency;
1948
+ }
1949
+ } else {
1950
+ this.transparency = 1;
1951
+ }
1952
+ }
1953
+ });
1954
+ document.addEventListener("mousemove", (e) => {
1955
+ if (!this) return;
1956
+ if (!this.mouseInOutAnimationEnabled) return;
1957
+ const selectedObject = pickingPlugin == null ? void 0 : pickingPlugin.getSelectedObject();
1958
+ if (selectedObject && this.enableDynamicSelection) {
1959
+ if (e.target !== viewer.canvas) {
1960
+ if (!this._animationCallBack && this._state === "in") {
1961
+ this._animationCallBack = this._startTransparencyAnimation(this.highlightTransparency, 1, 600);
1962
+ this._state = "out";
1963
+ }
1964
+ } else {
1965
+ if (!this._animationCallBack && this._state === "out") {
1966
+ this._animationCallBack = this._startTransparencyAnimation(1, this.highlightTransparency, 600);
1967
+ this._state = "in";
1968
+ }
1969
+ }
1970
+ } else {
1971
+ this.transparency = selectedObject ? this.highlightTransparency : 1;
1972
+ }
1973
+ });
1974
+ }
1975
+ onRemove(viewer) {
1976
+ this._disposeTarget();
1977
+ if (this._pass) {
1978
+ viewer.renderManager.unregisterPass(this._pass);
1979
+ if (this._pass.dispose) this._pass.dispose();
1980
+ }
1981
+ this._pass = void 0;
1982
+ return super.onRemove(viewer);
1983
+ }
1984
+ // cannot be changed after creation (for now)
1985
+ _createTarget(recreate = true) {
1986
+ if (!this._viewer) return;
1987
+ if (recreate) this._disposeTarget();
1988
+ if (!this.target) this.target = this._viewer.renderManager.createTarget(
1989
+ {
1990
+ // depthBuffer: true,
1991
+ sizeMultiplier: 1,
1992
+ type: this.bufferType
1993
+ // magFilter: NearestFilter,
1994
+ // minFilter: NearestFilter,
1995
+ // generateMipmaps: false,
1996
+ // colorSpace: LinearSRGBColorSpace,
1997
+ }
1998
+ );
1999
+ this.texture = this.target.texture;
2000
+ this.texture.name = "normalBuffer";
2001
+ }
2002
+ _disposeTarget() {
2003
+ if (!this._viewer) return;
2004
+ if (this.target) {
2005
+ this._viewer.renderManager.disposeTarget(this.target);
2006
+ this.target = void 0;
2007
+ }
2008
+ this.texture = void 0;
2009
+ }
2010
+ _createPass() {
2011
+ this._createTarget(true);
2012
+ if (!this.target) throw new Error("OutlinePlugin: target not created");
2013
+ this.material.userData.isOutlinePluginMaterial = true;
2014
+ const pass = new OutlineRenderPass(this.passId, this._getSelectedObject, () => this.target, this.material);
2015
+ return pass;
2016
+ }
2017
+ async _startTransparencyAnimation(from, to, duration) {
2018
+ return animateTarget(this, "transparency", {
2019
+ from,
2020
+ to,
2021
+ duration,
2022
+ onComplete: () => {
2023
+ this._animationCallBack = void 0;
2024
+ }
2025
+ });
2026
+ }
2027
+ // endregion animation
2028
+ // region deprecated
2029
+ get outlineIntensity() {
2030
+ console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
2031
+ return this.intensity;
2032
+ }
2033
+ set outlineIntensity(v) {
2034
+ console.warn("OutlinePlugin.outlineIntensity is deprecated, use OutlinePlugin.intensity instead");
2035
+ this.intensity = v;
2036
+ }
2037
+ get outlineColor() {
2038
+ console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
2039
+ return this.intensity;
2040
+ }
2041
+ set outlineColor(v) {
2042
+ console.warn("OutlinePlugin.outlineColor is deprecated, use OutlinePlugin.intensity instead");
2043
+ this.intensity = v;
2044
+ }
2045
+ // endregion deprecated
2046
+ };
2047
+ OutlinePlugin.PluginType = "OutlinePlugin";
2048
+ OutlinePlugin.OldPluginType = "Outline";
2049
+ __decorateClass$3([
2050
+ onChange(OutlinePlugin.prototype.setDirty),
2051
+ uiToggle("Enable"),
2052
+ serialize()
2053
+ ], OutlinePlugin.prototype, "enabled", 2);
2054
+ __decorateClass$3([
2055
+ uiToggle("Highlight"),
2056
+ uniform({ propKey: "enableHighlight" }),
2057
+ serialize()
2058
+ ], OutlinePlugin.prototype, "enableHighlight", 2);
2059
+ __decorateClass$3([
2060
+ onChange(OutlinePlugin.prototype.setDirty),
2061
+ uiToggle("DynamicSelection"),
2062
+ serialize()
2063
+ ], OutlinePlugin.prototype, "enableDynamicSelection", 2);
2064
+ __decorateClass$3([
2065
+ uiSlider("Intensity", [0, 4], 1e-3),
2066
+ uniform({ propKey: "outlineIntensity" }),
2067
+ serialize("outlineIntensity")
2068
+ ], OutlinePlugin.prototype, "intensity", 2);
2069
+ __decorateClass$3([
2070
+ onChange(OutlinePlugin.prototype.setDirty),
2071
+ uiSlider("Transparency", [0, 1], 0.01),
2072
+ serialize()
2073
+ ], OutlinePlugin.prototype, "highlightTransparency", 2);
2074
+ __decorateClass$3([
2075
+ uiColor("Color"),
2076
+ uniform({ propKey: "outlineColor" }),
2077
+ serialize("outlineColor")
2078
+ ], OutlinePlugin.prototype, "color", 2);
2079
+ __decorateClass$3([
2080
+ uiSlider("Thickness", [0, 10], 0.01),
2081
+ uniform({ propKey: "outlineThickness" }),
2082
+ serialize("outlineThickness")
2083
+ ], OutlinePlugin.prototype, "thickness", 2);
2084
+ __decorateClass$3([
2085
+ uiToggle("Debug"),
2086
+ matDefineBool("DEBUG_OUTLINE", void 0, true)
2087
+ ], OutlinePlugin.prototype, "debugOutline", 2);
2088
+ __decorateClass$3([
2089
+ onChange(OutlinePlugin.prototype.setDirty),
2090
+ uiToggle("Highlight Selected Materials")
2091
+ ], OutlinePlugin.prototype, "highlightSelectedMaterials", 2);
2092
+ __decorateClass$3([
2093
+ onChange(OutlinePlugin.prototype.setDirty),
2094
+ uiToggle("Highlight Materials (same name)")
2095
+ ], OutlinePlugin.prototype, "highlightMaterialSameNames", 2);
2096
+ __decorateClass$3([
2097
+ uniform({ propKey: "highlightTransparency" })
2098
+ ], OutlinePlugin.prototype, "transparency", 2);
2099
+ __decorateClass$3([
2100
+ uniform({ propKey: "outlineBuffer" }),
2101
+ uiImage(
2102
+ "Outline Buffer"
2103
+ /* {readOnly: true}*/
2104
+ )
2105
+ ], OutlinePlugin.prototype, "texture", 2);
2106
+ OutlinePlugin = __decorateClass$3([
2107
+ uiFolderContainer("Outline")
2108
+ ], OutlinePlugin);
2109
+ let OutlineRenderPass = class extends RenderPass {
2110
+ constructor(passId2, _getSelectedObjectOrMaterial, target, overrideMaterial) {
2111
+ super(void 0, void 0, overrideMaterial, new Color(1, 1, 1), 1);
2112
+ this.passId = passId2;
2113
+ this._getSelectedObjectOrMaterial = _getSelectedObjectOrMaterial;
2114
+ this.target = target;
2115
+ this.isOutlineRenderPass = true;
2116
+ this.enabled = true;
2117
+ this.before = ["render"];
2118
+ this.after = ["gbuffer"];
2119
+ this.required = ["render", "gbuffer"];
2120
+ this.onDirty = [];
2121
+ }
2122
+ // constructor(private _getSelectedObjectOrMaterial: ()=>SelType, public target: WebGLRenderTarget, material: Material, clearColor: Color = new Color(1, 1, 1), clearAlpha = 1) {
2123
+ // super(undefined as any, undefined as any, material, clearColor, clearAlpha)
2124
+ // }
2125
+ /**
2126
+ * Renders to {@link target}
2127
+ * @param renderer
2128
+ * @param writeBuffer - this is ignored? or used as transmissionRenderTarget?
2129
+ * @param _1 - this is ignored
2130
+ * @param deltaTime
2131
+ * @param maskActive
2132
+ */
2133
+ render(renderer, writeBuffer, _1, deltaTime, maskActive) {
2134
+ if (!this.scene || !this.camera) return;
2135
+ const t = renderer.getRenderTarget();
2136
+ const activeCubeFace = renderer.getActiveCubeFace();
2137
+ const activeMipLevel = renderer.getActiveMipmapLevel();
2138
+ const selectedObject = this._getSelectedObjectOrMaterial();
2139
+ if (selectedObject) {
2140
+ this._renderSelectedObject(renderer, selectedObject, writeBuffer || null, deltaTime, maskActive);
2141
+ } else {
2142
+ renderer.setRenderTarget(getOrCall(this.target) || null);
2143
+ const color = new Color();
2144
+ renderer.getClearColor(color);
2145
+ renderer.setClearColor(new Color(16777215));
2146
+ renderer.clear(true, true);
2147
+ renderer.setClearColor(color);
2148
+ }
2149
+ renderer.setRenderTarget(t, activeCubeFace, activeMipLevel);
2150
+ }
2151
+ _renderSelectedObject(renderer, selectedObject, writeBuffer, deltaTime, maskActive) {
2152
+ if (!this.camera) return;
2153
+ const selectionLayer = 6;
2154
+ const objs = (Array.isArray(selectedObject) ? selectedObject : [selectedObject]).map((o) => {
2155
+ var _a2;
2156
+ return (o == null ? void 0 : o.isMaterial) ? [...(_a2 = o.appliedMeshes) == null ? void 0 : _a2.values()] : o;
2157
+ }).flat();
2158
+ for (const o1 of objs) {
2159
+ o1.traverse((o) => {
2160
+ o.layers.enable(selectionLayer);
2161
+ });
2162
+ }
2163
+ const mask = this.camera.layers.mask;
2164
+ this.camera.layers.set(selectionLayer);
2165
+ const ud = renderer.userData;
2166
+ if (!ud) console.error("threejs is not patched?");
2167
+ ud.transmissionRenderTarget = writeBuffer;
2168
+ renderer.renderWithModes({
2169
+ shadowMapRender: false,
2170
+ backgroundRender: false,
2171
+ opaqueRender: true,
2172
+ transparentRender: true,
2173
+ transmissionRender: true,
2174
+ mainRenderPass: false
2175
+ }, () => super.render(renderer, writeBuffer, getOrCall(this.target), deltaTime, maskActive));
2176
+ ud.transmissionRenderTarget = void 0;
2177
+ objs.forEach((o1) => o1.traverse((o) => {
2178
+ o.layers.disable(selectionLayer);
2179
+ }));
2180
+ this.camera.layers.mask = mask;
2181
+ }
2182
+ dispose() {
2183
+ var _a2;
2184
+ this.onDirty = [];
2185
+ this.scene = void 0;
2186
+ this.camera = void 0;
2187
+ (_a2 = super.dispose) == null ? void 0 : _a2.call(this);
2188
+ }
2189
+ setDirty() {
2190
+ this.onDirty.forEach((v) => v());
2191
+ }
2192
+ beforeRender(scene, camera, _) {
2193
+ this.scene = scene;
2194
+ this.camera = camera;
2195
+ camera.updateShaderProperties(this.overrideMaterial);
2196
+ }
2197
+ };
2198
+ __decorateClass$3([
2199
+ uiToggle("Enabled")
2200
+ ], OutlineRenderPass.prototype, "enabled", 2);
2201
+ OutlineRenderPass = __decorateClass$3([
2202
+ uiFolderContainer((c) => c.passId + " Render Pass")
2203
+ ], OutlineRenderPass);
2204
+ const ssgiPatch = "\n#if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0\nvec4 ssgi=tSSGIMapTexelToLinear(texture2D(tSSGIMap,viewToScreen(vViewPosition.xyz).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(geometry.normal,geometry.viewDir));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#endif\n";
2205
+ const ssrtaoShader = "uniform float sceneBoundingRadius;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;vec3 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\nvec3 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.));}";
2206
+ const ssaoBilateral = "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;}";
2207
+ var __defProp$2 = Object.defineProperty;
2208
+ var __decorateClass$2 = (decorators, target, key, kind) => {
2209
+ var result = void 0;
2210
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2211
+ if (decorator = decorators[i])
2212
+ result = decorator(target, key, result) || result;
2213
+ if (result) __defProp$2(target, key, result);
2214
+ return result;
2215
+ };
2216
+ class BilateralFilterPass extends ExtendedShaderPass {
2217
+ // @serialize() @uniform() smoothSigma = new Vector4(1, 0.2, 4., 1)
2218
+ // @serialize() @uniform() smoothScale = new Vector4(0, 10, 1, 0)
2219
+ constructor(target, sourceAccessor = "rgba") {
2220
+ super({
2221
+ vertexShader: CopyShader.vertexShader,
2222
+ fragmentShader: `
2223
+ // for gbuffer
2224
+ #include <packing>
2225
+ #define THREE_PACKING_INCLUDED
2226
+ ` + ssaoBilateral,
2227
+ uniforms: {
2228
+ bilDirection: { value: new Vector2(1, 0) },
2229
+ // tNormalDepth: {value: null},
2230
+ tDiffuse: { value: null },
2231
+ tDiffuseSize: { value: new Vector2() }
2232
+ },
2233
+ defines: {
2234
+ ["B_SRC_ACCESSOR"]: sourceAccessor
2235
+ }
2236
+ }, "tDiffuse");
2237
+ this.target = target;
2238
+ this.smoothEnabled = true;
2239
+ this.edgeSharpness = 0.1;
2240
+ this.clear = false;
2241
+ this.needsSwap = false;
2242
+ }
2243
+ render(renderer, writeBuffer, _readBuffer, deltaTime, maskActive) {
2244
+ var _a2, _b, _c, _d;
2245
+ if (!this.enabled) return;
2246
+ const target = getOrCall(this.target);
2247
+ if (!target) return;
2248
+ this.uniforms.bilDirection.value.set(1, 0);
2249
+ this.uniforms.tDiffuse.value = target.texture;
2250
+ this.uniforms.tDiffuseSize.value.set(((_a2 = this.uniforms.tDiffuse.value) == null ? void 0 : _a2.image.width) || 0, ((_b = this.uniforms.tDiffuse.value) == null ? void 0 : _b.image.height) || 0);
2251
+ super.render(renderer, writeBuffer, target, deltaTime, maskActive);
2252
+ this.uniforms.bilDirection.value.set(0, 1);
2253
+ this.uniforms.tDiffuse.value = writeBuffer.texture;
2254
+ this.uniforms.tDiffuseSize.value.set(((_c = this.uniforms.tDiffuse.value) == null ? void 0 : _c.image.width) || 0, ((_d = this.uniforms.tDiffuse.value) == null ? void 0 : _d.image.height) || 0);
2255
+ super.render(renderer, target, writeBuffer, deltaTime, maskActive);
2256
+ }
2257
+ }
2258
+ __decorateClass$2([
2259
+ serialize(),
2260
+ uniform()
2261
+ ], BilateralFilterPass.prototype, "smoothEnabled");
2262
+ __decorateClass$2([
2263
+ serialize(),
2264
+ uniform()
2265
+ ], BilateralFilterPass.prototype, "edgeSharpness");
2266
+ var __defProp$1 = Object.defineProperty;
2267
+ var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
2268
+ var __decorateClass$1 = (decorators, target, key, kind) => {
2269
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
2270
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2271
+ if (decorator = decorators[i])
2272
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2273
+ if (kind && result) __defProp$1(target, key, result);
2274
+ return result;
2275
+ };
2276
+ const passId = "ssrtgi";
2277
+ let SSGIPlugin = class extends PipelinePassPlugin {
2278
+ // cannot be changed after creation (for now)
2279
+ constructor(bufferType = UnsignedByteType, sizeMultiplier = 1, enabled = true) {
2280
+ super();
2281
+ this.passId = passId;
2282
+ this.dependencies = [GBufferPlugin, SSAAPlugin];
2283
+ this._gbufferUnpackExtension = void 0;
2284
+ this._gbufferUnpackExtensionChanged = () => {
2285
+ if (!this._pass || !this._viewer) throw new Error("SSGIPlugin: pass/viewer not created yet");
2286
+ const newExtension = this._viewer.renderManager.gbufferUnpackExtension;
2287
+ if (this._gbufferUnpackExtension === newExtension) return;
2288
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(void 0);
2289
+ this._gbufferUnpackExtension = newExtension;
2290
+ if (this._gbufferUnpackExtension) this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension);
2291
+ else this._viewer.console.warn("SSGIPlugin: GBuffer unpack extension removed");
2292
+ };
2293
+ this.enabled = enabled;
2294
+ this.bufferType = bufferType;
2295
+ this.sizeMultiplier = sizeMultiplier;
2296
+ }
2297
+ _createTarget(recreate = true) {
2298
+ if (!this._viewer) return;
2299
+ if (recreate) this._disposeTarget();
2300
+ if (!this.target)
2301
+ this.target = this._viewer.renderManager.createTarget(
2302
+ {
2303
+ depthBuffer: false,
2304
+ type: this.bufferType,
2305
+ sizeMultiplier: this.sizeMultiplier
2306
+ // magFilter: NearestFilter,
2307
+ // minFilter: NearestFilter,
2308
+ // generateMipmaps: false,
2309
+ // encoding: LinearEncoding,
2310
+ }
2311
+ );
2312
+ this.texture = this.target.texture;
2313
+ this.texture.name = "ssgiBuffer";
2314
+ }
2315
+ _disposeTarget() {
2316
+ if (!this._viewer) return;
2317
+ if (this.target) {
2318
+ this._viewer.renderManager.disposeTarget(this.target);
2319
+ this.target = void 0;
2320
+ }
2321
+ this.texture = void 0;
2322
+ }
2323
+ _createPass() {
2324
+ if (!this._viewer) throw new Error("SSGIPlugin: viewer not set");
2325
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension)
2326
+ throw new Error("SSGIPlugin: GBuffer target not created. GBufferPlugin is required.");
2327
+ this._createTarget(true);
2328
+ return new SSGIPluginPass(this.passId, () => this.target);
2329
+ }
2330
+ onAdded(viewer) {
2331
+ super.onAdded(viewer);
2332
+ if (viewer.getPlugin("Ground") || viewer.getPlugin("BaseGroundPlugin")) console.error("GroundPlugin must be added after SSGIPlugin");
2333
+ this._gbufferUnpackExtensionChanged();
2334
+ viewer.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
2335
+ }
2336
+ onRemove(viewer) {
2337
+ this._disposeTarget();
2338
+ viewer.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
2339
+ return super.onRemove(viewer);
2340
+ }
2341
+ _beforeRender(_, _1, _2) {
2342
+ var _a2, _b;
2343
+ if (!this._viewer) return false;
2344
+ const e = super._beforeRender(_, _1, _2);
2345
+ if (e) {
2346
+ const ssao = (_a2 = this._viewer) == null ? void 0 : _a2.getPlugin("SSAOPlugin");
2347
+ if (ssao && !ssao.isDisabled()) {
2348
+ ssao.disable(SSGIPlugin.PluginType);
2349
+ }
2350
+ }
2351
+ if (!e) return e;
2352
+ const progressive = this._viewer.getPlugin(ProgressivePlugin);
2353
+ (_b = this._pass) == null ? void 0 : _b.updateShaderProperties([progressive]);
2354
+ return e;
2355
+ }
2356
+ /**
2357
+ * @deprecated use {@link target} instead
2358
+ */
2359
+ get rtgiTarget() {
2360
+ console.warn("SSGIPlugin: rtgiTarget is deprecated, use target instead");
2361
+ return this.target;
2362
+ }
2363
+ };
2364
+ SSGIPlugin.PluginType = "SSGIPlugin";
2365
+ SSGIPlugin.OldPluginType = "SSGI";
2366
+ __decorateClass$1([
2367
+ uiImage(
2368
+ "SSGI Buffer"
2369
+ /* {readOnly: true}*/
2370
+ )
2371
+ ], SSGIPlugin.prototype, "texture", 2);
2372
+ __decorateClass$1([
2373
+ uiConfig()
2374
+ ], SSGIPlugin.prototype, "_pass", 2);
2375
+ SSGIPlugin = __decorateClass$1([
2376
+ uiFolderContainer("SSGI Plugin")
2377
+ ], SSGIPlugin);
2378
+ let SSGIPluginPass = class extends ExtendedShaderPass {
2379
+ constructor(pid, target, giEnabled = true) {
2380
+ super({
2381
+ defines: {
2382
+ ["RTAO_STEP_COUNT"]: 16,
2383
+ // ['SSRTAO_LOW_QUALITY_FRAMES']: 2,
2384
+ // ['SSRTAO_MASK_FRONT_RAYS']: true,
2385
+ ["PERSPECTIVE_CAMERA"]: 1
2386
+ // set in PerspectiveCamera2
2387
+ // ['CHECK_GBUFFER_FLAG']: 0, // todo like ssao plugin
2388
+ },
2389
+ uniforms: {
2390
+ // tDiffuse: {value: null},// todo
2391
+ // tNormalDepth: {value: null},// todo
2392
+ // smoothEnabled: {value: false},
2393
+ // smoothSigma: {value: new Vector4(0.5, 0.2, 4., 0.4)},
2394
+ // smoothScale: {value: new Vector4(1, 10, 1, 8)},
2395
+ tLastThis: { value: null },
2396
+ tLastFrame: { value: null },
2397
+ // set in progressive plugin
2398
+ // TODO required?
2399
+ screenSize: { value: new Vector2(0, 0) },
2400
+ // set in ExtendedRenderMaterial
2401
+ currentFrameCount: { value: 0 },
2402
+ // set in RenderManager
2403
+ frameCount: { value: 0 },
2404
+ // set in RenderManager
2405
+ cameraNearFar: { value: new Vector2(0.1, 1e3) },
2406
+ // set in PerspectiveCamera2
2407
+ cameraPositionWorld: { value: new Vector3() },
2408
+ // set in PerspectiveCamera2
2409
+ projection: { value: new Matrix4() },
2410
+ // set in PerspectiveCamera2
2411
+ // saoBiasEpsilon: {value: new Vector3(1, 1, 1)},
2412
+ opacity: { value: 1 },
2413
+ // todo?
2414
+ intensity: { value: 0 },
2415
+ objectRadius: { value: 0 },
2416
+ autoRadius: { value: giEnabled ? false : true },
2417
+ rayCount: { value: 0.1 },
2418
+ bias: { value: 0.015 },
2419
+ falloff: { value: 0.7 },
2420
+ power: { value: 1.1 },
2421
+ // maskFrontFactor: {value: -0.1},
2422
+ tolerance: { value: 0 },
2423
+ // ssrtaoRoughnessFactor: {value: 1},
2424
+ sceneBoundingRadius: { value: 0 }
2425
+ // todo do same in SSAO
2426
+ },
2427
+ vertexShader: shaderUtils.defaultVertex,
2428
+ fragmentShader: `
2429
+ varying vec2 vUv;
2430
+
2431
+ // for gbuffer
2432
+ #include <packing>
2433
+ #define THREE_PACKING_INCLUDED
2434
+ #include <cameraHelpers>
2435
+ #include <randomHelpers>
2436
+ ${samplePointHelpers}
2437
+
2438
+ ${ssrtShader}
2439
+
2440
+ ${ssrtaoShader}
2441
+ `
2442
+ }, "tDiffuse", "tLastThis", "tLastFrame");
2443
+ this.target = target;
2444
+ this.before = ["render"];
2445
+ this.after = ["gbuffer", "depth"];
2446
+ this.required = ["render", "progressive"];
2447
+ this.giEnabled = true;
2448
+ this.intensity = 2;
2449
+ this.power = 1.1;
2450
+ this.autoRadius = true;
2451
+ this.objectRadius = 1;
2452
+ this.tolerance = 1;
2453
+ this.bias = 0.015;
2454
+ this.falloff = 0.7;
2455
+ this.rayCount = 4;
2456
+ this.stepCount = 8;
2457
+ this.smoothEnabled = true;
2458
+ this.renderWithCamera = true;
2459
+ this.materialExtension = {
2460
+ // todo set priority wrt ssr etc
2461
+ extraUniforms: {
2462
+ tSSGIMap: () => {
2463
+ var _a2;
2464
+ return { value: ((_a2 = getOrCall(this.target)) == null ? void 0 : _a2.texture) ?? null };
2465
+ },
2466
+ ssaoPower: this.material.uniforms.power,
2467
+ ssgiIntensity: this.material.uniforms.intensity
2468
+ // ssrMaskFrontFactor: this.material.uniforms.maskFrontFactor,
2469
+ },
2470
+ extraDefines: {
2471
+ ["SSGI_ENABLED"]: () => this.material.defines.SSGI_ENABLED
2472
+ // ['RTAO_STEP_COUNT']: ()=>this.material.defines.SRTAOSTEP_COUNT,
2473
+ // ['SSRTAO_LOW_QUALITY_FRAMES']: ()=>this.material.defines.SSRTAO_LOW_QUALITY_FRAMES,
2474
+ // ['SSRTAO_MASK_FRONT_RAYS']: ()=>this.material.defines.SSRTAO_MASK_FRONT_RAYS,
2475
+ // ['PERSPECTIVE_CAMERA']: ()=>this.material.defines.PERSPECTIVE_CAMERA,
2476
+ // todo gbuffer stuff
2477
+ },
2478
+ shaderExtender: (shader, _material, _renderer) => {
2479
+ if (!shader.defines.SSRTAO_ENABLED) return;
2480
+ const ls = `
2481
+
2482
+ ${ssgiPatch}
2483
+
2484
+ #if defined(SSGI_ENABLED) && SSGI_ENABLED > 0
2485
+ // reflectedLight.directDiffuse = vec3(0.);
2486
+ // reflectedLight.indirectDiffuse = vec3(0.);
2487
+ // reflectedLight.directSpecular = vec3(0.);
2488
+ // reflectedLight.indirectSpecular = vec3(0.);
2489
+ #endif
2490
+ `;
2491
+ shader.fragmentShader = shaderReplaceString(
2492
+ shader.fragmentShader,
2493
+ "vec3 totalDiffuse =",
2494
+ ls,
2495
+ { prepend: true }
2496
+ );
2497
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <aomap_fragment>", "");
2498
+ },
2499
+ onObjectRender: (_object, material, renderer) => {
2500
+ var _a2, _b, _c;
2501
+ let x = this.enabled && (this.renderWithCamera || renderer.renderManager.frameCount > 1) && renderer.userData.screenSpaceRendering !== false && !((_a2 = material.userData) == null ? void 0 : _a2.pluginsDisabled) && !((_b = material.userData) == null ? void 0 : _b.ssrtaoDisabled) && !((_c = material.userData) == null ? void 0 : _c.ssaoDisabled) ? 1 : 0;
2502
+ if (material.defines.SSRTAO_ENABLED !== x) {
2503
+ material.defines.SSRTAO_ENABLED = x;
2504
+ material.needsUpdate = true;
2505
+ }
2506
+ },
2507
+ parsFragmentSnippet: (renderer) => {
2508
+ var _a2;
2509
+ return glsl`
2510
+ #if defined(SSRTAO_ENABLED) && SSRTAO_ENABLED > 0
2511
+ uniform float ssaoPower;
2512
+ uniform float ssgiIntensity;
2513
+ uniform sampler2D tSSGIMap;
2514
+ ${getTexelDecoding("tSSGIMap", (_a2 = getOrCall(this.target)) == null ? void 0 : _a2.texture, renderer.capabilities.isWebGL2)}
2515
+ ${/*tLastFrame not requried in material extension
2516
+ // uniform sampler2D tLastFrame;
2517
+ ${getTexelDecoding('tLastFrame', this.material.uniforms!.tLastFrame.value, renderer!.capabilities.isWebGL2)}
2518
+ */
2519
+ ""}
2520
+ #include <simpleCameraHelpers>
2521
+ #endif
2522
+ `;
2523
+ },
2524
+ computeCacheKey: () => {
2525
+ var _a2;
2526
+ const tex = (_a2 = getOrCall(this.target)) == null ? void 0 : _a2.texture;
2527
+ return (this.enabled ? "1" : "0") + (tex == null ? void 0 : tex.colorSpace) + (tex == null ? void 0 : tex.uuid) + Object.values(this.material.defines).map((v) => v + "").join(",");
2528
+ },
2529
+ uuid: SSGIPlugin.PluginType,
2530
+ ...uiConfigMaterialExtension(this._getUiConfig.bind(this), SSGIPlugin.PluginType),
2531
+ isCompatible: (material) => {
2532
+ return material.isPhysicalMaterial;
2533
+ }
2534
+ };
2535
+ this.passId = pid;
2536
+ this.needsSwap = true;
2537
+ this.clear = true;
2538
+ this.giEnabled = giEnabled;
2539
+ this.bilateralPass = new BilateralFilterPass(this.target, "rgba");
2540
+ }
2541
+ render(renderer, writeBuffer, readBuffer, deltaTime, maskActive) {
2542
+ if (!this.enabled) return;
2543
+ this.needsSwap = false;
2544
+ if (!this.renderWithCamera && renderer.renderManager.frameCount < 2) {
2545
+ return;
2546
+ }
2547
+ const target = getOrCall(this.target);
2548
+ if (!target) {
2549
+ console.warn("SSGIPluginPass: target not defined.");
2550
+ return;
2551
+ }
2552
+ renderer.renderManager.blit(writeBuffer, {
2553
+ source: target.texture
2554
+ });
2555
+ if (!this.material.defines.HAS_GBUFFER) {
2556
+ console.warn("SSGIPluginPass: DepthNormalBuffer required for ssrtao/ssgi");
2557
+ }
2558
+ this.uniforms.tLastThis.value = writeBuffer.texture;
2559
+ super.render(renderer, target, readBuffer, deltaTime, maskActive);
2560
+ if (this.smoothEnabled) {
2561
+ this.bilateralPass.render(renderer, writeBuffer, readBuffer, deltaTime, maskActive);
2562
+ }
2563
+ }
2564
+ beforeRender(scene, camera, renderManager) {
2565
+ if (!this.enabled) return;
2566
+ this.updateShaderProperties([scene, camera, renderManager]);
2567
+ }
2568
+ /**
2569
+ * Returns a uiConfig to toggle SSGI on a material.
2570
+ * This uiConfig is added to each material by extension
2571
+ * @param material
2572
+ * @private
2573
+ */
2574
+ _getUiConfig(material) {
2575
+ return {
2576
+ type: "folder",
2577
+ label: "SSGI",
2578
+ children: [
2579
+ {
2580
+ type: "checkbox",
2581
+ label: "Enabled",
2582
+ get value() {
2583
+ return !(material.userData.ssgiDisabled ?? false);
2584
+ },
2585
+ set value(v) {
2586
+ if (v === !(material.userData.ssgiDisabled ?? false)) return;
2587
+ material.userData.ssgiDisabled = !v;
2588
+ material.setDirty();
2589
+ },
2590
+ onChange: this.setDirty
2591
+ }
2592
+ // todo ssao cast
2593
+ // {
2594
+ // type: 'checkbox',
2595
+ // label: 'Non Physical',
2596
+ // get value() {
2597
+ // return material.userData.ssreflNonPhysical ?? false
2598
+ // },
2599
+ // set value(v) {
2600
+ // if (v === (material.userData.ssreflNonPhysical ?? false)) return
2601
+ // material.userData.ssreflNonPhysical = v
2602
+ // material.setDirty()
2603
+ // },
2604
+ // onChange: this.setDirty,
2605
+ // },
2606
+ ]
2607
+ };
2608
+ }
2609
+ set uniformsNeedUpdate(value) {
2610
+ this.material.uniformsNeedUpdate = value;
2611
+ this.setDirty();
2612
+ }
2613
+ setGBufferUnpackExtension(extension) {
2614
+ if (this._gbufferUnpackExtension === extension) return;
2615
+ if (this._gbufferUnpackExtension) {
2616
+ this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
2617
+ this.bilateralPass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]);
2618
+ }
2619
+ this._gbufferUnpackExtension = extension;
2620
+ if (this._gbufferUnpackExtension) {
2621
+ this.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
2622
+ this.bilateralPass.material.registerMaterialExtensions([this._gbufferUnpackExtension]);
2623
+ }
2624
+ if (!this._gbufferUnpackExtension) return;
2625
+ }
2626
+ // todo update gbuffer flag like in AO?
2627
+ setDirty() {
2628
+ var _a2, _b;
2629
+ (_b = (_a2 = this.materialExtension) == null ? void 0 : _a2.setDirty) == null ? void 0 : _b.call(_a2);
2630
+ super.setDirty();
2631
+ }
2632
+ };
2633
+ __decorateClass$1([
2634
+ serialize()
2635
+ ], SSGIPluginPass.prototype, "bilateralPass", 2);
2636
+ __decorateClass$1([
2637
+ uiToggle("GI Enabled"),
2638
+ serialize(),
2639
+ matDefineBool("SSGI_ENABLED", void 0, void 0, SSGIPluginPass.prototype.setDirty, false)
2640
+ ], SSGIPluginPass.prototype, "giEnabled", 2);
2641
+ __decorateClass$1([
2642
+ uiSlider("Intensity", [0, 4]),
2643
+ serialize(),
2644
+ uniform()
2645
+ ], SSGIPluginPass.prototype, "intensity", 2);
2646
+ __decorateClass$1([
2647
+ uiSlider("Power", [0, 3]),
2648
+ serialize(),
2649
+ uniform()
2650
+ ], SSGIPluginPass.prototype, "power", 2);
2651
+ __decorateClass$1([
2652
+ uiToggle("Auto radius"),
2653
+ serialize(),
2654
+ uniform()
2655
+ ], SSGIPluginPass.prototype, "autoRadius", 2);
2656
+ __decorateClass$1([
2657
+ uiSlider("Object Radius", [0.01, 10]),
2658
+ serialize(),
2659
+ uniform()
2660
+ ], SSGIPluginPass.prototype, "objectRadius", 2);
2661
+ __decorateClass$1([
2662
+ uiSlider("Tolerance", [0.1, 5]),
2663
+ serialize(),
2664
+ uniform()
2665
+ ], SSGIPluginPass.prototype, "tolerance", 2);
2666
+ __decorateClass$1([
2667
+ uiSlider("Bias", [-0.3, 0.3]),
2668
+ serialize(),
2669
+ uniform()
2670
+ ], SSGIPluginPass.prototype, "bias", 2);
2671
+ __decorateClass$1([
2672
+ uiSlider("Falloff", [1e-4, 4]),
2673
+ serialize(),
2674
+ uniform()
2675
+ ], SSGIPluginPass.prototype, "falloff", 2);
2676
+ __decorateClass$1([
2677
+ uiSlider("Ray Count", [1, 5], 1),
2678
+ serialize(),
2679
+ uniform()
2680
+ ], SSGIPluginPass.prototype, "rayCount", 2);
2681
+ __decorateClass$1([
2682
+ uiSlider("Step count", [1, 16], 1),
2683
+ serialize(),
2684
+ matDefine("RTAO_STEP_COUNT", void 0, void 0, SSGIPluginPass.prototype.setDirty)
2685
+ ], SSGIPluginPass.prototype, "stepCount", 2);
2686
+ __decorateClass$1([
2687
+ uiToggle("Smooth Enabled"),
2688
+ serialize()
2689
+ ], SSGIPluginPass.prototype, "smoothEnabled", 2);
2690
+ __decorateClass$1([
2691
+ uiToggle("Render with Camera")
2692
+ ], SSGIPluginPass.prototype, "renderWithCamera", 2);
2693
+ SSGIPluginPass = __decorateClass$1([
2694
+ uiFolderContainer("SSGI Pass")
2695
+ ], SSGIPluginPass);
2696
+ const anisotropyBsdf = "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;float D_GGX_Anisotropy(float at,float ab,float ToH,float BoH,float NoH){float a2=at*ab;highp vec3 d=vec3(ab*ToH,at*BoH,a2*NoH);highp float d2=dot(d,d);float b2=a2/d2;return a2*b2*b2*(1.0/PI);}float V_GGX_SmithCorrelated_Anisotropy(float at,float ab,float ToV,float BoV,float ToL,float BoL,float NoV,float NoL){float lambdaV=NoL*length(vec3(at*ToV,ab*BoV,NoV));float lambdaL=NoV*length(vec3(at*ToL,ab*BoL,NoL));float v=0.5/(lambdaV+lambdaL);return saturate(v);}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_Anisotropy(at,ab,dotTV,dotBV,dotTL,dotBL,dotNV,dotNL);float D=D_GGX_Anisotropy(at,ab,dotTH,dotBH,dotNH);return F*(V*D);}";
2697
+ const anisotropyTBN = "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));";
2698
+ var __defProp = Object.defineProperty;
2699
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2700
+ var __decorateClass = (decorators, target, key, kind) => {
2701
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
2702
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2703
+ if (decorator = decorators[i])
2704
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
2705
+ if (kind && result) __defProp(target, key, result);
2706
+ return result;
2707
+ };
2708
+ let AnisotropyPlugin = class extends AViewerPluginSync {
2709
+ constructor() {
2710
+ super();
2711
+ this.enabled = true;
2712
+ this._defines = {
2713
+ // ['ANISOTROPY_BICUBIC']: false,
2714
+ };
2715
+ this._uniforms = {
2716
+ anisotropyFactor: { value: 1 },
2717
+ anisotropyNoise: { value: 1 },
2718
+ anisotropyDirection: { value: 1 },
2719
+ anisotropyDirectionMap: { value: null },
2720
+ anisotropy2MapUvTransform: { value: new Matrix3() },
2721
+ frameCount: { value: 0 }
2722
+ };
2723
+ this.materialExtension = {
2724
+ uuid: AnisotropyPlugin.PluginType,
2725
+ priority: 10,
2726
+ // more than sscs(which is 5)
2727
+ shaderExtender: (shader, material, renderer) => {
2728
+ var _a2;
2729
+ if (this.isDisabled() || !(material == null ? void 0 : material.userData._isAnisotropic)) return;
2730
+ const rotMap = (_a2 = material.userData) == null ? void 0 : _a2._anisotropyDirectionMap;
2731
+ const bsdfs = glsl`
2732
+ //#if ANISOTROPY_ENABLED
2733
+ #include <randomHelpers>
2734
+ #ifndef D_frameCount
2735
+ #define D_frameCount
2736
+ uniform float frameCount;
2737
+ #endif
2738
+ ${anisotropyBsdf}
2739
+ ${rotMap ? getTexelDecoding("anisotropyDirectionMap", rotMap, renderer.capabilities.isWebGL2) : ""}\n
2740
+ `;
2741
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <common>", bsdfs, { append: true });
2742
+ shader.fragmentShader = shader.fragmentShader.replace("#include <lights_fragment_begin>", ShaderChunk.lights_fragment_begin);
2743
+ shader.fragmentShader = shaderReplaceString(
2744
+ shaderReplaceString(
2745
+ shader.fragmentShader,
2746
+ "IncidentLight directLight;",
2747
+ anisotropyTBN,
2748
+ { prepend: true }
2749
+ ),
2750
+ "RE_Direct( directLight, geometry, material, reflectedLight )",
2751
+ "RE_Direct( directLight, geometry, material, reflectedLight, anisotropicT, anisotropicB )",
2752
+ { replaceAll: true }
2753
+ );
2754
+ let lights_physical_pars_fragment = shaderReplaceString(
2755
+ ShaderChunk.lights_physical_pars_fragment,
2756
+ "void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {",
2757
+ "void RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight, const in vec3 anisotropicT, const in vec3 anisotropicB ) {"
2758
+ );
2759
+ lights_physical_pars_fragment = shaderReplaceString(
2760
+ lights_physical_pars_fragment,
2761
+ "BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material )",
2762
+ "BRDF_GGX_Anisotropy( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness, anisotropicT, anisotropicB )"
2763
+ );
2764
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <lights_physical_pars_fragment>", lights_physical_pars_fragment);
2765
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <normal_fragment_begin>", ShaderChunk.normal_fragment_begin);
2766
+ shader.fragmentShader = shaderReplaceString(
2767
+ shader.fragmentShader,
2768
+ "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )",
2769
+ "#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) || defined( USE_TANGENT )"
2770
+ );
2771
+ let lights_fragment_maps = glsl`
2772
+ #if defined( USE_ENVMAP )
2773
+ vec3 anisotropyBentNormal = indirectAnisotropyBentNormal(geometry.normal, geometry.viewDir, material.roughness, anisotropicT, anisotropicB);
2774
+ #endif
2775
+ ` + ShaderChunk.lights_fragment_maps;
2776
+ lights_fragment_maps = shaderReplaceString(
2777
+ lights_fragment_maps,
2778
+ "getIBLIrradiance( geometry.normal )",
2779
+ "getIBLIrradiance( anisotropyBentNormal )"
2780
+ );
2781
+ lights_fragment_maps = shaderReplaceString(
2782
+ lights_fragment_maps,
2783
+ "getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness )",
2784
+ "getIBLRadiance( geometry.viewDir, anisotropyBentNormal, material.roughness )"
2785
+ );
2786
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, "#include <lights_fragment_maps>", lights_fragment_maps);
2787
+ shader.vertexShader = shaderReplaceString(
2788
+ shader.vertexShader,
2789
+ "#include <uv_pars_vertex>",
2790
+ `
2791
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
2792
+ varying vec2 vAnisotropy2MapUv;
2793
+ uniform mat3 anisotropy2MapUvTransform;
2794
+ #endif
2795
+ `,
2796
+ { prepend: true }
2797
+ );
2798
+ shader.vertexShader = shaderReplaceString(
2799
+ shader.vertexShader,
2800
+ "#include <uv_vertex>",
2801
+ `
2802
+ #if defined(ANISOTROPY_ENABLED) && ANISOTROPY_ENABLED > 0
2803
+ vAnisotropy2MapUv = ( anisotropy2MapUvTransform * vec3( uv, 1 ) ).xy;
2804
+ #endif
2805
+ `,
2806
+ { prepend: true }
2807
+ );
2808
+ shader.defines.USE_UV = "";
2809
+ shader.vertexTangents = true;
2810
+ },
2811
+ onObjectRender: (object, material) => {
2812
+ var _a2;
2813
+ const userData = material.userData;
2814
+ if (!(userData == null ? void 0 : userData._isAnisotropic)) return;
2815
+ if (!object.isMesh || !object.geometry) return;
2816
+ if (!object.geometry.attributes.tangent) {
2817
+ throw new Error("AnisotropyPlugin: No tangents on the geometry");
2818
+ }
2819
+ this._uniforms.anisotropyFactor.value = userData._anisotropyFactor ?? 1;
2820
+ this._uniforms.anisotropyNoise.value = userData._anisotropyNoise ?? 0;
2821
+ this._uniforms.anisotropyDirection.value = userData._anisotropyDirection ?? 1;
2822
+ const tex = ((_a2 = userData._anisotropyDirectionMap) == null ? void 0 : _a2.isTexture) ? userData._anisotropyDirectionMap : null;
2823
+ this._uniforms.anisotropyDirectionMap.value = tex;
2824
+ if (tex) {
2825
+ tex.updateMatrix();
2826
+ this._uniforms.anisotropy2MapUvTransform.value.copy(tex.matrix);
2827
+ }
2828
+ updateMaterialDefines({
2829
+ ...this._defines,
2830
+ ["ANISOTROPY_ENABLED"]: +this.enabled,
2831
+ // CONSTANT | ROTATION | DIRECTION
2832
+ ["ANISOTROPY_TEX_MODE"]: !tex ? 0 : userData._anisotropyDirectionMode === "DIRECTION" ? 2 : userData._anisotropyDirectionMode === "ROTATION" ? 1 : 0
2833
+ }, material);
2834
+ },
2835
+ extraUniforms: {
2836
+ // ...this._uniforms, // done in constructor
2837
+ },
2838
+ computeCacheKey: (material1) => {
2839
+ var _a2, _b, _c;
2840
+ return (this.enabled ? "1" : "0") + (((_a2 = material1.userData) == null ? void 0 : _a2._isAnisotropic) ? "1" : "0") + ((_c = (_b = material1.userData) == null ? void 0 : _b._anisotropyDirectionMap) == null ? void 0 : _c.uuid);
2841
+ },
2842
+ isCompatible: (material1) => material1.isPhysicalMaterial,
2843
+ updaters: () => {
2844
+ var _a2;
2845
+ return [
2846
+ // this._viewer?.getPlugin(ProgressivePlugin),
2847
+ // this._viewer?.scene.mainCamera,
2848
+ (_a2 = this._viewer) == null ? void 0 : _a2.renderManager
2849
+ ];
2850
+ },
2851
+ getUiConfig: (material) => {
2852
+ const viewer = this._viewer;
2853
+ const enableAnisotropy = this.enableAnisotropy.bind(this);
2854
+ const state = material.userData;
2855
+ const config = {
2856
+ type: "folder",
2857
+ label: "Anisotropy",
2858
+ onChange: (ev) => {
2859
+ if (!ev.config) return;
2860
+ this.setDirty();
2861
+ },
2862
+ children: [
2863
+ {
2864
+ type: "checkbox",
2865
+ label: "Enabled",
2866
+ get value() {
2867
+ return state._isAnisotropic || false;
2868
+ },
2869
+ set value(v) {
2870
+ var _a2;
2871
+ if (v === state._isAnisotropic) return;
2872
+ if (v) {
2873
+ if (!enableAnisotropy(material))
2874
+ viewer.dialog.alert("AnisotropyPlugin - One or more geometries cannot be made anisotropic.");
2875
+ } else {
2876
+ state._isAnisotropic = false;
2877
+ if (material.setDirty) material.setDirty();
2878
+ }
2879
+ (_a2 = config.uiRefresh) == null ? void 0 : _a2.call(config, true, "postFrame");
2880
+ }
2881
+ },
2882
+ {
2883
+ type: "slider",
2884
+ label: "Factor",
2885
+ bounds: [-2, 2],
2886
+ hidden: () => !state._isAnisotropic,
2887
+ property: [state, "_anisotropyFactor"]
2888
+ // onChange: this.setDirty,
2889
+ },
2890
+ {
2891
+ type: "slider",
2892
+ label: "Noise",
2893
+ bounds: [0, 2],
2894
+ hidden: () => !state._isAnisotropic,
2895
+ property: [state, "_anisotropyNoise"]
2896
+ // onChange: this.setDirty,
2897
+ },
2898
+ {
2899
+ type: "dropdown",
2900
+ label: "Mode",
2901
+ hidden: () => !state._isAnisotropic,
2902
+ property: [state, "_anisotropyDirectionMode"],
2903
+ children: [
2904
+ "CONSTANT",
2905
+ "ROTATION",
2906
+ "DIRECTION"
2907
+ ].map((value) => ({
2908
+ label: value
2909
+ })),
2910
+ onChange: () => {
2911
+ var _a2;
2912
+ if (material.setDirty) material.setDirty();
2913
+ (_a2 = config.uiRefresh) == null ? void 0 : _a2.call(config, true, "postFrame");
2914
+ }
2915
+ },
2916
+ {
2917
+ type: "slider",
2918
+ label: "Direction",
2919
+ bounds: [0, 5],
2920
+ hidden: () => state._anisotropyDirectionMode === "CONSTANT" || !state._isAnisotropic,
2921
+ property: [state, "_anisotropicDirection"]
2922
+ // onChange: this.setDirty,
2923
+ },
2924
+ {
2925
+ type: "image",
2926
+ label: "Texture",
2927
+ hidden: () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT",
2928
+ property: [state, "_anisotropyDirectionMap"],
2929
+ onChange: () => {
2930
+ if (material.setDirty) material.setDirty();
2931
+ }
2932
+ },
2933
+ makeSamplerUi(state, "_anisotropyDirectionMap", "Sampler", () => !state._isAnisotropic || state._anisotropyDirectionMode === "CONSTANT", () => material.setDirty && material.setDirty())
2934
+ ]
2935
+ };
2936
+ return config;
2937
+ }
2938
+ };
2939
+ this.setDirty = () => {
2940
+ var _a2, _b, _c;
2941
+ (_b = (_a2 = this.materialExtension).setDirty) == null ? void 0 : _b.call(_a2);
2942
+ (_c = this._viewer) == null ? void 0 : _c.setDirty();
2943
+ };
2944
+ Object.assign(this.materialExtension.extraUniforms, this._uniforms);
2945
+ }
2946
+ enableAnisotropy(material, map, factor, noise, directionMode) {
2947
+ const ud = material == null ? void 0 : material.userData;
2948
+ if (!ud) return false;
2949
+ if (ud._isAnisotropic === void 0) {
2950
+ const meshes = material.appliedMeshes;
2951
+ let possible = true;
2952
+ if (meshes) for (const { geometry } of meshes) {
2953
+ if (geometry && (!geometry.attributes.position || !geometry.attributes.normal || !geometry.attributes.uv)) {
2954
+ possible = false;
2955
+ }
2956
+ if (possible && geometry && !geometry.attributes.tangent) {
2957
+ geometry.computeTangents();
2958
+ }
2959
+ }
2960
+ if (!possible) {
2961
+ return false;
2962
+ }
2963
+ }
2964
+ ud._isAnisotropic = true;
2965
+ ud._anisotropyFactor = factor ?? ud._anisotropyFactor ?? 1;
2966
+ ud._anisotropyNoise = noise ?? ud._anisotropyNoise ?? 0;
2967
+ ud._anisotropyDirection = /*direction ?? */
2968
+ ud._anisotropyDirection ?? 1;
2969
+ ud._anisotropyDirectionMode = directionMode ?? ud._anisotropyDirectionMode ?? "DIRECTION";
2970
+ ud._anisotropyDirectionMap = map ?? ud._anisotropyDirectionMap ?? null;
2971
+ if (material.setDirty) material.setDirty();
2972
+ return true;
2973
+ }
2974
+ onAdded(v) {
2975
+ super.onAdded(v);
2976
+ v.assetManager.materials.registerMaterialExtension(this.materialExtension);
2977
+ v.assetManager.registerGltfExtension(anisotropyGLTFExtension);
2978
+ }
2979
+ onRemove(v) {
2980
+ var _a2;
2981
+ (_a2 = v.assetManager.materials) == null ? void 0 : _a2.unregisterMaterialExtension(this.materialExtension);
2982
+ v.assetManager.unregisterGltfExtension(anisotropyGLTFExtension.name);
2983
+ return super.onRemove(v);
2984
+ }
2985
+ /**
2986
+ * @deprecated - use {@link enableAnisotropy} instead
2987
+ * @param material
2988
+ */
2989
+ makeAnisotropic(material) {
2990
+ return this.enableAnisotropy(material);
2991
+ }
2992
+ };
2993
+ AnisotropyPlugin.PluginType = "AnisotropyPlugin";
2994
+ AnisotropyPlugin.ANISOTROPY_GLTF_EXTENSION = "WEBGI_materials_anisotropy";
2995
+ __decorateClass([
2996
+ uiToggle("Enabled", (that) => ({ onChange: that.setDirty })),
2997
+ serialize()
2998
+ ], AnisotropyPlugin.prototype, "enabled", 2);
2999
+ AnisotropyPlugin = __decorateClass([
3000
+ uiFolderContainer("Anisotropy (MatExt)")
3001
+ ], AnisotropyPlugin);
3002
+ class GLTFMaterialsAnisotropyExtensionImport {
3003
+ constructor(parser) {
3004
+ this.parser = parser;
3005
+ this.name = anisotropyGLTFExtension.name;
3006
+ }
3007
+ async extendMaterialParams(materialIndex, materialParams) {
3008
+ const parser = this.parser;
3009
+ const materialDef = parser.json.materials[materialIndex];
3010
+ if (!materialDef.extensions || !materialDef.extensions[this.name]) {
3011
+ return Promise.resolve();
3012
+ }
3013
+ const pending = [];
3014
+ const extension = materialDef.extensions[this.name];
3015
+ if (!materialParams.userData) materialParams.userData = {};
3016
+ materialParams.userData._isAnisotropic = true;
3017
+ materialParams.userData._anisotropyFactor = extension.anisotropyFactor ?? 0;
3018
+ materialParams.userData._anisotropyNoise = extension.anisotropyNoiseFactor ?? extension.anisotropyNoise ?? 0;
3019
+ let { anisotropyDirectionMode, anisotropyDirection } = extension;
3020
+ if (!anisotropyDirectionMode) anisotropyDirectionMode = extension.anisotropyTextureMode;
3021
+ if (!anisotropyDirection) anisotropyDirection = extension.anisotropyRotation;
3022
+ materialParams.userData._anisotropyDirectionMode = anisotropyDirectionMode && typeof (anisotropyDirection == null ? void 0 : anisotropyDirection.index) === "number" ? anisotropyDirectionMode : "CONSTANT";
3023
+ if (anisotropyDirectionMode === "ROTATION" || anisotropyDirectionMode === "DIRECTION") {
3024
+ pending.push(parser.assignTexture(materialParams.userData, "_anisotropyDirectionMap", anisotropyDirection).then((t) => {
3025
+ t.colorSpace = SRGBColorSpace;
3026
+ }));
3027
+ } else {
3028
+ materialParams.userData._anisotropyDirection = anisotropyDirection ?? 0;
3029
+ }
3030
+ return Promise.all(pending);
3031
+ }
3032
+ afterRoot(result) {
3033
+ var _a2;
3034
+ (_a2 = result.scene) == null ? void 0 : _a2.traverse((object) => {
3035
+ var _a3, _b;
3036
+ const mat = (_b = (_a3 = object.material) == null ? void 0 : _a3.userData) == null ? void 0 : _b._isAnisotropic;
3037
+ if (!mat) return;
3038
+ const geom = object.geometry;
3039
+ if (!geom.attributes.tangent) {
3040
+ geom.computeTangents();
3041
+ geom.attributes.tangent.needsUpdate = true;
3042
+ }
3043
+ });
3044
+ return null;
3045
+ }
3046
+ }
3047
+ const glTFMaterialsAnisotropyExtensionExport = (w) => ({
3048
+ writeMaterial: (material, materialDef) => {
3049
+ if (!material.isMeshStandardMaterial || !material.userData._isAnisotropic) return;
3050
+ if ((material.userData._anisotropyFactor || 0) < 1e-3) return;
3051
+ materialDef.extensions = materialDef.extensions || {};
3052
+ const extensionDef = {};
3053
+ extensionDef.anisotropyFactor = material.userData._anisotropyFactor || 1;
3054
+ extensionDef.anisotropyNoiseFactor = material.userData._anisotropyNoise || 0;
3055
+ extensionDef.anisotropyDirectionMode = material.userData._anisotropyDirectionMode || "CONSTANT";
3056
+ if (material.userData._anisotropyDirectionMap && extensionDef.anisotropyDirectionMode !== "CONSTANT") {
3057
+ const anisotropyDirectionMapDef = { index: w.processTexture(material.userData._anisotropyDirectionMap) };
3058
+ w.applyTextureTransform(anisotropyDirectionMapDef, material.userData._anisotropyDirectionMap);
3059
+ extensionDef.anisotropyDirection = anisotropyDirectionMapDef;
3060
+ } else {
3061
+ extensionDef.anisotropyDirectionMode = "CONSTANT";
3062
+ extensionDef.anisotropyDirection = material.userData._anisotropyDirection || 0;
3063
+ }
3064
+ materialDef.extensions[anisotropyGLTFExtension.name] = extensionDef;
3065
+ w.extensionsUsed[anisotropyGLTFExtension.name] = true;
3066
+ }
3067
+ });
3068
+ const anisotropyGLTFExtension = {
3069
+ name: "WEBGI_materials_anisotropy",
3070
+ import: (p) => new GLTFMaterialsAnisotropyExtensionImport(p),
3071
+ export: glTFMaterialsAnisotropyExtensionExport,
3072
+ textures: {
3073
+ anisotropyDirection: "RGB"
3074
+ }
3075
+ };
3076
+ const webgiPlugins = [
3077
+ TemporalAAPlugin,
3078
+ VelocityBufferPlugin,
3079
+ BloomPlugin,
3080
+ SSReflectionPlugin,
3081
+ SSContactShadowsPlugin,
3082
+ DepthOfFieldPlugin,
3083
+ OutlinePlugin,
3084
+ SSGIPlugin,
3085
+ AnisotropyPlugin
1802
3086
  ];
1803
3087
  export {
3088
+ AnisotropyPlugin,
1804
3089
  BloomPlugin,
1805
3090
  BloomPluginPass,
1806
3091
  DepthOfFieldPlugin,
1807
3092
  DepthOfFieldPluginPass,
3093
+ OutlinePlugin,
3094
+ OutlineRenderPass,
1808
3095
  SSContactShadowsPlugin,
3096
+ SSGIPlugin,
3097
+ SSGIPluginPass,
1809
3098
  SSReflectionPlugin,
1810
3099
  SSReflectionPluginPass,
1811
3100
  SSVelocityMaterial,
1812
3101
  TemporalAAPlugin,
1813
3102
  TemporalAAPluginPass,
1814
3103
  VelocityBufferPlugin,
3104
+ anisotropyGLTFExtension,
1815
3105
  webgiPlugins
1816
3106
  };
1817
3107
  //# sourceMappingURL=index.mjs.map