three-gpu-pathtracer 0.0.7 → 0.0.8

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 (48) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +887 -815
  3. package/build/index.module.js +5796 -5451
  4. package/build/index.module.js.map +1 -1
  5. package/build/index.umd.cjs +5795 -5448
  6. package/build/index.umd.cjs.map +1 -1
  7. package/package.json +69 -68
  8. package/src/core/DynamicPathTracingSceneGenerator.js +119 -119
  9. package/src/core/MaterialReducer.js +256 -256
  10. package/src/core/PathTracingRenderer.js +270 -270
  11. package/src/core/PathTracingSceneGenerator.js +1 -1
  12. package/src/index.js +39 -35
  13. package/src/materials/AlphaDisplayMaterial.js +48 -48
  14. package/src/materials/AmbientOcclusionMaterial.js +197 -197
  15. package/src/materials/BlendMaterial.js +67 -67
  16. package/src/materials/DenoiseMaterial.js +142 -142
  17. package/src/materials/GraphMaterial.js +243 -243
  18. package/src/materials/LambertPathTracingMaterial.js +285 -285
  19. package/src/materials/MaterialBase.js +56 -56
  20. package/src/materials/PhysicalPathTracingMaterial.js +973 -970
  21. package/src/objects/EquirectCamera.js +13 -13
  22. package/src/objects/PhysicalCamera.js +28 -28
  23. package/src/objects/PhysicalSpotLight.js +14 -14
  24. package/src/objects/ShapedAreaLight.js +12 -12
  25. package/src/shader/shaderEnvMapSampling.js +59 -59
  26. package/src/shader/shaderGGXFunctions.js +100 -100
  27. package/src/shader/shaderIridescenceFunctions.js +130 -130
  28. package/src/shader/shaderLayerTexelFetchFunctions.js +25 -0
  29. package/src/shader/shaderLightSampling.js +231 -231
  30. package/src/shader/shaderMaterialSampling.js +504 -542
  31. package/src/shader/shaderSheenFunctions.js +98 -98
  32. package/src/shader/shaderStructs.js +321 -321
  33. package/src/shader/shaderUtils.js +403 -364
  34. package/src/textures/GradientEquirectTexture.js +35 -0
  35. package/src/textures/ProceduralEquirectTexture.js +75 -0
  36. package/src/uniforms/AttributesTextureArray.js +35 -0
  37. package/src/uniforms/EquirectHdrInfoUniform.js +259 -259
  38. package/src/uniforms/FloatAttributeTextureArray.js +169 -0
  39. package/src/uniforms/IESProfilesTexture.js +100 -100
  40. package/src/uniforms/LightsInfoUniformStruct.js +162 -162
  41. package/src/uniforms/MaterialsTexture.js +420 -426
  42. package/src/uniforms/PhysicalCameraUniform.js +36 -36
  43. package/src/uniforms/RenderTarget2DArray.js +97 -93
  44. package/src/uniforms/utils.js +21 -0
  45. package/src/utils/BlurredEnvMapGenerator.js +116 -113
  46. package/src/utils/IESLoader.js +325 -325
  47. package/src/utils/UVUnwrapper.js +101 -101
  48. package/src/workers/PathTracingSceneWorker.js +42 -42
