@threepipe/webgi-plugins 0.6.3 → 0.7.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.
Files changed (110) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +13 -23
  3. package/THIRD_PARTY_NOTICES.md +243 -0
  4. package/dist/dependencies.txt +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +4537 -19
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +4546 -19
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/plugins/buffer/VelocityBufferPlugin.d.ts.map +1 -1
  11. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts +3 -2
  12. package/dist/plugins/extras/AdvancedGroundPlugin.d.ts.map +1 -1
  13. package/dist/plugins/extras/AnisotropyPlugin.d.ts.map +1 -1
  14. package/dist/plugins/extras/WatchHandsPlugin.d.ts.map +1 -1
  15. package/dist/plugins/index.d.ts +24 -24
  16. package/dist/plugins/postprocessing/SSGIPlugin.d.ts +3 -2
  17. package/dist/plugins/postprocessing/SSGIPlugin.d.ts.map +1 -1
  18. package/dist/plugins/postprocessing/SSReflectionPlugin.d.ts +1 -1
  19. package/dist/utils/ShadowMapBaker.d.ts +1 -1
  20. package/dist/utils/ShadowMapBaker.d.ts.map +1 -1
  21. package/docs/assets/hierarchy.js +1 -0
  22. package/docs/assets/highlight.css +22 -0
  23. package/docs/assets/icons.js +18 -0
  24. package/docs/assets/icons.svg +1 -0
  25. package/docs/assets/main.js +60 -0
  26. package/docs/assets/navigation.js +1 -0
  27. package/docs/assets/search.js +1 -0
  28. package/docs/assets/style.css +1633 -0
  29. package/docs/classes/AdvancedGroundPlugin.html +69 -0
  30. package/docs/classes/AnisotropyPlugin.html +40 -0
  31. package/docs/classes/BloomPlugin.html +37 -0
  32. package/docs/classes/BloomPluginPass.html +34 -0
  33. package/docs/classes/DepthOfFieldPlugin.html +41 -0
  34. package/docs/classes/DepthOfFieldPluginPass.html +37 -0
  35. package/docs/classes/OutlinePlugin.html +75 -0
  36. package/docs/classes/OutlineRenderPass.html +25 -0
  37. package/docs/classes/SSContactShadowsPlugin.html +37 -0
  38. package/docs/classes/SSGIPlugin.html +42 -0
  39. package/docs/classes/SSGIPluginPass.html +44 -0
  40. package/docs/classes/SSReflectionPlugin.html +43 -0
  41. package/docs/classes/SSReflectionPluginPass.html +45 -0
  42. package/docs/classes/SSVelocityMaterial.html +7 -0
  43. package/docs/classes/TemporalAAPlugin.html +37 -0
  44. package/docs/classes/TemporalAAPluginPass.html +33 -0
  45. package/docs/classes/VelocityBufferPlugin.html +41 -0
  46. package/docs/classes/WatchHandsPlugin.html +39 -0
  47. package/docs/hierarchy.html +1 -0
  48. package/docs/index.html +1 -0
  49. package/docs/types/OutlinePluginPass.html +1 -0
  50. package/docs/types/OutlinePluginTarget.html +1 -0
  51. package/docs/types/SSGIPluginTarget.html +1 -0
  52. package/docs/types/SSReflectionPluginTarget.html +1 -0
  53. package/docs/types/VelocityBufferPluginPass.html +1 -0
  54. package/docs/types/VelocityBufferPluginTarget.html +1 -0
  55. package/docs/variables/anisotropyGLTFExtension.html +1 -0
  56. package/docs/variables/webgiPlugins.html +1 -0
  57. package/package.json +23 -22
  58. package/src/global.d.ts +27 -0
  59. package/src/index.ts +1 -0
  60. package/src/passes/BilateralFilterPass.ts +62 -0
  61. package/src/passes/shaders/ssaoBilateral.glsl +89 -0
  62. package/src/plugins/buffer/VelocityBufferPlugin.ts +270 -0
  63. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.frag.glsl +46 -0
  64. package/src/plugins/buffer/shaders/VelocityBufferPlugin.mat.vert.glsl +51 -0
  65. package/src/plugins/buffer/shaders/VelocityBufferPlugin.unpack.glsl +8 -0
  66. package/src/plugins/extras/AdvancedGroundPlugin.ts +385 -0
  67. package/src/plugins/extras/AnisotropyPlugin.ts +519 -0
  68. package/src/plugins/extras/WatchHandsPlugin.ts +156 -0
  69. package/src/plugins/extras/shaders/anisotropyBsdf.glsl +64 -0
  70. package/src/plugins/extras/shaders/anisotropyTBN.glsl +35 -0
  71. package/src/plugins/index.ts +38 -0
  72. package/src/plugins/postprocessing/BloomPlugin.ts +374 -0
  73. package/src/plugins/postprocessing/DepthOfFieldPlugin.ts +470 -0
  74. package/src/plugins/postprocessing/OutlinePlugin.ts +476 -0
  75. package/src/plugins/postprocessing/SSContactShadowsPlugin.ts +374 -0
  76. package/src/plugins/postprocessing/SSGIPlugin.ts +597 -0
  77. package/src/plugins/postprocessing/SSReflectionPlugin.ts +563 -0
  78. package/src/plugins/postprocessing/TemporalAAPlugin.ts +301 -0
  79. package/src/plugins/postprocessing/shaders/dofBlurBox.glsl +46 -0
  80. package/src/plugins/postprocessing/shaders/dofCombine.glsl +68 -0
  81. package/src/plugins/postprocessing/shaders/dofComputeCoC.glsl +21 -0
  82. package/src/plugins/postprocessing/shaders/dofExpandCoC.glsl +56 -0
  83. package/src/plugins/postprocessing/shaders/dofPoissonBox.glsl +90 -0
  84. package/src/plugins/postprocessing/shaders/giPatch.glsl +53 -0
  85. package/src/plugins/postprocessing/shaders/hdrBloom.glsl +101 -0
  86. package/src/plugins/postprocessing/shaders/outline.glsl +60 -0
  87. package/src/plugins/postprocessing/shaders/outlineDepthFrag.glsl +22 -0
  88. package/src/plugins/postprocessing/shaders/outlineDepthVert.glsl +26 -0
  89. package/src/plugins/postprocessing/shaders/poissonDiskSamples.glsl +19 -0
  90. package/src/plugins/postprocessing/shaders/samplePointHelpers.glsl +3 -0
  91. package/src/plugins/postprocessing/shaders/ssrPatch.glsl +145 -0
  92. package/src/plugins/postprocessing/shaders/ssreflectionMain.glsl +69 -0
  93. package/src/plugins/postprocessing/shaders/ssrt.glsl +118 -0
  94. package/src/utils/FSShadowMaterial.ts +65 -0
  95. package/src/utils/RandomizedDirectionalLight.ts +288 -0
  96. package/src/utils/Reflector2.ts +309 -0
  97. package/src/utils/ShadowMapBaker.ts +527 -0
  98. package/src/utils/shaders/computeScreenSpaceVelocity.glsl +16 -0
  99. package/src/utils/shaders/getWorldPositionFromViewZ.glsl +9 -0
  100. package/src/utils/shaders/poissonDiskSamples.glsl +19 -0
  101. package/src/utils/shaders/reflectorSample.glsl +54 -0
  102. package/src/utils/shaders/seperableBlurShaderMasked.glsl +28 -0
  103. package/src/utils/shaders/seperableShadowBlur.glsl +21 -0
  104. package/src/utils/shaders/ssreflection.glsl +141 -0
  105. package/src/utils/shaders/ssrtao.glsl +275 -0
  106. package/src/utils/shaders/temporalaa.glsl +233 -0
  107. package/src/utils/shaders.ts +24 -0
  108. package/tsconfig.json +39 -44
  109. package/dist/version.d.ts +0 -2
  110. package/dist/version.d.ts.map +0 -1
