1 #ifdef ADAPTIVE_SAMPLING
2 #extension GL_ARB_shader_image_load_store : require
3 #extension GL_NV_shader_atomic_float : require
7 #extension GL_ARB_bindless_texture : require
10 //! Normalized pixel coordinates.
13 //! Sub-pixel offset in X direction for FSAA.
14 uniform float uOffsetX = 0.f;
15 //! Sub-pixel offset in Y direction for FSAA.
16 uniform float uOffsetY = 0.f;
18 //! Origin of viewing ray in left-top corner.
19 uniform vec3 uOriginLT;
20 //! Origin of viewing ray in left-bottom corner.
21 uniform vec3 uOriginLB;
22 //! Origin of viewing ray in right-top corner.
23 uniform vec3 uOriginRT;
24 //! Origin of viewing ray in right-bottom corner.
25 uniform vec3 uOriginRB;
27 //! Width of the rendering window.
28 uniform int uWinSizeX;
29 //! Height of the rendering window.
30 uniform int uWinSizeY;
32 //! Direction of viewing ray in left-top corner.
33 uniform vec3 uDirectLT;
34 //! Direction of viewing ray in left-bottom corner.
35 uniform vec3 uDirectLB;
36 //! Direction of viewing ray in right-top corner.
37 uniform vec3 uDirectRT;
38 //! Direction of viewing ray in right-bottom corner.
39 uniform vec3 uDirectRB;
41 //! Inverse model-view-projection matrix.
42 uniform mat4 uUnviewMat;
44 //! Model-view-projection matrix.
45 uniform mat4 uViewMat;
47 //! Texture buffer of data records of bottom-level BVH nodes.
48 uniform isamplerBuffer uSceneNodeInfoTexture;
49 //! Texture buffer of minimum points of bottom-level BVH nodes.
50 uniform samplerBuffer uSceneMinPointTexture;
51 //! Texture buffer of maximum points of bottom-level BVH nodes.
52 uniform samplerBuffer uSceneMaxPointTexture;
53 //! Texture buffer of transformations of high-level BVH nodes.
54 uniform samplerBuffer uSceneTransformTexture;
56 //! Texture buffer of vertex coords.
57 uniform samplerBuffer uGeometryVertexTexture;
58 //! Texture buffer of vertex normals.
59 uniform samplerBuffer uGeometryNormalTexture;
61 //! Texture buffer of per-vertex UV-coordinates.
62 uniform samplerBuffer uGeometryTexCrdTexture;
64 //! Texture buffer of triangle indices.
65 uniform isamplerBuffer uGeometryTriangTexture;
67 //! Texture buffer of material properties.
68 uniform samplerBuffer uRaytraceMaterialTexture;
69 //! Texture buffer of light source properties.
70 uniform samplerBuffer uRaytraceLightSrcTexture;
71 //! Environment map texture.
72 uniform sampler2D uEnvironmentMapTexture;
74 //! Total number of light sources.
75 uniform int uLightCount;
76 //! Intensity of global ambient light.
77 uniform vec4 uGlobalAmbient;
79 //! Enables/disables hard shadows.
80 uniform int uShadowsEnabled;
81 //! Enables/disables specular reflections.
82 uniform int uReflectEnabled;
83 //! Enables/disables spherical environment map.
84 uniform int uSphereMapEnabled;
85 //! Enables/disables environment map background.
86 uniform int uSphereMapForBack;
88 //! Radius of bounding sphere of the scene.
89 uniform float uSceneRadius;
90 //! Scene epsilon to prevent self-intersections.
91 uniform float uSceneEpsilon;
94 //! Unique 64-bit handles of OpenGL textures.
95 uniform uvec2 uTextureSamplers[MAX_TEX_NUMBER];
98 #ifdef ADAPTIVE_SAMPLING
99 //! OpenGL image used for accumulating rendering result.
100 volatile restrict layout(size1x32) uniform image2D uRenderImage;
102 //! OpenGL image storing offsets of sampled pixels blocks.
103 coherent restrict layout(size2x32) uniform iimage2D uOffsetImage;
106 //! Top color of gradient background.
107 uniform vec4 uBackColorTop = vec4 (0.0);
108 //! Bottom color of gradient background.
109 uniform vec4 uBackColorBot = vec4 (0.0);
111 /////////////////////////////////////////////////////////////////////////////////////////
112 // Specific data types
114 //! Stores ray parameters.
122 //! Stores intersection parameters.
132 /////////////////////////////////////////////////////////////////////////////////////////
133 // Some useful constants
135 #define MAXFLOAT 1e15f
137 #define SMALL vec3 (exp2 (-80.0f))
139 #define ZERO vec3 (0.0f, 0.0f, 0.0f)
140 #define UNIT vec3 (1.0f, 1.0f, 1.0f)
142 #define AXIS_X vec3 (1.0f, 0.0f, 0.0f)
143 #define AXIS_Y vec3 (0.0f, 1.0f, 0.0f)
144 #define AXIS_Z vec3 (0.0f, 0.0f, 1.0f)
146 #define M_PI 3.14159265f
148 #define LUMA vec3 (0.2126f, 0.7152f, 0.0722f)
150 // =======================================================================
151 // function : MatrixRowMultiplyDir
152 // purpose : Multiplies a vector by matrix
153 // =======================================================================
154 vec3 MatrixRowMultiplyDir (in vec3 v,
159 return vec3 (dot (m0.xyz, v),
164 //! 32-bit state of random number generator.
167 // =======================================================================
168 // function : SeedRand
169 // purpose : Applies hash function by Thomas Wang to randomize seeds
170 // (see http://www.burtleburtle.net/bob/hash/integer.html)
171 // =======================================================================
172 void SeedRand (in int theSeed, in int theSizeX, in int theRadius)
174 RandState = uint (int (gl_FragCoord.y) / theRadius * theSizeX + int (gl_FragCoord.x) / theRadius + theSeed);
176 RandState = (RandState + 0x479ab41du) + (RandState << 8);
177 RandState = (RandState ^ 0xe4aa10ceu) ^ (RandState >> 5);
178 RandState = (RandState + 0x9942f0a6u) - (RandState << 14);
179 RandState = (RandState ^ 0x5aedd67du) ^ (RandState >> 3);
180 RandState = (RandState + 0x17bea992u) + (RandState << 7);
183 // =======================================================================
184 // function : RandInt
185 // purpose : Generates integer using Xorshift algorithm by G. Marsaglia
186 // =======================================================================
189 RandState ^= (RandState << 13);
190 RandState ^= (RandState >> 17);
191 RandState ^= (RandState << 5);
196 // =======================================================================
197 // function : RandFloat
198 // purpose : Generates a random float in [0, 1) range
199 // =======================================================================
202 return float (RandInt()) * (1.f / 4294967296.f);
205 // =======================================================================
206 // function : MatrixColMultiplyPnt
207 // purpose : Multiplies a vector by matrix
208 // =======================================================================
209 vec3 MatrixColMultiplyPnt (in vec3 v,
215 return vec3 (m0.x * v.x + m1.x * v.y + m2.x * v.z + m3.x,
216 m0.y * v.x + m1.y * v.y + m2.y * v.z + m3.y,
217 m0.z * v.x + m1.z * v.y + m2.z * v.z + m3.z);
220 // =======================================================================
221 // function : MatrixColMultiplyDir
222 // purpose : Multiplies a vector by matrix
223 // =======================================================================
224 vec3 MatrixColMultiplyDir (in vec3 v,
229 return vec3 (m0.x * v.x + m1.x * v.y + m2.x * v.z,
230 m0.y * v.x + m1.y * v.y + m2.y * v.z,
231 m0.z * v.x + m1.z * v.y + m2.z * v.z);
234 //=======================================================================
235 // function : InverseDirection
236 // purpose : Returns safely inverted direction of the given one
237 //=======================================================================
238 vec3 InverseDirection (in vec3 theInput)
240 vec3 anInverse = 1.f / max (abs (theInput), SMALL);
242 return mix (-anInverse, anInverse, step (ZERO, theInput));
245 //=======================================================================
246 // function : BackgroundColor
247 // purpose : Returns color of gradient background
248 //=======================================================================
249 vec4 BackgroundColor()
251 #ifdef ADAPTIVE_SAMPLING
253 ivec2 aFragCoord = ivec2 (gl_FragCoord.xy);
255 ivec2 aTileXY = imageLoad (uOffsetImage, ivec2 (aFragCoord.x / BLOCK_SIZE,
256 aFragCoord.y / BLOCK_SIZE)).xy;
258 aTileXY.y += aFragCoord.y % min (uWinSizeY - aTileXY.y, BLOCK_SIZE);
260 return mix (uBackColorBot, uBackColorTop, float (aTileXY.y) / uWinSizeY);
264 return mix (uBackColorBot, uBackColorTop, vPixel.y);
269 /////////////////////////////////////////////////////////////////////////////////////////
270 // Functions for compute ray-object intersection
272 // =======================================================================
273 // function : GenerateRay
275 // =======================================================================
276 SRay GenerateRay (in vec2 thePixel)
278 vec3 aP0 = mix (uOriginLB, uOriginRB, thePixel.x);
279 vec3 aP1 = mix (uOriginLT, uOriginRT, thePixel.x);
281 vec3 aD0 = mix (uDirectLB, uDirectRB, thePixel.x);
282 vec3 aD1 = mix (uDirectLT, uDirectRT, thePixel.x);
284 vec3 aDirection = normalize (mix (aD0, aD1, thePixel.y));
286 return SRay (mix (aP0, aP1, thePixel.y), aDirection);
289 // =======================================================================
290 // function : IntersectSphere
291 // purpose : Computes ray-sphere intersection
292 // =======================================================================
293 float IntersectSphere (in SRay theRay, in float theRadius)
295 float aDdotD = dot (theRay.Direct, theRay.Direct);
296 float aDdotO = dot (theRay.Direct, theRay.Origin);
297 float aOdotO = dot (theRay.Origin, theRay.Origin);
299 float aD = aDdotO * aDdotO - aDdotD * (aOdotO - theRadius * theRadius);
303 float aTime = (sqrt (aD) - aDdotO) * (1.0f / aDdotD);
305 return aTime > 0.0f ? aTime : MAXFLOAT;
311 // =======================================================================
312 // function : IntersectTriangle
313 // purpose : Computes ray-triangle intersection (branchless version)
314 // =======================================================================
315 void IntersectTriangle (in SRay theRay,
322 vec3 aToTrg = thePnt0 - theRay.Origin;
324 vec3 aEdge0 = thePnt1 - thePnt0;
325 vec3 aEdge1 = thePnt0 - thePnt2;
327 theNorm = cross (aEdge1, aEdge0);
329 vec3 theVect = cross (theRay.Direct, aToTrg);
331 theUVT = vec3 (dot (theNorm, aToTrg),
332 dot (theVect, aEdge1),
333 dot (theVect, aEdge0)) * (1.f / dot (theNorm, theRay.Direct));
335 theUVT.x = any (lessThan (theUVT, ZERO)) || (theUVT.y + theUVT.z) > 1.f ? MAXFLOAT : theUVT.x;
338 #define EMPTY_ROOT ivec4(0)
340 //! Utility structure containing information about
341 //! currently traversing sub-tree of scene's BVH.
347 //! Inversed ray direction.
350 //! Parameters of sub-root node.
354 #define MATERIAL_AMBN(index) (18 * index + 0)
355 #define MATERIAL_DIFF(index) (18 * index + 1)
356 #define MATERIAL_SPEC(index) (18 * index + 2)
357 #define MATERIAL_EMIS(index) (18 * index + 3)
358 #define MATERIAL_REFL(index) (18 * index + 4)
359 #define MATERIAL_REFR(index) (18 * index + 5)
360 #define MATERIAL_TRAN(index) (18 * index + 6)
361 #define MATERIAL_TRS1(index) (18 * index + 7)
362 #define MATERIAL_TRS2(index) (18 * index + 8)
363 #define MATERIAL_TRS3(index) (18 * index + 9)
365 #define TRS_OFFSET(treelet) treelet.SubData.x
366 #define BVH_OFFSET(treelet) treelet.SubData.y
367 #define VRT_OFFSET(treelet) treelet.SubData.z
368 #define TRG_OFFSET(treelet) treelet.SubData.w
370 //! Identifies the absence of intersection.
371 #define INALID_HIT ivec4 (-1)
373 //! Global stack shared between traversal functions.
374 int Stack[STACK_SIZE];
376 // =======================================================================
379 // =======================================================================
380 int pop (inout int theHead)
382 int aData = Stack[theHead];
384 int aMask = aData >> 26;
385 int aNode = aMask & 0x3;
389 if ((aMask & 0x3) == aNode)
395 aMask |= (aMask << 2) & 0x30;
397 Stack[theHead] = (aData & 0x03FFFFFF) | (aMask << 26);
400 return (aData & 0x03FFFFFF) + aNode;
403 // =======================================================================
404 // function : SceneNearestHit
405 // purpose : Finds intersection with nearest scene triangle
406 // =======================================================================
407 ivec4 SceneNearestHit (in SRay theRay, in vec3 theInverse, inout SIntersect theHit, out int theTrsfId)
409 ivec4 aTriIndex = INALID_HIT;
411 int aNode = 0; // node to traverse
412 int aHead = -1; // pointer of stack
413 int aStop = -1; // BVH level switch
415 SSubTree aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
417 for (bool toContinue = true; toContinue; /* none */)
419 ivec4 aData = texelFetch (uSceneNodeInfoTexture, aNode);
421 if (aData.x == 0) // if inner node
423 aData.y += BVH_OFFSET (aSubTree);
425 vec4 aHitTimes = vec4 (MAXFLOAT,
430 vec3 aRayOriginInverse = -aSubTree.TrsfRay.Origin * aSubTree.Inverse;
432 vec3 aNodeMin0 = texelFetch (uSceneMinPointTexture, aData.y + 0).xyz * aSubTree.Inverse + aRayOriginInverse;
433 vec3 aNodeMin1 = texelFetch (uSceneMinPointTexture, aData.y + 1).xyz * aSubTree.Inverse + aRayOriginInverse;
434 vec3 aNodeMin2 = texelFetch (uSceneMinPointTexture, aData.y + min (2, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
435 vec3 aNodeMin3 = texelFetch (uSceneMinPointTexture, aData.y + min (3, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
436 vec3 aNodeMax0 = texelFetch (uSceneMaxPointTexture, aData.y + 0).xyz * aSubTree.Inverse + aRayOriginInverse;
437 vec3 aNodeMax1 = texelFetch (uSceneMaxPointTexture, aData.y + 1).xyz * aSubTree.Inverse + aRayOriginInverse;
438 vec3 aNodeMax2 = texelFetch (uSceneMaxPointTexture, aData.y + min (2, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
439 vec3 aNodeMax3 = texelFetch (uSceneMaxPointTexture, aData.y + min (3, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
441 vec3 aTimeMax = max (aNodeMin0, aNodeMax0);
442 vec3 aTimeMin = min (aNodeMin0, aNodeMax0);
444 float aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
445 float aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
447 aHitTimes.x = mix (MAXFLOAT, aTimeEnter,
448 aTimeEnter <= aTimeLeave && aTimeEnter <= theHit.Time && aTimeLeave >= 0.f);
450 aTimeMax = max (aNodeMin1, aNodeMax1);
451 aTimeMin = min (aNodeMin1, aNodeMax1);
453 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
454 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
456 aHitTimes.y = mix (MAXFLOAT, aTimeEnter,
457 aTimeEnter <= aTimeLeave && aTimeEnter <= theHit.Time && aTimeLeave >= 0.f);
459 aTimeMax = max (aNodeMin2, aNodeMax2);
460 aTimeMin = min (aNodeMin2, aNodeMax2);
462 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
463 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
465 aHitTimes.z = mix (MAXFLOAT, aTimeEnter,
466 aTimeEnter <= aTimeLeave && aTimeEnter <= theHit.Time && aTimeLeave >= 0.f && aData.z > 1);
468 aTimeMax = max (aNodeMin3, aNodeMax3);
469 aTimeMin = min (aNodeMin3, aNodeMax3);
471 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
472 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
474 aHitTimes.w = mix (MAXFLOAT, aTimeEnter,
475 aTimeEnter <= aTimeLeave && aTimeEnter <= theHit.Time && aTimeLeave >= 0.f && aData.z > 2);
477 ivec4 aChildren = ivec4 (0, 1, 2, 3);
479 aChildren.xy = aHitTimes.y < aHitTimes.x ? aChildren.yx : aChildren.xy;
480 aHitTimes.xy = aHitTimes.y < aHitTimes.x ? aHitTimes.yx : aHitTimes.xy;
481 aChildren.zw = aHitTimes.w < aHitTimes.z ? aChildren.wz : aChildren.zw;
482 aHitTimes.zw = aHitTimes.w < aHitTimes.z ? aHitTimes.wz : aHitTimes.zw;
483 aChildren.xz = aHitTimes.z < aHitTimes.x ? aChildren.zx : aChildren.xz;
484 aHitTimes.xz = aHitTimes.z < aHitTimes.x ? aHitTimes.zx : aHitTimes.xz;
485 aChildren.yw = aHitTimes.w < aHitTimes.y ? aChildren.wy : aChildren.yw;
486 aHitTimes.yw = aHitTimes.w < aHitTimes.y ? aHitTimes.wy : aHitTimes.yw;
487 aChildren.yz = aHitTimes.z < aHitTimes.y ? aChildren.zy : aChildren.yz;
488 aHitTimes.yz = aHitTimes.z < aHitTimes.y ? aHitTimes.zy : aHitTimes.yz;
490 if (aHitTimes.x != MAXFLOAT)
492 int aHitMask = (aHitTimes.w != MAXFLOAT ? aChildren.w : aChildren.z) << 2
493 | (aHitTimes.z != MAXFLOAT ? aChildren.z : aChildren.y);
495 if (aHitTimes.y != MAXFLOAT)
496 Stack[++aHead] = aData.y | (aHitMask << 2 | aChildren.y) << 26;
498 aNode = aData.y + aChildren.x;
502 toContinue = (aHead >= 0);
504 if (aHead == aStop) // go to top-level BVH
506 aStop = -1; aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
513 else if (aData.x < 0) // leaf node (contains triangles)
518 for (int anIdx = aData.y; anIdx <= aData.z; ++anIdx)
520 ivec4 aTriangle = texelFetch (uGeometryTriangTexture, anIdx + TRG_OFFSET (aSubTree));
522 vec3 aPoint0 = texelFetch (uGeometryVertexTexture, aTriangle.x += VRT_OFFSET (aSubTree)).xyz;
523 vec3 aPoint1 = texelFetch (uGeometryVertexTexture, aTriangle.y += VRT_OFFSET (aSubTree)).xyz;
524 vec3 aPoint2 = texelFetch (uGeometryVertexTexture, aTriangle.z += VRT_OFFSET (aSubTree)).xyz;
526 IntersectTriangle (aSubTree.TrsfRay, aPoint0, aPoint1, aPoint2, aTimeUV, aNormal);
528 if (aTimeUV.x < theHit.Time)
530 aTriIndex = aTriangle;
532 theTrsfId = TRS_OFFSET (aSubTree);
534 theHit = SIntersect (aTimeUV.x, aTimeUV.yz, aNormal);
538 toContinue = (aHead >= 0);
540 if (aHead == aStop) // go to top-level BVH
542 aStop = -1; aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
548 else if (aData.x > 0) // switch node
550 aSubTree.SubData = ivec4 (4 * aData.x - 4, aData.yzw); // store BVH sub-root
552 vec4 aInvTransf0 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 0);
553 vec4 aInvTransf1 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 1);
554 vec4 aInvTransf2 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 2);
555 vec4 aInvTransf3 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 3);
557 aSubTree.TrsfRay.Direct = MatrixColMultiplyDir (theRay.Direct,
562 aSubTree.Inverse = mix (-UNIT, UNIT, step (ZERO, aSubTree.TrsfRay.Direct)) /
563 max (abs (aSubTree.TrsfRay.Direct), SMALL);
565 aSubTree.TrsfRay.Origin = MatrixColMultiplyPnt (theRay.Origin,
571 aNode = BVH_OFFSET (aSubTree); // go to sub-root node
573 aStop = aHead; // store current stack pointer
580 // =======================================================================
581 // function : SceneAnyHit
582 // purpose : Finds intersection with any scene triangle
583 // =======================================================================
584 float SceneAnyHit (in SRay theRay, in vec3 theInverse, in float theDistance)
588 int aNode = 0; // node to traverse
589 int aHead = -1; // pointer of stack
590 int aStop = -1; // BVH level switch
592 SSubTree aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
594 for (bool toContinue = true; toContinue; /* none */)
596 ivec4 aData = texelFetch (uSceneNodeInfoTexture, aNode);
598 if (aData.x == 0) // if inner node
600 aData.y += BVH_OFFSET (aSubTree);
602 vec4 aHitTimes = vec4 (MAXFLOAT,
607 vec3 aRayOriginInverse = -aSubTree.TrsfRay.Origin * aSubTree.Inverse;
609 vec3 aNodeMin0 = texelFetch (uSceneMinPointTexture, aData.y + 0).xyz * aSubTree.Inverse + aRayOriginInverse;
610 vec3 aNodeMin1 = texelFetch (uSceneMinPointTexture, aData.y + 1).xyz * aSubTree.Inverse + aRayOriginInverse;
611 vec3 aNodeMin2 = texelFetch (uSceneMinPointTexture, aData.y + min (2, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
612 vec3 aNodeMin3 = texelFetch (uSceneMinPointTexture, aData.y + min (3, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
613 vec3 aNodeMax0 = texelFetch (uSceneMaxPointTexture, aData.y + 0).xyz * aSubTree.Inverse + aRayOriginInverse;
614 vec3 aNodeMax1 = texelFetch (uSceneMaxPointTexture, aData.y + 1).xyz * aSubTree.Inverse + aRayOriginInverse;
615 vec3 aNodeMax2 = texelFetch (uSceneMaxPointTexture, aData.y + min (2, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
616 vec3 aNodeMax3 = texelFetch (uSceneMaxPointTexture, aData.y + min (3, aData.z)).xyz * aSubTree.Inverse + aRayOriginInverse;
618 vec3 aTimeMax = max (aNodeMin0, aNodeMax0);
619 vec3 aTimeMin = min (aNodeMin0, aNodeMax0);
621 float aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
622 float aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
624 aHitTimes.x = mix (MAXFLOAT, aTimeEnter,
625 aTimeEnter <= aTimeLeave && aTimeEnter <= theDistance && aTimeLeave >= 0.f);
627 aTimeMax = max (aNodeMin1, aNodeMax1);
628 aTimeMin = min (aNodeMin1, aNodeMax1);
630 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
631 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
633 aHitTimes.y = mix (MAXFLOAT, aTimeEnter,
634 aTimeEnter <= aTimeLeave && aTimeEnter <= theDistance && aTimeLeave >= 0.f);
636 aTimeMax = max (aNodeMin2, aNodeMax2);
637 aTimeMin = min (aNodeMin2, aNodeMax2);
639 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
640 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
642 aHitTimes.z = mix (MAXFLOAT, aTimeEnter,
643 aTimeEnter <= aTimeLeave && aTimeEnter <= theDistance && aTimeLeave >= 0.f && aData.z > 1);
645 aTimeMax = max (aNodeMin3, aNodeMax3);
646 aTimeMin = min (aNodeMin3, aNodeMax3);
648 aTimeLeave = min (aTimeMax.x, min (aTimeMax.y, aTimeMax.z));
649 aTimeEnter = max (aTimeMin.x, max (aTimeMin.y, aTimeMin.z));
651 aHitTimes.w = mix (MAXFLOAT, aTimeEnter,
652 aTimeEnter <= aTimeLeave && aTimeEnter <= theDistance && aTimeLeave >= 0.f && aData.z > 2);
654 ivec4 aChildren = ivec4 (0, 1, 2, 3);
656 aChildren.xy = aHitTimes.y < aHitTimes.x ? aChildren.yx : aChildren.xy;
657 aHitTimes.xy = aHitTimes.y < aHitTimes.x ? aHitTimes.yx : aHitTimes.xy;
658 aChildren.zw = aHitTimes.w < aHitTimes.z ? aChildren.wz : aChildren.zw;
659 aHitTimes.zw = aHitTimes.w < aHitTimes.z ? aHitTimes.wz : aHitTimes.zw;
660 aChildren.xz = aHitTimes.z < aHitTimes.x ? aChildren.zx : aChildren.xz;
661 aHitTimes.xz = aHitTimes.z < aHitTimes.x ? aHitTimes.zx : aHitTimes.xz;
662 aChildren.yw = aHitTimes.w < aHitTimes.y ? aChildren.wy : aChildren.yw;
663 aHitTimes.yw = aHitTimes.w < aHitTimes.y ? aHitTimes.wy : aHitTimes.yw;
664 aChildren.yz = aHitTimes.z < aHitTimes.y ? aChildren.zy : aChildren.yz;
665 aHitTimes.yz = aHitTimes.z < aHitTimes.y ? aHitTimes.zy : aHitTimes.yz;
667 if (aHitTimes.x != MAXFLOAT)
669 int aHitMask = (aHitTimes.w != MAXFLOAT ? aChildren.w : aChildren.z) << 2
670 | (aHitTimes.z != MAXFLOAT ? aChildren.z : aChildren.y);
672 if (aHitTimes.y != MAXFLOAT)
673 Stack[++aHead] = aData.y | (aHitMask << 2 | aChildren.y) << 26;
675 aNode = aData.y + aChildren.x;
679 toContinue = (aHead >= 0);
681 if (aHead == aStop) // go to top-level BVH
683 aStop = -1; aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
690 else if (aData.x < 0) // leaf node
695 for (int anIdx = aData.y; anIdx <= aData.z; ++anIdx)
697 ivec4 aTriangle = texelFetch (uGeometryTriangTexture, anIdx + TRG_OFFSET (aSubTree));
699 vec3 aPoint0 = texelFetch (uGeometryVertexTexture, aTriangle.x += VRT_OFFSET (aSubTree)).xyz;
700 vec3 aPoint1 = texelFetch (uGeometryVertexTexture, aTriangle.y += VRT_OFFSET (aSubTree)).xyz;
701 vec3 aPoint2 = texelFetch (uGeometryVertexTexture, aTriangle.z += VRT_OFFSET (aSubTree)).xyz;
703 IntersectTriangle (aSubTree.TrsfRay, aPoint0, aPoint1, aPoint2, aTimeUV, aNormal);
705 #ifdef TRANSPARENT_SHADOWS
706 if (aTimeUV.x < theDistance)
708 aFactor *= 1.f - texelFetch (uRaytraceMaterialTexture, MATERIAL_TRAN (aTriangle.w)).x;
711 if (aTimeUV.x < theDistance)
718 toContinue = (aHead >= 0) && (aFactor > 0.1f);
720 if (aHead == aStop) // go to top-level BVH
722 aStop = -1; aSubTree = SSubTree (theRay, theInverse, EMPTY_ROOT);
728 else if (aData.x > 0) // switch node
730 aSubTree.SubData = ivec4 (4 * aData.x - 4, aData.yzw); // store BVH sub-root
732 vec4 aInvTransf0 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 0);
733 vec4 aInvTransf1 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 1);
734 vec4 aInvTransf2 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 2);
735 vec4 aInvTransf3 = texelFetch (uSceneTransformTexture, TRS_OFFSET (aSubTree) + 3);
737 aSubTree.TrsfRay.Direct = MatrixColMultiplyDir (theRay.Direct,
742 aSubTree.TrsfRay.Origin = MatrixColMultiplyPnt (theRay.Origin,
748 aSubTree.Inverse = mix (-UNIT, UNIT, step (ZERO, aSubTree.TrsfRay.Direct)) / max (abs (aSubTree.TrsfRay.Direct), SMALL);
750 aNode = BVH_OFFSET (aSubTree); // go to sub-root node
752 aStop = aHead; // store current stack pointer
759 #define PI 3.1415926f
761 // =======================================================================
762 // function : Latlong
763 // purpose : Converts world direction to environment texture coordinates
764 // =======================================================================
765 vec2 Latlong (in vec3 thePoint, in float theRadius)
767 float aPsi = acos (-thePoint.z / theRadius);
769 float aPhi = atan (thePoint.y, thePoint.x) + PI;
771 return vec2 (aPhi * 0.1591549f,
775 // =======================================================================
776 // function : SmoothNormal
777 // purpose : Interpolates normal across the triangle
778 // =======================================================================
779 vec3 SmoothNormal (in vec2 theUV, in ivec4 theTriangle)
781 vec3 aNormal0 = texelFetch (uGeometryNormalTexture, theTriangle.x).xyz;
782 vec3 aNormal1 = texelFetch (uGeometryNormalTexture, theTriangle.y).xyz;
783 vec3 aNormal2 = texelFetch (uGeometryNormalTexture, theTriangle.z).xyz;
785 return normalize (aNormal1 * theUV.x +
787 aNormal0 * (1.0f - theUV.x - theUV.y));
790 // =======================================================================
791 // function : SmoothUV
792 // purpose : Interpolates UV coordinates across the triangle
793 // =======================================================================
795 vec2 SmoothUV (in vec2 theUV, in ivec4 theTriangle)
797 vec2 aTexCrd0 = texelFetch (uGeometryTexCrdTexture, theTriangle.x).st;
798 vec2 aTexCrd1 = texelFetch (uGeometryTexCrdTexture, theTriangle.y).st;
799 vec2 aTexCrd2 = texelFetch (uGeometryTexCrdTexture, theTriangle.z).st;
801 return aTexCrd1 * theUV.x +
803 aTexCrd0 * (1.0f - theUV.x - theUV.y);
807 // =======================================================================
808 // function : FetchEnvironment
810 // =======================================================================
811 vec4 FetchEnvironment (in vec2 theTexCoord)
813 return mix (vec4 (0.0f, 0.0f, 0.0f, 1.0f),
814 textureLod (uEnvironmentMapTexture, theTexCoord, 0.0f), float (uSphereMapEnabled));
817 // =======================================================================
818 // function : Refract
819 // purpose : Computes refraction ray (also handles TIR)
820 // =======================================================================
822 vec3 Refract (in vec3 theInput,
824 in float theRefractIndex,
825 in float theInvRefractIndex)
827 float aNdotI = dot (theInput, theNormal);
829 float anIndex = aNdotI < 0.0f
833 float aSquare = anIndex * anIndex * (1.0f - aNdotI * aNdotI);
837 return reflect (theInput, theNormal);
840 float aNdotT = sqrt (1.0f - aSquare);
842 return normalize (anIndex * theInput -
843 (anIndex * aNdotI + (aNdotI < 0.0f ? aNdotT : -aNdotT)) * theNormal);
847 #define MIN_SLOPE 0.0001f
848 #define EPS_SCALE 8.0000f
850 #define THRESHOLD vec3 (0.1f)
852 #define INVALID_BOUNCES 1000
854 #define LIGHT_POS(index) (2 * index + 1)
855 #define LIGHT_PWR(index) (2 * index + 0)
857 // =======================================================================
858 // function : Radiance
859 // purpose : Computes color along the given ray
860 // =======================================================================
862 vec4 Radiance (in SRay theRay, in vec3 theInverse)
864 vec3 aResult = vec3 (0.0f);
865 vec4 aWeight = vec4 (1.0f);
869 float aRaytraceDepth = MAXFLOAT;
871 for (int aDepth = 0; aDepth < NB_BOUNCES; ++aDepth)
873 SIntersect aHit = SIntersect (MAXFLOAT, vec2 (ZERO), ZERO);
875 ivec4 aTriIndex = SceneNearestHit (theRay, theInverse, aHit, aTrsfId);
877 if (aTriIndex.x == -1)
879 vec4 aColor = vec4 (0.0);
881 if (bool(uSphereMapForBack) || aWeight.w == 0.0f /* reflection */)
883 float aTime = IntersectSphere (theRay, uSceneRadius);
885 aColor = FetchEnvironment (Latlong (
886 theRay.Direct * aTime + theRay.Origin, uSceneRadius));
890 aColor = BackgroundColor();
893 aResult += aWeight.xyz * aColor.xyz; aWeight.w *= aColor.w;
895 break; // terminate path
898 vec3 aInvTransf0 = texelFetch (uSceneTransformTexture, aTrsfId + 0).xyz;
899 vec3 aInvTransf1 = texelFetch (uSceneTransformTexture, aTrsfId + 1).xyz;
900 vec3 aInvTransf2 = texelFetch (uSceneTransformTexture, aTrsfId + 2).xyz;
902 aHit.Normal = normalize (vec3 (dot (aInvTransf0, aHit.Normal),
903 dot (aInvTransf1, aHit.Normal),
904 dot (aInvTransf2, aHit.Normal)));
906 theRay.Origin += theRay.Direct * aHit.Time; // intersection point
908 // Evaluate depth on first hit
911 // For polygons that are parallel to the screen plane, the depth slope
912 // is equal to 1, resulting in small polygon offset. For polygons that
913 // that are at a large angle to the screen, the depth slope tends to 1,
914 // resulting in a larger polygon offset
915 float aPolygonOffset = uSceneEpsilon * EPS_SCALE /
916 max (abs (dot (theRay.Direct, aHit.Normal)), MIN_SLOPE);
918 // Hit point in NDC-space [-1,1] (the polygon offset is applied in the world space)
919 vec4 aNDCPoint = uViewMat * vec4 (theRay.Origin + theRay.Direct * aPolygonOffset, 1.f);
921 aRaytraceDepth = (aNDCPoint.z / aNDCPoint.w) * 0.5f + 0.5f;
924 vec3 aNormal = SmoothNormal (aHit.UV, aTriIndex);
926 aNormal = normalize (vec3 (dot (aInvTransf0, aNormal),
927 dot (aInvTransf1, aNormal),
928 dot (aInvTransf2, aNormal)));
930 vec3 aAmbient = texelFetch (
931 uRaytraceMaterialTexture, MATERIAL_AMBN (aTriIndex.w)).rgb;
932 vec4 aDiffuse = texelFetch (
933 uRaytraceMaterialTexture, MATERIAL_DIFF (aTriIndex.w));
934 vec4 aSpecular = texelFetch (
935 uRaytraceMaterialTexture, MATERIAL_SPEC (aTriIndex.w));
936 vec4 aOpacity = texelFetch (
937 uRaytraceMaterialTexture, MATERIAL_TRAN (aTriIndex.w));
940 if (aDiffuse.w >= 0.f)
942 vec4 aTexCoord = vec4 (SmoothUV (aHit.UV, aTriIndex), 0.f, 1.f);
944 vec4 aTrsfRow1 = texelFetch (
945 uRaytraceMaterialTexture, MATERIAL_TRS1 (aTriIndex.w));
946 vec4 aTrsfRow2 = texelFetch (
947 uRaytraceMaterialTexture, MATERIAL_TRS2 (aTriIndex.w));
949 aTexCoord.st = vec2 (dot (aTrsfRow1, aTexCoord),
950 dot (aTrsfRow2, aTexCoord));
952 vec3 aTexColor = textureLod (
953 sampler2D (uTextureSamplers[int(aDiffuse.w)]), aTexCoord.st, 0.f).rgb;
955 aDiffuse.rgb *= aTexColor;
956 aAmbient.rgb *= aTexColor;
960 vec3 aEmission = texelFetch (
961 uRaytraceMaterialTexture, MATERIAL_EMIS (aTriIndex.w)).rgb;
963 float aGeomFactor = dot (aNormal, theRay.Direct);
965 aResult.xyz += aWeight.xyz * aOpacity.x * (
966 uGlobalAmbient.xyz * aAmbient * max (abs (aGeomFactor), 0.5f) + aEmission);
968 vec3 aSidedNormal = mix (aNormal, -aNormal, step (0.0f, aGeomFactor));
970 for (int aLightIdx = 0; aLightIdx < uLightCount; ++aLightIdx)
972 vec4 aLight = texelFetch (
973 uRaytraceLightSrcTexture, LIGHT_POS (aLightIdx));
975 float aDistance = MAXFLOAT;
977 if (aLight.w != 0.0f) // point light source
979 aDistance = length (aLight.xyz -= theRay.Origin);
981 aLight.xyz *= 1.0f / aDistance;
984 float aLdotN = dot (aLight.xyz, aSidedNormal);
986 if (aLdotN > 0.0f) // first check if light source is important
988 float aVisibility = 1.0f;
990 if (bool(uShadowsEnabled))
992 SRay aShadow = SRay (theRay.Origin, aLight.xyz);
994 aShadow.Origin += uSceneEpsilon * (aLight.xyz +
995 mix (-aHit.Normal, aHit.Normal, step (0.0f, dot (aHit.Normal, aLight.xyz))));
997 vec3 aInverse = 1.0f / max (abs (aLight.xyz), SMALL);
999 aVisibility = SceneAnyHit (
1000 aShadow, mix (-aInverse, aInverse, step (ZERO, aLight.xyz)), aDistance);
1003 if (aVisibility > 0.0f)
1005 vec3 aIntensity = vec3 (texelFetch (
1006 uRaytraceLightSrcTexture, LIGHT_PWR (aLightIdx)));
1008 float aRdotV = dot (reflect (aLight.xyz, aSidedNormal), theRay.Direct);
1010 aResult.xyz += aWeight.xyz * (aOpacity.x * aVisibility) * aIntensity *
1011 (aDiffuse.xyz * aLdotN + aSpecular.xyz * pow (max (0.f, aRdotV), aSpecular.w));
1016 if (aOpacity.x != 1.0f)
1018 aWeight *= aOpacity.y;
1020 if (aOpacity.z != 1.0f)
1022 theRay.Direct = Refract (theRay.Direct, aNormal, aOpacity.z, aOpacity.w);
1027 aWeight *= bool(uReflectEnabled) ?
1028 texelFetch (uRaytraceMaterialTexture, MATERIAL_REFL (aTriIndex.w)) : vec4 (0.0f);
1030 vec3 aReflect = reflect (theRay.Direct, aNormal);
1032 if (dot (aReflect, aHit.Normal) * dot (theRay.Direct, aHit.Normal) > 0.0f)
1034 aReflect = reflect (theRay.Direct, aHit.Normal);
1037 theRay.Direct = aReflect;
1040 if (all (lessThanEqual (aWeight.xyz, THRESHOLD)))
1042 aDepth = INVALID_BOUNCES;
1044 else if (aOpacity.x == 1.0f || aOpacity.z != 1.0f) // if no simple transparency
1046 theRay.Origin += aHit.Normal * mix (
1047 -uSceneEpsilon, uSceneEpsilon, step (0.0f, dot (aHit.Normal, theRay.Direct)));
1049 theInverse = 1.0f / max (abs (theRay.Direct), SMALL);
1051 theInverse = mix (-theInverse, theInverse, step (ZERO, theRay.Direct));
1054 theRay.Origin += theRay.Direct * uSceneEpsilon;
1057 gl_FragDepth = aRaytraceDepth;
1059 return vec4 (aResult.x,