@@ -1,970 +1,973 @@
1
- import { Matrix4, Matrix3, Color, Vector2 } from 'three';
2
- import { MaterialBase } from './MaterialBase.js';
3
- import {
4
- MeshBVHUniformStruct, FloatVertexAttributeTexture, UIntVertexAttributeTexture,
5
- shaderStructs, shaderIntersectFunction,
6
- } from 'three-mesh-bvh';
7
- import { shaderMaterialStructs, shaderLightStruct } from '../shader/shaderStructs.js';
8
- import { MaterialsTexture } from '../uniforms/MaterialsTexture.js';
9
- import { RenderTarget2DArray } from '../uniforms/RenderTarget2DArray.js';
10
- import { shaderMaterialSampling } from '../shader/shaderMaterialSampling.js';
11
- import { shaderEnvMapSampling } from '../shader/shaderEnvMapSampling.js';
12
- import { shaderLightSampling } from '../shader/shaderLightSampling.js';
13
- import { shaderUtils } from '../shader/shaderUtils.js';
14
- import { PhysicalCameraUniform } from '../uniforms/PhysicalCameraUniform.js';
15
- import { EquirectHdrInfoUniform } from '../uniforms/EquirectHdrInfoUniform.js';
16
- import { LightsInfoUniformStruct } from '../uniforms/LightsInfoUniformStruct.js';
17
- import { IESProfilesTexture } from '../uniforms/IESProfilesTexture.js';
18
-
19
- export class PhysicalPathTracingMaterial extends MaterialBase {
20
-
21
- onBeforeRender() {
22
-
23
- this.setDefine( 'FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1 );
24
-
25
- }
26
-
27
- constructor( parameters ) {
28
-
29
- super( {
30
-
31
- transparent: true,
32
- depthWrite: false,
33
-
34
- defines: {
35
- FEATURE_MIS: 1,
36
- FEATURE_DOF: 1,
37
- FEATURE_GRADIENT_BG: 0,
38
- TRANSPARENT_TRAVERSALS: 5,
39
- // 0 = Perspective
40
- // 1 = Orthographic
41
- // 2 = Equirectangular
42
- CAMERA_TYPE: 0,
43
- },
44
-
45
- uniforms: {
46
- resolution: { value: new Vector2() },
47
-
48
- bounces: { value: 3 },
49
- physicalCamera: { value: new PhysicalCameraUniform() },
50
-
51
- bvh: { value: new MeshBVHUniformStruct() },
52
- normalAttribute: { value: new FloatVertexAttributeTexture() },
53
- tangentAttribute: { value: new FloatVertexAttributeTexture() },
54
- uvAttribute: { value: new FloatVertexAttributeTexture() },
55
- colorAttribute: { value: new FloatVertexAttributeTexture() },
56
- materialIndexAttribute: { value: new UIntVertexAttributeTexture() },
57
- materials: { value: new MaterialsTexture() },
58
- textures: { value: new RenderTarget2DArray().texture },
59
- lights: { value: new LightsInfoUniformStruct() },
60
- iesProfiles: { value: new IESProfilesTexture().texture },
61
- cameraWorldMatrix: { value: new Matrix4() },
62
- invProjectionMatrix: { value: new Matrix4() },
63
- backgroundBlur: { value: 0.0 },
64
- environmentIntensity: { value: 1.0 },
65
- environmentRotation: { value: new Matrix3() },
66
- envMapInfo: { value: new EquirectHdrInfoUniform() },
67
-
68
- seed: { value: 0 },
69
- opacity: { value: 1 },
70
- filterGlossyFactor: { value: 0.0 },
71
-
72
- bgGradientTop: { value: new Color( 0x111111 ) },
73
- bgGradientBottom: { value: new Color( 0x000000 ) },
74
- backgroundAlpha: { value: 1.0 },
75
- },
76
-
77
- vertexShader: /* glsl */`
78
-
79
- varying vec2 vUv;
80
- void main() {
81
-
82
- vec4 mvPosition = vec4( position, 1.0 );
83
- mvPosition = modelViewMatrix * mvPosition;
84
- gl_Position = projectionMatrix * mvPosition;
85
-
86
- vUv = uv;
87
-
88
- }
89
-
90
- `,
91
-
92
- fragmentShader: /* glsl */`
93
- #define RAY_OFFSET 1e-4
94
-
95
- precision highp isampler2D;
96
- precision highp usampler2D;
97
- precision highp sampler2DArray;
98
- vec4 envMapTexelToLinear( vec4 a ) { return a; }
99
- #include <common>
100
-
101
- ${ shaderStructs }
102
- ${ shaderIntersectFunction }
103
- ${ shaderMaterialStructs }
104
- ${ shaderLightStruct }
105
-
106
- ${ shaderUtils }
107
- ${ shaderMaterialSampling }
108
- ${ shaderEnvMapSampling }
109
-
110
- uniform mat3 environmentRotation;
111
- uniform float backgroundBlur;
112
- uniform float backgroundAlpha;
113
-
114
- #if FEATURE_GRADIENT_BG
115
-
116
- uniform vec3 bgGradientTop;
117
- uniform vec3 bgGradientBottom;
118
-
119
- #endif
120
-
121
- #if FEATURE_DOF
122
-
123
- uniform PhysicalCamera physicalCamera;
124
-
125
- #endif
126
-
127
- uniform vec2 resolution;
128
- uniform int bounces;
129
- uniform mat4 cameraWorldMatrix;
130
- uniform mat4 invProjectionMatrix;
131
- uniform sampler2D normalAttribute;
132
- uniform sampler2D tangentAttribute;
133
- uniform sampler2D uvAttribute;
134
- uniform sampler2D colorAttribute;
135
- uniform usampler2D materialIndexAttribute;
136
- uniform BVH bvh;
137
- uniform float environmentIntensity;
138
- uniform float filterGlossyFactor;
139
- uniform int seed;
140
- uniform float opacity;
141
- uniform sampler2D materials;
142
- uniform LightsInfo lights;
143
- uniform sampler2DArray iesProfiles;
144
-
145
- ${ shaderLightSampling }
146
-
147
- uniform EquirectHdrInfo envMapInfo;
148
-
149
- uniform sampler2DArray textures;
150
- varying vec2 vUv;
151
-
152
- float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
153
-
154
- return clamp(
155
- max(
156
- roughness,
157
- accumulatedRoughness * filterGlossyFactor * 5.0 ),
158
- 0.0,
159
- 1.0
160
- );
161
-
162
- }
163
-
164
- vec3 sampleBackground( vec3 direction ) {
165
-
166
- #if FEATURE_GRADIENT_BG
167
-
168
- direction = normalize( direction + randDirection() * 0.05 );
169
-
170
- float value = ( direction.y + 1.0 ) / 2.0;
171
- value = pow( value, 2.0 );
172
-
173
- return mix( bgGradientBottom, bgGradientTop, value );
174
-
175
- #else
176
-
177
- vec3 sampleDir = normalize( direction + getHemisphereSample( direction, rand2() ) * 0.5 * backgroundBlur );
178
- return environmentIntensity * sampleEquirectEnvMapColor( sampleDir, envMapInfo.map );
179
-
180
- #endif
181
-
182
- }
183
-
184
- // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
185
- bool attenuateHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, int traversals, bool isShadowRay, out vec3 color ) {
186
-
187
- // hit results
188
- uvec4 faceIndices = uvec4( 0u );
189
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
190
- vec3 barycoord = vec3( 0.0 );
191
- float side = 1.0;
192
- float dist = 0.0;
193
-
194
- color = vec3( 1.0 );
195
-
196
- for ( int i = 0; i < traversals; i ++ ) {
197
-
198
- if ( bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) ) {
199
-
200
- // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
201
- // Should be able to work using the material BSDF functions which will take into account specularity, etc.
202
- // TODO: should we account for emissive surfaces here?
203
-
204
- vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
205
- vec4 vertexColor = textureSampleBarycoord( colorAttribute, barycoord, faceIndices.xyz );
206
- uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
207
- Material material = readMaterialInfo( materials, materialIndex );
208
-
209
- // adjust the ray to the new surface
210
- bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
211
- vec3 point = rayOrigin + rayDirection * dist;
212
- vec3 absPoint = abs( point );
213
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
214
- rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
215
-
216
- if ( ! material.castShadow && isShadowRay ) {
217
-
218
- continue;
219
-
220
- }
221
-
222
- // Opacity Test
223
-
224
- // albedo
225
- vec4 albedo = vec4( material.color, material.opacity );
226
- if ( material.map != - 1 ) {
227
-
228
- vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
229
- albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
230
-
231
- }
232
-
233
- if ( material.vertexColors ) {
234
-
235
- albedo *= vertexColor;
236
-
237
- }
238
-
239
- // alphaMap
240
- if ( material.alphaMap != - 1 ) {
241
-
242
- albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
243
-
244
- }
245
-
246
- // transmission
247
- float transmission = material.transmission;
248
- if ( material.transmissionMap != - 1 ) {
249
-
250
- vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
251
- transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
252
-
253
- }
254
-
255
- // metalness
256
- float metalness = material.metalness;
257
- if ( material.metalnessMap != - 1 ) {
258
-
259
- vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
260
- metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
261
-
262
- }
263
-
264
- float alphaTest = material.alphaTest;
265
- bool useAlphaTest = alphaTest != 0.0;
266
- float transmissionFactor = ( 1.0 - metalness ) * transmission;
267
- if (
268
- transmissionFactor < rand() && ! (
269
- // material sidedness
270
- material.side != 0.0 && side == material.side
271
-
272
- // alpha test
273
- || useAlphaTest && albedo.a < alphaTest
274
-
275
- // opacity
276
- || material.transparent && ! useAlphaTest && albedo.a < rand()
277
- )
278
- ) {
279
-
280
- return true;
281
-
282
- }
283
-
284
- if ( side == 1.0 && isBelowSurface ) {
285
-
286
- // only attenuate by surface color on the way in
287
- color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
288
-
289
- } else if ( side == - 1.0 ) {
290
-
291
- // attenuate by medium once we hit the opposite side of the model
292
- color *= transmissionAttenuation( dist, material.attenuationColor, material.attenuationDistance );
293
-
294
- }
295
-
296
- } else {
297
-
298
- return false;
299
-
300
- }
301
-
302
- }
303
-
304
- return true;
305
-
306
- }
307
-
308
- // returns whether the ray hit anything before a certain distance, not just the first surface. Could be optimized to not check the full hierarchy.
309
- bool anyCloserHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, float maxDist ) {
310
-
311
- uvec4 faceIndices = uvec4( 0u );
312
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
313
- vec3 barycoord = vec3( 0.0 );
314
- float side = 1.0;
315
- float dist = 0.0;
316
- bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
317
- return hit && dist < maxDist;
318
-
319
- }
320
-
321
- // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
322
- // erichlof/THREE.js-PathTracing-Renderer/
323
- float tentFilter( float x ) {
324
-
325
- return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
326
-
327
- }
328
-
329
- vec3 ndcToRayOrigin( vec2 coord ) {
330
-
331
- vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
332
- return rayOrigin4.xyz / rayOrigin4.w;
333
- }
334
-
335
- void getCameraRay( out vec3 rayDirection, out vec3 rayOrigin ) {
336
-
337
- vec2 ssd = vec2( 1.0 ) / resolution;
338
-
339
- // Jitter the camera ray by finding a uv coordinate at a random sample
340
- // around this pixel's UV coordinate
341
- vec2 jitteredUv = vUv + vec2( tentFilter( rand() ) * ssd.x, tentFilter( rand() ) * ssd.y );
342
-
343
- #if CAMERA_TYPE == 2
344
-
345
- // Equirectangular projection
346
-
347
- vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
348
- vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
349
-
350
- rayDirection4 = cameraWorldMatrix * rayDirection4;
351
- rayOrigin4 = cameraWorldMatrix * rayOrigin4;
352
-
353
- rayDirection = normalize( rayDirection4.xyz );
354
- rayOrigin = rayOrigin4.xyz / rayOrigin4.w;
355
-
356
- #else
357
-
358
- // get [- 1, 1] normalized device coordinates
359
- vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
360
-
361
- rayOrigin = ndcToRayOrigin( ndc );
362
-
363
- #if CAMERA_TYPE == 1
364
-
365
- // Orthographic projection
366
-
367
- rayDirection = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
368
- rayDirection = normalize( rayDirection );
369
-
370
- #else
371
-
372
- // Perspective projection
373
-
374
- rayDirection = normalize( mat3(cameraWorldMatrix) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
375
-
376
- #endif
377
-
378
- #endif
379
-
380
- #if FEATURE_DOF
381
- {
382
-
383
- // depth of field
384
- vec3 focalPoint = rayOrigin + normalize( rayDirection ) * physicalCamera.focusDistance;
385
-
386
- // get the aperture sample
387
- vec2 apertureSample = sampleAperture( physicalCamera.apertureBlades ) * physicalCamera.bokehSize * 0.5 * 1e-3;
388
-
389
- // rotate the aperture shape
390
- float ac = cos( physicalCamera.apertureRotation );
391
- float as = sin( physicalCamera.apertureRotation );
392
- apertureSample = vec2(
393
- apertureSample.x * ac - apertureSample.y * as,
394
- apertureSample.x * as + apertureSample.y * ac
395
- );
396
- apertureSample.x *= saturate( physicalCamera.anamorphicRatio );
397
- apertureSample.y *= saturate( 1.0 / physicalCamera.anamorphicRatio );
398
-
399
- // create the new ray
400
- rayOrigin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
401
- rayDirection = focalPoint - rayOrigin;
402
-
403
- }
404
- #endif
405
-
406
- rayDirection = normalize( rayDirection );
407
-
408
- }
409
-
410
- void main() {
411
-
412
- rng_initialize( gl_FragCoord.xy, seed );
413
-
414
- vec3 rayDirection;
415
- vec3 rayOrigin;
416
-
417
- getCameraRay( rayDirection, rayOrigin );
418
-
419
- // inverse environment rotation
420
- mat3 invEnvironmentRotation = inverse( environmentRotation );
421
-
422
- // final color
423
- gl_FragColor = vec4( 0.0 );
424
- gl_FragColor.a = 1.0;
425
-
426
- // hit results
427
- uvec4 faceIndices = uvec4( 0u );
428
- vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
429
- vec3 barycoord = vec3( 0.0 );
430
- float side = 1.0;
431
- float dist = 0.0;
432
-
433
- // path tracing state
434
- float accumulatedRoughness = 0.0;
435
- float accumulatedClearcoatRoughness = 0.0;
436
- bool transmissiveRay = true;
437
- int transparentTraversals = TRANSPARENT_TRAVERSALS;
438
- vec3 throughputColor = vec3( 1.0 );
439
- SampleRec sampleRec;
440
- int i;
441
- bool isShadowRay = false;
442
-
443
- for ( i = 0; i < bounces; i ++ ) {
444
-
445
- bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
446
-
447
- LightSampleRec lightHit = lightsClosestHit( lights.tex, lights.count, rayOrigin, rayDirection );
448
-
449
- if ( lightHit.hit && ( lightHit.dist < dist || !hit ) ) {
450
-
451
- if ( i == 0 || transmissiveRay ) {
452
-
453
- gl_FragColor.rgb += lightHit.emission * throughputColor;
454
-
455
- } else {
456
-
457
- #if FEATURE_MIS
458
-
459
- // NOTE: we skip MIS for spotlights since we haven't fixed the forward
460
- // path tracing code path, yet
461
- if ( lightHit.type == SPOT_LIGHT_TYPE ) {
462
-
463
- gl_FragColor.rgb += lightHit.emission * throughputColor;
464
-
465
- } else {
466
-
467
- // weight the contribution
468
- float misWeight = misHeuristic( sampleRec.pdf, lightHit.pdf / float( lights.count + 1u ) );
469
- gl_FragColor.rgb += lightHit.emission * throughputColor * misWeight;
470
-
471
- }
472
-
473
- #else
474
-
475
- gl_FragColor.rgb += lightHit.emission * throughputColor;
476
-
477
- #endif
478
-
479
- }
480
- break;
481
-
482
- }
483
-
484
- if ( ! hit ) {
485
-
486
- if ( i == 0 || transmissiveRay ) {
487
-
488
- gl_FragColor.rgb += sampleBackground( environmentRotation * rayDirection ) * throughputColor;
489
- gl_FragColor.a = backgroundAlpha;
490
-
491
- } else {
492
-
493
- #if FEATURE_MIS
494
-
495
- // get the PDF of the hit envmap point
496
- vec3 envColor;
497
- float envPdf = envMapSample( environmentRotation * rayDirection, envMapInfo, envColor );
498
- envPdf /= float( lights.count + 1u );
499
-
500
- // and weight the contribution
501
- float misWeight = misHeuristic( sampleRec.pdf, envPdf );
502
- gl_FragColor.rgb += environmentIntensity * envColor * throughputColor * misWeight;
503
-
504
- #else
505
-
506
- gl_FragColor.rgb +=
507
- environmentIntensity *
508
- sampleEquirectEnvMapColor( environmentRotation * rayDirection, envMapInfo.map ) *
509
- throughputColor;
510
-
511
- #endif
512
-
513
- }
514
- break;
515
-
516
- }
517
-
518
- uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
519
- Material material = readMaterialInfo( materials, materialIndex );
520
-
521
- if ( material.matte && i == 0 ) {
522
-
523
- gl_FragColor = vec4( 0.0 );
524
- break;
525
-
526
- }
527
-
528
- // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
529
- // then skip it
530
- if ( ! material.castShadow && isShadowRay ) {
531
-
532
- vec3 point = rayOrigin + rayDirection * dist;
533
- vec3 absPoint = abs( point );
534
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
535
- rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
536
-
537
- continue;
538
-
539
- }
540
-
541
- // uv coord for textures
542
- vec2 uv = textureSampleBarycoord( uvAttribute, barycoord, faceIndices.xyz ).xy;
543
- vec4 vertexColor = textureSampleBarycoord( colorAttribute, barycoord, faceIndices.xyz );
544
-
545
- // albedo
546
- vec4 albedo = vec4( material.color, material.opacity );
547
- if ( material.map != - 1 ) {
548
-
549
- vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
550
- albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
551
- }
552
-
553
- if ( material.vertexColors ) {
554
-
555
- albedo *= vertexColor;
556
-
557
- }
558
-
559
- // alphaMap
560
- if ( material.alphaMap != - 1 ) {
561
-
562
- albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
563
-
564
- }
565
-
566
- // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
567
- // and it's single sided.
568
- // - alpha test is disabled when it === 0
569
- // - the material sidedness test is complicated because we want light to pass through the back side but still
570
- // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
571
- // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
572
- float alphaTest = material.alphaTest;
573
- bool useAlphaTest = alphaTest != 0.0;
574
- if (
575
- // material sidedness
576
- material.side != 0.0 && side != material.side
577
-
578
- // alpha test
579
- || useAlphaTest && albedo.a < alphaTest
580
-
581
- // opacity
582
- || material.transparent && ! useAlphaTest && albedo.a < rand()
583
- ) {
584
-
585
- vec3 point = rayOrigin + rayDirection * dist;
586
- vec3 absPoint = abs( point );
587
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
588
- rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
589
-
590
- // only allow a limited number of transparency discards otherwise we could
591
- // crash the context with too long a loop.
592
- i -= sign( transparentTraversals );
593
- transparentTraversals -= sign( transparentTraversals );
594
- continue;
595
-
596
- }
597
-
598
- // fetch the interpolated smooth normal
599
- vec3 normal = normalize( textureSampleBarycoord(
600
- normalAttribute,
601
- barycoord,
602
- faceIndices.xyz
603
- ).xyz );
604
-
605
- // roughness
606
- float roughness = material.roughness;
607
- if ( material.roughnessMap != - 1 ) {
608
-
609
- vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
610
- roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
611
-
612
- }
613
-
614
- // metalness
615
- float metalness = material.metalness;
616
- if ( material.metalnessMap != - 1 ) {
617
-
618
- vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
619
- metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
620
-
621
- }
622
-
623
- // emission
624
- vec3 emission = material.emissiveIntensity * material.emissive;
625
- if ( material.emissiveMap != - 1 ) {
626
-
627
- vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
628
- emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
629
-
630
- }
631
-
632
- // transmission
633
- float transmission = material.transmission;
634
- if ( material.transmissionMap != - 1 ) {
635
-
636
- vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
637
- transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
638
-
639
- }
640
-
641
- // normal
642
- vec3 baseNormal = normal;
643
- if ( material.normalMap != - 1 ) {
644
-
645
- vec4 tangentSample = textureSampleBarycoord(
646
- tangentAttribute,
647
- barycoord,
648
- faceIndices.xyz
649
- );
650
-
651
- // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
652
- // resulting in NaNs and slow path tracing.
653
- if ( length( tangentSample.xyz ) > 0.0 ) {
654
-
655
- vec3 tangent = normalize( tangentSample.xyz );
656
- vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
657
- mat3 vTBN = mat3( tangent, bitangent, normal );
658
-
659
- vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
660
- vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
661
- texNormal.xy *= material.normalScale;
662
- normal = vTBN * texNormal;
663
-
664
- }
665
-
666
- }
667
-
668
- normal *= side;
669
-
670
- // clearcoat
671
- float clearcoat = material.clearcoat;
672
- if ( material.clearcoatMap != - 1 ) {
673
-
674
- vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
675
- clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
676
-
677
- }
678
-
679
- // clearcoatRoughness
680
- float clearcoatRoughness = material.clearcoatRoughness;
681
- if ( material.clearcoatRoughnessMap != - 1 ) {
682
-
683
- vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
684
- clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
685
-
686
- }
687
-
688
- // clearcoatNormal
689
- vec3 clearcoatNormal = baseNormal;
690
- if ( material.clearcoatNormalMap != - 1 ) {
691
-
692
- vec4 tangentSample = textureSampleBarycoord(
693
- tangentAttribute,
694
- barycoord,
695
- faceIndices.xyz
696
- );
697
-
698
- // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
699
- // resulting in NaNs and slow path tracing.
700
- if ( length( tangentSample.xyz ) > 0.0 ) {
701
-
702
- vec3 tangent = normalize( tangentSample.xyz );
703
- vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
704
- mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
705
-
706
- vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
707
- vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
708
- texNormal.xy *= material.clearcoatNormalScale;
709
- clearcoatNormal = vTBN * texNormal;
710
-
711
- }
712
-
713
- }
714
-
715
- clearcoatNormal *= side;
716
-
717
- // sheenColor
718
- vec3 sheenColor = material.sheenColor;
719
- if ( material.sheenColorMap != - 1 ) {
720
-
721
- vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
722
- sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
723
-
724
- }
725
-
726
- // sheenRoughness
727
- float sheenRoughness = material.sheenRoughness;
728
- if ( material.sheenRoughnessMap != - 1 ) {
729
-
730
- vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
731
- sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
732
-
733
- }
734
-
735
- // iridescence
736
- float iridescence = material.iridescence;
737
- if ( material.iridescenceMap != - 1 ) {
738
-
739
- vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
740
- iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
741
-
742
- }
743
-
744
- // iridescence thickness
745
- float iridescenceThickness = material.iridescenceThicknessMaximum;
746
- if ( material.iridescenceThicknessMap != - 1 ) {
747
-
748
- vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
749
- float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
750
- iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
751
-
752
- }
753
-
754
- iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
755
-
756
- // specular color
757
- vec3 specularColor = material.specularColor;
758
- if ( material.specularColorMap != - 1 ) {
759
-
760
- vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
761
- specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
762
-
763
- }
764
-
765
- // specular intensity
766
- float specularIntensity = material.specularIntensity;
767
- if ( material.specularIntensityMap != - 1 ) {
768
-
769
- vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
770
- specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
771
-
772
- }
773
-
774
- SurfaceRec surfaceRec;
775
- surfaceRec.normal = normal;
776
- surfaceRec.faceNormal = faceNormal;
777
- surfaceRec.transmission = transmission;
778
- surfaceRec.ior = material.ior;
779
- surfaceRec.emission = emission;
780
- surfaceRec.metalness = metalness;
781
- surfaceRec.color = albedo.rgb;
782
- surfaceRec.clearcoat = clearcoat;
783
- surfaceRec.sheenColor = sheenColor;
784
- surfaceRec.iridescence = iridescence;
785
- surfaceRec.iridescenceIor = material.iridescenceIor;
786
- surfaceRec.iridescenceThickness = iridescenceThickness;
787
- surfaceRec.specularColor = specularColor;
788
- surfaceRec.specularIntensity = specularIntensity;
789
- surfaceRec.attenuationColor = material.attenuationColor;
790
- surfaceRec.attenuationDistance = material.attenuationDistance;
791
-
792
- // apply perceptual roughness factor from gltf
793
- // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
794
- surfaceRec.roughness = roughness * roughness;
795
- surfaceRec.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
796
- surfaceRec.sheenRoughness = sheenRoughness * sheenRoughness;
797
-
798
- // frontFace is used to determine transmissive properties and PDF. If no transmission is used
799
- // then we can just always assume this is a front face.
800
- surfaceRec.frontFace = side == 1.0 || transmission == 0.0;
801
- surfaceRec.iorRatio = material.thinFilm || surfaceRec.frontFace ? 1.0 / material.ior : material.ior;
802
- surfaceRec.thinFilm = material.thinFilm;
803
-
804
- // Compute the filtered roughness value to use during specular reflection computations.
805
- // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
806
- // If we're exiting something transmissive then scale the factor down significantly so we can retain
807
- // sharp internal reflections
808
- surfaceRec.filteredRoughness = applyFilteredGlossy( surfaceRec.roughness, accumulatedRoughness );
809
- surfaceRec.filteredClearcoatRoughness = applyFilteredGlossy( surfaceRec.clearcoatRoughness, accumulatedClearcoatRoughness );
810
-
811
- mat3 normalBasis = getBasisFromNormal( surfaceRec.normal );
812
- mat3 invBasis = inverse( normalBasis );
813
-
814
- mat3 clearcoatNormalBasis = getBasisFromNormal( clearcoatNormal );
815
- mat3 clearcoatInvBasis = inverse( clearcoatNormalBasis );
816
-
817
- vec3 outgoing = - normalize( invBasis * rayDirection );
818
- vec3 clearcoatOutgoing = - normalize( clearcoatInvBasis * rayDirection );
819
- sampleRec = bsdfSample( outgoing, clearcoatOutgoing, normalBasis, invBasis, clearcoatNormalBasis, clearcoatInvBasis, surfaceRec );
820
-
821
- isShadowRay = sampleRec.specularPdf < rand();
822
-
823
- // adjust the hit point by the surface normal by a factor of some offset and the
824
- // maximum component-wise value of the current point to accommodate floating point
825
- // error as values increase.
826
- vec3 point = rayOrigin + rayDirection * dist;
827
- vec3 absPoint = abs( point );
828
- float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
829
- rayDirection = normalize( normalBasis * sampleRec.direction );
830
-
831
- bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
832
- rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
833
-
834
- // direct env map sampling
835
- #if FEATURE_MIS
836
-
837
- // uniformly pick a light or environment map
838
- if( rand() > 1.0 / float( lights.count + 1u ) ) {
839
-
840
- // sample a light or environment
841
- LightSampleRec lightSampleRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin );
842
-
843
- bool isSampleBelowSurface = dot( faceNormal, lightSampleRec.direction ) < 0.0;
844
- if ( isSampleBelowSurface ) {
845
-
846
- lightSampleRec.pdf = 0.0;
847
-
848
- }
849
-
850
- // check if a ray could even reach the light area
851
- if (
852
- lightSampleRec.pdf > 0.0 &&
853
- isDirectionValid( lightSampleRec.direction, normal, faceNormal ) &&
854
- ! anyCloserHit( bvh, rayOrigin, lightSampleRec.direction, lightSampleRec.dist )
855
- ) {
856
-
857
- // get the material pdf
858
- vec3 sampleColor;
859
- float lightMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * lightSampleRec.direction ), normalize( clearcoatInvBasis * lightSampleRec.direction ), surfaceRec, sampleColor );
860
- bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
861
- if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
862
-
863
- // weight the direct light contribution
864
- float lightPdf = lightSampleRec.pdf / float( lights.count + 1u );
865
- float misWeight = misHeuristic( lightPdf, lightMaterialPdf );
866
- gl_FragColor.rgb += lightSampleRec.emission * throughputColor * sampleColor * misWeight / lightPdf;
867
-
868
- }
869
-
870
- }
871
-
872
- } else {
873
-
874
- // find a sample in the environment map to include in the contribution
875
- vec3 envColor, envDirection;
876
- float envPdf = randomEnvMapSample( envMapInfo, envColor, envDirection );
877
- envDirection = invEnvironmentRotation * envDirection;
878
-
879
- // this env sampling is not set up for transmissive sampling and yields overly bright
880
- // results so we ignore the sample in this case.
881
- // TODO: this should be improved but how? The env samples could traverse a few layers?
882
- bool isSampleBelowSurface = dot( faceNormal, envDirection ) < 0.0;
883
- if ( isSampleBelowSurface ) {
884
-
885
- envPdf = 0.0;
886
-
887
- }
888
-
889
- // check if a ray could even reach the surface
890
- vec3 attenuatedColor;
891
- if (
892
- envPdf > 0.0 &&
893
- isDirectionValid( envDirection, normal, faceNormal ) &&
894
- ! attenuateHit( bvh, rayOrigin, envDirection, bounces - i, isShadowRay, attenuatedColor )
895
- ) {
896
-
897
- // get the material pdf
898
- vec3 sampleColor;
899
- float envMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * envDirection ), normalize( clearcoatInvBasis * envDirection ), surfaceRec, sampleColor );
900
- bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
901
- if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
902
-
903
- // weight the direct light contribution
904
- envPdf /= float( lights.count + 1u );
905
- float misWeight = misHeuristic( envPdf, envMaterialPdf );
906
- gl_FragColor.rgb += attenuatedColor * environmentIntensity * envColor * throughputColor * sampleColor * misWeight / envPdf;
907
-
908
- }
909
-
910
- }
911
-
912
- }
913
- #endif
914
-
915
- // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
916
- // to a single pixel resulting in fireflies
917
- if ( ! isBelowSurface ) {
918
-
919
- // determine if this is a rough normal or not by checking how far off straight up it is
920
- vec3 halfVector = normalize( outgoing + sampleRec.direction );
921
- accumulatedRoughness += sin( acosApprox( halfVector.z ) );
922
-
923
- vec3 clearcoatHalfVector = normalize( clearcoatOutgoing + sampleRec.clearcoatDirection );
924
- accumulatedClearcoatRoughness += sin( acosApprox( clearcoatHalfVector.z ) );
925
-
926
- transmissiveRay = false;
927
-
928
- }
929
-
930
- // accumulate color
931
- gl_FragColor.rgb += ( emission * throughputColor );
932
-
933
- // skip the sample if our PDF or ray is impossible
934
- if ( sampleRec.pdf <= 0.0 || ! isDirectionValid( rayDirection, normal, faceNormal) ) {
935
-
936
- break;
937
-
938
- }
939
-
940
- throughputColor *= sampleRec.color / sampleRec.pdf;
941
-
942
- // attenuate the throughput color by the medium color
943
- if ( side == - 1.0 ) {
944
-
945
- throughputColor *= transmissionAttenuation( dist, surfaceRec.attenuationColor, surfaceRec.attenuationDistance );
946
-
947
- }
948
-
949
- // discard the sample if there are any NaNs
950
- if ( any( isnan( throughputColor ) ) || any( isinf( throughputColor ) ) ) {
951
-
952
- break;
953
-
954
- }
955
-
956
- }
957
-
958
- gl_FragColor.a *= opacity;
959
-
960
- }
961
-
962
- `
963
-
964
- } );
965
-
966
- this.setValues( parameters );
967
-
968
- }
969
-
970
- }
1
+ import { Matrix4, Vector2 } from 'three';
2
+ import { MaterialBase } from './MaterialBase.js';
3
+ import {
4
+ MeshBVHUniformStruct, UIntVertexAttributeTexture,
5
+ shaderStructs, shaderIntersectFunction,
6
+ } from 'three-mesh-bvh';
7
+ import { shaderMaterialStructs, shaderLightStruct } from '../shader/shaderStructs.js';
8
+ import { MaterialsTexture } from '../uniforms/MaterialsTexture.js';
9
+ import { RenderTarget2DArray } from '../uniforms/RenderTarget2DArray.js';
10
+ import { shaderMaterialSampling } from '../shader/shaderMaterialSampling.js';
11
+ import { shaderEnvMapSampling } from '../shader/shaderEnvMapSampling.js';
12
+ import { shaderLightSampling } from '../shader/shaderLightSampling.js';
13
+ import { shaderUtils } from '../shader/shaderUtils.js';
14
+ import { shaderLayerTexelFetchFunctions } from '../shader/shaderLayerTexelFetchFunctions.js';
15
+ import { PhysicalCameraUniform } from '../uniforms/PhysicalCameraUniform.js';
16
+ import { EquirectHdrInfoUniform } from '../uniforms/EquirectHdrInfoUniform.js';
17
+ import { LightsInfoUniformStruct } from '../uniforms/LightsInfoUniformStruct.js';
18
+ import { IESProfilesTexture } from '../uniforms/IESProfilesTexture.js';
19
+ import { AttributesTextureArray } from '../uniforms/AttributesTextureArray.js';
20
+
21
+ export class PhysicalPathTracingMaterial extends MaterialBase {
22
+
23
+ onBeforeRender() {
24
+
25
+ this.setDefine( 'FEATURE_DOF', this.physicalCamera.bokehSize === 0 ? 0 : 1 );
26
+ this.setDefine( 'FEATURE_BACKGROUND_MAP', this.backgroundMap ? 1 : 0 );
27
+
28
+ }
29
+
30
+ constructor( parameters ) {
31
+
32
+ super( {
33
+
34
+ transparent: true,
35
+ depthWrite: false,
36
+
37
+ defines: {
38
+ FEATURE_MIS: 1,
39
+ FEATURE_DOF: 1,
40
+ FEATURE_BACKGROUND_MAP: 0,
41
+ TRANSPARENT_TRAVERSALS: 5,
42
+ // 0 = Perspective
43
+ // 1 = Orthographic
44
+ // 2 = Equirectangular
45
+ CAMERA_TYPE: 0,
46
+
47
+ ATTR_NORMAL: 0,
48
+ ATTR_TANGENT: 1,
49
+ ATTR_UV: 2,
50
+ ATTR_COLOR: 3,
51
+ },
52
+
53
+ uniforms: {
54
+ resolution: { value: new Vector2() },
55
+
56
+ bounces: { value: 3 },
57
+ physicalCamera: { value: new PhysicalCameraUniform() },
58
+
59
+ bvh: { value: new MeshBVHUniformStruct() },
60
+ attributesArray: { value: new AttributesTextureArray() },
61
+ materialIndexAttribute: { value: new UIntVertexAttributeTexture() },
62
+ materials: { value: new MaterialsTexture() },
63
+ textures: { value: new RenderTarget2DArray().texture },
64
+ lights: { value: new LightsInfoUniformStruct() },
65
+ iesProfiles: { value: new IESProfilesTexture().texture },
66
+ cameraWorldMatrix: { value: new Matrix4() },
67
+ invProjectionMatrix: { value: new Matrix4() },
68
+ backgroundBlur: { value: 0.0 },
69
+ environmentIntensity: { value: 1.0 },
70
+ environmentRotation: { value: new Matrix4() },
71
+ envMapInfo: { value: new EquirectHdrInfoUniform() },
72
+ backgroundMap: { value: null },
73
+
74
+ seed: { value: 0 },
75
+ opacity: { value: 1 },
76
+ filterGlossyFactor: { value: 0.0 },
77
+
78
+ backgroundAlpha: { value: 1.0 },
79
+ },
80
+
81
+ vertexShader: /* glsl */`
82
+
83
+ varying vec2 vUv;
84
+ void main() {
85
+
86
+ vec4 mvPosition = vec4( position, 1.0 );
87
+ mvPosition = modelViewMatrix * mvPosition;
88
+ gl_Position = projectionMatrix * mvPosition;
89
+
90
+ vUv = uv;
91
+
92
+ }
93
+
94
+ `,
95
+
96
+ fragmentShader: /* glsl */`
97
+ #define RAY_OFFSET 1e-4
98
+
99
+ precision highp isampler2D;
100
+ precision highp usampler2D;
101
+ precision highp sampler2DArray;
102
+ vec4 envMapTexelToLinear( vec4 a ) { return a; }
103
+ #include <common>
104
+
105
+ ${ shaderStructs }
106
+ ${ shaderIntersectFunction }
107
+ ${ shaderMaterialStructs }
108
+ ${ shaderLightStruct }
109
+
110
+ ${ shaderLayerTexelFetchFunctions }
111
+ ${ shaderUtils }
112
+ ${ shaderMaterialSampling }
113
+ ${ shaderEnvMapSampling }
114
+
115
+ uniform mat4 environmentRotation;
116
+ uniform float backgroundBlur;
117
+ uniform float backgroundAlpha;
118
+
119
+ #if FEATURE_BACKGROUND_MAP
120
+
121
+ uniform sampler2D backgroundMap;
122
+
123
+ #endif
124
+
125
+ #if FEATURE_DOF
126
+
127
+ uniform PhysicalCamera physicalCamera;
128
+
129
+ #endif
130
+
131
+ uniform vec2 resolution;
132
+ uniform int bounces;
133
+ uniform mat4 cameraWorldMatrix;
134
+ uniform mat4 invProjectionMatrix;
135
+ uniform sampler2DArray attributesArray;
136
+ uniform usampler2D materialIndexAttribute;
137
+ uniform BVH bvh;
138
+ uniform float environmentIntensity;
139
+ uniform float filterGlossyFactor;
140
+ uniform int seed;
141
+ uniform float opacity;
142
+ uniform sampler2D materials;
143
+ uniform LightsInfo lights;
144
+ uniform sampler2DArray iesProfiles;
145
+
146
+ ${ shaderLightSampling }
147
+
148
+ uniform EquirectHdrInfo envMapInfo;
149
+
150
+ uniform sampler2DArray textures;
151
+ varying vec2 vUv;
152
+
153
+ float applyFilteredGlossy( float roughness, float accumulatedRoughness ) {
154
+
155
+ return clamp(
156
+ max(
157
+ roughness,
158
+ accumulatedRoughness * filterGlossyFactor * 5.0 ),
159
+ 0.0,
160
+ 1.0
161
+ );
162
+
163
+ }
164
+
165
+ vec3 sampleBackground( vec3 direction ) {
166
+
167
+ vec3 sampleDir = normalize( direction + getHemisphereSample( direction, rand2() ) * 0.5 * backgroundBlur );
168
+
169
+ #if FEATURE_BACKGROUND_MAP
170
+
171
+ return sampleEquirectEnvMapColor( sampleDir, backgroundMap );
172
+
173
+ #else
174
+
175
+ return environmentIntensity * sampleEquirectEnvMapColor( sampleDir, envMapInfo.map );
176
+
177
+ #endif
178
+
179
+ }
180
+
181
+ // step through multiple surface hits and accumulate color attenuation based on transmissive surfaces
182
+ bool attenuateHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, int traversals, bool isShadowRay, out vec3 color ) {
183
+
184
+ // hit results
185
+ uvec4 faceIndices = uvec4( 0u );
186
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
187
+ vec3 barycoord = vec3( 0.0 );
188
+ float side = 1.0;
189
+ float dist = 0.0;
190
+
191
+ color = vec3( 1.0 );
192
+
193
+ for ( int i = 0; i < traversals; i ++ ) {
194
+
195
+ if ( bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) ) {
196
+
197
+ // TODO: attenuate the contribution based on the PDF of the resulting ray including refraction values
198
+ // Should be able to work using the material BSDF functions which will take into account specularity, etc.
199
+ // TODO: should we account for emissive surfaces here?
200
+
201
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, barycoord, faceIndices.xyz ).xy;
202
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, barycoord, faceIndices.xyz );
203
+
204
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
205
+ Material material = readMaterialInfo( materials, materialIndex );
206
+
207
+ // adjust the ray to the new surface
208
+ bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
209
+ vec3 point = rayOrigin + rayDirection * dist;
210
+ vec3 absPoint = abs( point );
211
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
212
+ rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
213
+
214
+ if ( ! material.castShadow && isShadowRay ) {
215
+
216
+ continue;
217
+
218
+ }
219
+
220
+ // Opacity Test
221
+
222
+ // albedo
223
+ vec4 albedo = vec4( material.color, material.opacity );
224
+ if ( material.map != - 1 ) {
225
+
226
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
227
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
228
+
229
+ }
230
+
231
+ if ( material.vertexColors ) {
232
+
233
+ albedo *= vertexColor;
234
+
235
+ }
236
+
237
+ // alphaMap
238
+ if ( material.alphaMap != - 1 ) {
239
+
240
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
241
+
242
+ }
243
+
244
+ // transmission
245
+ float transmission = material.transmission;
246
+ if ( material.transmissionMap != - 1 ) {
247
+
248
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
249
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
250
+
251
+ }
252
+
253
+ // metalness
254
+ float metalness = material.metalness;
255
+ if ( material.metalnessMap != - 1 ) {
256
+
257
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
258
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
259
+
260
+ }
261
+
262
+ float alphaTest = material.alphaTest;
263
+ bool useAlphaTest = alphaTest != 0.0;
264
+ float transmissionFactor = ( 1.0 - metalness ) * transmission;
265
+ if (
266
+ transmissionFactor < rand() && ! (
267
+ // material sidedness
268
+ material.side != 0.0 && side == material.side
269
+
270
+ // alpha test
271
+ || useAlphaTest && albedo.a < alphaTest
272
+
273
+ // opacity
274
+ || material.transparent && ! useAlphaTest && albedo.a < rand()
275
+ )
276
+ ) {
277
+
278
+ return true;
279
+
280
+ }
281
+
282
+ if ( side == 1.0 && isBelowSurface ) {
283
+
284
+ // only attenuate by surface color on the way in
285
+ color *= mix( vec3( 1.0 ), albedo.rgb, transmissionFactor );
286
+
287
+ } else if ( side == - 1.0 ) {
288
+
289
+ // attenuate by medium once we hit the opposite side of the model
290
+ color *= transmissionAttenuation( dist, material.attenuationColor, material.attenuationDistance );
291
+
292
+ }
293
+
294
+ } else {
295
+
296
+ return false;
297
+
298
+ }
299
+
300
+ }
301
+
302
+ return true;
303
+
304
+ }
305
+
306
+ // returns whether the ray hit anything before a certain distance, not just the first surface. Could be optimized to not check the full hierarchy.
307
+ bool anyCloserHit( BVH bvh, vec3 rayOrigin, vec3 rayDirection, float maxDist ) {
308
+
309
+ uvec4 faceIndices = uvec4( 0u );
310
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
311
+ vec3 barycoord = vec3( 0.0 );
312
+ float side = 1.0;
313
+ float dist = 0.0;
314
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
315
+ return hit && dist < maxDist;
316
+
317
+ }
318
+
319
+ // tentFilter from Peter Shirley's 'Realistic Ray Tracing (2nd Edition)' book, pg. 60
320
+ // erichlof/THREE.js-PathTracing-Renderer/
321
+ float tentFilter( float x ) {
322
+
323
+ return x < 0.5 ? sqrt( 2.0 * x ) - 1.0 : 1.0 - sqrt( 2.0 - ( 2.0 * x ) );
324
+
325
+ }
326
+
327
+ vec3 ndcToRayOrigin( vec2 coord ) {
328
+
329
+ vec4 rayOrigin4 = cameraWorldMatrix * invProjectionMatrix * vec4( coord, - 1.0, 1.0 );
330
+ return rayOrigin4.xyz / rayOrigin4.w;
331
+ }
332
+
333
+ void getCameraRay( out vec3 rayDirection, out vec3 rayOrigin ) {
334
+
335
+ vec2 ssd = vec2( 1.0 ) / resolution;
336
+
337
+ // Jitter the camera ray by finding a uv coordinate at a random sample
338
+ // around this pixel's UV coordinate
339
+ vec2 jitteredUv = vUv + vec2( tentFilter( rand() ) * ssd.x, tentFilter( rand() ) * ssd.y );
340
+
341
+ #if CAMERA_TYPE == 2
342
+
343
+ // Equirectangular projection
344
+
345
+ vec4 rayDirection4 = vec4( equirectUvToDirection( jitteredUv ), 0.0 );
346
+ vec4 rayOrigin4 = vec4( 0.0, 0.0, 0.0, 1.0 );
347
+
348
+ rayDirection4 = cameraWorldMatrix * rayDirection4;
349
+ rayOrigin4 = cameraWorldMatrix * rayOrigin4;
350
+
351
+ rayDirection = normalize( rayDirection4.xyz );
352
+ rayOrigin = rayOrigin4.xyz / rayOrigin4.w;
353
+
354
+ #else
355
+
356
+ // get [- 1, 1] normalized device coordinates
357
+ vec2 ndc = 2.0 * jitteredUv - vec2( 1.0 );
358
+
359
+ rayOrigin = ndcToRayOrigin( ndc );
360
+
361
+ #if CAMERA_TYPE == 1
362
+
363
+ // Orthographic projection
364
+
365
+ rayDirection = ( cameraWorldMatrix * vec4( 0.0, 0.0, - 1.0, 0.0 ) ).xyz;
366
+ rayDirection = normalize( rayDirection );
367
+
368
+ #else
369
+
370
+ // Perspective projection
371
+
372
+ rayDirection = normalize( mat3(cameraWorldMatrix) * ( invProjectionMatrix * vec4( ndc, 0.0, 1.0 ) ).xyz );
373
+
374
+ #endif
375
+
376
+ #endif
377
+
378
+ #if FEATURE_DOF
379
+ {
380
+
381
+ // depth of field
382
+ vec3 focalPoint = rayOrigin + normalize( rayDirection ) * physicalCamera.focusDistance;
383
+
384
+ // get the aperture sample
385
+ vec2 apertureSample = sampleAperture( physicalCamera.apertureBlades ) * physicalCamera.bokehSize * 0.5 * 1e-3;
386
+
387
+ // rotate the aperture shape
388
+ float ac = cos( physicalCamera.apertureRotation );
389
+ float as = sin( physicalCamera.apertureRotation );
390
+ apertureSample = vec2(
391
+ apertureSample.x * ac - apertureSample.y * as,
392
+ apertureSample.x * as + apertureSample.y * ac
393
+ );
394
+ apertureSample.x *= saturate( physicalCamera.anamorphicRatio );
395
+ apertureSample.y *= saturate( 1.0 / physicalCamera.anamorphicRatio );
396
+
397
+ // create the new ray
398
+ rayOrigin += ( cameraWorldMatrix * vec4( apertureSample, 0.0, 0.0 ) ).xyz;
399
+ rayDirection = focalPoint - rayOrigin;
400
+
401
+ }
402
+ #endif
403
+
404
+ rayDirection = normalize( rayDirection );
405
+
406
+ }
407
+
408
+ void main() {
409
+
410
+ rng_initialize( gl_FragCoord.xy, seed );
411
+
412
+ vec3 rayDirection;
413
+ vec3 rayOrigin;
414
+
415
+ getCameraRay( rayDirection, rayOrigin );
416
+
417
+ // inverse environment rotation
418
+ mat3 envRotation3x3 = mat3( environmentRotation );
419
+ mat3 invEnvRotation3x3 = inverse( envRotation3x3 );
420
+
421
+ // final color
422
+ gl_FragColor = vec4( 0.0 );
423
+ gl_FragColor.a = 1.0;
424
+
425
+ // hit results
426
+ uvec4 faceIndices = uvec4( 0u );
427
+ vec3 faceNormal = vec3( 0.0, 0.0, 1.0 );
428
+ vec3 barycoord = vec3( 0.0 );
429
+ float side = 1.0;
430
+ float dist = 0.0;
431
+
432
+ // path tracing state
433
+ float accumulatedRoughness = 0.0;
434
+ float accumulatedClearcoatRoughness = 0.0;
435
+ bool transmissiveRay = true;
436
+ int transparentTraversals = TRANSPARENT_TRAVERSALS;
437
+ vec3 throughputColor = vec3( 1.0 );
438
+ SampleRec sampleRec;
439
+ int i;
440
+ bool isShadowRay = false;
441
+
442
+ for ( i = 0; i < bounces; i ++ ) {
443
+
444
+ bool hit = bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist );
445
+
446
+ LightSampleRec lightHit = lightsClosestHit( lights.tex, lights.count, rayOrigin, rayDirection );
447
+
448
+ if ( lightHit.hit && ( lightHit.dist < dist || !hit ) ) {
449
+
450
+ if ( i == 0 || transmissiveRay ) {
451
+
452
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
453
+
454
+ } else {
455
+
456
+ #if FEATURE_MIS
457
+
458
+ // NOTE: we skip MIS for spotlights since we haven't fixed the forward
459
+ // path tracing code path, yet
460
+ if ( lightHit.type == SPOT_LIGHT_TYPE ) {
461
+
462
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
463
+
464
+ } else {
465
+
466
+ // weight the contribution
467
+ float misWeight = misHeuristic( sampleRec.pdf, lightHit.pdf / float( lights.count + 1u ) );
468
+ gl_FragColor.rgb += lightHit.emission * throughputColor * misWeight;
469
+
470
+ }
471
+
472
+ #else
473
+
474
+ gl_FragColor.rgb += lightHit.emission * throughputColor;
475
+
476
+ #endif
477
+
478
+ }
479
+ break;
480
+
481
+ }
482
+
483
+ if ( ! hit ) {
484
+
485
+ if ( i == 0 || transmissiveRay ) {
486
+
487
+ gl_FragColor.rgb += sampleBackground( envRotation3x3 * rayDirection ) * throughputColor;
488
+ gl_FragColor.a = backgroundAlpha;
489
+
490
+ } else {
491
+
492
+ #if FEATURE_MIS
493
+
494
+ // get the PDF of the hit envmap point
495
+ vec3 envColor;
496
+ float envPdf = envMapSample( envRotation3x3 * rayDirection, envMapInfo, envColor );
497
+ envPdf /= float( lights.count + 1u );
498
+
499
+ // and weight the contribution
500
+ float misWeight = misHeuristic( sampleRec.pdf, envPdf );
501
+ gl_FragColor.rgb += environmentIntensity * envColor * throughputColor * misWeight;
502
+
503
+ #else
504
+
505
+ gl_FragColor.rgb +=
506
+ environmentIntensity *
507
+ sampleEquirectEnvMapColor( envRotation3x3 * rayDirection, envMapInfo.map ) *
508
+ throughputColor;
509
+
510
+ #endif
511
+
512
+ }
513
+ break;
514
+
515
+ }
516
+
517
+ uint materialIndex = uTexelFetch1D( materialIndexAttribute, faceIndices.x ).r;
518
+ Material material = readMaterialInfo( materials, materialIndex );
519
+
520
+ if ( material.matte && i == 0 ) {
521
+
522
+ gl_FragColor = vec4( 0.0 );
523
+ break;
524
+
525
+ }
526
+
527
+ // if we've determined that this is a shadow ray and we've hit an item with no shadow casting
528
+ // then skip it
529
+ if ( ! material.castShadow && isShadowRay ) {
530
+
531
+ vec3 point = rayOrigin + rayDirection * dist;
532
+ vec3 absPoint = abs( point );
533
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
534
+ rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
535
+
536
+ continue;
537
+
538
+ }
539
+
540
+ // uv coord for textures
541
+ vec2 uv = textureSampleBarycoord( attributesArray, ATTR_UV, barycoord, faceIndices.xyz ).xy;
542
+ vec4 vertexColor = textureSampleBarycoord( attributesArray, ATTR_COLOR, barycoord, faceIndices.xyz );
543
+
544
+ // albedo
545
+ vec4 albedo = vec4( material.color, material.opacity );
546
+ if ( material.map != - 1 ) {
547
+
548
+ vec3 uvPrime = material.mapTransform * vec3( uv, 1 );
549
+ albedo *= texture2D( textures, vec3( uvPrime.xy, material.map ) );
550
+ }
551
+
552
+ if ( material.vertexColors ) {
553
+
554
+ albedo *= vertexColor;
555
+
556
+ }
557
+
558
+ // alphaMap
559
+ if ( material.alphaMap != - 1 ) {
560
+
561
+ albedo.a *= texture2D( textures, vec3( uv, material.alphaMap ) ).x;
562
+
563
+ }
564
+
565
+ // possibly skip this sample if it's transparent, alpha test is enabled, or we hit the wrong material side
566
+ // and it's single sided.
567
+ // - alpha test is disabled when it === 0
568
+ // - the material sidedness test is complicated because we want light to pass through the back side but still
569
+ // be able to see the front side. This boolean checks if the side we hit is the front side on the first ray
570
+ // and we're rendering the other then we skip it. Do the opposite on subsequent bounces to get incoming light.
571
+ float alphaTest = material.alphaTest;
572
+ bool useAlphaTest = alphaTest != 0.0;
573
+ if (
574
+ // material sidedness
575
+ material.side != 0.0 && side != material.side
576
+
577
+ // alpha test
578
+ || useAlphaTest && albedo.a < alphaTest
579
+
580
+ // opacity
581
+ || material.transparent && ! useAlphaTest && albedo.a < rand()
582
+ ) {
583
+
584
+ vec3 point = rayOrigin + rayDirection * dist;
585
+ vec3 absPoint = abs( point );
586
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
587
+ rayOrigin = point - ( maxPoint + 1.0 ) * faceNormal * RAY_OFFSET;
588
+
589
+ // only allow a limited number of transparency discards otherwise we could
590
+ // crash the context with too long a loop.
591
+ i -= sign( transparentTraversals );
592
+ transparentTraversals -= sign( transparentTraversals );
593
+ continue;
594
+
595
+ }
596
+
597
+ // fetch the interpolated smooth normal
598
+ vec3 normal = normalize( textureSampleBarycoord(
599
+ attributesArray,
600
+ ATTR_NORMAL,
601
+ barycoord,
602
+ faceIndices.xyz
603
+ ).xyz );
604
+
605
+ // roughness
606
+ float roughness = material.roughness;
607
+ if ( material.roughnessMap != - 1 ) {
608
+
609
+ vec3 uvPrime = material.roughnessMapTransform * vec3( uv, 1 );
610
+ roughness *= texture2D( textures, vec3( uvPrime.xy, material.roughnessMap ) ).g;
611
+
612
+ }
613
+
614
+ // metalness
615
+ float metalness = material.metalness;
616
+ if ( material.metalnessMap != - 1 ) {
617
+
618
+ vec3 uvPrime = material.metalnessMapTransform * vec3( uv, 1 );
619
+ metalness *= texture2D( textures, vec3( uvPrime.xy, material.metalnessMap ) ).b;
620
+
621
+ }
622
+
623
+ // emission
624
+ vec3 emission = material.emissiveIntensity * material.emissive;
625
+ if ( material.emissiveMap != - 1 ) {
626
+
627
+ vec3 uvPrime = material.emissiveMapTransform * vec3( uv, 1 );
628
+ emission *= texture2D( textures, vec3( uvPrime.xy, material.emissiveMap ) ).xyz;
629
+
630
+ }
631
+
632
+ // transmission
633
+ float transmission = material.transmission;
634
+ if ( material.transmissionMap != - 1 ) {
635
+
636
+ vec3 uvPrime = material.transmissionMapTransform * vec3( uv, 1 );
637
+ transmission *= texture2D( textures, vec3( uvPrime.xy, material.transmissionMap ) ).r;
638
+
639
+ }
640
+
641
+ // normal
642
+ vec3 baseNormal = normal;
643
+ if ( material.normalMap != - 1 ) {
644
+
645
+ vec4 tangentSample = textureSampleBarycoord(
646
+ attributesArray,
647
+ ATTR_TANGENT,
648
+ barycoord,
649
+ faceIndices.xyz
650
+ );
651
+
652
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
653
+ // resulting in NaNs and slow path tracing.
654
+ if ( length( tangentSample.xyz ) > 0.0 ) {
655
+
656
+ vec3 tangent = normalize( tangentSample.xyz );
657
+ vec3 bitangent = normalize( cross( normal, tangent ) * tangentSample.w );
658
+ mat3 vTBN = mat3( tangent, bitangent, normal );
659
+
660
+ vec3 uvPrime = material.normalMapTransform * vec3( uv, 1 );
661
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.normalMap ) ).xyz * 2.0 - 1.0;
662
+ texNormal.xy *= material.normalScale;
663
+ normal = vTBN * texNormal;
664
+
665
+ }
666
+
667
+ }
668
+
669
+ normal *= side;
670
+
671
+ // clearcoat
672
+ float clearcoat = material.clearcoat;
673
+ if ( material.clearcoatMap != - 1 ) {
674
+
675
+ vec3 uvPrime = material.clearcoatMapTransform * vec3( uv, 1 );
676
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatMap ) ).r;
677
+
678
+ }
679
+
680
+ // clearcoatRoughness
681
+ float clearcoatRoughness = material.clearcoatRoughness;
682
+ if ( material.clearcoatRoughnessMap != - 1 ) {
683
+
684
+ vec3 uvPrime = material.clearcoatRoughnessMapTransform * vec3( uv, 1 );
685
+ clearcoat *= texture2D( textures, vec3( uvPrime.xy, material.clearcoatRoughnessMap ) ).g;
686
+
687
+ }
688
+
689
+ // clearcoatNormal
690
+ vec3 clearcoatNormal = baseNormal;
691
+ if ( material.clearcoatNormalMap != - 1 ) {
692
+
693
+ vec4 tangentSample = textureSampleBarycoord(
694
+ attributesArray,
695
+ ATTR_TANGENT,
696
+ barycoord,
697
+ faceIndices.xyz
698
+ );
699
+
700
+ // some provided tangents can be malformed (0, 0, 0) causing the normal to be degenerate
701
+ // resulting in NaNs and slow path tracing.
702
+ if ( length( tangentSample.xyz ) > 0.0 ) {
703
+
704
+ vec3 tangent = normalize( tangentSample.xyz );
705
+ vec3 bitangent = normalize( cross( clearcoatNormal, tangent ) * tangentSample.w );
706
+ mat3 vTBN = mat3( tangent, bitangent, clearcoatNormal );
707
+
708
+ vec3 uvPrime = material.clearcoatNormalMapTransform * vec3( uv, 1 );
709
+ vec3 texNormal = texture2D( textures, vec3( uvPrime.xy, material.clearcoatNormalMap ) ).xyz * 2.0 - 1.0;
710
+ texNormal.xy *= material.clearcoatNormalScale;
711
+ clearcoatNormal = vTBN * texNormal;
712
+
713
+ }
714
+
715
+ }
716
+
717
+ clearcoatNormal *= side;
718
+
719
+ // sheenColor
720
+ vec3 sheenColor = material.sheenColor;
721
+ if ( material.sheenColorMap != - 1 ) {
722
+
723
+ vec3 uvPrime = material.sheenColorMapTransform * vec3( uv, 1 );
724
+ sheenColor *= texture2D( textures, vec3( uvPrime.xy, material.sheenColorMap ) ).rgb;
725
+
726
+ }
727
+
728
+ // sheenRoughness
729
+ float sheenRoughness = material.sheenRoughness;
730
+ if ( material.sheenRoughnessMap != - 1 ) {
731
+
732
+ vec3 uvPrime = material.sheenRoughnessMapTransform * vec3( uv, 1 );
733
+ sheenRoughness *= texture2D( textures, vec3( uvPrime.xy, material.sheenRoughnessMap ) ).a;
734
+
735
+ }
736
+
737
+ // iridescence
738
+ float iridescence = material.iridescence;
739
+ if ( material.iridescenceMap != - 1 ) {
740
+
741
+ vec3 uvPrime = material.iridescenceMapTransform * vec3( uv, 1 );
742
+ iridescence *= texture2D( textures, vec3( uvPrime.xy, material.iridescenceMap ) ).r;
743
+
744
+ }
745
+
746
+ // iridescence thickness
747
+ float iridescenceThickness = material.iridescenceThicknessMaximum;
748
+ if ( material.iridescenceThicknessMap != - 1 ) {
749
+
750
+ vec3 uvPrime = material.iridescenceThicknessMapTransform * vec3( uv, 1 );
751
+ float iridescenceThicknessSampled = texture2D( textures, vec3( uvPrime.xy, material.iridescenceThicknessMap ) ).g;
752
+ iridescenceThickness = mix( material.iridescenceThicknessMinimum, material.iridescenceThicknessMaximum, iridescenceThicknessSampled );
753
+
754
+ }
755
+
756
+ iridescence = iridescenceThickness == 0.0 ? 0.0 : iridescence;
757
+
758
+ // specular color
759
+ vec3 specularColor = material.specularColor;
760
+ if ( material.specularColorMap != - 1 ) {
761
+
762
+ vec3 uvPrime = material.specularColorMapTransform * vec3( uv, 1 );
763
+ specularColor *= texture2D( textures, vec3( uvPrime.xy, material.specularColorMap ) ).rgb;
764
+
765
+ }
766
+
767
+ // specular intensity
768
+ float specularIntensity = material.specularIntensity;
769
+ if ( material.specularIntensityMap != - 1 ) {
770
+
771
+ vec3 uvPrime = material.specularIntensityMapTransform * vec3( uv, 1 );
772
+ specularIntensity *= texture2D( textures, vec3( uvPrime.xy, material.specularIntensityMap ) ).a;
773
+
774
+ }
775
+
776
+ SurfaceRec surfaceRec;
777
+ surfaceRec.normal = normal;
778
+ surfaceRec.faceNormal = faceNormal;
779
+ surfaceRec.transmission = transmission;
780
+ surfaceRec.ior = material.ior;
781
+ surfaceRec.emission = emission;
782
+ surfaceRec.metalness = metalness;
783
+ surfaceRec.color = albedo.rgb;
784
+ surfaceRec.clearcoat = clearcoat;
785
+ surfaceRec.sheenColor = sheenColor;
786
+ surfaceRec.iridescence = iridescence;
787
+ surfaceRec.iridescenceIor = material.iridescenceIor;
788
+ surfaceRec.iridescenceThickness = iridescenceThickness;
789
+ surfaceRec.specularColor = specularColor;
790
+ surfaceRec.specularIntensity = specularIntensity;
791
+ surfaceRec.attenuationColor = material.attenuationColor;
792
+ surfaceRec.attenuationDistance = material.attenuationDistance;
793
+
794
+ // apply perceptual roughness factor from gltf
795
+ // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#microfacet-surfaces
796
+ surfaceRec.roughness = roughness * roughness;
797
+ surfaceRec.clearcoatRoughness = clearcoatRoughness * clearcoatRoughness;
798
+ surfaceRec.sheenRoughness = sheenRoughness * sheenRoughness;
799
+
800
+ // frontFace is used to determine transmissive properties and PDF. If no transmission is used
801
+ // then we can just always assume this is a front face.
802
+ surfaceRec.frontFace = side == 1.0 || transmission == 0.0;
803
+ surfaceRec.eta = material.thinFilm || surfaceRec.frontFace ? 1.0 / material.ior : material.ior;
804
+ surfaceRec.f0 = iorRatioToF0( surfaceRec.eta );
805
+ surfaceRec.thinFilm = material.thinFilm;
806
+
807
+ // Compute the filtered roughness value to use during specular reflection computations.
808
+ // The accumulated roughness value is scaled by a user setting and a "magic value" of 5.0.
809
+ // If we're exiting something transmissive then scale the factor down significantly so we can retain
810
+ // sharp internal reflections
811
+ surfaceRec.filteredRoughness = applyFilteredGlossy( surfaceRec.roughness, accumulatedRoughness );
812
+ surfaceRec.filteredClearcoatRoughness = applyFilteredGlossy( surfaceRec.clearcoatRoughness, accumulatedClearcoatRoughness );
813
+
814
+ mat3 normalBasis = getBasisFromNormal( surfaceRec.normal );
815
+ mat3 invBasis = inverse( normalBasis );
816
+
817
+ mat3 clearcoatNormalBasis = getBasisFromNormal( clearcoatNormal );
818
+ mat3 clearcoatInvBasis = inverse( clearcoatNormalBasis );
819
+
820
+ vec3 outgoing = - normalize( invBasis * rayDirection );
821
+ vec3 clearcoatOutgoing = - normalize( clearcoatInvBasis * rayDirection );
822
+ sampleRec = bsdfSample( outgoing, clearcoatOutgoing, normalBasis, invBasis, clearcoatNormalBasis, clearcoatInvBasis, surfaceRec );
823
+
824
+ isShadowRay = sampleRec.specularPdf < rand();
825
+
826
+ // adjust the hit point by the surface normal by a factor of some offset and the
827
+ // maximum component-wise value of the current point to accommodate floating point
828
+ // error as values increase.
829
+ vec3 point = rayOrigin + rayDirection * dist;
830
+ vec3 absPoint = abs( point );
831
+ float maxPoint = max( absPoint.x, max( absPoint.y, absPoint.z ) );
832
+ rayDirection = normalize( normalBasis * sampleRec.direction );
833
+
834
+ bool isBelowSurface = dot( rayDirection, faceNormal ) < 0.0;
835
+ rayOrigin = point + faceNormal * ( maxPoint + 1.0 ) * ( isBelowSurface ? - RAY_OFFSET : RAY_OFFSET );
836
+
837
+ // direct env map sampling
838
+ #if FEATURE_MIS
839
+
840
+ // uniformly pick a light or environment map
841
+ if( rand() > 1.0 / float( lights.count + 1u ) ) {
842
+
843
+ // sample a light or environment
844
+ LightSampleRec lightSampleRec = randomLightSample( lights.tex, iesProfiles, lights.count, rayOrigin );
845
+
846
+ bool isSampleBelowSurface = dot( faceNormal, lightSampleRec.direction ) < 0.0;
847
+ if ( isSampleBelowSurface ) {
848
+
849
+ lightSampleRec.pdf = 0.0;
850
+
851
+ }
852
+
853
+ // check if a ray could even reach the light area
854
+ if (
855
+ lightSampleRec.pdf > 0.0 &&
856
+ isDirectionValid( lightSampleRec.direction, normal, faceNormal ) &&
857
+ ! anyCloserHit( bvh, rayOrigin, lightSampleRec.direction, lightSampleRec.dist )
858
+ ) {
859
+
860
+ // get the material pdf
861
+ vec3 sampleColor;
862
+ float lightMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * lightSampleRec.direction ), normalize( clearcoatInvBasis * lightSampleRec.direction ), surfaceRec, sampleColor );
863
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
864
+ if ( lightMaterialPdf > 0.0 && isValidSampleColor ) {
865
+
866
+ // weight the direct light contribution
867
+ float lightPdf = lightSampleRec.pdf / float( lights.count + 1u );
868
+ float misWeight = misHeuristic( lightPdf, lightMaterialPdf );
869
+ gl_FragColor.rgb += lightSampleRec.emission * throughputColor * sampleColor * misWeight / lightPdf;
870
+
871
+ }
872
+
873
+ }
874
+
875
+ } else {
876
+
877
+ // find a sample in the environment map to include in the contribution
878
+ vec3 envColor, envDirection;
879
+ float envPdf = randomEnvMapSample( envMapInfo, envColor, envDirection );
880
+ envDirection = invEnvRotation3x3 * envDirection;
881
+
882
+ // this env sampling is not set up for transmissive sampling and yields overly bright
883
+ // results so we ignore the sample in this case.
884
+ // TODO: this should be improved but how? The env samples could traverse a few layers?
885
+ bool isSampleBelowSurface = dot( faceNormal, envDirection ) < 0.0;
886
+ if ( isSampleBelowSurface ) {
887
+
888
+ envPdf = 0.0;
889
+
890
+ }
891
+
892
+ // check if a ray could even reach the surface
893
+ vec3 attenuatedColor;
894
+ if (
895
+ envPdf > 0.0 &&
896
+ isDirectionValid( envDirection, normal, faceNormal ) &&
897
+ ! attenuateHit( bvh, rayOrigin, envDirection, bounces - i, isShadowRay, attenuatedColor )
898
+ ) {
899
+
900
+ // get the material pdf
901
+ vec3 sampleColor;
902
+ float envMaterialPdf = bsdfResult( outgoing, clearcoatOutgoing, normalize( invBasis * envDirection ), normalize( clearcoatInvBasis * envDirection ), surfaceRec, sampleColor );
903
+ bool isValidSampleColor = all( greaterThanEqual( sampleColor, vec3( 0.0 ) ) );
904
+ if ( envMaterialPdf > 0.0 && isValidSampleColor ) {
905
+
906
+ // weight the direct light contribution
907
+ envPdf /= float( lights.count + 1u );
908
+ float misWeight = misHeuristic( envPdf, envMaterialPdf );
909
+ gl_FragColor.rgb += attenuatedColor * environmentIntensity * envColor * throughputColor * sampleColor * misWeight / envPdf;
910
+
911
+ }
912
+
913
+ }
914
+
915
+ }
916
+ #endif
917
+
918
+ // accumulate a roughness value to offset diffuse, specular, diffuse rays that have high contribution
919
+ // to a single pixel resulting in fireflies
920
+ if ( ! isBelowSurface ) {
921
+
922
+ // determine if this is a rough normal or not by checking how far off straight up it is
923
+ vec3 halfVector = normalize( outgoing + sampleRec.direction );
924
+ accumulatedRoughness += sin( acosApprox( halfVector.z ) );
925
+
926
+ vec3 clearcoatHalfVector = normalize( clearcoatOutgoing + sampleRec.clearcoatDirection );
927
+ accumulatedClearcoatRoughness += sin( acosApprox( clearcoatHalfVector.z ) );
928
+
929
+ transmissiveRay = false;
930
+
931
+ }
932
+
933
+ // accumulate color
934
+ gl_FragColor.rgb += ( emission * throughputColor );
935
+
936
+ // skip the sample if our PDF or ray is impossible
937
+ if ( sampleRec.pdf <= 0.0 || ! isDirectionValid( rayDirection, normal, faceNormal) ) {
938
+
939
+ break;
940
+
941
+ }
942
+
943
+ throughputColor *= sampleRec.color / sampleRec.pdf;
944
+
945
+ // attenuate the throughput color by the medium color
946
+ if ( side == - 1.0 ) {
947
+
948
+ throughputColor *= transmissionAttenuation( dist, surfaceRec.attenuationColor, surfaceRec.attenuationDistance );
949
+
950
+ }
951
+
952
+ // discard the sample if there are any NaNs
953
+ if ( any( isnan( throughputColor ) ) || any( isinf( throughputColor ) ) ) {
954
+
955
+ break;
956
+
957
+ }
958
+
959
+ }
960
+
961
+ gl_FragColor.a *= opacity;
962
+
963
+ }
964
+
965
+ `
966
+
967
+ } );
968
+
969
+ this.setValues( parameters );
970
+
971
+ }
972
+
973
+ }