@threepipe/webgi-plugins 0.1.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 ADDED
@@ -0,0 +1,1528 @@
1
+ import { PipelinePassPlugin as I, GBufferPlugin as T, ProgressivePlugin as O, generateUiConfig as Y, uiToggle as R, uiConfig as Q, ExtendedShaderPass as $, CopyShader as ce, Vector2 as d, Matrix4 as E, serialize as c, uniform as f, uiVector as ue, matDefineBool as fe, shaderReplaceString as B, UnsignedByteType as de, LinearSRGBColorSpace as pe, GBufferRenderPass as Te, Color as he, uiImage as ve, uiFolderContainer as z, ShaderMaterial as be, Matrix3 as Pe, NoBlending as me, DoubleSide as Ce, uiConfigMaterialExtension as ge, updateBit as we, Vector4 as Ee, HalfFloatType as K, AdditiveBlending as De, uiSlider as u, onChange as N, matDefine as V, Vector3 as U, PickingPlugin as j, now as re, FrameFadePlugin as Re, ExtendedShaderMaterial as Z, shaderUtils as k, bindToValue as X, NearestFilter as ie, RGBAFormat as Ue, AViewerPluginSync as Me, glsl as _e, ShaderChunk as ae, updateMaterialDefines as Le, BaseGroundPlugin as se, SSAAPlugin as Fe, getOrCall as H, getTexelDecoding as oe } from "threepipe";
2
+ /**
3
+ * @license
4
+ * @threepipe/webgi-plugins v0.1.0
5
+ * Copyright 2022-2024 repalash <palash@shaders.app>
6
+ * GPL-3.0-only License
7
+ */
8
+ const Be = `#if defined(HAS_VELOCITY_BUFFER)
9
+ uniform 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.));}
10
+ #endif
11
+ `, Ae = `#ifdef USE_ALPHAMAP
12
+ #define USE_UV
13
+ #endif
14
+ #include <uv_pars_vertex>
15
+ #include <morphtarget_pars_vertex>
16
+ #include <skinning_pars_vertex>
17
+ #include <logdepthbuf_pars_vertex>
18
+ #include <clipping_planes_pars_vertex>
19
+ varying vec3 vWorldPosition;varying vec3 vWorldPositionPrevious;uniform mat4 modelMatrixPrevious;void main(){
20
+ #include <uv_vertex>
21
+ #include <skinbase_vertex>
22
+ #include <begin_vertex>
23
+ #include <morphtarget_vertex>
24
+ #include <skinning_vertex>
25
+ #include <displacementmap_vertex>
26
+ vec4 mvPosition=vec4(transformed,1.0);
27
+ #ifdef USE_INSTANCING
28
+ mvPosition=instanceMatrix*mvPosition;
29
+ #endif
30
+ vWorldPosition=(modelMatrix*mvPosition).xyz;vWorldPositionPrevious=(modelMatrixPrevious*mvPosition).xyz;mvPosition=modelViewMatrix*mvPosition;gl_Position=projectionMatrix*mvPosition;
31
+ #include <logdepthbuf_vertex>
32
+ #include <clipping_planes_vertex>
33
+ }`, ze = "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.);}", Ne = `#include <common>
34
+ #include <gbuffer_unpack>
35
+ #ifdef HAS_VELOCITY_BUFFER
36
+ #endif
37
+ #include <cameraHelpers>
38
+ varying vec2 vUv;uniform vec2 previousRTSize;uniform mat4 lastProjectionViewMatrix;uniform mat4 currentProjectionViewMatrix;uniform mat4 inverseViewMatrix;uniform vec2 jitterSample;uniform vec2 feedBack;uniform bool firstFrame;
39
+ #ifndef HAS_VELOCITY_BUFFER
40
+ #define HAS_VELOCITY_BUFFER 0
41
+ #endif
42
+ vec3 find_closest_fragment_3x3(const in vec2 uv){const vec3 offset=vec3(-1.0,1.0,0.0);vec2 texelSize=1.0/previousRTSize;vec3 dtr=vec3(1,1,getDepth(uv+offset.yy*texelSize));vec3 dtc=vec3(0,1,getDepth(uv+offset.zy*texelSize));vec3 dtl=vec3(-1,1,getDepth(uv+offset.xy*texelSize));vec3 dml=vec3(-1,0,getDepth(uv+offset.xz*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dmr=vec3(1,0,getDepth(uv+offset.yz*texelSize));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.xx*texelSize));vec3 dbc=vec3(0,-1,getDepth(uv+offset.zx*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.yx*texelSize));vec3 dmin=dtl;if(dmin.z>dtc.z)dmin=dtc;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dml.z)dmin=dml;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dmr.z)dmin=dmr;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbc.z)dmin=dbc;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+texelSize.xy*dmin.xy,dmin.z);}vec3 find_closest_fragment_5tap(const in vec2 uv){vec2 texelSize=1.0/previousRTSize;vec2 offset=vec2(1.0,-1.0);vec3 dtl=vec3(-1,1,getDepth(uv+offset.yx*texelSize));vec3 dtr=vec3(1,1,getDepth(uv+offset.xx*texelSize));vec3 dmc=vec3(0,0,getDepth(uv));vec3 dbl=vec3(-1,-1,getDepth(uv+offset.yy*texelSize));vec3 dbr=vec3(1,-1,getDepth(uv+offset.xy*texelSize));vec3 dmin=dtl;if(dmin.z>dtr.z)dmin=dtr;if(dmin.z>dmc.z)dmin=dmc;if(dmin.z>dbl.z)dmin=dbl;if(dmin.z>dbr.z)dmin=dbr;return vec3(uv+dmin.xy*texelSize,dmin.z);}vec4 clip_aabb(const in vec4 aabb_min,const in vec4 aabb_max,vec4 p){const float FLT_EPS=1e-8;vec4 p_clip=0.5*(aabb_max+aabb_min);vec4 e_clip=0.5*(aabb_max-aabb_min)+FLT_EPS;vec4 v_clip=p-p_clip;vec4 v_unit=abs(v_clip/e_clip);float ma_unit=max(v_unit.x,max(v_unit.y,v_unit.z));if(ma_unit>1.0)return p_clip+v_clip/ma_unit;else return p;}
43
+ #if HAS_VELOCITY_BUFFER == 0
44
+ vec2 computeScreenSpaceVelocity(const in vec3 worldPosition){vec4 currentPositionClip=currentProjectionViewMatrix*vec4(worldPosition,1.0);vec4 prevPositionClip=lastProjectionViewMatrix*vec4(worldPosition,1.0);vec2 currentPositionNDC=currentPositionClip.xy/currentPositionClip.w;vec2 prevPositionNDC=prevPositionClip.xy/prevPositionClip.w;if(prevPositionNDC.x>=1.0||prevPositionNDC.x<=-1.0||prevPositionNDC.x>=1.0||prevPositionNDC.y<=-1.0){return vec2(0.0);}return 0.5*(currentPositionNDC-prevPositionNDC);}
45
+ #endif
46
+ vec4 computeTAA(const in vec2 uv,const in vec2 screenSpaceVelocity){vec2 jitterOffset=jitterSample/previousRTSize;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=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.yx*texelSize));vec4 tc=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.zx*texelSize));vec4 tr=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.xx*texelSize));vec4 ml=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.yz*texelSize));vec4 mc=currentColor;vec4 mr=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.xz*texelSize));vec4 bl=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.yy*texelSize));vec4 bc=currentRTTexelToLinear(texture2D(currentRT,uvUnJitter+offset.zy*texelSize));vec4 br=currentRTTexelToLinear(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,k_feedback);}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(){vec2 jitterOffset=jitterSample/previousRTSize;
47
+ #if HAS_VELOCITY_BUFFER == 0
48
+ #if QUALITY == 1
49
+ vec3 c_frag=find_closest_fragment_3x3(vUv);
50
+ #else
51
+ vec3 c_frag=find_closest_fragment_5tap(vUv);
52
+ #endif
53
+ #else
54
+ vec3 c_frag=vec3(0.0);
55
+ #endif
56
+ if(c_frag.z>=0.999){gl_FragColor=currentRTTexelToLinear(texture2D(currentRT,vUv-jitterOffset));}else{
57
+ #if HAS_VELOCITY_BUFFER == 0
58
+ float sampleViewZ=mix(-cameraNearFar.x,-cameraNearFar.y,c_frag.z);vec3 worldPosition=getWorldPositionFromViewZ(c_frag.xy,sampleViewZ);vec2 screenSpaceVelocity=computeScreenSpaceVelocity(worldPosition);
59
+ #else
60
+ screenSpaceVelocity=getVelocity(vUv);
61
+ #endif
62
+ gl_FragColor=firstFrame ? currentRTTexelToLinear(texture2D(currentRT,vUv)): computeTAA(vUv,screenSpaceVelocity);
63
+ #ifdef DEBUG_VELOCITY
64
+ gl_FragColor=vec4(10.*length(screenSpaceVelocity));
65
+ #endif
66
+ }
67
+ #include <encodings_fragment>
68
+ }`;
69
+ var Oe = Object.defineProperty, ke = Object.getOwnPropertyDescriptor, q = (a, e, i, r) => {
70
+ for (var t = r > 1 ? void 0 : r ? ke(e, i) : e, s = a.length - 1, o; s >= 0; s--)
71
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
72
+ return r && t && Oe(e, i, t), t;
73
+ };
74
+ const Ie = "taa", G = class G extends I {
75
+ // readonly materialExtension: MaterialExtension = uiConfigMaterialExtension(this._getUiConfig.bind(this), TemporalAAPlugin.PluginType)
76
+ constructor(e = !0) {
77
+ super(), this.passId = Ie, this._stableNoise = !0, this._gbufferUnpackExtension = void 0, this._gbufferUnpackExtensionChanged = () => {
78
+ if (!this._pass || !this._viewer)
79
+ throw new Error("TemporalAAPlugin: pass/viewer not created yet");
80
+ const i = this._viewer.renderManager.gbufferUnpackExtension;
81
+ this._gbufferUnpackExtension !== i && (this._gbufferUnpackExtension && this._pass.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]), this._gbufferUnpackExtension = i, this._gbufferUnpackExtension ? this._pass.material.registerMaterialExtensions([this._gbufferUnpackExtension]) : this._viewer.console.warn("TemporalAAPlugin: GBuffer unpack extension removed"));
82
+ }, this.dependencies = [T, O], this.uiConfig = {
83
+ type: "folder",
84
+ label: "TemporalAA Plugin",
85
+ onChange: this.setDirty.bind(this),
86
+ children: [
87
+ ...Y(this) || []
88
+ ]
89
+ }, this.enabled = e, this.setDirty = this.setDirty.bind(this);
90
+ }
91
+ get stableNoise() {
92
+ var e;
93
+ return ((e = this._viewer) == null ? void 0 : e.renderManager.stableNoise) ?? this._stableNoise;
94
+ }
95
+ set stableNoise(e) {
96
+ this._viewer && (this._viewer.renderManager.stableNoise = e), this._stableNoise = e;
97
+ }
98
+ _createPass() {
99
+ if (!this._viewer)
100
+ throw new Error("TemporalAAPlugin: viewer not set");
101
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension)
102
+ throw new Error("TemporalAAPlugin: GBuffer target not created. GBufferPlugin is required.");
103
+ return new ee(this.passId, this._viewer.getPlugin(O).target);
104
+ }
105
+ // todo use gbufferUnpackExtension from render manager to support depth buffer plugin as well.
106
+ onAdded(e) {
107
+ super.onAdded(e), this._gbufferUnpackExtensionChanged(), e.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged), e.renderManager.addEventListener("resize", this._pass.onSizeUpdate);
108
+ }
109
+ onRemove(e) {
110
+ e.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged), e.renderManager.removeEventListener("resize", this._pass.onSizeUpdate), super.onRemove(e);
111
+ }
112
+ _beforeRender(e, i, r) {
113
+ if (!super._beforeRender(e, i, r))
114
+ return !1;
115
+ const t = this.pass, s = this._viewer;
116
+ if (!t || !s)
117
+ return !1;
118
+ const o = r.frameCount;
119
+ if (t.taaEnabled = o <= 1 && e.renderCamera === e.mainCamera, !t.taaEnabled)
120
+ return !1;
121
+ const n = i;
122
+ return n ? (n.updateMatrixWorld(!0), n.updateShaderProperties(t.material), t.updateCameraProperties(n), t.target = s.getPlugin(O).target, !0) : !1;
123
+ }
124
+ // region to be done or removed
125
+ // static AddTemporalAAData(material: IMaterial, params?: IMaterialUserData['TemporalAA'], setDirty = true): IMaterialUserData['TemporalAA']|null {
126
+ // const ud = material?.userData
127
+ // if (!ud) return null
128
+ // if (!ud[TemporalAAPlugin.PluginType]) {
129
+ // ud[TemporalAAPlugin.PluginType] = {}
130
+ // }
131
+ // const data = ud[TemporalAAPlugin.PluginType]!
132
+ // data.enable = true
133
+ // params && Object.assign(data, params)
134
+ // if (setDirty && material.setDirty) material.setDirty()
135
+ // return data
136
+ // }
137
+ /**
138
+ * This uiConfig is added to each material by extension
139
+ * @param material
140
+ * @private
141
+ */
142
+ // private _getUiConfig(material: IMaterial) {
143
+ // const config: UiObjectConfig = {
144
+ // type: 'folder',
145
+ // label: 'TemporalAA',
146
+ // children: [
147
+ // {
148
+ // type: 'checkbox',
149
+ // label: 'Enabled',
150
+ // get value() {
151
+ // return material.userData[TemporalAAPlugin.PluginType]?.enable ?? true
152
+ // },
153
+ // set value(v) {
154
+ // let data = material.userData[TemporalAAPlugin.PluginType]
155
+ // if (v === data?.enable) return
156
+ // if (!data) data = TemporalAAPlugin.AddTemporalAAData(material, undefined, false)!
157
+ // data.enable = v
158
+ // material.setDirty()
159
+ // config.uiRefresh?.(true, 'postFrame')
160
+ // },
161
+ // onChange: this.setDirty,
162
+ // },
163
+ // ],
164
+ // }
165
+ // return config
166
+ // }
167
+ // endregion
168
+ };
169
+ G.PluginType = "TAA", G.OldPluginType = "TemporalAAPlugin";
170
+ let M = G;
171
+ q([
172
+ R("Stable Noise (Total frame count)")
173
+ ], M.prototype, "stableNoise", 1);
174
+ q([
175
+ Q()
176
+ ], M.prototype, "_pass", 2);
177
+ class ee extends $ {
178
+ constructor(e, i) {
179
+ var r;
180
+ super({
181
+ vertexShader: ce.vertexShader,
182
+ fragmentShader: Ne,
183
+ uniforms: {
184
+ currentRT: { value: null },
185
+ previousRT: { value: null },
186
+ previousRTSize: { value: new d() },
187
+ cameraNearFar: { value: new d() },
188
+ lastProjectionViewMatrix: { value: new E() },
189
+ currentProjectionViewMatrix: { value: new E() },
190
+ projection: { value: new E() },
191
+ inverseViewMatrix: { value: new E() },
192
+ jitterSample: { value: new d() },
193
+ firstFrame: { value: !0 }
194
+ },
195
+ defines: {
196
+ // eslint-disable-next-line @typescript-eslint/naming-convention
197
+ QUALITY: 1,
198
+ // eslint-disable-next-line @typescript-eslint/naming-convention
199
+ UNJITTER: 0
200
+ }
201
+ }, "currentRT", "previousRT"), this.before = ["progressive"], this.after = [], this.required = ["render", "progressive"], this.taaEnabled = !0, this.feedBack = new d(0.88, 0.97), this.debugVelocity = !1, this.uiConfig = {
202
+ type: "folder",
203
+ label: "Temporal AA Pass",
204
+ onChange: this.setDirty,
205
+ children: [
206
+ {
207
+ type: "checkbox",
208
+ label: "Enabled",
209
+ property: [this, "enabled"],
210
+ onChange: () => this.onSizeUpdate()
211
+ },
212
+ ...((r = Y(this)) == null ? void 0 : r.filter((t) => t && t.label !== "Enabled")) || []
213
+ ]
214
+ }, this.passId = e, this.onSizeUpdate = this.onSizeUpdate.bind(this), this.target = i, this.clear = !1, this.needsSwap = !0;
215
+ }
216
+ render(e, i, r, t, s) {
217
+ if (!this.taaEnabled || !this.enabled) {
218
+ this.needsSwap = !1;
219
+ return;
220
+ }
221
+ this.needsSwap = !0, this.uniforms.previousRT.value = this.target.texture, super.render(e, i, r, t, s), this.uniforms.lastProjectionViewMatrix.value.copy(this.uniforms.currentProjectionViewMatrix.value), this.uniforms.firstFrame.value = !1;
222
+ }
223
+ updateCameraProperties(e) {
224
+ e && (this.uniforms.currentProjectionViewMatrix.value.multiplyMatrices(e.projectionMatrix, e.matrixWorldInverse), this.uniforms.inverseViewMatrix.value.copy(e.matrixWorld));
225
+ }
226
+ onSizeUpdate() {
227
+ this.uniforms.firstFrame.value = !0, this.setDirty();
228
+ }
229
+ setSize(e, i) {
230
+ super.setSize(e, i), this.onSizeUpdate();
231
+ }
232
+ }
233
+ q([
234
+ c(),
235
+ f(),
236
+ ue("Feedback", void 0, 1e-4)
237
+ ], ee.prototype, "feedBack", 2);
238
+ q([
239
+ R(),
240
+ fe("DEBUG_VELOCITY", void 0, !1, void 0, !0)
241
+ ], ee.prototype, "debugVelocity", 2);
242
+ var Ve = Object.defineProperty, je = Object.getOwnPropertyDescriptor, xe = (a, e, i, r) => {
243
+ for (var t = r > 1 ? void 0 : r ? je(e, i) : e, s = a.length - 1, o; s >= 0; s--)
244
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
245
+ return r && t && Ve(e, i, t), t;
246
+ };
247
+ let L = class extends I {
248
+ constructor(a = de, e = !0, i = !0) {
249
+ super(), this.passId = "velocityBuffer", this.material = new He(), this.unpackExtension = {
250
+ shaderExtender: (r) => {
251
+ r.fragmentShader = B(
252
+ r.fragmentShader,
253
+ "//velocity_unpack",
254
+ `
255
+ ` + Be + `
256
+ `
257
+ );
258
+ },
259
+ extraUniforms: {
260
+ tVelocity: () => {
261
+ var r;
262
+ return { value: (r = this.target) == null ? void 0 : r.texture };
263
+ }
264
+ },
265
+ extraDefines: {
266
+ HAS_VELOCITY_BUFFER: () => {
267
+ var r;
268
+ return (r = this.target) != null && r.texture ? 1 : void 0;
269
+ }
270
+ },
271
+ priority: 100,
272
+ isCompatible: () => !0
273
+ }, this.enabled = e, this.bufferType = a, this._attachToTaa = i;
274
+ }
275
+ // cannot be changed after creation (for now)
276
+ _createTarget(a = !0) {
277
+ this._viewer && (a && this._disposeTarget(), this.target || (this.target = this._viewer.renderManager.createTarget(
278
+ {
279
+ depthBuffer: !0,
280
+ // samples: v.renderManager.composerTarget.samples || 0,
281
+ samples: 0,
282
+ type: this.bufferType,
283
+ // magFilter: NearestFilter,
284
+ // minFilter: NearestFilter,
285
+ generateMipmaps: !1,
286
+ colorSpace: pe
287
+ }
288
+ )), this.texture = this.target.texture, this.texture.name = "velocityBuffer", this._pass && (this._pass.target = this.target));
289
+ }
290
+ _disposeTarget() {
291
+ this._viewer && (this.target && (this._viewer.renderManager.disposeTarget(this.target), this.target = void 0), this.texture = void 0);
292
+ }
293
+ _createPass() {
294
+ if (this._createTarget(!0), !this.target)
295
+ throw new Error("VelocityBufferPlugin: target not created");
296
+ this.material.userData.isGBufferMaterial = !0;
297
+ const a = this._viewer, e = new class extends Te {
298
+ constructor() {
299
+ super(...arguments), this._firstCall = !0;
300
+ }
301
+ render(r, t, s, o, n) {
302
+ if (a.renderManager.frameCount > 0 || !this.enabled || !this.camera)
303
+ return;
304
+ const l = this.overrideMaterial;
305
+ l.uniforms.currentProjectionViewMatrix.value.copy(this.camera.projectionMatrix).multiply(this.camera.matrixWorldInverse), this._firstCall && (l.uniforms.lastProjectionViewMatrix.value.copy(l.uniforms.currentProjectionViewMatrix.value), this._firstCall = !1), super.render(r, t, s, o, n), l.uniforms.lastProjectionViewMatrix.value.copy(l.uniforms.currentProjectionViewMatrix.value);
306
+ }
307
+ }(this.passId, this.target, this.material, new he(0.5, 0.5, 0.5), 1), i = e.preprocessMaterial;
308
+ return e.preprocessMaterial = (r) => {
309
+ var t;
310
+ return i(r, (t = r.userData[L.PluginType]) == null ? void 0 : t.disabled);
311
+ }, e.before = ["render"], e.after = [], e.required = ["render"], e;
312
+ }
313
+ onAdded(a) {
314
+ var e;
315
+ if (super.onAdded(a), this._attachToTaa) {
316
+ const i = a.getPlugin(M);
317
+ i ? (e = i.pass) == null || e.material.registerMaterialExtensions([this.unpackExtension]) : a.console.warn("VelocityBufferPlugin: TemporalAAPlugin not found, set attachToTaa to false if not required");
318
+ }
319
+ }
320
+ onRemove(a) {
321
+ var e, i;
322
+ return this._disposeTarget(), this._attachToTaa && ((i = (e = a.getPlugin(M)) == null ? void 0 : e.pass) == null || i.material.unregisterMaterialExtensions([this.unpackExtension])), super.onRemove(a);
323
+ }
324
+ _beforeRender(a, e, i) {
325
+ if (!super._beforeRender(a, e, i))
326
+ return !1;
327
+ const r = this.pass;
328
+ return !r || i.frameCount > 0 ? !1 : (r.scene = a, r.camera = e, e.updateShaderProperties(r.overrideMaterial), !0);
329
+ }
330
+ };
331
+ L.PluginType = "VelocityBuffer";
332
+ L.OldPluginType = "VelocityBufferPlugin";
333
+ xe([
334
+ ve(
335
+ "Velocity Buffer"
336
+ /* {readOnly: true}*/
337
+ )
338
+ ], L.prototype, "texture", 2);
339
+ L = xe([
340
+ z("Velocity Buffer Plugin (for TAA)")
341
+ ], L);
342
+ class He extends be {
343
+ constructor() {
344
+ super({
345
+ vertexShader: Ae,
346
+ fragmentShader: ze,
347
+ uniforms: {
348
+ cameraNearFar: { value: new d(0.1, 1e3) },
349
+ alphaMap: { value: null },
350
+ alphaTest: { value: null },
351
+ alphaMapTransform: { value: /* @__PURE__ */ new Pe() },
352
+ currentProjectionViewMatrix: { value: new E() },
353
+ lastProjectionViewMatrix: { value: new E() }
354
+ },
355
+ blending: me
356
+ // todo?
357
+ }), this.extraUniformsToUpload = {
358
+ modelMatrixPrevious: { value: new E().identity() }
359
+ }, this._previousWorldMatrices = {};
360
+ }
361
+ // this gets called for each object.
362
+ onBeforeRender(e, i, r, t, s) {
363
+ const o = this._previousWorldMatrices[s.uuid];
364
+ this.extraUniformsToUpload.modelMatrixPrevious.value.copy(o ?? s.matrixWorld), o ? o.copy(s.matrixWorld) : this._previousWorldMatrices[s.uuid] = s.matrixWorld.clone();
365
+ let n = s.material;
366
+ Array.isArray(n) && (n = n[0]), this.uniforms.alphaMap.value = (n == null ? void 0 : n.alphaMap) ?? null, this.uniforms.alphaTest.value = !n || !n.alphaTest || n.alphaTest < 1e-7 ? 1e-3 : n.alphaTest;
367
+ let l = this.uniforms.alphaMap.value ? 1 : void 0;
368
+ l !== this.defines.USE_ALPHAMAP && (l === void 0 ? delete this.defines.USE_ALPHAMAP : this.defines.USE_ALPHAMAP = l, this.needsUpdate = !0), l = n != null && n.userData.ALPHA_I_RGBA_PACKING ? 1 : void 0, l !== this.defines.ALPHA_I_RGBA_PACKING && (l === void 0 ? delete this.defines.ALPHA_I_RGBA_PACKING : this.defines.ALPHA_I_RGBA_PACKING = l, this.needsUpdate = !0), this.side = (n == null ? void 0 : n.side) ?? Ce;
369
+ }
370
+ }
371
+ const Ge = `#include <packing>
372
+ uniform float intensity;uniform float opacity;uniform vec2 tDiffuseSize;varying vec2 vUv;uniform float weight;
373
+ #if PASS_STEP == 0
374
+ uniform vec4 prefilter;vec4 Prefilter(vec4 c){
375
+ #ifdef HAS_GBUFFER
376
+ #if !BACKGROUND_BLOOM
377
+ if(getDepth(vUv)>0.999){return vec4(0.0);}
378
+ #endif
379
+ #endif
380
+ float 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);}
381
+ #endif
382
+ vec4 Sample(vec2 uv){return 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){
383
+ #ifdef WebGL2Context
384
+ return(number/4)% 2;
385
+ #else
386
+ return int(mod(floor(float(number)/4.),2.));
387
+ #endif
388
+ }void main(){
389
+ #if PASS_STEP == 0
390
+ #ifdef GBUFFER_HAS_FLAGS
391
+ int doBloom=getBloomBit(getGBufferFlags(vUv).a);
392
+ #else
393
+ int doBloom=1;
394
+ #endif
395
+ gl_FragColor=float(doBloom)*weight*Prefilter(SampleBox(vUv,1.));gl_FragColor.a=1.;
396
+ #elif PASS_STEP == 1
397
+ gl_FragColor=weight*(SampleBox(vUv,1.));gl_FragColor.a=1.;
398
+ #elif PASS_STEP == 2
399
+ gl_FragColor=(SampleBox(vUv,0.5));gl_FragColor.a=1.;
400
+ #elif PASS_STEP == 3
401
+ vec4 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;
402
+ #elif PASS_STEP == 4
403
+ vec4 texel=vec4(0.);texel.rgb+=intensity*SampleBox(vUv,0.5).rgb;texel.a=1.;gl_FragColor=texel;
404
+ #endif
405
+ #include <encodings_fragment>
406
+ }`;
407
+ var We = Object.defineProperty, Ye = Object.getOwnPropertyDescriptor, P = (a, e, i, r) => {
408
+ for (var t = r > 1 ? void 0 : r ? Ye(e, i) : e, s = a.length - 1, o; s >= 0; s--)
409
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
410
+ return r && t && We(e, i, t), t;
411
+ };
412
+ const $e = "bloom";
413
+ var _;
414
+ const Se = (_ = class extends I {
415
+ constructor() {
416
+ super(...arguments), this.passId = $e, this.materialExtension = ge(this._getUiConfig.bind(this), _.PluginType), this.dependencies = [T], this._onPluginAdd = (e) => {
417
+ var r, t, s, o;
418
+ if (((t = (r = e.plugin) == null ? void 0 : r.constructor) == null ? void 0 : t.PluginType) !== T.PluginType)
419
+ return;
420
+ const i = e.plugin;
421
+ i.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this)), (s = this._pass) == null || s.material.registerMaterialExtensions([i.unpackExtension]), (o = this._viewer) == null || o.removeEventListener("addPlugin", this._onPluginAdd);
422
+ }, this.uiConfig = {
423
+ type: "folder",
424
+ label: "Bloom Plugin",
425
+ onChange: this.setDirty.bind(this),
426
+ children: [
427
+ ...Y(this) || []
428
+ ]
429
+ };
430
+ }
431
+ _createPass() {
432
+ return new h(this.passId);
433
+ }
434
+ onAdded(e) {
435
+ super.onAdded(e);
436
+ const i = e.getPlugin(T);
437
+ i ? (i.registerGBufferUpdater(this.constructor.PluginType, this.updateGBufferFlags.bind(this)), this._pass.material.registerMaterialExtensions([i.unpackExtension])) : e.addEventListener("addPlugin", this._onPluginAdd), e.materialManager.registerMaterialExtension(this.materialExtension);
438
+ }
439
+ onRemove(e) {
440
+ var r;
441
+ e.removeEventListener("addPlugin", this._onPluginAdd);
442
+ const i = e.getPlugin(T);
443
+ i == null || i.unregisterGBufferUpdater(this.constructor.PluginType), i && ((r = this._pass) == null || r.material.unregisterMaterialExtensions([i.unpackExtension])), e.materialManager.unregisterMaterialExtension(this.materialExtension), super.onRemove(e);
444
+ }
445
+ updateGBufferFlags(e, i) {
446
+ var s;
447
+ if (!i.material || !i.material.userData)
448
+ return;
449
+ const t = ((s = i.material.userData[_.PluginType]) == null ? void 0 : s.enable) === !1 || i.material.userData.pluginsDisabled ? 0 : 1;
450
+ e.w = we(e.w, 2, t);
451
+ }
452
+ static AddBloomData(e, i, r = !0) {
453
+ const t = e == null ? void 0 : e.userData;
454
+ if (!t)
455
+ return null;
456
+ t[_.PluginType] || (t[_.PluginType] = {});
457
+ const s = t[_.PluginType];
458
+ return s.enable = !0, i && Object.assign(s, i), r && e.setDirty && e.setDirty(), s;
459
+ }
460
+ /**
461
+ * This uiConfig is added to each material by extension
462
+ * @param material
463
+ * @private
464
+ */
465
+ _getUiConfig(e) {
466
+ const i = {
467
+ type: "folder",
468
+ label: "Bloom",
469
+ children: [
470
+ {
471
+ type: "checkbox",
472
+ label: "Enabled",
473
+ get value() {
474
+ var r;
475
+ return ((r = e.userData[_.PluginType]) == null ? void 0 : r.enable) ?? !0;
476
+ },
477
+ set value(r) {
478
+ var s;
479
+ let t = e.userData[_.PluginType];
480
+ r !== (t == null ? void 0 : t.enable) && (t || (t = _.AddBloomData(e, void 0, !1)), t.enable = r, e.setDirty(), (s = i.uiRefresh) == null || s.call(i, !0, "postFrame"));
481
+ },
482
+ onChange: this.setDirty
483
+ }
484
+ ]
485
+ };
486
+ return i;
487
+ }
488
+ }, _.PluginType = "Bloom", _.OldPluginType = "BloomPlugin", _);
489
+ P([
490
+ Q()
491
+ ], Se.prototype, "_pass", 2);
492
+ let qe = Se, h = class extends $ {
493
+ constructor(a) {
494
+ super({
495
+ vertexShader: ce.vertexShader,
496
+ defines: {
497
+ // eslint-disable-next-line @typescript-eslint/naming-convention
498
+ PASS_STEP: 1
499
+ },
500
+ uniforms: {
501
+ tSource: { value: null },
502
+ tDiffuse: { value: null },
503
+ // intensity: {value: 0.2},
504
+ opacity: { value: 1 },
505
+ // prefilter: {value: new Vector4(1, 0.5, 0, 0)},
506
+ tDiffuseSize: { value: new d() },
507
+ weight: { value: 1 }
508
+ // tNormalDepth: {value: null},
509
+ // tGBufferFlags: {value: null},
510
+ },
511
+ fragmentShader: Ge
512
+ }, "tDiffuse", "tSource"), this.uiConfig = void 0, this.before = ["screen"], this.after = ["render", "progressive"], this.required = ["render"], this.prefilter = new Ee(2, 0.5, 0, 0), this.threshold = 2, this.softThreshold = 0.5, this.intensity = 0.2, this.backgroundBloom = !1, this.bloomIterations = 4, this.radius = 0.6, this.power = 1, this.bloomDebug = !1, this._weights = [], this.passId = a, this._updateWeights = this._updateWeights.bind(this), this._thresholdsUpdated = this._thresholdsUpdated.bind(this), this._updateWeights(), this._thresholdsUpdated(), this.clear = !0;
513
+ }
514
+ _thresholdsUpdated() {
515
+ this.prefilter.x = this.threshold, this.prefilter.y = this.softThreshold, this.prefilter.z = 2 * this.prefilter.x * this.prefilter.y, this.prefilter.w = 0.125 / (this.uniforms.prefilter.value.z + 1e-5);
516
+ }
517
+ render(a, e, i, r, t) {
518
+ const s = a.renderManager;
519
+ this.material.defines.PASS_STEP = 0, this.clear = !0, this.needsSwap = !1;
520
+ const o = i;
521
+ if (!o) {
522
+ console.warn("BloomPluginPass: No source to read from");
523
+ return;
524
+ }
525
+ this.needsSwap = !0;
526
+ let n = 0.5, l = o.width * n, m = o.height * n;
527
+ const g = [];
528
+ let C = s.getTempTarget({ sizeMultiplier: 1, type: K });
529
+ g.push(C);
530
+ let w = o;
531
+ this.material.needsUpdate = !0, this.material.uniforms.weight.value = this._weights[0], super.render(a, C, w, r, t), w = C;
532
+ let y = 1;
533
+ for (; y < this.bloomIterations && (l /= 2, m /= 2, n /= 2, !(m < 2 || l < 2)); y++) {
534
+ C = s.getTempTarget({ sizeMultiplier: n, type: K }), g.push(C), this.material.defines.PASS_STEP = 1;
535
+ let te = this._weights[y];
536
+ te = this._weights[y - 1] !== 0 ? this._weights[y] / this._weights[y - 1] : this._weights[y], this.material.uniforms.weight.value = te, this.material.needsUpdate = !0, super.render(a, C, w, r, t), w = C;
537
+ }
538
+ this.clear = !1;
539
+ const ye = a.autoClear;
540
+ for (a.autoClear = !1, y -= 2; y >= 0; y--)
541
+ C = g[y], g[y] = void 0, this.material.defines.PASS_STEP = 2, this.material.transparent = !0, this.material.blending = De, this.material.needsUpdate = !0, a.autoClear = !1, super.render(a, C, w, r, t), this.material.blending = me, s.releaseTempTarget(w), w = C;
542
+ this.clear = !0, a.autoClear = ye, a.autoClear = !0, this.bloomDebug ? (this.material.defines.PASS_STEP = 4, this.material.needsUpdate = !0, super.render(a, e, w, r, t)) : (this.uniforms.tSource.value = o.texture, this.material.defines.PASS_STEP = 3, this.material.needsUpdate = !0, super.render(a, e, w, r, t), this.uniforms.tSource.value = null), s.releaseTempTarget(w);
543
+ }
544
+ _updateWeights() {
545
+ if (!this._weights)
546
+ return;
547
+ const a = Math.max(Math.min(this.radius, 1), 0), e = 1 / (this.bloomIterations - 1);
548
+ for (let i = 0; i < this.bloomIterations; i++) {
549
+ let r = i * e + 0.1, t = 1.2 - r;
550
+ r = Math.pow(r, this.power), t = Math.pow(t, this.power), this._weights[i] = t * (1 - a) + r * a;
551
+ }
552
+ this.setDirty();
553
+ }
554
+ };
555
+ P([
556
+ f()
557
+ ], h.prototype, "prefilter", 2);
558
+ P([
559
+ u("Threshold", [0, 2]),
560
+ N(h.prototype._thresholdsUpdated),
561
+ c()
562
+ ], h.prototype, "threshold", 2);
563
+ P([
564
+ u("Soft Threshold", [0, 1]),
565
+ N(h.prototype._thresholdsUpdated),
566
+ c()
567
+ ], h.prototype, "softThreshold", 2);
568
+ P([
569
+ u("Intensity", [0, 3]),
570
+ c(),
571
+ f()
572
+ ], h.prototype, "intensity", 2);
573
+ P([
574
+ R("Background Bloom"),
575
+ c(),
576
+ V("BACKGROUND_BLOOM", void 0, !1, void 0, (a) => a ? "1" : "0", (a) => a && a !== "0")
577
+ ], h.prototype, "backgroundBloom", 2);
578
+ P([
579
+ u("Iterations", [0, 7], 1),
580
+ N(h.prototype._updateWeights),
581
+ c()
582
+ ], h.prototype, "bloomIterations", 2);
583
+ P([
584
+ u("Radius", [0, 1], 0.01),
585
+ N(h.prototype._updateWeights),
586
+ c()
587
+ ], h.prototype, "radius", 2);
588
+ P([
589
+ u("Power", [0.2, 10], 0.01),
590
+ N(h.prototype._updateWeights),
591
+ c()
592
+ ], h.prototype, "power", 2);
593
+ P([
594
+ R("Debug")
595
+ ], h.prototype, "bloomDebug", 2);
596
+ h = P([
597
+ z("Bloom Pass")
598
+ ], h);
599
+ const Ke = `#include <common>
600
+ #include <packing>
601
+ varying 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);}
602
+ #include <encodings_fragment>
603
+ }`, Ze = `#include <randomHelpers>
604
+ #include <common>
605
+ varying vec2 vUv;uniform vec2 colorTextureSize;uniform float blurRadius;uniform float frameCount;vec4 CircularBlur(){vec4 color=colorTextureTexelToLinear(texture2D(colorTexture,vUv));
606
+ #ifdef DOF_MODE
607
+ float blurDist=blurRadius*(2.*color.a-1.);
608
+ #else
609
+ float blurDist=blurRadius*color.a;
610
+ #endif
611
+ float rnd=PI2*random3(vec3(vUv,frameCount*0.1));float costheta=cos(rnd);float sintheta=sin(rnd);vec4 rotationMatrix=vec4(costheta,-sintheta,sintheta,costheta);vec3 colorSum=vec3(0.0);float weightSum=0.001;vec2 ofs;vec4 sampleColor;setPds();
612
+ #pragma unroll_loop_start
613
+ for(int i=0;i<16;i++){ofs=poisson_disk_samples[UNROLLED_LOOP_INDEX];ofs=vec2(dot(ofs,rotationMatrix.xy),dot(ofs,rotationMatrix.zw));sampleColor=colorTextureTexelToLinear(texture2D(colorTexture,vUv+blurDist*ofs/colorTextureSize.xy));
614
+ #ifdef DOF_MODE
615
+ sampleColor.a=abs(sampleColor.a*2.0-1.0);sampleColor.a*=sampleColor.a*sampleColor.a;
616
+ #endif
617
+ colorSum+=sampleColor.rgb*sampleColor.a;weightSum+=sampleColor.a;}
618
+ #pragma unroll_loop_end
619
+ colorSum/=weightSum;return vec4(min(vec3(72.),max(vec3(0.),colorSum)),1.0);}void main(){gl_FragColor=CircularBlur();
620
+ #include <encodings_fragment>
621
+ }`, Je = "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);}", Qe = `#include <common>
622
+ #include <packing>
623
+ varying 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);
624
+ #include <encodings_fragment>
625
+ }`, Xe = `#include <common>
626
+ #include <gbuffer_unpack>
627
+ varying 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);
628
+ #include <encodings_fragment>
629
+ }`;
630
+ var et = Object.defineProperty, tt = Object.getOwnPropertyDescriptor, S = (a, e, i, r) => {
631
+ for (var t = r > 1 ? void 0 : r ? tt(e, i) : e, s = a.length - 1, o; s >= 0; s--)
632
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
633
+ return r && t && et(e, i, t), t;
634
+ };
635
+ const rt = "depthOfField", W = class W extends I {
636
+ // ms
637
+ constructor(e = !0, i = !1) {
638
+ super(), this.passId = rt, this.enableEdit = !1, this._focalPointHit = new U(0, 0, 0), this.crossFadeTime = 200, this._focalPointHitTime = 0, this.dependencies = [T], this._onPluginAdd = (r) => {
639
+ var s, o, n, l, m;
640
+ const t = r.plugin;
641
+ if (t) {
642
+ if (((s = t.constructor) == null ? void 0 : s.PluginType) === T.PluginType) {
643
+ const g = t;
644
+ (o = this._pass) == null || o.material.registerMaterialExtensions([g.unpackExtension]), (n = this._pass) == null || n.computeCocMaterial.registerMaterialExtensions([g.unpackExtension]), (l = this._pass) == null || l.expandCocMaterial.registerMaterialExtensions([g.unpackExtension]);
645
+ }
646
+ ((m = t.constructor) == null ? void 0 : m.PluginType) === j.PluginType && t.addEventListener("hitObject", this._onObjectHit);
647
+ }
648
+ }, this._onPluginRemove = (r) => {
649
+ var s, o, n, l, m;
650
+ const t = r.plugin;
651
+ if (t) {
652
+ if (((s = t.constructor) == null ? void 0 : s.PluginType) === T.PluginType) {
653
+ const g = r.plugin;
654
+ (o = this._pass) == null || o.material.unregisterMaterialExtensions([g.unpackExtension]), (n = this._pass) == null || n.computeCocMaterial.unregisterMaterialExtensions([g.unpackExtension]), (l = this._pass) == null || l.expandCocMaterial.unregisterMaterialExtensions([g.unpackExtension]);
655
+ }
656
+ ((m = t.constructor) == null ? void 0 : m.PluginType) === j.PluginType && r.plugin.removeEventListener("hitObject", this._onObjectHit);
657
+ }
658
+ }, this.uiConfig = {
659
+ type: "folder",
660
+ label: "DepthOfField",
661
+ onChange: this.setDirty.bind(this),
662
+ children: [
663
+ ...Y(this) || [],
664
+ () => {
665
+ var r;
666
+ return (r = this._pass) == null ? void 0 : r.uiConfig;
667
+ }
668
+ ]
669
+ }, this._tempVec = new U(), this.enabled = e, this.enableEdit = i, this._onObjectHit = this._onObjectHit.bind(this), this.setDirty = this.setDirty.bind(this);
670
+ }
671
+ get _frameFadeTime() {
672
+ return this.crossFadeTime * 2.5;
673
+ }
674
+ // todo make this a property.
675
+ setFocalPoint(e, i = !0, r = !1) {
676
+ var t, s;
677
+ this._focalPointHit.copy(e), i && ((s = (t = this._viewer) == null ? void 0 : t.getPlugin("FrameFadePlugin")) == null || s.startTransition(this._frameFadeTime)), r && (this._focalPointHitTime = re()), this.setDirty();
678
+ }
679
+ getFocalPoint() {
680
+ return this._focalPointHit;
681
+ }
682
+ _onObjectHit(e) {
683
+ var i, r;
684
+ !this._pass || !e.intersects.intersect || this.isDisabled() || !this.enableEdit || (this._focalPointHit.copy(e.intersects.intersect.point), this._focalPointHitTime = e.time, e.intersects.selectedObject = null, (r = (i = this._viewer) == null ? void 0 : i.getPlugin(Re)) == null || r.startTransition(this._frameFadeTime), this.setDirty());
685
+ }
686
+ _createPass() {
687
+ return new b(this.passId);
688
+ }
689
+ // todo use gbufferUnpackExtension from render manager to support depth buffer plugin as well.
690
+ onAdded(e) {
691
+ super.onAdded(e), e.addEventListener("addPlugin", this._onPluginAdd), e.addEventListener("removePlugin", this._onPluginRemove), this._onPluginAdd({ plugin: e.getPlugin(T) }), this._onPluginAdd({ plugin: e.getPlugin(j) });
692
+ }
693
+ onRemove(e) {
694
+ e.removeEventListener("addPlugin", this._onPluginAdd), e.removeEventListener("removePlugin", this._onPluginRemove), this._onPluginRemove({ plugin: e.getPlugin(T) }), this._onPluginRemove({ plugin: e.getPlugin(j) }), super.onRemove(e);
695
+ }
696
+ _beforeRender(e, i, r) {
697
+ if (!super._beforeRender(e, i, r))
698
+ return !1;
699
+ const t = this.pass;
700
+ if (!t)
701
+ return !1;
702
+ t.dofBlurMaterial.uniforms.frameCount && (r == null || r.updateShaderProperties(t.dofBlurMaterial));
703
+ const s = i;
704
+ if (!s)
705
+ return !1;
706
+ s.updateMatrixWorld(!0), s.updateShaderProperties(t.material), s.getWorldPosition(this._tempVec), this._tempVec.subVectors(this._focalPointHit, this._tempVec), t.focalDepthRange.x = this._tempVec.length(), t.focalDepthRange.x *= s.getWorldDirection(new U()).dot(this._tempVec.normalize());
707
+ let o = (re() - this._focalPointHitTime) / this.crossFadeTime;
708
+ if (o = 1 - Math.min(1, Math.max(0, o)), Math.abs(o - t.crossAlpha) > 0.01 && (t.crossAlpha = o, this.setDirty()), o > 0) {
709
+ const n = this._tempVec.copy(this._focalPointHit).project(s).addScalar(1).divideScalar(2);
710
+ t.crossCenter.set(n.x, n.y), t.computeCocMaterial.uniformsNeedUpdate = !0, t.expandCocMaterial.uniformsNeedUpdate = !0;
711
+ }
712
+ return !0;
713
+ }
714
+ // region to be done or removed
715
+ // static AddDepthOfFieldData(material: IMaterial, params?: IMaterialUserData['DepthOfField'], setDirty = true): IMaterialUserData['DepthOfField']|null {
716
+ // const ud = material?.userData
717
+ // if (!ud) return null
718
+ // if (!ud[DepthOfFieldPlugin.PluginType]) {
719
+ // ud[DepthOfFieldPlugin.PluginType] = {}
720
+ // }
721
+ // const data = ud[DepthOfFieldPlugin.PluginType]!
722
+ // data.enable = true
723
+ // params && Object.assign(data, params)
724
+ // if (setDirty && material.setDirty) material.setDirty()
725
+ // return data
726
+ // }
727
+ // updateGBufferFlags(data: Vector4, c: GBufferUpdaterContext): void {
728
+ // if (!c.material || !c.material.userData) return
729
+ // const disabled = c.material.userData[DepthOfFieldPlugin.PluginType]?.enable === false ||
730
+ // c.material.userData.pluginsDisabled
731
+ // const x = disabled ? 0 : 1
732
+ // data.w = updateBit(data.w, 4, x)
733
+ // }
734
+ /*
735
+ get depthRange() {
736
+ return this.pass?.focalDepthRange.y ?? 0
737
+ }
738
+
739
+ set depthRange(v: number) {
740
+ if (this.pass) this.pass.focalDepthRange.y = v
741
+ this.setDirty()
742
+ }
743
+
744
+ get nearBlurScale() {
745
+ return this.pass?.nearFarBlurScale.x ?? 0
746
+ }
747
+ set nearBlurScale(v: number) {
748
+ if (this.pass) this.pass.nearFarBlurScale.x = v
749
+ this.setDirty()
750
+ }
751
+
752
+ get farBlurScale() {
753
+ return this.pass?.nearFarBlurScale.y ?? 0
754
+ }
755
+ set farBlurScale(v: number) {
756
+ if (this.pass) this.pass.nearFarBlurScale.y = v
757
+ this.setDirty()
758
+ }
759
+ */
760
+ /**
761
+ * This uiConfig is added to each material by extension
762
+ * @param material
763
+ * @private
764
+ */
765
+ // private _getUiConfig(material: IMaterial) {
766
+ // const config: UiObjectConfig = {
767
+ // type: 'folder',
768
+ // label: 'DepthOfField',
769
+ // children: [
770
+ // {
771
+ // type: 'checkbox',
772
+ // label: 'Enabled',
773
+ // get value() {
774
+ // return material.userData[DepthOfFieldPlugin.PluginType]?.enable ?? true
775
+ // },
776
+ // set value(v) {
777
+ // let data = material.userData[DepthOfFieldPlugin.PluginType]
778
+ // if (v === data?.enable) return
779
+ // if (!data) data = DepthOfFieldPlugin.AddDepthOfFieldData(material, undefined, false)!
780
+ // data.enable = v
781
+ // material.setDirty()
782
+ // config.uiRefresh?.(true, 'postFrame')
783
+ // },
784
+ // onChange: this.setDirty,
785
+ // },
786
+ // ],
787
+ // }
788
+ // return config
789
+ // }
790
+ // endregion
791
+ };
792
+ W.PluginType = "DepthOfField", W.OldPluginType = "DepthOfFieldPlugin";
793
+ let A = W;
794
+ S([
795
+ c(),
796
+ R()
797
+ ], A.prototype, "enableEdit", 2);
798
+ S([
799
+ c("focalPoint")
800
+ ], A.prototype, "_focalPointHit", 2);
801
+ S([
802
+ c()
803
+ ], A.prototype, "crossFadeTime", 2);
804
+ const it = new Z({
805
+ uniforms: {
806
+ colorTexture: { value: null },
807
+ colorTextureSize: { value: new d() },
808
+ direction: { value: new d() },
809
+ frameCount: { value: 0 },
810
+ blurRadius: { value: 16 }
811
+ },
812
+ vertexShader: k.defaultVertex,
813
+ fragmentShader: Je + `
814
+ ` + Ze,
815
+ defines: {
816
+ DOF_MODE: 1
817
+ }
818
+ }, ["colorTexture"]);
819
+ let b = class extends $ {
820
+ constructor(a) {
821
+ super({
822
+ uniforms: {
823
+ colorTexture: { value: null },
824
+ blurTexture: { value: null },
825
+ cocTexture: { value: null },
826
+ cocTextureSize: { value: new d() },
827
+ cameraNearFar: { value: new d() }
828
+ },
829
+ vertexShader: k.defaultVertex,
830
+ fragmentShader: Ke
831
+ }, "colorTexture", "cocTexture", "blurTexture"), this.uiConfig = void 0, this.before = ["progressive", "screen"], this.after = ["render"], this.required = ["render"], this.dofBlurMaterial = it, this.nearFarBlurScale = new d(0.25, 0.25), this.focalDepthRange = new d(0.5, 1.5), this.crossCenter = new d(0.5, 0.5), this.crossRadius = 0.04, this.crossAlpha = 1, this.crossColor = new he(16750848), this.passId = a, this.computeCocMaterial = new Z({
832
+ uniforms: {
833
+ colorTexture: { value: null },
834
+ cameraNearFar: this.uniforms.cameraNearFar,
835
+ nearFarBlurScale: this.uniforms.nearFarBlurScale,
836
+ focalDepthRange: this.uniforms.focalDepthRange
837
+ },
838
+ vertexShader: k.defaultVertex,
839
+ fragmentShader: Qe
840
+ }, ["colorTexture"]), this.expandCocMaterial = new Z({
841
+ uniforms: {
842
+ colorTexture: { value: null },
843
+ colorTextureSize: { value: new d() },
844
+ direction: { value: new d() },
845
+ nearFarBlurScale: this.uniforms.nearFarBlurScale
846
+ },
847
+ vertexShader: k.defaultVertex,
848
+ fragmentShader: Xe
849
+ }, ["colorTexture"]);
850
+ }
851
+ render(a, e, i, r, t) {
852
+ if (!this.enabled)
853
+ return;
854
+ if (!i) {
855
+ console.error("DepthOfFieldPluginPass: No readBuffer");
856
+ return;
857
+ }
858
+ const s = a.renderManager, o = {
859
+ minFilter: ie,
860
+ magFilter: ie,
861
+ // type: UnsignedByteType,
862
+ // encoding: RGBM16Encoding,
863
+ type: K,
864
+ // encoding: LinearEncoding,
865
+ colorSpace: pe,
866
+ sizeMultiplier: 0.5,
867
+ // samples: 1,
868
+ format: Ue,
869
+ depthBuffer: !1,
870
+ generateMipmaps: !1
871
+ }, n = s.getTempTarget(o), l = s.getTempTarget(o);
872
+ if (this.computeCocMaterial.uniforms.colorTexture.value = i.texture, s.blit(n, { material: this.computeCocMaterial }), this.expandCocMaterial.uniforms.colorTexture.value = n.texture, this.expandCocMaterial.uniforms.direction.value.set(1, 0), s.blit(l, { material: this.expandCocMaterial }), this.expandCocMaterial.uniforms.colorTexture.value = l.texture, this.expandCocMaterial.uniforms.direction.value.set(0, 1), s.blit(n, { material: this.expandCocMaterial }), this.dofBlurMaterial.uniforms.frameCount)
873
+ this.dofBlurMaterial.uniforms.colorTexture.value = n.texture, s.blit(l, { material: this.dofBlurMaterial });
874
+ else {
875
+ const m = s.getTempTarget(o);
876
+ this.dofBlurMaterial.uniforms.cocTexture.value = n.texture, this.dofBlurMaterial.uniforms.colorTexture.value = n.texture, this.dofBlurMaterial.uniforms.direction.value.set(1, 0), s.blit(m, { material: this.dofBlurMaterial }), this.dofBlurMaterial.uniforms.colorTexture.value = m.texture, this.dofBlurMaterial.uniforms.direction.value.set(0, 1), s.blit(l, { material: this.dofBlurMaterial }), s.releaseTempTarget(m);
877
+ }
878
+ this.material.uniforms.blurTexture.value = l.texture, this.material.uniforms.cocTexture.value = n.texture, super.render(a, e, i, r, t), s.releaseTempTarget(n), s.releaseTempTarget(l);
879
+ }
880
+ };
881
+ S([
882
+ X({ obj: "focalDepthRange", key: "y" }),
883
+ u("Depth Range", [0.25, 3])
884
+ ], b.prototype, "depthRange", 2);
885
+ S([
886
+ X({ obj: "nearFarBlurScale", key: "x" }),
887
+ u("Near Blur Scale", [0, 1])
888
+ ], b.prototype, "nearBlurScale", 2);
889
+ S([
890
+ X({ obj: "nearFarBlurScale", key: "y" }),
891
+ u("Far Blur Scale", [0, 1])
892
+ ], b.prototype, "farBlurScale", 2);
893
+ S([
894
+ c(),
895
+ f()
896
+ ], b.prototype, "nearFarBlurScale", 2);
897
+ S([
898
+ c(),
899
+ f()
900
+ ], b.prototype, "focalDepthRange", 2);
901
+ S([
902
+ f()
903
+ ], b.prototype, "crossCenter", 2);
904
+ S([
905
+ f()
906
+ ], b.prototype, "crossRadius", 2);
907
+ S([
908
+ f()
909
+ ], b.prototype, "crossAlpha", 2);
910
+ S([
911
+ f()
912
+ ], b.prototype, "crossColor", 2);
913
+ b = S([
914
+ z("DepthOfField Pass")
915
+ ], b);
916
+ const J = `#ifndef SSRT_PARS_SNIP
917
+ #define SSRT_PARS_SNIP
918
+ #define pow2(a) a*a
919
+ float getDepth2(const in vec2 uv,const in float lod){float viewDepth=getDepth(uv);return depthToViewZ(viewDepth);}
920
+ #define LOD_DEPTH 1.0
921
+ #define LOD_COLOR 5.0
922
+ void _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.;
923
+ #pragma unroll_loop_start
924
+ for(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;}}
925
+ #pragma unroll_loop_end
926
+ }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)**/
927
+ #endif
928
+ `;
929
+ var at = Object.defineProperty, st = Object.getOwnPropertyDescriptor, F = (a, e, i, r) => {
930
+ for (var t = r > 1 ? void 0 : r ? st(e, i) : e, s = a.length - 1, o; s >= 0; s--)
931
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
932
+ return r && t && at(e, i, t), t;
933
+ };
934
+ let p = class extends Me {
935
+ // private _loaderCreate({loader}: {loader: GLTFLoader2}) {
936
+ // if (!loader.isGLTFLoader2) return
937
+ // loader.register((p) => new GLTFMaterialsSSContactShadowsExtensionImport(p))
938
+ // }
939
+ constructor(a = !0) {
940
+ super(), this.enabled = !0, this._uniforms = {
941
+ sscsRadius: { value: 0.03 },
942
+ sscsIntensity: { value: 1 },
943
+ sscsTolerance: { value: 1.5 },
944
+ // tLastFrame: {value: null}, // not needed since we dont need color
945
+ frameCount: { value: 0 },
946
+ projection: { value: new E() },
947
+ cameraPositionWorld: { value: new U() },
948
+ cameraNearFar: { value: new d(0.1, 1e3) },
949
+ sceneBoundingRadius: { value: 0 }
950
+ }, this.radius = 0.015, this.intensity = 1, this.tolerance = 1.5, this._defines = {
951
+ PERSPECTIVE_CAMERA: 1
952
+ // set in PerspectiveCamera2
953
+ }, this.onlySSCSDebug = !1, this.stepCount = 2, this.dependencies = [T], this.materialExtension = {
954
+ uuid: p.PluginType,
955
+ shaderExtender: (e, i, r) => {
956
+ var n, l;
957
+ if (!e.defines.SSCS_ENABLED)
958
+ return;
959
+ const t = "float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {", s = _e`
960
+ #ifndef D_sceneBoundingRadius
961
+ #define D_sceneBoundingRadius
962
+ uniform float sceneBoundingRadius;
963
+ #endif
964
+ uniform float frameCount;
965
+ float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, vec3 lightDirection ) {
966
+ vec3 ray_origin_view = -vViewPosition;
967
+ float rnd = interleavedGradientNoise(gl_FragCoord.xy, frameCount+34.);
968
+ float cameraDist = length(cameraPositionWorld);
969
+ // float radius = mix((cameraNearFar.y) + ray_origin_view.z, -ray_origin_view.z - cameraNearFar.x, rnd * 0.5 + 0.5)*sscsRadius;
970
+ float radius = mix((cameraDist + sceneBoundingRadius) + ray_origin_view.z, -ray_origin_view.z - max(0.0, cameraDist - sceneBoundingRadius), rnd * 0.5 + 0.5)*sscsRadius;
971
+ vec3 state = vec3(1.,(rnd+0.5)/float(SSCS_STEP_COUNT),2.);
972
+ traceRay(ray_origin_view, normalize(lightDirection) * radius, sscsTolerance * radius * 2., state, SSCS_STEP_COUNT);
973
+ state.z = state.z > 0.99 ? 1. : max(0.,min(state.z * state.z * (1.-sscsIntensity), 1.));
974
+ #if defined(SSCS_DEBUG) && SSCS_DEBUG > 0
975
+ return state.z;
976
+ #endif
977
+ `, o = `
978
+ #if SSCS_ENABLED
979
+
980
+ uniform float sscsIntensity;
981
+ uniform float sscsRadius;
982
+ uniform float sscsTolerance;
983
+
984
+ #define THREE_PACKING_INCLUDED // by threejs
985
+ #include <cameraHelpers>
986
+ #include <randomHelpers>
987
+ ${J}
988
+
989
+ #endif
990
+
991
+ ` + B(ae.shadowmap_pars_fragment, t, `${s}
992
+ `).replace("return shadow;", "return min(shadow, state.z);");
993
+ e.fragmentShader = B(e.fragmentShader, "#include <shadowmap_pars_fragment>", o), e.fragmentShader = e.fragmentShader.replace("#include <lights_fragment_begin>", ae.lights_fragment_begin), e.fragmentShader = B(
994
+ e.fragmentShader,
995
+ "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;",
996
+ "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ], directLight.direction ) : 1.0;"
997
+ ), e.fragmentShader = B(
998
+ e.fragmentShader,
999
+ "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;",
1000
+ "directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ], directLight.direction ) : 1.0;"
1001
+ ), (l = (n = this._gbufferUnpackExtension) == null ? void 0 : n.shaderExtender) == null || l.call(n, e, i, r);
1002
+ },
1003
+ onObjectRender: (e, i, r) => {
1004
+ var s, o;
1005
+ const t = this.enabled && r.userData.screenSpaceRendering !== !1 && !((s = i.userData) != null && s.pluginsDisabled) && !((o = i.userData) != null && o.sscsDisabled) ? 1 : 0;
1006
+ Le({
1007
+ ...this._defines,
1008
+ SSCS_ENABLED: t
1009
+ }, i);
1010
+ },
1011
+ extraUniforms: {
1012
+ ...this._uniforms
1013
+ // todo should not be static because of multiple viewers
1014
+ },
1015
+ extraDefines: {},
1016
+ computeCacheKey: (e) => this.isDisabled() ? "0" : "1",
1017
+ isCompatible: (e) => e.isPhysicalMaterial,
1018
+ // getUiConfig: (material: PhysicalMaterial) => {
1019
+ // const viewer = this._viewer!
1020
+ // if (material.userData._clearcoatTint === undefined) material.userData._clearcoatTint = {}
1021
+ // const state = material.userData._clearcoatTint
1022
+ // const config: UiObjectConfig = {
1023
+ // type: 'folder',
1024
+ // label: 'Clearcoat Tint',
1025
+ // onChange: (ev)=>{
1026
+ // if (!ev.config) return
1027
+ // this.setDirty()
1028
+ // },
1029
+ // children: [
1030
+ // {
1031
+ // type: 'checkbox',
1032
+ // label: 'Enabled',
1033
+ // get value() {
1034
+ // return state.enableTint || false
1035
+ // },
1036
+ // set value(v) {
1037
+ // if (v === state.enableTint) return
1038
+ // if (v) {
1039
+ // if (!SSContactShadowsPlugin.AddSSContactShadows(material))
1040
+ // viewer.dialog.alert('Cannot add clearcoat tint.')
1041
+ // } else {
1042
+ // state.enableTint = false
1043
+ // if (material.setDirty) material.setDirty()
1044
+ // }
1045
+ // config.uiRefresh?.(true, 'postFrame')
1046
+ // },
1047
+ // },
1048
+ // {
1049
+ // type: 'color',
1050
+ // label: 'Tint color',
1051
+ // hidden: () => !state.enableTint,
1052
+ // property: [state, 'tintColor'],
1053
+ // },
1054
+ // {
1055
+ // type: 'input',
1056
+ // label: 'Thickness',
1057
+ // hidden: () => !state.enableTint,
1058
+ // property: [state, 'thickness'],
1059
+ // },
1060
+ // {
1061
+ // type: 'slider',
1062
+ // bounds: [0.8, 2.5],
1063
+ // label: 'IOR',
1064
+ // hidden: () => !state.enableTint,
1065
+ // property: [state, 'ior'],
1066
+ // },
1067
+ // ],
1068
+ // }
1069
+ // return config
1070
+ // },
1071
+ updaters: () => {
1072
+ var e, i, r, t;
1073
+ return [
1074
+ // this._viewer?.getPlugin(GBufferPlugin),
1075
+ (e = this._viewer) == null ? void 0 : e.getPlugin(O),
1076
+ (i = this._viewer) == null ? void 0 : i.scene.renderCamera,
1077
+ (r = this._viewer) == null ? void 0 : r.renderManager,
1078
+ (t = this._viewer) == null ? void 0 : t.scene
1079
+ ];
1080
+ }
1081
+ }, this._gbufferUnpackExtension = void 0, this._gbufferUnpackExtensionChanged = () => {
1082
+ if (!this._viewer)
1083
+ throw new Error("SSContactShadowPlugin: pass/viewer not created yet");
1084
+ const e = this._viewer.renderManager.gbufferUnpackExtension;
1085
+ this._gbufferUnpackExtension !== e && (this._gbufferUnpackExtension && this.setGBufferUnpackExtension(void 0), this._gbufferUnpackExtension = e, this._gbufferUnpackExtension ? this.setGBufferUnpackExtension(this._gbufferUnpackExtension) : this._viewer.console.warn("SSContactShadowPlugin: GBuffer unpack extension removed"));
1086
+ }, this.enabled = a;
1087
+ }
1088
+ setDirty() {
1089
+ var a, e, i;
1090
+ (e = (a = this.materialExtension) == null ? void 0 : a.setDirty) == null || e.call(a), (i = this._viewer) == null || i.setDirty();
1091
+ }
1092
+ onAdded(a) {
1093
+ super.onAdded(a), a.assetManager.materials.registerMaterialExtension(this.materialExtension), a.getPlugin(se) && (a.getPlugin(se).material.userData.sscsDisabled = !1), this._gbufferUnpackExtensionChanged(), a.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1094
+ }
1095
+ onRemove(a) {
1096
+ var e;
1097
+ return (e = a.assetManager.materials) == null || e.unregisterMaterialExtension(this.materialExtension), a.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged), super.onRemove(a);
1098
+ }
1099
+ setGBufferUnpackExtension(a) {
1100
+ this._gbufferUnpackExtension = a, this._gbufferUnpackExtension && (Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms), Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines));
1101
+ }
1102
+ // public static readonly CLEARCOAT_TINT_GLTF_EXTENSION = 'WEBGI_materials_clearcoat_tint'
1103
+ };
1104
+ p.PluginType = "SSContactShadows";
1105
+ p.OldPluginType = "SSContactShadowsPlugin";
1106
+ F([
1107
+ R("Enabled"),
1108
+ c(),
1109
+ N(p.prototype.setDirty)
1110
+ ], p.prototype, "enabled", 2);
1111
+ F([
1112
+ f({ propKey: "sscsRadius", onChange: p.prototype.setDirty }),
1113
+ u("Radius", [1e-4, 0.1], 1e-4),
1114
+ c()
1115
+ ], p.prototype, "radius", 2);
1116
+ F([
1117
+ f({ propKey: "sscsIntensity", onChange: p.prototype.setDirty }),
1118
+ u("Intensity", [1e-4, 1], 1e-4),
1119
+ c()
1120
+ ], p.prototype, "intensity", 2);
1121
+ F([
1122
+ f({ propKey: "sscsTolerance", onChange: p.prototype.setDirty }),
1123
+ u("Tolerance", [0.1, 5]),
1124
+ c()
1125
+ ], p.prototype, "tolerance", 2);
1126
+ F([
1127
+ V("SSCS_DEBUG", void 0, !0, p.prototype.setDirty),
1128
+ R("Debug only SSCS"),
1129
+ c()
1130
+ ], p.prototype, "onlySSCSDebug", 2);
1131
+ F([
1132
+ V("SSCS_STEP_COUNT", void 0, !0, p.prototype.setDirty),
1133
+ u("Step count", [1, 8], 1),
1134
+ c()
1135
+ ], p.prototype, "stepCount", 2);
1136
+ p = F([
1137
+ z("SS Contact Shadows")
1138
+ ], p);
1139
+ const ne = `#define PI 3.141592653589793
1140
+ mat3 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;}`, le = `uniform float currentFrameCount;uniform float frameCount;uniform float objectRadius;uniform float radius;uniform float tolerance;uniform bool autoRadius;
1141
+ #ifndef D_sceneBoundingRadius
1142
+ #define D_sceneBoundingRadius
1143
+ uniform float sceneBoundingRadius;
1144
+ #endif
1145
+ vec3 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=autoRadius ?mix((cameraDist+objectRadius*sceneBoundingRadius)+viewPos.z,-viewPos.z-max(0.0,cameraDist-objectRadius*sceneBoundingRadius),L.z*0.5+0.5):objectRadius*sceneBoundingRadius;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.);}`, ot = `
1146
+ #if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0
1147
+ vec3 screenPos=viewToScreen(geometry.position);vec4 ssrColor=vec4(0,0,0,0);float alphaModifier=1.0-clamp(material.roughness*.3,0.,1.);alphaModifier*=ssrIntensity;
1148
+ #if defined(SSR_MASK_FRONT_RAYS) && SSR_MASK_FRONT_RAYS > 0
1149
+ alphaModifier*=clamp(-4.0*dot(geometry.viewDir,normal)+(4.0+ssrMaskFrontFactor),0.0,1.0);
1150
+ #endif
1151
+ #ifdef USE_TRANSMISSION
1152
+ alphaModifier*=1.-transmission;
1153
+ #endif
1154
+ float vignette=1.;if(true){float fadeStrength=0.1;float dist=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){
1155
+ #if defined(SSR_INLINE) && SSR_INLINE > 0
1156
+ ssrColor=calculateSSR(8.,vec3(screenPos.xy,geometry.position.z),geometry.normal,1.,material.roughness);
1157
+ #else
1158
+ ssrColor=tSSReflMapTexelToLinear(texture2D(tSSReflMap,screenPos.xy));
1159
+ #endif
1160
+ }ssrColor.rgb*=ssrBoost;ssrColor.a*=alphaModifier;ssrColor.rgb=pow(ssrColor.rgb,vec3(ssrPower));ssrColor.a=min(ssrColor.a,1.0);
1161
+ #if defined(SSR_NON_PHYSICAL) && SSR_NON_PHYSICAL > 0
1162
+ diffuseColor.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);
1163
+ #else
1164
+ reflectedLight.indirectSpecular=mix(reflectedLight.indirectSpecular,(specularColor.rgb*ssrColor.rgb),ssrColor.a);
1165
+ #endif
1166
+ #endif
1167
+ `, nt = `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.));}
1168
+ #include <encodings_fragment>
1169
+ }`;
1170
+ var lt = Object.defineProperty, ct = Object.getOwnPropertyDescriptor, x = (a, e, i, r) => {
1171
+ for (var t = r > 1 ? void 0 : r ? ct(e, i) : e, s = a.length - 1, o; s >= 0; s--)
1172
+ (o = a[s]) && (t = (r ? o(e, i, t) : o(t)) || t);
1173
+ return r && t && lt(e, i, t), t;
1174
+ };
1175
+ const ut = "ssrefl";
1176
+ let D = class extends I {
1177
+ // cannot be changed after creation (for now)
1178
+ constructor(a = !0, e = de, i = 1, r = !0) {
1179
+ super(), this.inlineShaderRayTrace = a, this.passId = ut, this.dependencies = [T, Fe], this._gbufferUnpackExtension = void 0, this._gbufferUnpackExtensionChanged = () => {
1180
+ if (!this._pass || !this._viewer)
1181
+ throw new Error("SSReflectionPlugin: pass/viewer not created yet");
1182
+ const t = this._viewer.renderManager.gbufferUnpackExtension;
1183
+ this._gbufferUnpackExtension !== t && (this._gbufferUnpackExtension && this._pass.setGBufferUnpackExtension(void 0), this._gbufferUnpackExtension = t, this._gbufferUnpackExtension ? this._pass.setGBufferUnpackExtension(this._gbufferUnpackExtension) : this._viewer.console.warn("SSReflectionPlugin: GBuffer unpack extension removed"));
1184
+ }, this.enabled = r, this.bufferType = e, this.sizeMultiplier = i;
1185
+ }
1186
+ _createTarget(a = !0) {
1187
+ this._viewer && (a && this._disposeTarget(), !this.inlineShaderRayTrace && (this.target || (this.target = this._viewer.renderManager.createTarget(
1188
+ {
1189
+ depthBuffer: !1,
1190
+ type: this.bufferType,
1191
+ sizeMultiplier: this.sizeMultiplier
1192
+ // magFilter: NearestFilter,
1193
+ // minFilter: NearestFilter,
1194
+ // generateMipmaps: false,
1195
+ // encoding: LinearEncoding,
1196
+ }
1197
+ )), this.texture = this.target.texture, this.texture.name = "ssreflBuffer", this._pass && (this._pass.target = this.target)));
1198
+ }
1199
+ _disposeTarget() {
1200
+ this._viewer && (this.target && (this._viewer.renderManager.disposeTarget(this.target), this.target = void 0), this.texture = void 0);
1201
+ }
1202
+ _createPass() {
1203
+ if (!this._viewer)
1204
+ throw new Error("SSReflectionPlugin: viewer not set");
1205
+ if (!this._viewer.renderManager.gbufferTarget || !this._viewer.renderManager.gbufferUnpackExtension)
1206
+ throw new Error("SSReflectionPlugin: GBuffer target not created. GBufferPlugin is required.");
1207
+ return this._createTarget(!0), new v(this.passId, this.target, this.inlineShaderRayTrace);
1208
+ }
1209
+ onAdded(a) {
1210
+ super.onAdded(a), a.getPlugin("Ground") && console.error("GroundPlugin must be added after SSReflectionPlugin"), this._gbufferUnpackExtensionChanged(), a.renderManager.addEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged);
1211
+ }
1212
+ onRemove(a) {
1213
+ return this._disposeTarget(), a.renderManager.removeEventListener("gbufferUnpackExtensionChanged", this._gbufferUnpackExtensionChanged), super.onRemove(a);
1214
+ }
1215
+ _beforeRender(a, e, i) {
1216
+ var r;
1217
+ return this._viewer ? ((r = this._pass) == null || r.updateShaderProperties([this._viewer.getPlugin(O)]), super._beforeRender(a, e, i)) : !1;
1218
+ }
1219
+ /**
1220
+ * @deprecated use {@link target} instead
1221
+ */
1222
+ get ssrTarget() {
1223
+ return console.warn("SSReflectionPlugin: ssrTarget is deprecated, use target instead"), this.target;
1224
+ }
1225
+ };
1226
+ D.PluginType = "SSReflection";
1227
+ D.OldPluginType = "SSReflectionPlugin";
1228
+ x([
1229
+ ve(
1230
+ "SSReflection Buffer"
1231
+ /* {readOnly: true}*/
1232
+ )
1233
+ ], D.prototype, "texture", 2);
1234
+ x([
1235
+ Q()
1236
+ ], D.prototype, "_pass", 2);
1237
+ D = x([
1238
+ z("SSReflection Plugin")
1239
+ ], D);
1240
+ let v = class extends $ {
1241
+ constructor(a, e, i = !0) {
1242
+ super({
1243
+ defines: {
1244
+ SSR_STEP_COUNT: 16,
1245
+ SSR_LOW_QUALITY_FRAMES: 2,
1246
+ // todo: only on mobile
1247
+ SSR_INLINE: i ? "1" : "0",
1248
+ // ['SSR_NON_PHYSICAL']: '0', only in inline, so it should not be here
1249
+ SSR_MASK_FRONT_RAYS: !0,
1250
+ PERSPECTIVE_CAMERA: 1
1251
+ // set in PerspectiveCamera2
1252
+ // ['SSREFL_PACKING']: 1, // 1 is (r: ssrefl, gba: depth), 2 is (rgb: ssrefl, a: 1), 3 is (rgba: packed_ssrefl), 4 is (rgb: packed_ssrefl, a: 1)
1253
+ },
1254
+ uniforms: {
1255
+ tLastThis: { value: null },
1256
+ tLastFrame: { value: null },
1257
+ // set in progressive plugin
1258
+ // TODO required?
1259
+ screenSize: { value: new d(0, 0) },
1260
+ // set in ExtendedRenderMaterial
1261
+ currentFrameCount: { value: 0 },
1262
+ // set in RenderManager
1263
+ frameCount: { value: 0 },
1264
+ // set in RenderManager
1265
+ cameraNearFar: { value: new d(0.1, 1e3) },
1266
+ // set in PerspectiveCamera2
1267
+ cameraPositionWorld: { value: new U() },
1268
+ // set in PerspectiveCamera2
1269
+ projection: { value: new E() },
1270
+ // set in PerspectiveCamera2
1271
+ saoBiasEpsilon: { value: new U(1, 1, 1) },
1272
+ opacity: { value: 1 },
1273
+ // todo?
1274
+ intensity: { value: 0 },
1275
+ boost: { value: new U(0, 0, 0) },
1276
+ objectRadius: { value: 0 },
1277
+ autoRadius: { value: !1 },
1278
+ power: { value: 0 },
1279
+ maskFrontFactor: { value: -0.1 },
1280
+ tolerance: { value: 0 },
1281
+ sceneBoundingRadius: { value: 0 }
1282
+ // todo do same in SSAO
1283
+ },
1284
+ vertexShader: k.defaultVertex,
1285
+ fragmentShader: `
1286
+ varying vec2 vUv;
1287
+
1288
+ // for gbuffer
1289
+ #include <packing>
1290
+ #define THREE_PACKING_INCLUDED
1291
+ #include <cameraHelpers>
1292
+ #include <randomHelpers>
1293
+ ${ne}
1294
+
1295
+ ${J}
1296
+
1297
+ ${le}
1298
+
1299
+ ${nt}
1300
+ `
1301
+ }, "tDiffuse", "tLastThis", "tLastFrame"), this.target = e, this.inlineShaderRayTrace = i, this.before = ["render"], this.after = ["gbuffer", "depth"], this.required = ["render", "progressive"], this.intensity = 1, this.boost = new U(1, 1, 1), this.objectRadius = 1, this.autoRadius = !0, this.power = 1.1, this.tolerance = 0.5, this.stepCount = 16, this.lowQualityFrames = 0, this.maskFrontRays = !0, this.maskFrontFactor = -0.2, this.materialExtension = {
1302
+ extraUniforms: {
1303
+ tSSReflMap: () => {
1304
+ var r;
1305
+ return { value: ((r = H(this.target)) == null ? void 0 : r.texture) ?? null };
1306
+ },
1307
+ ssrPower: this.material.uniforms.power,
1308
+ ssrIntensity: this.material.uniforms.intensity,
1309
+ ssrMaskFrontFactor: this.material.uniforms.maskFrontFactor,
1310
+ ssrBoost: this.material.uniforms.boost
1311
+ },
1312
+ extraDefines: {
1313
+ SSR_STEP_COUNT: () => this.material.defines.SSR_STEP_COUNT,
1314
+ SSR_LOW_QUALITY_FRAMES: () => this.material.defines.SSR_LOW_QUALITY_FRAMES,
1315
+ SSR_INLINE: () => this.material.defines.SSR_INLINE,
1316
+ SSR_MASK_FRONT_RAYS: () => this.material.defines.SSR_MASK_FRONT_RAYS,
1317
+ PERSPECTIVE_CAMERA: () => this.material.defines.PERSPECTIVE_CAMERA
1318
+ // todo gbuffer stuff
1319
+ },
1320
+ shaderExtender: (r, t, s) => {
1321
+ var n, l;
1322
+ if (!r.defines.SSREFL_ENABLED)
1323
+ return;
1324
+ const o = `
1325
+
1326
+ ${ot}
1327
+
1328
+ // reflectedLight.directDiffuse = vec3(0.);
1329
+ // reflectedLight.indirectDiffuse = vec3(0.);
1330
+ // reflectedLight.directSpecular = vec3(0.);
1331
+ // reflectedLight.indirectSpecular = vec3(0.);
1332
+
1333
+ `;
1334
+ r.fragmentShader = B(
1335
+ r.fragmentShader,
1336
+ "#glMarker beforeModulation",
1337
+ o,
1338
+ { prepend: !0 }
1339
+ ), (l = (n = this._gbufferUnpackExtension) == null ? void 0 : n.shaderExtender) == null || l.call(n, r, t, s);
1340
+ },
1341
+ onObjectRender: (r, t, s) => {
1342
+ var n, l, m;
1343
+ let o = this.enabled && s.userData.screenSpaceRendering !== !1 && !((n = t.userData) != null && n.pluginsDisabled) && !((l = t.userData) != null && l.ssreflDisabled) ? 1 : 0;
1344
+ t.defines.SSREFL_ENABLED !== o && (t.defines.SSREFL_ENABLED = o, t.needsUpdate = !0), o = (m = t.userData) != null && m.ssreflNonPhysical ? 1 : 0, t.defines.SSR_NON_PHYSICAL !== o && (t.defines.SSR_NON_PHYSICAL = o, t.needsUpdate = !0);
1345
+ },
1346
+ parsFragmentSnippet: (r) => {
1347
+ var t;
1348
+ return _e`
1349
+ #if defined(SSREFL_ENABLED) && SSREFL_ENABLED > 0
1350
+ uniform float ssrPower;
1351
+ uniform float ssrIntensity;
1352
+ uniform float ssrMaskFrontFactor;
1353
+ uniform vec3 ssrBoost;
1354
+ uniform sampler2D tSSReflMap;
1355
+ uniform sampler2D tLastFrame;
1356
+ ${oe("tSSReflMap", (t = H(this.target)) == null ? void 0 : t.texture, r.capabilities.isWebGL2)}
1357
+ ${oe("tLastFrame", this.material.uniforms.tLastFrame.value, r.capabilities.isWebGL2)}
1358
+ ${this.inlineShaderRayTrace ? `
1359
+ #define THREE_PACKING_INCLUDED // by threejs
1360
+ #include <cameraHelpers>
1361
+ #include <randomHelpers>
1362
+ ${ne}
1363
+ ${J}
1364
+ ${le}
1365
+ ` : ""}
1366
+ #include <simpleCameraHelpers>
1367
+ #endif
1368
+ `;
1369
+ },
1370
+ computeCacheKey: () => {
1371
+ var r, t;
1372
+ return this.enabled ? "1" : "0" + ((t = (r = H(this.target)) == null ? void 0 : r.texture) == null ? void 0 : t.colorSpace) + Object.values(this.material.defines).map((s) => s + "").join(",");
1373
+ },
1374
+ uuid: D.PluginType,
1375
+ ...ge(this._getUiConfig.bind(this), D.PluginType),
1376
+ isCompatible: (r) => r.isPhysicalMaterial
1377
+ }, this.passId = a, this.needsSwap = !1, this.clear = !0, i && Object.assign(this.materialExtension.extraUniforms, {
1378
+ tNormalDepth: this.material.uniforms.tNormalDepth,
1379
+ tLastFrame: this.material.uniforms.tLastFrame,
1380
+ objectRadius: this.material.uniforms.objectRadius,
1381
+ autoRadius: this.material.uniforms.autoRadius,
1382
+ tolerance: this.material.uniforms.tolerance,
1383
+ frameCount: this.material.uniforms.frameCount,
1384
+ // currentFrameCount: this.material.uniforms.currentFrameCount, // todo required?
1385
+ projection: this.material.uniforms.projection,
1386
+ cameraPositionWorld: this.material.uniforms.cameraPositionWorld,
1387
+ cameraNearFar: this.material.uniforms.cameraNearFar,
1388
+ sceneBoundingRadius: this.material.uniforms.sceneBoundingRadius
1389
+ });
1390
+ }
1391
+ render(a, e, i, r, t) {
1392
+ if (!this.enabled)
1393
+ return;
1394
+ if (this.inlineShaderRayTrace) {
1395
+ this.needsSwap = !1;
1396
+ return;
1397
+ }
1398
+ const s = H(this.target);
1399
+ if (!s) {
1400
+ console.warn("SSReflectionPluginPass: target not defined. It must be set when inlineShaderRayTrace is false");
1401
+ return;
1402
+ }
1403
+ this.material.defines.HAS_GBUFFER || console.warn("SSReflectionPluginPass: DepthNormalBuffer required for ssrefl"), a.renderManager.blit(e, {
1404
+ source: s.texture
1405
+ }), this.uniforms.tLastThis.value = e.texture, super.render(a, s, i, r, t), this.needsSwap = !1;
1406
+ }
1407
+ beforeRender(a, e, i) {
1408
+ this.enabled && this.updateShaderProperties([a, e, i]);
1409
+ }
1410
+ /**
1411
+ * Returns a uiConfig to toggle SSReflection on a material.
1412
+ * This uiConfig is added to each material by extension
1413
+ * @param material
1414
+ * @private
1415
+ */
1416
+ _getUiConfig(a) {
1417
+ return {
1418
+ type: "folder",
1419
+ label: "SSReflection",
1420
+ children: [
1421
+ {
1422
+ type: "checkbox",
1423
+ label: "Enabled",
1424
+ get value() {
1425
+ return !(a.userData.ssreflDisabled ?? !1);
1426
+ },
1427
+ set value(e) {
1428
+ e !== !(a.userData.ssreflDisabled ?? !1) && (a.userData.ssreflDisabled = !e, a.setDirty());
1429
+ },
1430
+ onChange: this.setDirty
1431
+ },
1432
+ {
1433
+ type: "checkbox",
1434
+ label: "Non Physical",
1435
+ get value() {
1436
+ return a.userData.ssreflNonPhysical ?? !1;
1437
+ },
1438
+ set value(e) {
1439
+ e !== (a.userData.ssreflNonPhysical ?? !1) && (a.userData.ssreflNonPhysical = e, a.setDirty());
1440
+ },
1441
+ onChange: this.setDirty
1442
+ }
1443
+ ]
1444
+ };
1445
+ }
1446
+ set uniformsNeedUpdate(a) {
1447
+ this.material.uniformsNeedUpdate = a, this.setDirty();
1448
+ }
1449
+ setGBufferUnpackExtension(a) {
1450
+ this._gbufferUnpackExtension !== a && (this._gbufferUnpackExtension && this.material.unregisterMaterialExtensions([this._gbufferUnpackExtension]), this._gbufferUnpackExtension = a, this._gbufferUnpackExtension && this.material.registerMaterialExtensions([this._gbufferUnpackExtension]), this._gbufferUnpackExtension && (Object.assign(this.materialExtension.extraUniforms, this._gbufferUnpackExtension.extraUniforms), Object.assign(this.materialExtension.extraDefines, this._gbufferUnpackExtension.extraDefines)));
1451
+ }
1452
+ };
1453
+ x([
1454
+ u("Intensity", [0, 4]),
1455
+ c(),
1456
+ f()
1457
+ ], v.prototype, "intensity", 2);
1458
+ x([
1459
+ ue("Boost"),
1460
+ c(),
1461
+ f()
1462
+ ], v.prototype, "boost", 2);
1463
+ x([
1464
+ u("Object Radius", [0.01, 2]),
1465
+ c(),
1466
+ f()
1467
+ ], v.prototype, "objectRadius", 2);
1468
+ x([
1469
+ R("Auto radius"),
1470
+ c(),
1471
+ f()
1472
+ ], v.prototype, "autoRadius", 2);
1473
+ x([
1474
+ u("Power", [0, 3]),
1475
+ c(),
1476
+ f()
1477
+ ], v.prototype, "power", 2);
1478
+ x([
1479
+ u("Tolerance", [0.1, 5]),
1480
+ c(),
1481
+ f()
1482
+ ], v.prototype, "tolerance", 2);
1483
+ x([
1484
+ u("Step count", [1, 32], 1),
1485
+ c(),
1486
+ V("SSR_STEP_COUNT", void 0, void 0, v.prototype.setDirty)
1487
+ ], v.prototype, "stepCount", 2);
1488
+ x([
1489
+ u("Low Quality Frames", [0, 4], 1),
1490
+ c(),
1491
+ V("SSR_LOW_QUALITY_FRAMES", void 0, void 0, v.prototype.setDirty)
1492
+ ], v.prototype, "lowQualityFrames", 2);
1493
+ x([
1494
+ R("Ignore front rays"),
1495
+ c(),
1496
+ fe("SSR_MASK_FRONT_RAYS", void 0, void 0, v.prototype.setDirty)
1497
+ ], v.prototype, "maskFrontRays", 2);
1498
+ x([
1499
+ u("Mask front rays factor", [-1, 1], 0.01, (a) => ({ hidden: () => !a.maskFrontRays })),
1500
+ c(),
1501
+ f()
1502
+ ], v.prototype, "maskFrontFactor", 2);
1503
+ v = x([
1504
+ z("SSReflection Pass")
1505
+ ], v);
1506
+ const dt = [
1507
+ M,
1508
+ L,
1509
+ qe,
1510
+ D,
1511
+ p,
1512
+ A
1513
+ ];
1514
+ export {
1515
+ qe as BloomPlugin,
1516
+ h as BloomPluginPass,
1517
+ A as DepthOfFieldPlugin,
1518
+ b as DepthOfFieldPluginPass,
1519
+ p as SSContactShadowsPlugin,
1520
+ D as SSReflectionPlugin,
1521
+ v as SSReflectionPluginPass,
1522
+ He as SSVelocityMaterial,
1523
+ M as TemporalAAPlugin,
1524
+ ee as TemporalAAPluginPass,
1525
+ L as VelocityBufferPlugin,
1526
+ dt as webgiPlugins
1527
+ };
1528
+ //# sourceMappingURL=index.mjs.map