@@ -0,0 +1,288 @@
1
+ import {
2
+ Color,
3
+ copyObject3DUserData,
4
+ DirectionalLight2,
5
+ IDisposable,
6
+ Serialization,
7
+ SerializationMetaType,
8
+ serialize,
9
+ ThreeSerialization,
10
+ Vector2,
11
+ Vector3
12
+ } from 'threepipe'
13
+ import Rand from "rand-seed";
14
+
15
+ export interface RDShadowParams {
16
+ frustumSize: number,
17
+ far: number,
18
+ bias: number,
19
+ width: number,
20
+ near: number,
21
+ enabled: boolean,
22
+ height: number,
23
+ normalBias: number,
24
+ radius: number
25
+ }
26
+
27
+ export interface RDRandomParams {
28
+ minDistanceScale: Vector3,
29
+ distanceScale: number,
30
+ focus: number,
31
+ spread: number,
32
+ direction: Vector3
33
+ normalDirection: Vector3
34
+ }
35
+
36
+ export class RandomizedDirectionalLight extends DirectionalLight2 implements IDisposable {
37
+ @serialize('shadowParams')
38
+ private _shadowParams: RDShadowParams = {
39
+ enabled: true,
40
+ radius: 2,
41
+ width: 1024,
42
+ height: 1024,
43
+ bias: -0.001,
44
+ normalBias: 0,
45
+ near: 1.5,
46
+ far: 4,
47
+ frustumSize: 4,
48
+ }
49
+
50
+ @serialize('randomParams')
51
+ private _randomParams: RDRandomParams = {
52
+ focus: 1, // 0 to 1
53
+ spread: 0.01, // 0 to 4
54
+ distanceScale: 50, // distance from target sort of
55
+ minDistanceScale: new Vector3(10, 10, 10), // distance from target sort of
56
+ // normalDirection: new Vector3(0.01, 0.33, 0.9).normalize(),
57
+ normalDirection: new Vector3(0.01, 0.98, 0.01).normalize(),
58
+ direction: new Vector3(-.9, 0.5, -1.),
59
+ // direction: new Vector3(3, 2, 1).multiply(this.camera.position),
60
+ }
61
+ isRandomizedDirectionalLight = true
62
+
63
+ // Set renderer.shadowMap settings if using shadows.
64
+ constructor(color?: Color | string | number, intensity?: number, shadow?: Partial<RDShadowParams>, random?: Partial<RDRandomParams>) {
65
+ super(color, intensity)
66
+ this.shadowParams = shadow ?? {}
67
+ this.randomParams = random ?? {}
68
+ this.updateShadowParams = this.updateShadowParams.bind(this)
69
+ // this.target.removeFromParent()
70
+ }
71
+
72
+ /**
73
+ * call setter to change. or call updateShadowParams after changing
74
+ */
75
+ get shadowParams(): Partial<RDShadowParams> {
76
+ return this._shadowParams
77
+ }
78
+
79
+ set shadowParams(value: Partial<RDShadowParams>) {
80
+ // @ts-expect-error ignore
81
+ Object.keys(value).forEach(key => value[key] === undefined && delete value[key])
82
+ this._shadowParams = {...this._shadowParams, ...value}
83
+ this.updateShadowParams()
84
+ }
85
+
86
+
87
+ get randomParams(): Partial<RDRandomParams> {
88
+ return this._randomParams
89
+ }
90
+
91
+ set randomParams(value: Partial<RDRandomParams>) {
92
+ // @ts-expect-error ignore
93
+ Object.keys(value).forEach(key => value[key] === undefined && delete value[key])
94
+ Object.assign(this._randomParams, value)
95
+ }
96
+
97
+ updateShadowParams() {
98
+ this.castShadow = this._shadowParams.enabled
99
+
100
+ this.shadow.mapSize.x = this._shadowParams.width // default
101
+ this.shadow.mapSize.y = this._shadowParams.height // default
102
+ // this.shadow.bias = -0.001;
103
+ this.shadow.bias = this._shadowParams.bias
104
+ this.shadow.normalBias = this._shadowParams.normalBias
105
+ // this.shadow.normalBias = 0.0000001;
106
+ // this.shadow.camera.near = 20;
107
+ // this.shadow.camera.far = 75;
108
+ // this.shadow.camera.near = this._shadowParams.near;
109
+ // this.shadow.camera.far = this._shadowParams.far;
110
+ this.refreshShadowCamNearFar()
111
+
112
+ this.shadow.radius = this._shadowParams.radius
113
+
114
+ this.shadow.camera.right = this._shadowParams.frustumSize / 2
115
+ this.shadow.camera.left = -this._shadowParams.frustumSize / 2
116
+ this.shadow.camera.top = this._shadowParams.frustumSize / 2
117
+ this.shadow.camera.bottom = -this._shadowParams.frustumSize / 2
118
+
119
+ this.shadow.camera.updateProjectionMatrix()
120
+ this.matrixWorldNeedsUpdate = true
121
+ }
122
+
123
+ randomizePosition(seed: number, focus: number|null = null, spread: number|null = null) {
124
+ // todo remove dependency to rand-seed
125
+ const rand = new Rand(seed.toString())
126
+
127
+ const rnd = new Vector2(rand.next() * Math.PI * 2, Math.asin(rand.next() * 2 - 1))
128
+ let dir = new Vector3(Math.cos(rnd.x) * Math.cos(rnd.y), Math.sin(rnd.y), Math.sin(rnd.x) * Math.cos(rnd.y))
129
+ // const dir = vec3.random(vec3.create(), 30);
130
+ // const light_params = {
131
+ // directionalWeight: 0.7,
132
+ // randomWeight: 1.5,
133
+ // sampleHemisphere: true,
134
+ // direction: new Vector3(-2, 1, 2),
135
+ // // direction: new Vector3(3, 2, 1).multiply(this.camera.position),
136
+ // }
137
+ // if (rand.next() < Math.pow(focus ?? this._randomParams.focus, 2)) {
138
+ // dir.multiplyScalar((spread ?? this._randomParams.spread) * Math.sqrt(rand.next())).add(this._randomParams.direction);
139
+ // }
140
+
141
+ /**
142
+ * @type {string}
143
+ */
144
+ // let h = this._randomParams.hemisphere;
145
+ // while ((h?.length ?? 0) >= 2) { // negate direction if < or > 0
146
+ // if ((dir[h[0]] * (h[1] === '+' ? -1 : 1)) < 0) dir[h[0]] *= -1;
147
+ // h = h.substr(2);
148
+ // }
149
+
150
+ const v2 = new Vector2()
151
+
152
+ for (let kk = 0; kk < 5; kk++) {
153
+ v2.set(rand.next(), rand.next())
154
+ dir = getSample(v2, this._randomParams.normalDirection, 0.4)
155
+
156
+ if (rand.next() < Math.sqrt(focus ?? this._randomParams.focus)) {
157
+ v2.set(rand.next(), rand.next())
158
+ dir = getSample(v2, this._randomParams.direction, Math.pow((spread ?? this._randomParams.spread) / 2., 2))
159
+ }
160
+
161
+ const cd = dir.dot(this._randomParams.normalDirection)
162
+ if (cd > 0 && cd < 0.4) break
163
+ }
164
+ dir.normalize()
165
+
166
+ dir.multiplyScalar(this._randomParams.distanceScale)
167
+
168
+ // dir.x += Math.sign(dir.x) * this._randomParams.minDistanceScale.x;
169
+ // dir.y += Math.sign(dir.y) * this._randomParams.minDistanceScale.y;
170
+ // dir.z += Math.sign(dir.z) * this._randomParams.minDistanceScale.z;
171
+ // dir.z = 15. + 10 * dir.z / 50;
172
+ // vec3.mul(dir, dir, [500, 500, 500]);
173
+ // console.log(vec3.len(dir));
174
+ // vec3.add(dir, dir, [0,10,0]);
175
+
176
+ // let useY = Math.max(...dir.toArray()) !== dir.y;
177
+ // let up = new Vector3(!useY?1:0, useY?1:0, 0).cross(dir).normalize();
178
+ // console.log(dir);
179
+ this.position.set(0, 0, 0)
180
+ this.target.position.copy(dir.normalize().negate())
181
+ this.target.updateMatrixWorld()
182
+ this.refreshShadowCamNearFar()
183
+
184
+ this.updateMatrixWorld()
185
+
186
+ }
187
+
188
+ refreshShadowCamNearFar() {
189
+ const dist = new Vector3().subVectors(this.target.position, this.shadow.camera.position).length()
190
+ this.shadow.camera.near = dist - this._shadowParams.near * this._shadowParams.frustumSize / 2
191
+ this.shadow.camera.far = dist + this._shadowParams.far * this._shadowParams.frustumSize / 2
192
+ }
193
+
194
+ dispose(): void {
195
+ super.dispose() // DirectionalLight: frees the shadow map
196
+ }
197
+
198
+ // todo move to commons and base class in threepipe like materials
199
+ toJSON(meta?: SerializationMetaType, _internal = false): any {
200
+ // todo uncomment after ts-browser-helpers update
201
+ // if (!_internal) {
202
+ // return ThreeSerialization.Serialize(this, meta, false)
203
+ // }
204
+ const {userData, children} = this
205
+ this.userData = {}
206
+ this.children = []
207
+ const data: any = super.toJSON(meta)
208
+ const copiedData = copyObject3DUserData({}, userData)
209
+ data.userData = Serialization.Serialize(copiedData) // no meta here, since we dont support textures etc inside lights
210
+ this.userData = userData
211
+ this.children = children
212
+
213
+ data.type = 'DirectionalLight2'
214
+ data.target = this.target.position.toArray()
215
+ // return Object.assign(data, serializeObject(this, true, meta)) // for subclasses like RandomizedDirectionalLight
216
+ return {
217
+ ...data,
218
+ ...ThreeSerialization.Serialize(this, meta, true), // this will serialize the properties of this class(like defined with @serialize and @serialize attribute)
219
+ } // for subclasses like RandomizedDirectionalLight
220
+ // this will call toJSON again, but with baseOnly=true, that's why we set isThis to false.
221
+ }
222
+
223
+ // todo move to commons and base class in threepipe
224
+ fromJSON(data: any, meta?: SerializationMetaType, _internal = false): this | null {
225
+ // todo uncomment after ts-browser-helpers update
226
+ // if(!_internal) {
227
+ // return ThreeSerialization.Deserialize(data, this, meta, false)
228
+ // }
229
+
230
+ if (data.type !== 'DirectionalLight2') return null // todo type
231
+ const target = data.target
232
+ const object = data.object
233
+ if (data.target) {
234
+ this.target.position.fromArray(data.target)
235
+ this.target.updateMatrixWorld()
236
+ delete data.target
237
+ }
238
+ if (data.object) {
239
+ delete data.object
240
+ }
241
+ ThreeSerialization.Deserialize(data, this, meta, true)
242
+ if (target) {
243
+ data.target = target
244
+ }
245
+ if (object) {
246
+ if (object.color !== undefined) this.color.set(object.color)
247
+ if (object.intensity !== undefined) this.intensity = object.intensity
248
+ data.object = object
249
+ }
250
+ // todo: shadow (use ObjectLoader)
251
+
252
+
253
+ // for this class
254
+ this.updateShadowParams()
255
+
256
+
257
+ return this
258
+ }
259
+
260
+ // fromJSON(data: any, meta?: any): this | null {
261
+ // // if (!super.fromJSON(data, meta)) return null
262
+ // this.updateShadowParams()
263
+ // return this
264
+ // }
265
+
266
+ //
267
+ // setDefaultPosition() {
268
+ // this.position.copy(this._randomParams.direction).multiplyScalar(this._randomParams.distanceScale)
269
+ // this.position.z = 15. + 10 * this.position.z / 50;
270
+ // this.updateMatrixWorld()
271
+ // }
272
+ }
273
+
274
+ /**
275
+ * Random direction, uniformly distributed over the cone around `dir` in which cos(angle to dir)
276
+ * is between 1 - extent and 1: phi = 2 pi u, cos(theta) = 1 - v extent, with (u, v) = rand in [0, 1).
277
+ * Basis: b1 = (0, -dir.z, dir.y) and b2 = dir x b1, both zero when dir is along x.
278
+ */
279
+ function getSample(rand: Vector2, dir: Vector3, extent: number) {
280
+ const w = dir.clone().normalize()
281
+ const b1 = new Vector3(0., -w.z, w.y).normalize()
282
+ const b2 = new Vector3().crossVectors(w, b1).normalize()
283
+
284
+ const phi = rand.x * 2. * Math.PI
285
+ const cosTheta = 1.0 - rand.y * extent
286
+ const sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta)
287
+ return b1.multiplyScalar(Math.cos(phi) * sinTheta).add(b2.multiplyScalar(Math.sin(phi) * sinTheta)).add(w.multiplyScalar(cosTheta))
288
+ }
@@ -0,0 +1,309 @@
1
+ import {
2
+ BufferGeometry2,
3
+ getOrCall,
4
+ IMaterial,
5
+ IShaderPropertiesUpdater,
6
+ IWebGLRenderer,
7
+ MaterialExtension,
8
+ MathUtils,
9
+ Matrix4,
10
+ Mesh2,
11
+ onChange,
12
+ PerspectiveCamera,
13
+ PhysicalMaterial,
14
+ Plane,
15
+ shaderReplaceString,
16
+ Texture,
17
+ ValOrFunc,
18
+ Vector2,
19
+ Vector3,
20
+ Vector4,
21
+ WebGLRenderTarget
22
+ } from 'threepipe'
23
+ import poissonDiskSamples from './shaders/poissonDiskSamples.glsl'
24
+ import reflectorSample from './shaders/reflectorSample.glsl'
25
+
26
+ export class Reflector2<TG extends BufferGeometry2 = BufferGeometry2> extends Mesh2<TG, PhysicalMaterial> {
27
+ public type = 'Reflector'
28
+ public readonly isReflector2 = true
29
+ private _renderTarget: ValOrFunc<WebGLRenderTarget|undefined>
30
+ // private _renderTarget2: WebGLRenderTarget
31
+ public readonly textureMatrix: Matrix4
32
+
33
+ private _getRenderTarget(){
34
+ const target = getOrCall(this._renderTarget)
35
+ if(target) {
36
+ if (target.texture.generateMipmaps && (!MathUtils.isPowerOfTwo(target.texture.image.width) || !MathUtils.isPowerOfTwo(target.texture.image.height)))
37
+ target.texture.generateMipmaps = false
38
+
39
+ this.materialExtension.extraUniforms.tRefDiffuse.value = target.texture
40
+ this.materialExtension.extraUniforms.tRefDiffuseSize.value.set(target.width, target.height)
41
+ // this.materialExtension.extraUniforms.tRefDepth.value = target.depthTexture
42
+ }
43
+ return target
44
+ }
45
+
46
+ @onChange(Reflector2.prototype._updateExtension)
47
+ public enabled = true
48
+
49
+ @onChange(Reflector2.prototype._updateExtension)
50
+ public reflectorModePhysical = true // shows envmap in reflection
51
+
52
+ public reflectionTargetNeedsUpdate = true
53
+ public transparentReflectionBackground = true // todo change to reflectBackground or something
54
+
55
+ private _updateExtension() {
56
+ this.transparentReflectionBackground = this.reflectorModePhysical
57
+ this.materialExtension?.setDirty?.()
58
+ }
59
+
60
+ constructor(geometry: TG, renderTarget: ValOrFunc<WebGLRenderTarget|undefined>, clipBias = 0, material: PhysicalMaterial) {
61
+ super(geometry, material)
62
+
63
+ this._renderTarget = renderTarget
64
+ // todo: do we need to dispose this on RT dispose??
65
+ // this._renderTarget.depthTexture = new DepthTexture(renderTarget.width / 2, renderTarget.height / 2, UnsignedByteType)
66
+
67
+ const reflectorPlane = new Plane()
68
+ const normal = new Vector3()
69
+ const reflectorWorldPosition = new Vector3()
70
+ const cameraWorldPosition = new Vector3()
71
+ const rotationMatrix = new Matrix4()
72
+ const lookAtPosition = new Vector3(0, 0, -1)
73
+ const clipPlane = new Vector4()
74
+
75
+ const view = new Vector3()
76
+ const target = new Vector3()
77
+ const q = new Vector4()
78
+
79
+ const textureMatrix = new Matrix4()
80
+ const virtualCamera = new PerspectiveCamera()
81
+
82
+ this.onBeforeRender = (renderer: IWebGLRenderer, scene, camera) => {
83
+
84
+ if (!this.enabled || !(renderer as any).userData.mainRenderPass) return // mainRenderPass is set in RenderPass2
85
+
86
+ if (!this.reflectionTargetNeedsUpdate) {
87
+ return
88
+ }
89
+ const thisRenderTarget = this._getRenderTarget()
90
+ if(!thisRenderTarget){
91
+ console.warn('Reflector2: No render target set.')
92
+ return
93
+ }
94
+
95
+ const viewOffset = (camera as PerspectiveCamera).view ? Object.assign({}, (camera as PerspectiveCamera).view) : null
96
+ // clear camera jitter
97
+ viewOffset && (camera as PerspectiveCamera).clearViewOffset && (camera as PerspectiveCamera).clearViewOffset()
98
+
99
+ reflectorWorldPosition.setFromMatrixPosition(this.matrixWorld)
100
+ cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld)
101
+
102
+ rotationMatrix.extractRotation(this.matrixWorld)
103
+
104
+ normal.set(0, 0, 1)
105
+ normal.applyMatrix4(rotationMatrix)
106
+
107
+ view.subVectors(reflectorWorldPosition, cameraWorldPosition)
108
+
109
+ // Avoid rendering when reflector is facing away
110
+
111
+ if (view.dot(normal) > 0) return
112
+
113
+ view.reflect(normal).negate()
114
+ view.add(reflectorWorldPosition)
115
+
116
+ rotationMatrix.extractRotation(camera.matrixWorld)
117
+
118
+ lookAtPosition.set(0, 0, -1)
119
+ lookAtPosition.applyMatrix4(rotationMatrix)
120
+ lookAtPosition.add(cameraWorldPosition)
121
+
122
+ target.subVectors(reflectorWorldPosition, lookAtPosition)
123
+ target.reflect(normal).negate()
124
+ target.add(reflectorWorldPosition)
125
+
126
+ virtualCamera.position.copy(view)
127
+ virtualCamera.up.set(0, 1, 0)
128
+ virtualCamera.up.applyMatrix4(rotationMatrix)
129
+ virtualCamera.up.reflect(normal)
130
+ virtualCamera.lookAt(target)
131
+
132
+ virtualCamera.far = 2. // Used in WebGLBackground
133
+ virtualCamera.near = 0. // Used in WebGLBackground
134
+
135
+ virtualCamera.updateMatrixWorld()
136
+ virtualCamera.projectionMatrix.copy(camera.projectionMatrix)
137
+
138
+ // Update the texture matrix
139
+ textureMatrix.set(
140
+ 0.5, 0.0, 0.0, 0.5,
141
+ 0.0, 0.5, 0.0, 0.5,
142
+ 0.0, 0.0, 0.5, 0.5,
143
+ 0.0, 0.0, 0.0, 1.0
144
+ )
145
+ textureMatrix.multiply(virtualCamera.projectionMatrix)
146
+ textureMatrix.multiply(virtualCamera.matrixWorldInverse)
147
+ textureMatrix.multiply(this.matrixWorld)
148
+
149
+ // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
150
+ // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
151
+ reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition)
152
+ reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse)
153
+
154
+ clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant)
155
+
156
+ const projectionMatrix = virtualCamera.projectionMatrix
157
+
158
+ q.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[ 8 ]) / projectionMatrix.elements[ 0 ]
159
+ q.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[ 9 ]) / projectionMatrix.elements[ 5 ]
160
+ q.z = -1.0
161
+ q.w = (1.0 + projectionMatrix.elements[ 10 ]) / projectionMatrix.elements[ 14 ]
162
+
163
+ // Calculate the scaled plane vector
164
+ clipPlane.multiplyScalar(2.0 / clipPlane.dot(q))
165
+
166
+ // Replacing the third row of the projection matrix
167
+ projectionMatrix.elements[ 2 ] = clipPlane.x
168
+ projectionMatrix.elements[ 6 ] = clipPlane.y
169
+ projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias
170
+ projectionMatrix.elements[ 14 ] = clipPlane.w
171
+
172
+ // Render
173
+ this.visible = false
174
+
175
+ const currentRenderTarget = renderer.getRenderTarget()
176
+
177
+ const currentXrEnabled = renderer.xr.enabled
178
+ const currentShadowAutoUpdate = renderer.shadowMap.autoUpdate
179
+
180
+ renderer.xr.enabled = false // Avoid camera modification
181
+ renderer.shadowMap.autoUpdate = false // Avoid re-computing shadows
182
+
183
+ renderer.setRenderTarget(thisRenderTarget)
184
+
185
+ renderer.state.buffers.depth.setMask(true) // make sure the depth buffer is writable so it can be properly cleared, see #18897
186
+
187
+ // noinspection PointlessBooleanExpressionJS
188
+ if (renderer.autoClear === false) renderer.clear()
189
+
190
+ const sceneBackground = scene.background as any
191
+ // console.log((sceneBackground as any)?.uuid)
192
+ if (this.transparentReflectionBackground) scene.background = null // Avoid the background in the reflection
193
+
194
+ const renderBackground = !this.transparentReflectionBackground
195
+ if (sceneBackground?.isTexture && renderBackground) {
196
+ if (!sceneBackground.userData) sceneBackground.userData = {}
197
+ sceneBackground.userData.flipX = !sceneBackground.userData.flipX
198
+ }
199
+
200
+ renderer.renderWithModes({
201
+ shadowMapRender:false,
202
+ backgroundRender: renderBackground,
203
+ opaqueRender:true,
204
+ transparentRender:true,
205
+ transmissionRender:false, // todo: render transmissive objects somehow
206
+ screenSpaceRendering:false,
207
+ }, ()=> renderer.render(scene, virtualCamera))
208
+
209
+ if (sceneBackground?.isTexture && renderBackground) {
210
+ sceneBackground.userData.flipX = !sceneBackground.userData.flipX || undefined
211
+ }
212
+
213
+ if (this.transparentReflectionBackground) scene.background = sceneBackground
214
+
215
+ renderer.xr.enabled = currentXrEnabled
216
+ renderer.shadowMap.autoUpdate = currentShadowAutoUpdate
217
+
218
+ renderer.setRenderTarget(currentRenderTarget)
219
+
220
+ if (viewOffset?.enabled && (camera as PerspectiveCamera).setViewOffset)
221
+ (camera as PerspectiveCamera).setViewOffset(viewOffset.fullWidth, viewOffset.fullHeight, viewOffset.offsetX, viewOffset.offsetY, viewOffset.width, viewOffset.height)
222
+
223
+ // Restore viewport
224
+
225
+ const viewport = (camera as any).viewport
226
+
227
+ if (viewport !== undefined) {
228
+
229
+ renderer.state.viewport(viewport)
230
+
231
+ }
232
+
233
+ this.visible = true
234
+
235
+ this.reflectionTargetNeedsUpdate = false
236
+
237
+ }
238
+
239
+ this.textureMatrix = textureMatrix
240
+ this.materialExtension.extraUniforms.refTextureMatrix.value = textureMatrix
241
+
242
+ }
243
+
244
+ getRenderTarget() {
245
+ return this._renderTarget
246
+ }
247
+
248
+ readonly materialExtension = {
249
+ extraUniforms: {
250
+ // tRefDepth: {value: null},
251
+ tRefDiffuse: {value: null as Texture|null},
252
+ tRefDiffuseSize: {value: new Vector2()},
253
+ refTextureMatrix: {value: new Matrix4()},
254
+ frameCount: {value: 0},
255
+ sceneBoundingRadius: {value: 0},
256
+ },
257
+ extraDefines: {
258
+ // eslint-disable-next-line @typescript-eslint/naming-convention
259
+ USE_UV: '',
260
+ },
261
+ updaters: [] as IShaderPropertiesUpdater[] | (() => IShaderPropertiesUpdater[]),
262
+ shaderExtender: (shader, _material, _renderer) => {
263
+ if (this.enabled) {
264
+ shader.vertexShader = shaderReplaceString(shader.vertexShader, 'void main() {', 'void main() {\nvRefUv = refTextureMatrix * vec4( position, 1.0 );')
265
+ // if (!shader.fragmentShader.includes('#include <map_fragment>')) console.error('Shader modified before this.')
266
+ const ls = '#glMarker beforeModulation'
267
+ shader.fragmentShader = shaderReplaceString(shader.fragmentShader, ls, `
268
+ if(roughnessFactor < 0.95) {
269
+ float d = 0.;//textureProj(tRefDepth, vRefUv).r;
270
+ // d = min(2., max(0., (d-0.06) * ((7./3.-ior)) * sceneBoundingRadius));
271
+ vec4 refBaseColor = getReflectionColor(material.roughness, material.roughness * d);
272
+ // refBaseColor.rgb = vec3(refBaseColor.a);
273
+ // refBaseColor.a *= 1.0 - clamp(material.roughness * .3, 0., 1.);
274
+ `
275
+ + (this.reflectorModePhysical ? `
276
+ #if !defined(SSR_ENABLED) || SSR_ENABLED < 1
277
+ vec3 specularColor = EnvironmentBRDF(geometryNormal, geometryViewDir, material.specularColor.rgb, material.specularF90, material.roughness);
278
+ #endif
279
+ reflectedLight.indirectSpecular = mix(vec3(reflectedLight.indirectSpecular), saturate(specularColor.rgb * refBaseColor.rgb), refBaseColor.a);
280
+ ` : `
281
+ reflectedLight.indirectSpecular = saturate(diffuseColor.rgb * refBaseColor.rgb);
282
+ diffuseColor.a *= refBaseColor.a;
283
+ `) +
284
+ '}\n' + ls) // todo: this is a hacky way to handle transparent object, use a MeshBasicMaterial instead // ;(shader as any).vertexUvs = true
285
+ }
286
+
287
+ },
288
+ parsVertexSnippet: ()=>!this.enabled ? '' : `
289
+ uniform mat4 refTextureMatrix;
290
+ varying vec4 vRefUv;
291
+ `,
292
+ parsFragmentSnippet: ()=>this.enabled ? poissonDiskSamples + '\n' + reflectorSample : '',
293
+ computeCacheKey: (material: IMaterial)=>{
294
+ return this.enabled + ' ' + material.transparent + ' ' + this.reflectorModePhysical + ' '
295
+ },
296
+ onObjectRender: (_object, material) => {
297
+ if (material.userData.__lastTransparent !== material.transparent) {
298
+ material.needsUpdate = true
299
+ material.userData.__lastTransparent = material.transparent
300
+ }
301
+ },
302
+ isCompatible: material => {
303
+ return (material as PhysicalMaterial).isPhysicalMaterial
304
+ },
305
+ setDirty: ()=>(this.materialExtension as MaterialExtension).__setDirty?.()
306
+ } satisfies MaterialExtension
307
+ }
308
+
309
+ (Reflector2.prototype as any).isReflector = true