@xviewer.js/postprocessing 1.0.0-alpha.12 → 1.0.0-alpha.14

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/main.js CHANGED
@@ -48,6 +48,7 @@ class EffectComposerPlugin extends core.Plugin {
48
48
  }
49
49
  constructor(props){
50
50
  super();
51
+ this.type = "EffectComposerPlugin";
51
52
  this.install = ()=>{
52
53
  const { renderer, scene, camera } = this.viewer;
53
54
  this._renderPass = new postprocessing.RenderPass(scene, camera);
@@ -66,35 +67,6 @@ class EffectComposerPlugin extends core.Plugin {
66
67
  }
67
68
  }
68
69
 
69
- /******************************************************************************
70
- Copyright (c) Microsoft Corporation.
71
-
72
- Permission to use, copy, modify, and/or distribute this software for any
73
- purpose with or without fee is hereby granted.
74
-
75
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
76
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
77
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
78
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
79
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
80
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
81
- PERFORMANCE OF THIS SOFTWARE.
82
- ***************************************************************************** */
83
- /* global Reflect, Promise, SuppressedError, Symbol */
84
-
85
-
86
- function __decorate(decorators, target, key, desc) {
87
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
88
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
89
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
90
- return c > 3 && r && Object.defineProperty(target, key, r), r;
91
- }
92
-
93
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
94
- var e = new Error(message);
95
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
96
- };
97
-
98
70
  class PassPlugin extends core.Plugin {
99
71
  get enable() {
100
72
  return this.pass.enabled;
@@ -109,9 +81,6 @@ class PassPlugin extends core.Plugin {
109
81
  this.composer.activePass(this.pass, v);
110
82
  }
111
83
  }
112
- __decorate([
113
- core.property
114
- ], PassPlugin.prototype, "enable", null);
115
84
 
116
85
  class ToneMappingPlugin extends PassPlugin {
117
86
  get mode() {
@@ -122,6 +91,7 @@ class ToneMappingPlugin extends PassPlugin {
122
91
  }
123
92
  constructor(props){
124
93
  super();
94
+ this.type = "ToneMappingPlugin";
125
95
  this.install = ()=>{
126
96
  this.effect = new postprocessing.ToneMappingEffect(props);
127
97
  this.pass = this.composer.addPass(new postprocessing.EffectPass(this.viewer.camera, this.effect));
@@ -131,25 +101,39 @@ class ToneMappingPlugin extends PassPlugin {
131
101
  };
132
102
  }
133
103
  }
134
- __decorate([
135
- core.property({
136
- value: postprocessing.ToneMappingMode
137
- })
138
- ], ToneMappingPlugin.prototype, "mode", null);
104
+ core.PropertyManager._getClassProperties("ToneMappingPlugin").property("enable").property("mode", {
105
+ value: postprocessing.ToneMappingMode
106
+ });
107
+
108
+ function _extends() {
109
+ _extends = Object.assign || function assign(target) {
110
+ for (var i = 1; i < arguments.length; i++) {
111
+ var source = arguments[i];
112
+ for (var key in source) if (Object.prototype.hasOwnProperty.call(source, key)) target[key] = source[key];
113
+ }
114
+
115
+ return target;
116
+ };
117
+
118
+ return _extends.apply(this, arguments);
119
+ }
139
120
 
140
121
  class BloomPlugin extends PassPlugin {
122
+ // @property({ min: 0, max: 2, step: 0.01 })
141
123
  get intensity() {
142
124
  return this.effect.intensity;
143
125
  }
144
126
  set intensity(v) {
145
127
  this.effect.intensity = v;
146
128
  }
129
+ // @property({ min: 0, max: 10, step: 0.01 })
147
130
  get luminanceThreshold() {
148
131
  return this.effect.luminanceMaterial.threshold;
149
132
  }
150
133
  set luminanceThreshold(v) {
151
134
  this.effect.luminanceMaterial.threshold = v;
152
135
  }
136
+ // @property({ min: 0, max: 10, step: 0.01 })
153
137
  get luminanceSmoothing() {
154
138
  return this.effect.luminanceMaterial.smoothing;
155
139
  }
@@ -158,11 +142,11 @@ class BloomPlugin extends PassPlugin {
158
142
  }
159
143
  constructor(props){
160
144
  super();
145
+ this.type = "BloomPlugin";
161
146
  this.install = ()=>{
162
- this.effect = new postprocessing.BloomEffect({
163
- blendFunction: postprocessing.BlendFunction.ADD,
164
- ...props
165
- });
147
+ this.effect = new postprocessing.BloomEffect(_extends({
148
+ blendFunction: postprocessing.BlendFunction.ADD
149
+ }, props));
166
150
  this.pass = this.composer.addPass(new postprocessing.EffectPass(this.viewer.camera, this.effect));
167
151
  };
168
152
  this.uninstall = ()=>{
@@ -170,31 +154,24 @@ class BloomPlugin extends PassPlugin {
170
154
  };
171
155
  }
172
156
  }
173
- __decorate([
174
- core.property({
175
- min: 0,
176
- max: 2,
177
- step: 0.01
178
- })
179
- ], BloomPlugin.prototype, "intensity", null);
180
- __decorate([
181
- core.property({
182
- min: 0,
183
- max: 10,
184
- step: 0.01
185
- })
186
- ], BloomPlugin.prototype, "luminanceThreshold", null);
187
- __decorate([
188
- core.property({
189
- min: 0,
190
- max: 10,
191
- step: 0.01
192
- })
193
- ], BloomPlugin.prototype, "luminanceSmoothing", null);
157
+ core.PropertyManager._getClassProperties("BloomPlugin").property("enable").property("intensity", {
158
+ min: 0,
159
+ max: 2,
160
+ step: 0.01
161
+ }).property("luminanceThreshold", {
162
+ min: 0,
163
+ max: 10,
164
+ step: 0.01
165
+ }).property("luminanceSmoothing", {
166
+ min: 0,
167
+ max: 10,
168
+ step: 0.01
169
+ });
194
170
 
195
171
  class FXAAPlugin extends PassPlugin {
196
172
  constructor(){
197
173
  super();
174
+ this.type = "FXAAPlugin";
198
175
  this.install = ()=>{
199
176
  this.pass = this.composer.addPass(new postprocessing.EffectPass(this.viewer.camera, new postprocessing.FXAAEffect()));
200
177
  };
@@ -203,8 +180,10 @@ class FXAAPlugin extends PassPlugin {
203
180
  };
204
181
  }
205
182
  }
183
+ core.PropertyManager._getClassProperties("FXAAPlugin").property("enable");
206
184
 
207
185
  class SMAAPlugin extends PassPlugin {
186
+ // @property({ value: SMAAPreset })
208
187
  get preset() {
209
188
  return this._preset;
210
189
  }
@@ -214,12 +193,14 @@ class SMAAPlugin extends PassPlugin {
214
193
  this.effect.applyPreset(v);
215
194
  }
216
195
  }
196
+ // @property({ value: EdgeDetectionMode })
217
197
  get edgeDetectionMode() {
218
198
  return this.effect.edgeDetectionMaterial.edgeDetectionMode;
219
199
  }
220
200
  set edgeDetectionMode(v) {
221
201
  this.effect.edgeDetectionMaterial.edgeDetectionMode = v;
222
202
  }
203
+ // @property({ value: PredicationMode })
223
204
  get predicationMode() {
224
205
  return this.effect.edgeDetectionMaterial.predicationMode;
225
206
  }
@@ -228,6 +209,7 @@ class SMAAPlugin extends PassPlugin {
228
209
  }
229
210
  constructor(props = {}){
230
211
  super();
212
+ this.type = "SMAAPlugin";
231
213
  this._preset = postprocessing.SMAAPreset.MEDIUM;
232
214
  this.install = ()=>{
233
215
  this.effect = new postprocessing.SMAAEffect(props);
@@ -238,21 +220,13 @@ class SMAAPlugin extends PassPlugin {
238
220
  };
239
221
  }
240
222
  }
241
- __decorate([
242
- core.property({
243
- value: postprocessing.SMAAPreset
244
- })
245
- ], SMAAPlugin.prototype, "preset", null);
246
- __decorate([
247
- core.property({
248
- value: postprocessing.EdgeDetectionMode
249
- })
250
- ], SMAAPlugin.prototype, "edgeDetectionMode", null);
251
- __decorate([
252
- core.property({
253
- value: postprocessing.PredicationMode
254
- })
255
- ], SMAAPlugin.prototype, "predicationMode", null);
223
+ core.PropertyManager._getClassProperties("SMAAPlugin").property("enable").property("preset", {
224
+ value: postprocessing.SMAAPreset
225
+ }).property("edgeDetectionMode", {
226
+ value: postprocessing.EdgeDetectionMode
227
+ }).property("predicationMode", {
228
+ value: postprocessing.PredicationMode
229
+ });
256
230
 
257
231
  class MSAAPlugin extends core.Plugin {
258
232
  get enable() {
@@ -266,6 +240,7 @@ class MSAAPlugin extends core.Plugin {
266
240
  }
267
241
  constructor(){
268
242
  super();
243
+ this.type = "MSAAPlugin";
269
244
  this._maxSamples = 4;
270
245
  this.install = ()=>{
271
246
  const { renderer } = this.viewer;
@@ -277,14 +252,749 @@ class MSAAPlugin extends core.Plugin {
277
252
  };
278
253
  }
279
254
  }
280
- __decorate([
281
- core.property
282
- ], MSAAPlugin.prototype, "enable", null);
255
+ core.PropertyManager._getClassProperties("MSAAPlugin").property("enable");
256
+
257
+ // from: https://news.ycombinator.com/item?id=17876741
258
+ // reference: http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
259
+ // eslint-disable-next-line no-unused-vars
260
+ const g = 1.32471795724474602596090885447809 // Plastic number
261
+ ;
262
+ const a1 = 1.0 / g;
263
+ const a2 = 1.0 / (g * g);
264
+ const base = 1.1127756842787055 // harmoniousNumber(7), yields better coverage compared to using 0.5
265
+ ;
266
+ const generateR2 = (count)=>{
267
+ const points = [];
268
+ for(let n = 0; n < count; n++){
269
+ points.push([
270
+ (base + a1 * n) % 1,
271
+ (base + a2 * n) % 1
272
+ ]);
273
+ }
274
+ return points;
275
+ };
276
+
277
+ const r2Sequence = generateR2(256).map(([a, b])=>[
278
+ a - 0.5,
279
+ b - 0.5
280
+ ]);
281
+ function jitter(width, height, camera, frame, jitterScale = 1) {
282
+ const [x, y] = r2Sequence[frame % r2Sequence.length];
283
+ if (camera.setViewOffset) {
284
+ camera.setViewOffset(width, height, x * jitterScale, y * jitterScale, width, height);
285
+ }
286
+ }
287
+
288
+ var vertexShader = "#define GLSLIFY 1\nvarying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}"; // eslint-disable-line
289
+
290
+ var fragmentShader = "#define GLSLIFY 1\nvarying vec2 vUv;uniform highp sampler2D inputTexture;uniform highp sampler2D velocityTexture;uniform highp sampler2D depthTexture;uniform highp sampler2D lastVelocityTexture;uniform float maxBlend;uniform float neighborhoodClampIntensity;uniform bool fullAccumulate;uniform vec2 invTexSize;uniform float cameraNear;uniform float cameraFar;uniform mat4 projectionMatrix;uniform mat4 projectionMatrixInverse;uniform mat4 cameraMatrixWorld;uniform vec3 cameraPos;uniform vec3 prevCameraPos;uniform mat4 prevViewMatrix;uniform mat4 prevCameraMatrixWorld;uniform mat4 prevProjectionMatrix;uniform mat4 prevProjectionMatrixInverse;uniform float keepData;\n#define EPSILON 0.00001\n#define DIFFUSE_SPECULAR 0\n#define DIFFUSE 1\n#define SPECULAR 2\n#include <gbuffer_packing>\n#include <packing>\n#include <reproject>\nvec3 reprojectedUvDiffuse=vec3(-1.0),reprojectedUvSpecular=vec3(-1.0);void accumulate(inout vec4 outputColor,inout vec4 inp,inout vec4 acc,inout float roughness,inout float moveFactor,bool doReprojectSpecular){vec3 reprojectedUvConfidence=doReprojectSpecular ? reprojectedUvSpecular : reprojectedUvDiffuse;vec2 reprojectedUv=reprojectedUvConfidence.xy;float confidence=reprojectedUvConfidence.z;confidence=pow(confidence,confidencePower);float accumBlend=1.-1./(acc.a+1.0);accumBlend=mix(0.,accumBlend,confidence);float maxValue=(fullAccumulate ? 1. : maxBlend)*keepData;\n#if inputType != DIFFUSE\nconst float roughnessMaximum=0.1;if(doReprojectSpecular&&roughness>=0.0&&roughness<roughnessMaximum){float maxRoughnessValue=mix(0.,maxValue,roughness/roughnessMaximum);maxValue=mix(maxValue,maxRoughnessValue,min(100.*moveFactor,1.));}\n#endif\nfloat temporalReprojectMix=min(accumBlend,maxValue);acc.a=1./(1.-temporalReprojectMix)-1.;acc.a=min(65536.,acc.a);outputColor.rgb=mix(inp.rgb,acc.rgb,temporalReprojectMix);outputColor.a=acc.a;undoColorTransform(outputColor.rgb);}void reproject(inout vec4 inp,inout vec4 acc,sampler2D accumulatedTexture,inout bool wasSampled,bool doNeighborhoodClamp,bool doReprojectSpecular){vec3 uvc=doReprojectSpecular ? reprojectedUvSpecular : reprojectedUvDiffuse;vec2 uv=uvc.xy;acc=sampleReprojectedTexture(accumulatedTexture,uv);transformColor(acc.rgb);if(!wasSampled){inp.rgb=acc.rgb;return;}acc.a++;vec3 clampedColor=acc.rgb;int clampRadius=doReprojectSpecular&&roughness<0.25 ? 1 : 2;clampNeighborhood(inputTexture,clampedColor,inp.rgb,clampRadius,doReprojectSpecular);float r=doReprojectSpecular ? roughness : 1.0;float clampAggressiveness=min(1.,uvc.z*r);float clampIntensity=mix(0.,min(1.,moveFactor*50.+neighborhoodClampIntensity),clampAggressiveness);vec3 newColor=mix(acc.rgb,clampedColor,clampIntensity);float colorDiff=min(length(newColor-acc.rgb),1.);acc.a*=1.-colorDiff;acc.rgb=newColor;}void preprocessInput(inout highp vec4 texel,inout bool sampledThisFrame){sampledThisFrame=texel.r>=0.;texel.rgb=max(texel.rgb,vec3(0.));transformColor(texel.rgb);}void getTexels(inout highp vec4 inputTexel[textureCount],inout bool sampledThisFrame[textureCount]){\n#if inputType == DIFFUSE_SPECULAR\nhighp vec4 tex=textureLod(inputTexture,vUv,0.);unpackTwoVec4(tex,inputTexel[0],inputTexel[1]);preprocessInput(inputTexel[0],sampledThisFrame[0]);preprocessInput(inputTexel[1],sampledThisFrame[1]);\n#else\ninputTexel[0]=textureLod(inputTexture,vUv,0.0);preprocessInput(inputTexel[0],sampledThisFrame[0]);\n#endif\n}void computeGVariables(vec2 dilatedUv,float depth){worldPos=screenSpaceToWorldSpace(dilatedUv,depth,cameraMatrixWorld,projectionMatrixInverse);vec3 viewPos=(viewMatrix*vec4(worldPos,1.0)).xyz;viewDir=normalize(viewPos);vec3 viewNormal=(vec4(worldNormal,0.0)*viewMatrix).xyz;viewAngle=dot(-viewDir,viewNormal);}void computeReprojectedUv(float depth,vec3 worldPos,vec3 worldNormal){reprojectedUvDiffuse=getReprojectedUV(false,depth,worldPos,worldNormal);\n#if inputType == DIFFUSE_SPECULAR || inputType == SPECULAR\nreprojectedUvSpecular=getReprojectedUV(true,depth,worldPos,worldNormal);if(reprojectedUvSpecular.x==-1.0){reprojectedUvSpecular=reprojectedUvDiffuse;}\n#endif\n}void getRoughnessRayLength(inout highp vec4 inputTexel[textureCount]){\n#if inputType == DIFFUSE_SPECULAR\nrayLength=inputTexel[1].a;roughness=clamp(inputTexel[0].a,0.,1.);\n#elif inputType == SPECULAR\nvec2 data=unpackHalf2x16(floatBitsToUint(inputTexel[0].a));rayLength=data.r;roughness=clamp(data.g,0.,1.);\n#endif\n}void main(){vec2 dilatedUv=vUv;getVelocityNormalDepth(dilatedUv,velocity,worldNormal,depth);highp vec4 inputTexel[textureCount],accumulatedTexel[textureCount];bool textureSampledThisFrame[textureCount];getTexels(inputTexel,textureSampledThisFrame);\n#if inputType != DIFFUSE\nif(depth==1.0&&fwidth(depth)==0.0){discard;return;}\n#endif\ncurvature=getCurvature(worldNormal);computeGVariables(dilatedUv,depth);getRoughnessRayLength(inputTexel);computeReprojectedUv(depth,worldPos,worldNormal);moveFactor=min(dot(velocity,velocity)*10000.,1.);\n#pragma unroll_loop_start\nfor(int i=0;i<textureCount;i++){reproject(inputTexel[i],accumulatedTexel[i],accumulatedTexture[i],textureSampledThisFrame[i],neighborhoodClamp[i],reprojectSpecular[i]);accumulate(gOutput[i],inputTexel[i],accumulatedTexel[i],roughness,moveFactor,reprojectSpecular[i]);}\n#pragma unroll_loop_end\n}"; // eslint-disable-line
291
+
292
+ var reproject = "#define GLSLIFY 1\nvec2 dilatedUv,velocity;vec3 worldNormal,worldPos,viewDir;float depth,curvature,viewAngle,rayLength,angleMix;float roughness=1.;float moveFactor=0.;\n#define luminance(a) dot(vec3(0.2125, 0.7154, 0.0721), a)\nfloat getViewZ(const in float depth){\n#ifdef PERSPECTIVE_CAMERA\nreturn perspectiveDepthToViewZ(depth,cameraNear,cameraFar);\n#else\nreturn orthographicDepthToViewZ(depth,cameraNear,cameraFar);\n#endif\n}vec3 screenSpaceToWorldSpace(const vec2 uv,const float depth,mat4 curMatrixWorld,const mat4 projMatrixInverse){vec4 ndc=vec4((uv.x-0.5)*2.0,(uv.y-0.5)*2.0,(depth-0.5)*2.0,1.0);vec4 clip=projMatrixInverse*ndc;vec4 view=curMatrixWorld*(clip/clip.w);return view.xyz;}vec2 viewSpaceToScreenSpace(const vec3 position,const mat4 projMatrix){vec4 projectedCoord=projMatrix*vec4(position,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=projectedCoord.xy*0.5+0.5;return projectedCoord.xy;}\n#ifdef logTransform\nvoid transformColor(inout vec3 color){color=log(color+1.);}void undoColorTransform(inout vec3 color){color=exp(color)-1.;}\n#else\n#define transformColor\n#define undoColorTransform\n#endif\nvoid getNeighborhoodAABB(const sampler2D tex,const int clampRadius,inout vec3 minNeighborColor,inout vec3 maxNeighborColor,const bool isSpecular){for(int x=-clampRadius;x<=clampRadius;x++){for(int y=-clampRadius;y<=clampRadius;y++){vec2 offset=vec2(x,y)*invTexSize;vec2 neighborUv=vUv+offset;\n#if inputType == DIFFUSE_SPECULAR\nvec4 t1,t2;vec4 packedNeighborTexel=textureLod(inputTexture,neighborUv,0.0);unpackTwoVec4(packedNeighborTexel,t1,t2);vec4 neighborTexel=isSpecular ? t2 : t1;\n#else\nvec4 neighborTexel=textureLod(inputTexture,neighborUv,0.0);\n#endif\nif(neighborTexel.r>=0.){minNeighborColor=min(neighborTexel.rgb,minNeighborColor);maxNeighborColor=max(neighborTexel.rgb,maxNeighborColor);}}}}void clampNeighborhood(const sampler2D tex,inout vec3 color,vec3 inputColor,const int clampRadius,const bool isSpecular){undoColorTransform(inputColor);vec3 minNeighborColor=inputColor;vec3 maxNeighborColor=inputColor;getNeighborhoodAABB(tex,clampRadius,minNeighborColor,maxNeighborColor,isSpecular);transformColor(minNeighborColor);transformColor(maxNeighborColor);color=clamp(color,minNeighborColor,maxNeighborColor);}void getVelocityNormalDepth(inout vec2 dilatedUv,out vec2 vel,out vec3 normal,out float depth){vec2 centerUv=dilatedUv;vec4 velocityTexel=textureLod(velocityTexture,centerUv,0.0);vel=velocityTexel.rg;normal=unpackNormal(velocityTexel.b);depth=velocityTexel.a;}\n#define PLANE_DISTANCE 20.\n#define WORLD_DISTANCE 10.\n#define NORMAL_DISTANCE 1.\nfloat planeDistanceDisocclusionCheck(const vec3 worldPos,const vec3 lastWorldPos,const vec3 worldNormal,const float distFactor){vec3 toCurrent=worldPos-lastWorldPos;float distToPlane=abs(dot(toCurrent,worldNormal));return distToPlane/PLANE_DISTANCE*distFactor;}float worldDistanceDisocclusionCheck(const vec3 worldPos,const vec3 lastWorldPos,const float distFactor){return length(worldPos-lastWorldPos)/WORLD_DISTANCE*distFactor;}float normalDisocclusionCheck(const vec3 worldNormal,const vec3 lastWorldNormal,const float distFactor){return min(1.-dot(worldNormal,lastWorldNormal),1.)/NORMAL_DISTANCE*distFactor;}float validateReprojectedUV(const vec2 reprojectedUv,const vec3 worldPos,const vec3 worldNormal,const bool isHitPoint){if(reprojectedUv.x>1.0||reprojectedUv.x<0.0||reprojectedUv.y>1.0||reprojectedUv.y<0.0)return 0.;vec2 dilatedReprojectedUv=reprojectedUv;vec2 lastVelocity=vec2(0.0);vec3 lastWorldNormal=vec3(0.0);float lastDepth=0.0;getVelocityNormalDepth(dilatedReprojectedUv,lastVelocity,lastWorldNormal,lastDepth);vec3 lastWorldPos=screenSpaceToWorldSpace(dilatedReprojectedUv,lastDepth,prevCameraMatrixWorld,prevProjectionMatrixInverse);vec3 lastViewPos=(prevViewMatrix*vec4(lastWorldPos,1.0)).xyz;vec3 lastViewDir=normalize(lastViewPos);vec3 lastViewNormal=(vec4(lastWorldNormal,0.0)*prevViewMatrix).xyz;float lastViewAngle=dot(-lastViewDir,lastViewNormal);angleMix=abs(lastViewAngle-viewAngle);float viewZ=abs(getViewZ(depth));float distFactor=1.+1./(viewZ+1.0);float disoccl=0.;disoccl+=worldDistanceDisocclusionCheck(worldPos,lastWorldPos,distFactor);disoccl+=planeDistanceDisocclusionCheck(worldPos,lastWorldPos,worldNormal,distFactor);disoccl+=normalDisocclusionCheck(worldNormal,lastWorldNormal,distFactor);float confidence=1.-min(disoccl,1.);confidence=max(confidence,0.);confidence=pow(confidence,confidencePower);return confidence;}vec2 reprojectHitPoint(const vec3 rayOrig,const float rayLength){if(curvature>0.05||rayLength<0.01){return vec2(-1.);}vec3 cameraRay=normalize(rayOrig-cameraPos);vec3 parallaxHitPoint=cameraPos+cameraRay*rayLength;vec4 reprojectedHitPoint=prevProjectionMatrix*prevViewMatrix*vec4(parallaxHitPoint,1.0);reprojectedHitPoint.xyz/=reprojectedHitPoint.w;reprojectedHitPoint.xy=reprojectedHitPoint.xy*0.5+0.5;vec2 diffuseUv=vUv-velocity.xy;float m=min(max(0.,roughness-0.25)/0.25,1.);return reprojectedHitPoint.xy;}vec3 getReprojectedUV(const bool doReprojectSpecular,const float depth,const vec3 worldPos,const vec3 worldNormal){if(doReprojectSpecular){vec2 reprojectedUv=reprojectHitPoint(worldPos,rayLength);float confidence=validateReprojectedUV(reprojectedUv,worldPos,worldNormal,true);return vec3(reprojectedUv,confidence);}else{vec2 reprojectedUv=vUv-velocity;float confidence=validateReprojectedUV(reprojectedUv,worldPos,worldNormal,false);return vec3(reprojectedUv,confidence);}}vec4 BiCubicCatmullRom5Tap(sampler2D tex,vec2 P){vec2 Weight[3];vec2 Sample[3];vec2 UV=P/invTexSize;vec2 tc=floor(UV-0.5)+0.5;vec2 f=UV-tc;vec2 f2=f*f;vec2 f3=f2*f;vec2 w0=f2-0.5*(f3+f);vec2 w1=1.5*f3-2.5*f2+vec2(1.);vec2 w3=0.5*(f3-f2);vec2 w2=vec2(1.)-w0-w1-w3;Weight[0]=w0;Weight[1]=w1+w2;Weight[2]=w3;Sample[0]=tc-vec2(1.);Sample[1]=tc+w2/Weight[1];Sample[2]=tc+vec2(2.);Sample[0]*=invTexSize;Sample[1]*=invTexSize;Sample[2]*=invTexSize;float sampleWeight[5];sampleWeight[0]=Weight[1].x*Weight[0].y;sampleWeight[1]=Weight[0].x*Weight[1].y;sampleWeight[2]=Weight[1].x*Weight[1].y;sampleWeight[3]=Weight[2].x*Weight[1].y;sampleWeight[4]=Weight[1].x*Weight[2].y;vec4 Ct=textureLod(tex,vec2(Sample[1].x,Sample[0].y),0.)*sampleWeight[0];vec4 Cl=textureLod(tex,vec2(Sample[0].x,Sample[1].y),0.)*sampleWeight[1];vec4 Cc=textureLod(tex,vec2(Sample[1].x,Sample[1].y),0.)*sampleWeight[2];vec4 Cr=textureLod(tex,vec2(Sample[2].x,Sample[1].y),0.)*sampleWeight[3];vec4 Cb=textureLod(tex,vec2(Sample[1].x,Sample[2].y),0.)*sampleWeight[4];float WeightMultiplier=1./(sampleWeight[0]+sampleWeight[1]+sampleWeight[2]+sampleWeight[3]+sampleWeight[4]);return max((Ct+Cl+Cc+Cr+Cb)*WeightMultiplier,vec4(0.));}vec4 sampleReprojectedTexture(const sampler2D tex,const vec2 reprojectedUv){vec4 catmull=BiCubicCatmullRom5Tap(tex,reprojectedUv);return catmull;}float getCurvature(vec3 n){float curvature=length(fwidth(n));return curvature;}"; // eslint-disable-line
293
+
294
+ var gbuffer_packing = "#define GLSLIFY 1\nuniform highp sampler2D gBufferTexture;struct Material{highp vec4 diffuse;highp vec3 normal;highp float roughness;highp float metalness;highp vec3 emissive;};\n#define ONE_SAFE 0.999999\n#define NON_ZERO_OFFSET 0.0001\nconst highp float c_precision=256.0;const highp float c_precisionp1=c_precision+1.0;highp float color2float(in highp vec3 color){color=min(color+NON_ZERO_OFFSET,vec3(ONE_SAFE));return floor(color.r*c_precision+0.5)+floor(color.b*c_precision+0.5)*c_precisionp1+floor(color.g*c_precision+0.5)*c_precisionp1*c_precisionp1;}highp vec3 float2color(in highp float value){highp vec3 color;color.r=mod(value,c_precisionp1)/c_precision;color.b=mod(floor(value/c_precisionp1),c_precisionp1)/c_precision;color.g=floor(value/(c_precisionp1*c_precisionp1))/c_precision;color-=NON_ZERO_OFFSET;color=max(color,vec3(0.0));return color;}highp vec2 OctWrap(highp vec2 v){highp vec2 w=1.0-abs(v.yx);if(v.x<0.0)w.x=-w.x;if(v.y<0.0)w.y=-w.y;return w;}highp vec2 encodeOctWrap(highp vec3 n){n/=(abs(n.x)+abs(n.y)+abs(n.z));n.xy=n.z>0.0 ? n.xy : OctWrap(n.xy);n.xy=n.xy*0.5+0.5;return n.xy;}highp vec3 decodeOctWrap(highp vec2 f){f=f*2.0-1.0;highp vec3 n=vec3(f.x,f.y,1.0-abs(f.x)-abs(f.y));highp float t=max(-n.z,0.0);n.x+=n.x>=0.0 ?-t : t;n.y+=n.y>=0.0 ?-t : t;return normalize(n);}highp float packNormal(highp vec3 normal){return uintBitsToFloat(packHalf2x16(encodeOctWrap(normal)));}highp vec3 unpackNormal(highp float packedNormal){return decodeOctWrap(unpackHalf2x16(floatBitsToUint(packedNormal)));}highp vec4 packTwoVec4(highp vec4 v1,highp vec4 v2){highp vec4 encoded=vec4(0.0);v1+=NON_ZERO_OFFSET;v2+=NON_ZERO_OFFSET;highp uint v1r=packHalf2x16(v1.rg);highp uint v1g=packHalf2x16(v1.ba);highp uint v2r=packHalf2x16(v2.rg);highp uint v2g=packHalf2x16(v2.ba);encoded.r=uintBitsToFloat(v1r);encoded.g=uintBitsToFloat(v1g);encoded.b=uintBitsToFloat(v2r);encoded.a=uintBitsToFloat(v2g);return encoded;}void unpackTwoVec4(highp vec4 encoded,out highp vec4 v1,out highp vec4 v2){highp uint r=floatBitsToUint(encoded.r);highp uint g=floatBitsToUint(encoded.g);highp uint b=floatBitsToUint(encoded.b);highp uint a=floatBitsToUint(encoded.a);v1.rg=unpackHalf2x16(r);v1.ba=unpackHalf2x16(g);v2.rg=unpackHalf2x16(b);v2.ba=unpackHalf2x16(a);v1-=NON_ZERO_OFFSET;v2-=NON_ZERO_OFFSET;}vec4 unpackTwoVec4(highp vec4 encoded,const int index){highp uint r=floatBitsToUint(index==0 ? encoded.r : encoded.b);highp uint g=floatBitsToUint(index==0 ? encoded.g : encoded.a);vec4 v;v.rg=unpackHalf2x16(r);v.ba=unpackHalf2x16(g);v-=NON_ZERO_OFFSET;return v;}highp vec4 encodeRGBE8(highp vec3 rgb){highp vec4 vEncoded;highp float maxComponent=max(max(rgb.r,rgb.g),rgb.b);highp float fExp=ceil(log2(maxComponent));vEncoded.rgb=rgb/exp2(fExp);vEncoded.a=(fExp+128.0)/255.0;return vEncoded;}highp vec3 decodeRGBE8(highp vec4 rgbe){highp vec3 vDecoded;highp float fExp=rgbe.a*255.0-128.0;vDecoded=rgbe.rgb*exp2(fExp);return vDecoded;}highp float vec4ToFloat(highp vec4 vec){vec=min(vec+NON_ZERO_OFFSET,vec4(ONE_SAFE));highp uvec4 v=uvec4(vec*255.0);highp uint value=(v.a<<24u)|(v.b<<16u)|(v.g<<8u)|(v.r);return uintBitsToFloat(value);}highp vec4 floatToVec4(highp float f){highp uint value=floatBitsToUint(f);highp vec4 v;v.r=float(value&0xFFu)/255.0;v.g=float((value>>8u)&0xFFu)/255.0;v.b=float((value>>16u)&0xFFu)/255.0;v.a=float((value>>24u)&0xFFu)/255.0;v-=NON_ZERO_OFFSET;v=max(v,vec4(0.0));return v;}highp vec4 packGBuffer(highp vec4 diffuse,highp vec3 normal,highp float roughness,highp float metalness,highp vec3 emissive){highp vec4 gBuffer;gBuffer.r=vec4ToFloat(diffuse);gBuffer.g=packNormal(normal);gBuffer.b=color2float(vec3(roughness,metalness,0.));gBuffer.a=vec4ToFloat(encodeRGBE8(emissive));return gBuffer;}Material getMaterial(highp sampler2D gBufferTexture,highp vec2 uv){highp vec4 gBuffer=textureLod(gBufferTexture,uv,0.0);highp vec4 diffuse=floatToVec4(gBuffer.r);highp vec3 normal=unpackNormal(gBuffer.g);highp vec3 roughnessMetalness=float2color(gBuffer.b);highp float roughness=roughnessMetalness.r;highp float metalness=roughnessMetalness.g;highp vec3 emissive=decodeRGBE8(floatToVec4(gBuffer.a));return Material(diffuse,normal,roughness,metalness,emissive);}Material getMaterial(highp vec2 uv){return getMaterial(gBufferTexture,uv);}highp vec3 getNormal(highp sampler2D gBufferTexture,highp vec2 uv){return unpackNormal(textureLod(gBufferTexture,uv,0.0).g);}"; // eslint-disable-line
295
+
296
+ // source: https://github.com/mrdoob/three.js/blob/b9bc47ab1978022ab0947a9bce1b1209769b8d91/src/renderers/webgl/WebGLProgram.js#L228
297
+ // Unroll Loops
298
+ const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
299
+ function unrollLoops(string) {
300
+ return string.replace(unrollLoopPattern, loopReplacer);
301
+ }
302
+ function loopReplacer(match, start, end, snippet) {
303
+ let string = "";
304
+ for(let i = parseInt(start); i < parseInt(end); i++){
305
+ string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i);
306
+ }
307
+ return string;
308
+ }
309
+
310
+ class TemporalReprojectMaterial extends three.ShaderMaterial {
311
+ constructor(textureCount = 1){
312
+ let finalFragmentShader = fragmentShader.replace("#include <reproject>", reproject).replace("#include <gbuffer_packing>", gbuffer_packing);
313
+ let definitions = "";
314
+ for(let i = 0; i < textureCount; i++){
315
+ definitions += /* glsl */ `
316
+ uniform sampler2D accumulatedTexture${i};
317
+
318
+ layout(location = ${i}) out vec4 gOutput${i};
319
+ `;
320
+ }
321
+ finalFragmentShader = definitions + finalFragmentShader.replaceAll("textureCount", textureCount);
322
+ finalFragmentShader = unrollLoops(finalFragmentShader);
323
+ const matches2 = finalFragmentShader.matchAll(/accumulatedTexture\[\s*[0-9]+\s*]/g);
324
+ for (const [key] of matches2){
325
+ const number = key.replace(/[^0-9]/g, "");
326
+ finalFragmentShader = finalFragmentShader.replace(key, "accumulatedTexture" + number);
327
+ }
328
+ const matches3 = finalFragmentShader.matchAll(/gOutput\[\s*[0-9]+\s*]/g);
329
+ for (const [key] of matches3){
330
+ const number = key.replace(/[^0-9]/g, "");
331
+ finalFragmentShader = finalFragmentShader.replace(key, "gOutput" + number);
332
+ }
333
+ super({
334
+ type: "TemporalReprojectMaterial",
335
+ uniforms: {
336
+ inputTexture: new three.Uniform(null),
337
+ velocityTexture: new three.Uniform(null),
338
+ depthTexture: new three.Uniform(null),
339
+ lastVelocityTexture: new three.Uniform(null),
340
+ neighborhoodClampIntensity: new three.Uniform(0),
341
+ fullAccumulate: new three.Uniform(false),
342
+ keepData: new three.Uniform(1),
343
+ delta: new three.Uniform(0),
344
+ invTexSize: new three.Uniform(new three.Vector2()),
345
+ projectionMatrix: new three.Uniform(new three.Matrix4()),
346
+ projectionMatrixInverse: new three.Uniform(new three.Matrix4()),
347
+ cameraMatrixWorld: new three.Uniform(new three.Matrix4()),
348
+ viewMatrix: new three.Uniform(new three.Matrix4()),
349
+ prevViewMatrix: new three.Uniform(new three.Matrix4()),
350
+ prevCameraMatrixWorld: new three.Uniform(new three.Matrix4()),
351
+ prevProjectionMatrix: new three.Uniform(new three.Matrix4()),
352
+ prevProjectionMatrixInverse: new three.Uniform(new three.Matrix4()),
353
+ cameraPos: new three.Uniform(new three.Vector3()),
354
+ prevCameraPos: new three.Uniform(new three.Vector3()),
355
+ cameraNear: new three.Uniform(0),
356
+ cameraFar: new three.Uniform(0),
357
+ maxBlend: new three.Uniform(0)
358
+ },
359
+ vertexShader,
360
+ fragmentShader: finalFragmentShader,
361
+ blending: three.NoBlending,
362
+ depthWrite: false,
363
+ depthTest: false,
364
+ toneMapped: false,
365
+ glslVersion: three.GLSL3
366
+ });
367
+ for(let i = 0; i < textureCount; i++){
368
+ this.uniforms["inputTexture" + i] = new three.Uniform(null);
369
+ this.uniforms["accumulatedTexture" + i] = new three.Uniform(null);
370
+ }
371
+ }
372
+ }
373
+
374
+ const isGroundProjectedEnv = (c)=>{
375
+ var _c_material_fragmentShader;
376
+ return (_c_material_fragmentShader = c.material.fragmentShader) == null ? void 0 : _c_material_fragmentShader.includes("float intersection2 = diskIntersectWithBackFaceCulling( camPos, p, h, vec3( 0.0, 1.0, 0.0 ), radius );");
377
+ };
378
+ const isChildMaterialRenderable = (c, material = c.material)=>{
379
+ return material.visible && material.depthWrite && material.depthTest && (!material.transparent || material.opacity > 0) && !isGroundProjectedEnv(c);
380
+ };
381
+ const didCameraMove = (camera, lastCameraPosition, lastCameraQuaternion)=>{
382
+ if (camera.position.distanceToSquared(lastCameraPosition) > 0.000001) {
383
+ return true;
384
+ }
385
+ if (camera.quaternion.angleTo(lastCameraQuaternion) > 0.001) {
386
+ return true;
387
+ }
388
+ return false;
389
+ };
390
+ const getVisibleChildren = (object)=>{
391
+ const queue = [
392
+ object
393
+ ];
394
+ const objects = [];
395
+ while(queue.length !== 0){
396
+ const mesh = queue.shift();
397
+ if (mesh.material) objects.push(mesh);
398
+ for (const c of mesh.children){
399
+ if (c.visible) queue.push(c);
400
+ }
401
+ }
402
+ return objects;
403
+ };
404
+
405
+ const defaultTemporalReprojectPassOptions = {
406
+ dilation: false,
407
+ fullAccumulate: false,
408
+ neighborhoodClamp: false,
409
+ neighborhoodClampRadius: 1,
410
+ neighborhoodClampIntensity: 1,
411
+ maxBlend: 1,
412
+ logTransform: false,
413
+ depthDistance: 2,
414
+ worldDistance: 4,
415
+ reprojectSpecular: false,
416
+ renderTarget: null,
417
+ copyTextures: true,
418
+ confidencePower: 0.75,
419
+ inputType: "diffuse"
420
+ };
421
+ const tmpProjectionMatrix$1 = new three.Matrix4();
422
+ const tmpProjectionMatrixInverse$1 = new three.Matrix4();
423
+ const tmpVec2 = new three.Vector2();
424
+ class TemporalReprojectPass extends postprocessing.Pass {
425
+ setInputTexture(texture) {
426
+ this.fullscreenMaterial.uniforms.inputTexture.value = texture;
427
+ }
428
+ dispose() {
429
+ super.dispose();
430
+ this.renderTarget.dispose();
431
+ this.fullscreenMaterial.dispose();
432
+ }
433
+ setSize(width, height) {
434
+ var _this_framebufferTexture;
435
+ this.renderTarget.setSize(width, height);
436
+ this.fullscreenMaterial.uniforms.invTexSize.value.set(1 / width, 1 / height);
437
+ (_this_framebufferTexture = this.framebufferTexture) == null ? void 0 : _this_framebufferTexture.dispose();
438
+ const inputTexture = this.fullscreenMaterial.uniforms.inputTexture.value;
439
+ this.framebufferTexture = new three.FramebufferTexture(width, height, inputTexture.format);
440
+ this.framebufferTexture.type = inputTexture.type;
441
+ this.framebufferTexture.minFilter = three.LinearFilter;
442
+ this.framebufferTexture.magFilter = three.LinearFilter;
443
+ this.framebufferTexture.needsUpdate = true;
444
+ for(let i = 0; i < this.textureCount; i++){
445
+ var _this_overrideAccumulatedTextures_i;
446
+ const accumulatedTexture = (_this_overrideAccumulatedTextures_i = this.overrideAccumulatedTextures[i]) != null ? _this_overrideAccumulatedTextures_i : this.framebufferTexture;
447
+ this.fullscreenMaterial.uniforms["accumulatedTexture" + i].value = accumulatedTexture;
448
+ }
449
+ }
450
+ get texture() {
451
+ return this.renderTarget.texture;
452
+ }
453
+ reset() {
454
+ this.fullscreenMaterial.uniforms.keepData.value = 0;
455
+ }
456
+ render(renderer) {
457
+ this.frame = (this.frame + 1) % 4096;
458
+ const delta = Math.min(1 / 10, this.clock.getDelta());
459
+ this.fullscreenMaterial.uniforms.delta.value = delta;
460
+ tmpProjectionMatrix$1.copy(this._camera.projectionMatrix);
461
+ tmpProjectionMatrixInverse$1.copy(this._camera.projectionMatrixInverse);
462
+ if (this._camera.view) this._camera.view.enabled = false;
463
+ this._camera.updateProjectionMatrix();
464
+ this.fullscreenMaterial.uniforms.projectionMatrix.value.copy(this._camera.projectionMatrix);
465
+ this.fullscreenMaterial.uniforms.projectionMatrixInverse.value.copy(this._camera.projectionMatrixInverse);
466
+ this.fullscreenMaterial.uniforms.lastVelocityTexture.value = this.velocityDepthNormalPass.lastVelocityTexture;
467
+ this.fullscreenMaterial.uniforms.fullAccumulate.value = this.options.fullAccumulate && !didCameraMove(this._camera, this.lastCameraTransform.position, this.lastCameraTransform.quaternion);
468
+ this.lastCameraTransform.position.copy(this._camera.position);
469
+ this.lastCameraTransform.quaternion.copy(this._camera.quaternion);
470
+ if (this._camera.view) this._camera.view.enabled = true;
471
+ this._camera.projectionMatrix.copy(tmpProjectionMatrix$1);
472
+ this._camera.projectionMatrixInverse.copy(tmpProjectionMatrixInverse$1);
473
+ this.fullscreenMaterial.uniforms.cameraNear.value = this._camera.near;
474
+ this.fullscreenMaterial.uniforms.cameraFar.value = this._camera.far;
475
+ renderer.setRenderTarget(this.renderTarget);
476
+ renderer.render(this.scene, this.camera);
477
+ this.fullscreenMaterial.uniforms.keepData.value = 1;
478
+ if (this.overrideAccumulatedTextures.length === 0) {
479
+ this.framebufferTexture.needsUpdate = true;
480
+ renderer.copyFramebufferToTexture(tmpVec2, this.framebufferTexture);
481
+ }
482
+ // save last transformations
483
+ this.fullscreenMaterial.uniforms.prevCameraMatrixWorld.value.copy(this._camera.matrixWorld);
484
+ this.fullscreenMaterial.uniforms.prevViewMatrix.value.copy(this._camera.matrixWorldInverse);
485
+ this.fullscreenMaterial.uniforms.prevProjectionMatrix.value.copy(this.fullscreenMaterial.uniforms.projectionMatrix.value);
486
+ this.fullscreenMaterial.uniforms.prevProjectionMatrixInverse.value.copy(this.fullscreenMaterial.uniforms.projectionMatrixInverse.value);
487
+ this.fullscreenMaterial.uniforms.prevCameraPos.value.copy(this._camera.position);
488
+ }
489
+ jitter(jitterScale = 1) {
490
+ this.unjitter();
491
+ jitter(this.renderTarget.width, this.renderTarget.height, this._camera, this.frame, jitterScale);
492
+ }
493
+ unjitter() {
494
+ if (this._camera.clearViewOffset) this._camera.clearViewOffset();
495
+ }
496
+ constructor(scene, camera, velocityDepthNormalPass, texture, textureCount, options = defaultTemporalReprojectPassOptions){
497
+ super("TemporalReprojectPass");
498
+ this.needsSwap = false;
499
+ this.overrideAccumulatedTextures = [];
500
+ this.clock = new three.Clock();
501
+ this.r2Sequence = [];
502
+ this.frame = 0;
503
+ this.lastCameraTransform = {
504
+ position: new three.Vector3(),
505
+ quaternion: new three.Quaternion()
506
+ };
507
+ this._scene = scene;
508
+ this._camera = camera;
509
+ this.textureCount = textureCount;
510
+ options = _extends({}, defaultTemporalReprojectPassOptions, options);
511
+ this.renderTarget = new three.WebGLRenderTarget(1, 1, {
512
+ count: textureCount,
513
+ minFilter: three.NearestFilter,
514
+ magFilter: three.NearestFilter,
515
+ type: texture.type,
516
+ depthBuffer: false
517
+ });
518
+ this.renderTarget.textures.forEach((texture, index)=>texture.name = "TemporalReprojectPass.accumulatedTexture" + index);
519
+ this.fullscreenMaterial = new TemporalReprojectMaterial(textureCount);
520
+ this.fullscreenMaterial.defines.textureCount = textureCount;
521
+ if (options.dilation) this.fullscreenMaterial.defines.dilation = "";
522
+ if (options.neighborhoodClamp) this.fullscreenMaterial.defines.neighborhoodClamp = "";
523
+ if (options.logTransform) this.fullscreenMaterial.defines.logTransform = "";
524
+ if (camera.isPerspectiveCamera) this.fullscreenMaterial.defines.PERSPECTIVE_CAMERA = "";
525
+ this.fullscreenMaterial.defines.neighborhoodClampRadius = parseInt(options.neighborhoodClampRadius);
526
+ this.fullscreenMaterial.defines.depthDistance = options.depthDistance.toPrecision(5);
527
+ this.fullscreenMaterial.defines.worldDistance = options.worldDistance.toPrecision(5);
528
+ this.fullscreenMaterial.uniforms.fullAccumulate.value = options.fullAccumulate;
529
+ this.fullscreenMaterial.uniforms.neighborhoodClampIntensity.value = options.neighborhoodClampIntensity;
530
+ this.fullscreenMaterial.uniforms.maxBlend.value = options.maxBlend;
531
+ this.fullscreenMaterial.uniforms.projectionMatrix.value = camera.projectionMatrix.clone();
532
+ this.fullscreenMaterial.uniforms.projectionMatrixInverse.value = camera.projectionMatrixInverse.clone();
533
+ this.fullscreenMaterial.uniforms.cameraMatrixWorld.value = camera.matrixWorld;
534
+ this.fullscreenMaterial.uniforms.viewMatrix.value = camera.matrixWorldInverse;
535
+ this.fullscreenMaterial.uniforms.cameraPos.value = camera.position;
536
+ this.fullscreenMaterial.uniforms.prevViewMatrix.value = camera.matrixWorldInverse.clone();
537
+ this.fullscreenMaterial.uniforms.prevCameraMatrixWorld.value = camera.matrixWorld.clone();
538
+ this.fullscreenMaterial.uniforms.prevProjectionMatrix.value = camera.projectionMatrix.clone();
539
+ this.fullscreenMaterial.uniforms.prevProjectionMatrixInverse.value = camera.projectionMatrixInverse.clone();
540
+ this.fullscreenMaterial.uniforms.velocityTexture.value = velocityDepthNormalPass.renderTarget.texture;
541
+ this.fullscreenMaterial.uniforms.depthTexture.value = velocityDepthNormalPass.depthTexture;
542
+ var _indexOf;
543
+ this.fullscreenMaterial.defines.inputType = (_indexOf = [
544
+ "diffuseSpecular",
545
+ "diffuse",
546
+ "specular"
547
+ ].indexOf(options.inputType)) != null ? _indexOf : 1;
548
+ for (const opt of [
549
+ "reprojectSpecular",
550
+ "neighborhoodClamp"
551
+ ]){
552
+ let value = options[opt];
553
+ if (typeof value !== "array") value = Array(textureCount).fill(value);
554
+ this.fullscreenMaterial.defines[opt] = /* glsl */ `bool[](${value.join(", ")})`;
555
+ }
556
+ this.fullscreenMaterial.defines.confidencePower = options.confidencePower.toPrecision(5);
557
+ this.options = options;
558
+ this.velocityDepthNormalPass = velocityDepthNormalPass;
559
+ this.fullscreenMaterial.uniforms.inputTexture.value = texture;
560
+ }
561
+ }
562
+
563
+ var traa_compose = "#define GLSLIFY 1\nuniform sampler2D accumulatedTexture;void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor){vec4 accumulatedTexel=textureLod(accumulatedTexture,uv,0.);outputColor=vec4(accumulatedTexel.rgb,1.);}"; // eslint-disable-line
564
+
565
+ class TRAAEffect extends postprocessing.Effect {
566
+ setSize(width, height) {
567
+ var _this_temporalReprojectPass;
568
+ (_this_temporalReprojectPass = this.temporalReprojectPass) == null ? void 0 : _this_temporalReprojectPass.setSize(width, height);
569
+ }
570
+ dispose() {
571
+ super.dispose();
572
+ this.temporalReprojectPass.dispose();
573
+ }
574
+ reset() {
575
+ this.temporalReprojectPass.reset();
576
+ }
577
+ update(renderer, inputBuffer) {
578
+ if (!this.temporalReprojectPass) {
579
+ this.temporalReprojectPass = new TemporalReprojectPass(this._scene, this._camera, this.velocityDepthNormalPass, inputBuffer.texture, 1, this.options);
580
+ this.temporalReprojectPass.setSize(inputBuffer.width, inputBuffer.height);
581
+ this.uniforms.get("accumulatedTexture").value = this.temporalReprojectPass.texture;
582
+ }
583
+ this.temporalReprojectPass.setInputTexture(inputBuffer.texture);
584
+ this.temporalReprojectPass.unjitter();
585
+ this.unjitteredProjectionMatrix = this._camera.projectionMatrix.clone();
586
+ this._camera.projectionMatrix.copy(this.unjitteredProjectionMatrix);
587
+ this.temporalReprojectPass.jitter();
588
+ this.temporalReprojectPass.render(renderer);
589
+ }
590
+ constructor(scene, camera, velocityDepthNormalPass, options = defaultTemporalReprojectPassOptions){
591
+ super("TRAAEffect", traa_compose, {
592
+ type: "FinalTRAAEffectMaterial",
593
+ uniforms: new Map([
594
+ [
595
+ "accumulatedTexture",
596
+ new three.Uniform(null)
597
+ ]
598
+ ])
599
+ });
600
+ this._scene = scene;
601
+ this._camera = camera;
602
+ this.velocityDepthNormalPass = velocityDepthNormalPass;
603
+ options = _extends({}, options, {
604
+ maxBlend: 0.9,
605
+ neighborhoodClamp: true,
606
+ neighborhoodClampIntensity: 1,
607
+ neighborhoodClampRadius: 1,
608
+ logTransform: true,
609
+ confidencePower: 4
610
+ });
611
+ this.options = _extends({}, defaultTemporalReprojectPassOptions, options);
612
+ this.setSize(options.width, options.height);
613
+ }
614
+ }
615
+
616
+ // this shader is from: https://github.com/gkjohnson/threejs-sandbox
617
+ // Modified ShaderChunk.skinning_pars_vertex to handle
618
+ // a second set of bone information from the previous frame
619
+ const prev_skinning_pars_vertex = /* glsl */ `
620
+ #ifdef USE_SKINNING
621
+ #ifdef BONE_TEXTURE
622
+ uniform sampler2D prevBoneTexture;
623
+ mat4 getPrevBoneMatrix( const in float i ) {
624
+ float j = i * 4.0;
625
+ float x = mod( j, float( boneTextureSize ) );
626
+ float y = floor( j / float( boneTextureSize ) );
627
+ float dx = 1.0 / float( boneTextureSize );
628
+ float dy = 1.0 / float( boneTextureSize );
629
+ y = dy * ( y + 0.5 );
630
+ vec4 v1 = textureLod( prevBoneTexture, vec2( dx * ( x + 0.5 ), y ), 0. );
631
+ vec4 v2 = textureLod( prevBoneTexture, vec2( dx * ( x + 1.5 ), y ), 0. );
632
+ vec4 v3 = textureLod( prevBoneTexture, vec2( dx * ( x + 2.5 ), y ), 0. );
633
+ vec4 v4 = textureLod( prevBoneTexture, vec2( dx * ( x + 3.5 ), y ), 0. );
634
+ mat4 bone = mat4( v1, v2, v3, v4 );
635
+ return bone;
636
+ }
637
+ #else
638
+ uniform mat4 prevBoneMatrices[ MAX_BONES ];
639
+ mat4 getPrevBoneMatrix( const in float i ) {
640
+ mat4 bone = prevBoneMatrices[ int(i) ];
641
+ return bone;
642
+ }
643
+ #endif
644
+ #endif
645
+ `;
646
+ const velocity_vertex_pars = /* glsl */ `
647
+ #define MAX_BONES 64
648
+
649
+ ${three.ShaderChunk.skinning_pars_vertex}
650
+ ${prev_skinning_pars_vertex}
651
+
652
+ uniform mat4 velocityMatrix;
653
+ uniform mat4 prevVelocityMatrix;
654
+ varying vec4 prevPosition;
655
+ varying vec4 newPosition;
656
+
657
+ varying vec2 vHighPrecisionZW;
658
+ `;
659
+ // Returns the body of the vertex shader for the velocity buffer
660
+ const velocity_vertex_main = /* glsl */ `
661
+ // Get the current vertex position
662
+ transformed = vec3( position );
663
+ ${three.ShaderChunk.skinning_vertex}
664
+ newPosition = velocityMatrix * vec4( transformed, 1.0 );
665
+
666
+ // Get the previous vertex position
667
+ transformed = vec3( position );
668
+ ${three.ShaderChunk.skinbase_vertex.replace(/mat4 /g, "").replace(/getBoneMatrix/g, "getPrevBoneMatrix")}
669
+ ${three.ShaderChunk.skinning_vertex.replace(/vec4 /g, "")}
670
+ prevPosition = prevVelocityMatrix * vec4( transformed, 1.0 );
671
+
672
+ gl_Position = newPosition;
673
+
674
+ vHighPrecisionZW = gl_Position.zw;
675
+ `;
676
+ const velocity_fragment_pars = /* glsl */ `
677
+ varying vec4 prevPosition;
678
+ varying vec4 newPosition;
679
+
680
+ varying vec2 vHighPrecisionZW;
681
+ `;
682
+ const velocity_fragment_main = /* glsl */ `
683
+ vec2 pos0 = (prevPosition.xy / prevPosition.w) * 0.5 + 0.5;
684
+ vec2 pos1 = (newPosition.xy / newPosition.w) * 0.5 + 0.5;
685
+
686
+ vec2 vel = pos1 - pos0;
687
+
688
+ float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
689
+
690
+ gl_FragColor = vec4(vel.x, vel.y, 0., 0.);
691
+ `;
692
+ const velocity_uniforms = {
693
+ prevVelocityMatrix: {
694
+ value: new three.Matrix4()
695
+ },
696
+ velocityMatrix: {
697
+ value: new three.Matrix4()
698
+ },
699
+ prevBoneTexture: {
700
+ value: null
701
+ },
702
+ boneTexture: {
703
+ value: null
704
+ },
705
+ normalMap: {
706
+ value: null
707
+ },
708
+ normalScale: {
709
+ value: new three.Vector2(1, 1)
710
+ },
711
+ uvTransform: {
712
+ value: new three.Matrix3()
713
+ }
714
+ };
715
+ class VelocityDepthNormalMaterial extends three.ShaderMaterial {
716
+ constructor(camera){
717
+ super({
718
+ uniforms: _extends({}, three.UniformsUtils.clone(velocity_uniforms), {
719
+ cameraMatrixWorld: {
720
+ value: camera.matrixWorld
721
+ }
722
+ }),
723
+ vertexShader: /* glsl */ `
724
+ #include <common>
725
+ #include <uv_pars_vertex>
726
+ #include <displacementmap_pars_vertex>
727
+ #include <normal_pars_vertex>
728
+ #include <morphtarget_pars_vertex>
729
+ #include <logdepthbuf_pars_vertex>
730
+ #include <clipping_planes_pars_vertex>
731
+
732
+ varying vec2 vUv;
733
+
734
+ varying vec3 vViewPosition;
735
+
736
+ ${velocity_vertex_pars}
737
+
738
+ void main() {
739
+ vec3 transformed;
740
+
741
+ #include <uv_vertex>
742
+
743
+ #include <skinbase_vertex>
744
+ #include <beginnormal_vertex>
745
+ #include <skinnormal_vertex>
746
+ #include <defaultnormal_vertex>
747
+
748
+ #include <morphnormal_vertex>
749
+ #include <normal_vertex>
750
+ #include <morphtarget_vertex>
751
+ #include <displacementmap_vertex>
752
+ #include <project_vertex>
753
+ #include <logdepthbuf_vertex>
754
+ #include <clipping_planes_vertex>
755
+
756
+ ${velocity_vertex_main}
757
+
758
+ vViewPosition = - mvPosition.xyz;
759
+
760
+ vUv = uv;
761
+
762
+ }`,
763
+ fragmentShader: /* glsl */ `
764
+ precision highp float;
765
+ uniform mat4 cameraMatrixWorld;
766
+
767
+ varying vec3 vViewPosition;
768
+
769
+ ${velocity_fragment_pars}
770
+ #include <packing>
771
+
772
+ #include <uv_pars_fragment>
773
+ #include <normal_pars_fragment>
774
+ #include <normalmap_pars_fragment>
775
+
776
+ varying vec2 vUv;
777
+
778
+ // source: https://knarkowicz.wordpress.com/2014/04/16/octahedron-normal-vector-encoding/
779
+ vec2 OctWrap( vec2 v ) {
780
+ vec2 w = 1.0 - abs( v.yx );
781
+ if (v.x < 0.0) w.x = -w.x;
782
+ if (v.y < 0.0) w.y = -w.y;
783
+ return w;
784
+ }
785
+
786
+ vec2 encodeOctWrap(vec3 n) {
787
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
788
+ n.xy = n.z > 0.0 ? n.xy : OctWrap(n.xy);
789
+ n.xy = n.xy * 0.5 + 0.5;
790
+ return n.xy;
791
+ }
792
+
793
+ float packNormal(vec3 normal) {
794
+ return uintBitsToFloat(packHalf2x16(encodeOctWrap(normal)));
795
+ }
796
+
797
+ void main() {
798
+ #define vNormalMapUv vUv
799
+
800
+ #include <normal_fragment_begin>
801
+ #include <normal_fragment_maps>
802
+
803
+ ${velocity_fragment_main}
804
+ vec3 worldNormal = normalize((cameraMatrixWorld * vec4(normal, 0.)).xyz);
805
+ gl_FragColor.b = packNormal(worldNormal);
806
+ gl_FragColor.a = fragCoordZ;
807
+ }`
808
+ });
809
+ }
810
+ }
811
+
812
+ const materialProps = [
813
+ "vertexTangent",
814
+ "vertexColors",
815
+ "vertexAlphas",
816
+ "vertexUvs",
817
+ "uvsVertexOnly",
818
+ "supportsVertexTextures",
819
+ "instancing",
820
+ "instancingColor",
821
+ "side",
822
+ "flatShading",
823
+ "skinning",
824
+ "doubleSided",
825
+ "flipSided"
826
+ ];
827
+ const copyNecessaryProps = (originalMaterial, newMaterial)=>{
828
+ for (const props of materialProps)newMaterial[props] = originalMaterial[props];
829
+ };
830
+ const keepMaterialMapUpdated = (mrtMaterial, originalMaterial, prop, define, useKey)=>{
831
+ {
832
+ if (originalMaterial[prop] !== mrtMaterial[prop]) {
833
+ mrtMaterial[prop] = originalMaterial[prop];
834
+ mrtMaterial.uniforms[prop].value = originalMaterial[prop];
835
+ if (originalMaterial[prop]) {
836
+ mrtMaterial.defines[define] = "";
837
+ } else {
838
+ delete mrtMaterial.defines[define];
839
+ }
840
+ mrtMaterial.needsUpdate = true;
841
+ }
842
+ }
843
+ };
844
+
845
+ const backgroundColor = new three.Color(0);
846
+ const zeroVec2 = new three.Vector2();
847
+ const tmpProjectionMatrix = new three.Matrix4();
848
+ const tmpProjectionMatrixInverse = new three.Matrix4();
849
+ const saveBoneTexture = (object, floatType)=>{
850
+ let boneTexture = object.material.uniforms.prevBoneTexture.value;
851
+ if (boneTexture && boneTexture.image.width === object.skeleton.boneTexture.width) {
852
+ boneTexture = object.material.uniforms.prevBoneTexture.value;
853
+ boneTexture.image.data.set(object.skeleton.boneTexture.image.data);
854
+ } else {
855
+ boneTexture == null ? void 0 : boneTexture.dispose();
856
+ const boneMatrices = object.skeleton.boneTexture.image.data.slice();
857
+ const size = object.skeleton.boneTexture.image.width;
858
+ boneTexture = new three.DataTexture(boneMatrices, size, size, three.RGBAFormat, floatType);
859
+ object.material.uniforms.prevBoneTexture.value = boneTexture;
860
+ boneTexture.needsUpdate = true;
861
+ }
862
+ };
863
+ const updateVelocityDepthNormalMaterialBeforeRender = (c, camera)=>{
864
+ var _c_skeleton;
865
+ if ((_c_skeleton = c.skeleton) == null ? void 0 : _c_skeleton.boneTexture) {
866
+ c.material.uniforms.boneTexture.value = c.skeleton.boneTexture;
867
+ if (!("USE_SKINNING" in c.material.defines)) {
868
+ c.material.defines.USE_SKINNING = "";
869
+ c.material.defines.BONE_TEXTURE = "";
870
+ c.material.needsUpdate = true;
871
+ }
872
+ }
873
+ c.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, c.matrixWorld);
874
+ c.material.uniforms.velocityMatrix.value.multiplyMatrices(camera.projectionMatrix, c.modelViewMatrix);
875
+ };
876
+ const updateVelocityDepthNormalMaterialAfterRender = (c, camera, floatType)=>{
877
+ var _c_skeleton;
878
+ c.material.uniforms.prevVelocityMatrix.value.multiplyMatrices(camera.projectionMatrix, c.modelViewMatrix);
879
+ if ((_c_skeleton = c.skeleton) == null ? void 0 : _c_skeleton.boneTexture) saveBoneTexture(c, floatType);
880
+ };
881
+ class VelocityDepthNormalPass extends postprocessing.Pass {
882
+ get texture() {
883
+ return this.renderTarget.texture;
884
+ }
885
+ setVelocityDepthNormalMaterialInScene() {
886
+ this.visibleMeshes = getVisibleChildren(this._scene);
887
+ for (const c of this.visibleMeshes){
888
+ const originalMaterial = c.material;
889
+ let [cachedOriginalMaterial, velocityDepthNormalMaterial] = this.cachedMaterials.get(c) || [];
890
+ if (originalMaterial !== cachedOriginalMaterial) {
891
+ var _c_skeleton;
892
+ velocityDepthNormalMaterial = new VelocityDepthNormalMaterial(this._camera);
893
+ copyNecessaryProps(originalMaterial, velocityDepthNormalMaterial);
894
+ c.material = velocityDepthNormalMaterial;
895
+ if ((_c_skeleton = c.skeleton) == null ? void 0 : _c_skeleton.boneTexture) saveBoneTexture(c, this._floatType);
896
+ this.cachedMaterials.set(c, [
897
+ originalMaterial,
898
+ velocityDepthNormalMaterial
899
+ ]);
900
+ }
901
+ c.material = velocityDepthNormalMaterial;
902
+ c.visible = isChildMaterialRenderable(c, originalMaterial);
903
+ keepMaterialMapUpdated(velocityDepthNormalMaterial, originalMaterial, "normalMap", "USE_NORMALMAP_TANGENTSPACE");
904
+ velocityDepthNormalMaterial.uniforms.normalMap.value = originalMaterial.normalMap;
905
+ const map = originalMaterial.map || originalMaterial.normalMap || originalMaterial.roughnessMap || originalMaterial.metalnessMap;
906
+ if (map) velocityDepthNormalMaterial.uniforms.uvTransform.value = map.matrix;
907
+ updateVelocityDepthNormalMaterialBeforeRender(c, this._camera);
908
+ }
909
+ }
910
+ unsetVelocityDepthNormalMaterialInScene() {
911
+ for (const c of this.visibleMeshes){
912
+ c.visible = true;
913
+ updateVelocityDepthNormalMaterialAfterRender(c, this._camera, this._floatType);
914
+ c.material = this.cachedMaterials.get(c)[0];
915
+ }
916
+ }
917
+ setSize(width, height) {
918
+ var _this_lastVelocityTexture;
919
+ this.renderTarget.setSize(width, height);
920
+ (_this_lastVelocityTexture = this.lastVelocityTexture) == null ? void 0 : _this_lastVelocityTexture.dispose();
921
+ this.lastVelocityTexture = new three.FramebufferTexture(width, height, three.RGBAFormat);
922
+ this.lastVelocityTexture.type = this._floatType;
923
+ this.lastVelocityTexture.minFilter = three.NearestFilter;
924
+ this.lastVelocityTexture.magFilter = three.NearestFilter;
925
+ }
926
+ dispose() {
927
+ super.dispose();
928
+ this.renderTarget.dispose();
929
+ }
930
+ render(renderer) {
931
+ tmpProjectionMatrix.copy(this._camera.projectionMatrix);
932
+ tmpProjectionMatrixInverse.copy(this._camera.projectionMatrixInverse);
933
+ if (this._camera.view) this._camera.view.enabled = false;
934
+ this._camera.updateProjectionMatrix();
935
+ // in case a RenderPass is not being used, so we need to update the camera's world matrix manually
936
+ this._camera.updateMatrixWorld();
937
+ this.setVelocityDepthNormalMaterialInScene();
938
+ const { background } = this._scene;
939
+ this._scene.background = backgroundColor;
940
+ renderer.setRenderTarget(this.renderTarget);
941
+ renderer.copyFramebufferToTexture(zeroVec2, this.lastVelocityTexture);
942
+ renderer.render(this._scene, this._camera);
943
+ this._scene.background = background;
944
+ this.unsetVelocityDepthNormalMaterialInScene();
945
+ if (this._camera.view) this._camera.view.enabled = true;
946
+ this._camera.projectionMatrix.copy(tmpProjectionMatrix);
947
+ this._camera.projectionMatrixInverse.copy(tmpProjectionMatrixInverse);
948
+ }
949
+ constructor(scene, camera, floatType = three.HalfFloatType){
950
+ super("VelocityDepthNormalPass");
951
+ this.cachedMaterials = new WeakMap();
952
+ this.visibleMeshes = [];
953
+ this.needsSwap = false;
954
+ this._scene = scene;
955
+ this._camera = camera;
956
+ this._floatType = floatType;
957
+ this.renderTarget = new three.WebGLRenderTarget(1, 1, {
958
+ type: floatType,
959
+ minFilter: three.NearestFilter,
960
+ magFilter: three.NearestFilter
961
+ });
962
+ this.renderTarget.texture.name = "VelocityDepthNormalPass.Texture";
963
+ this.renderTarget.depthTexture = new three.DepthTexture(1, 1);
964
+ this.renderTarget.depthTexture.type = floatType;
965
+ }
966
+ }
967
+
968
+ function getVelocityDepthNormalPass(viewer, autoAdd = true) {
969
+ const composer = EffectComposerPlugin.Instance(viewer);
970
+ let vdnPass = composer.getPass(VelocityDepthNormalPass);
971
+ if (vdnPass === undefined && autoAdd) {
972
+ vdnPass = composer.addPass(new VelocityDepthNormalPass(viewer.scene, viewer.camera));
973
+ }
974
+ return vdnPass;
975
+ }
976
+
977
+ class TRAAPlugin extends PassPlugin {
978
+ constructor(props = {}){
979
+ super();
980
+ this.type = "TRAAPlugin";
981
+ this.install = ()=>{
982
+ const { scene, camera } = this.viewer;
983
+ this._effect = new TRAAEffect(scene, camera, getVelocityDepthNormalPass(this.viewer), props);
984
+ this.pass = this.composer.addPass(new postprocessing.EffectPass(camera, this._effect));
985
+ };
986
+ this.uninstall = ()=>{
987
+ this.composer.removePass(this.pass);
988
+ };
989
+ }
990
+ }
991
+ core.PropertyManager._getClassProperties("TRAAPlugin").property("enable");
283
992
 
284
993
  exports.BloomPlugin = BloomPlugin;
285
994
  exports.EffectComposerPlugin = EffectComposerPlugin;
286
995
  exports.FXAAPlugin = FXAAPlugin;
287
996
  exports.MSAAPlugin = MSAAPlugin;
288
997
  exports.SMAAPlugin = SMAAPlugin;
998
+ exports.TRAAPlugin = TRAAPlugin;
289
999
  exports.ToneMappingPlugin = ToneMappingPlugin;
290
1000
  //# sourceMappingURL=main.js.map