2 #define PATH_TRACING // just for editing in MS VS
8 typedef struct { float x; float y; } vec2;
9 typedef struct { float x; float y; float z; } vec3;
10 typedef struct { float x; float y; float z; float w; } vec4;
15 ///////////////////////////////////////////////////////////////////////////////////////
16 // Specific data types
18 //! Describes local space at the hit point (visualization space).
31 //! Describes material properties (BSDF).
34 //! Weight of coat specular/glossy BRDF.
37 //! Weight of base diffuse BRDF + base color texture index in W.
40 //! Weight of base specular/glossy BRDF.
43 //! Weight of base specular/glossy BTDF + metallic-roughness texture index in W.
46 //! Fresnel coefficients of coat layer.
49 //! Fresnel coefficients of base layer.
53 ///////////////////////////////////////////////////////////////////////////////////////
54 // Support subroutines
56 //=======================================================================
57 // function : buildLocalSpace
58 // purpose : Generates local space for the given normal
59 //=======================================================================
60 SLocalSpace buildLocalSpace (in vec3 theNormal)
62 vec3 anAxisX = vec3 (theNormal.z, 0.f, -theNormal.x);
63 vec3 anAxisY = vec3 (0.f, -theNormal.z, theNormal.y);
65 float aSqrLenX = dot (anAxisX, anAxisX);
66 float aSqrLenY = dot (anAxisY, anAxisY);
68 if (aSqrLenX > aSqrLenY)
70 anAxisX *= inversesqrt (aSqrLenX);
71 anAxisY = cross (anAxisX, theNormal);
75 anAxisY *= inversesqrt (aSqrLenY);
76 anAxisX = cross (anAxisY, theNormal);
79 return SLocalSpace (anAxisX, anAxisY, theNormal);
82 //=======================================================================
83 // function : toLocalSpace
84 // purpose : Transforms the vector to local space from world space
85 //=======================================================================
86 vec3 toLocalSpace (in vec3 theVector, in SLocalSpace theSpace)
88 return vec3 (dot (theVector, theSpace.AxisX),
89 dot (theVector, theSpace.AxisY),
90 dot (theVector, theSpace.AxisZ));
93 //=======================================================================
94 // function : fromLocalSpace
95 // purpose : Transforms the vector from local space to world space
96 //=======================================================================
97 vec3 fromLocalSpace (in vec3 theVector, in SLocalSpace theSpace)
99 return theVector.x * theSpace.AxisX +
100 theVector.y * theSpace.AxisY +
101 theVector.z * theSpace.AxisZ;
104 //=======================================================================
105 // function : convolve
106 // purpose : Performs a linear convolution of the vector components
107 //=======================================================================
108 float convolve (in vec3 theVector, in vec3 theFactor)
110 return dot (theVector, theFactor) * (1.f / max (theFactor.x + theFactor.y + theFactor.z, 1e-15f));
113 //=======================================================================
114 // function : fresnelSchlick
115 // purpose : Computes the Fresnel reflection formula using
116 // Schlick's approximation.
117 //=======================================================================
118 vec3 fresnelSchlick (in float theCosI, in vec3 theSpecularColor)
120 return theSpecularColor + (UNIT - theSpecularColor) * pow (1.f - theCosI, 5.f);
123 //=======================================================================
124 // function : fresnelDielectric
125 // purpose : Computes the Fresnel reflection formula for dielectric in
126 // case of circularly polarized light (Based on PBRT code).
127 //=======================================================================
128 float fresnelDielectric (in float theCosI,
133 float aParl = (theEtaT * theCosI - theEtaI * theCosT) /
134 (theEtaT * theCosI + theEtaI * theCosT);
136 float aPerp = (theEtaI * theCosI - theEtaT * theCosT) /
137 (theEtaI * theCosI + theEtaT * theCosT);
139 return (aParl * aParl + aPerp * aPerp) * 0.5f;
142 #define ENVIRONMENT_IOR 1.f
144 //=======================================================================
145 // function : fresnelDielectric
146 // purpose : Computes the Fresnel reflection formula for dielectric in
147 // case of circularly polarized light (based on PBRT code)
148 //=======================================================================
149 float fresnelDielectric (in float theCosI, in float theIndex)
151 float aFresnel = 1.f;
153 float anEtaI = theCosI > 0.f ? 1.f : theIndex;
154 float anEtaT = theCosI > 0.f ? theIndex : 1.f;
156 float aSinT2 = (anEtaI * anEtaI) / (anEtaT * anEtaT) * (1.f - theCosI * theCosI);
160 aFresnel = fresnelDielectric (abs (theCosI), sqrt (1.f - aSinT2), anEtaI, anEtaT);
166 //=======================================================================
167 // function : fresnelConductor
168 // purpose : Computes the Fresnel reflection formula for conductor in case
169 // of circularly polarized light (based on PBRT source code)
170 //=======================================================================
171 float fresnelConductor (in float theCosI, in float theEta, in float theK)
173 float aTmp = 2.f * theEta * theCosI;
175 float aTmp1 = theEta * theEta + theK * theK;
177 float aSPerp = (aTmp1 - aTmp + theCosI * theCosI) /
178 (aTmp1 + aTmp + theCosI * theCosI);
180 float aTmp2 = aTmp1 * theCosI * theCosI;
182 float aSParl = (aTmp2 - aTmp + 1.f) /
183 (aTmp2 + aTmp + 1.f);
185 return (aSPerp + aSParl) * 0.5f;
188 #define FRESNEL_SCHLICK -0.5f
189 #define FRESNEL_CONSTANT -1.5f
190 #define FRESNEL_CONDUCTOR -2.5f
191 #define FRESNEL_DIELECTRIC -3.5f
193 //=======================================================================
194 // function : fresnelMedia
195 // purpose : Computes the Fresnel reflection formula for general medium
196 // in case of circularly polarized light.
197 //=======================================================================
198 vec3 fresnelMedia (in float theCosI, in vec3 theFresnel)
202 if (theFresnel.x > FRESNEL_SCHLICK)
204 aFresnel = fresnelSchlick (abs (theCosI), theFresnel);
206 else if (theFresnel.x > FRESNEL_CONSTANT)
208 aFresnel = vec3 (theFresnel.z);
210 else if (theFresnel.x > FRESNEL_CONDUCTOR)
212 aFresnel = vec3 (fresnelConductor (abs (theCosI), theFresnel.y, theFresnel.z));
216 aFresnel = vec3 (fresnelDielectric (theCosI, theFresnel.y));
222 //=======================================================================
223 // function : transmitted
224 // purpose : Computes transmitted direction in tangent space
225 // (in case of TIR returned result is undefined!)
226 //=======================================================================
227 void transmitted (in float theIndex, in vec3 theIncident, out vec3 theTransmit)
229 // Compute relative index of refraction
230 float anEta = (theIncident.z > 0.f) ? 1.f / theIndex : theIndex;
232 // Handle total internal reflection (TIR)
233 float aSinT2 = anEta * anEta * (1.f - theIncident.z * theIncident.z);
235 // Compute direction of transmitted ray
236 float aCosT = sqrt (1.f - min (aSinT2, 1.f)) * sign (-theIncident.z);
238 theTransmit = normalize (vec3 (-anEta * theIncident.x,
239 -anEta * theIncident.y,
243 //////////////////////////////////////////////////////////////////////////////////////////////
244 // Handlers and samplers for materials
245 //////////////////////////////////////////////////////////////////////////////////////////////
247 //=======================================================================
248 // function : EvalLambertianReflection
249 // purpose : Evaluates Lambertian BRDF, with cos(N, PSI)
250 //=======================================================================
251 float EvalLambertianReflection (in vec3 theWi, in vec3 theWo)
253 return (theWi.z <= 0.f || theWo.z <= 0.f) ? 0.f : theWi.z * (1.f / M_PI);
256 #define FLT_EPSILON 1.0e-5f
258 //=======================================================================
259 // function : SmithG1
261 //=======================================================================
262 float SmithG1 (in vec3 theDirection, in vec3 theM, in float theRoughness)
266 if (dot (theDirection, theM) * theDirection.z > 0.f)
268 float aTanThetaM = sqrt (1.f - theDirection.z * theDirection.z) / theDirection.z;
270 if (aTanThetaM == 0.f)
276 float aVal = 1.f / (theRoughness * aTanThetaM);
278 // Use rational approximation to shadowing-masking function (from Mitsuba)
279 aResult = (3.535f + 2.181f * aVal) / (1.f / aVal + 2.276f + 2.577f * aVal);
283 return min (aResult, 1.f);
286 //=======================================================================
287 // function : EvalBlinnReflection
288 // purpose : Evaluates Blinn glossy BRDF, with cos(N, PSI)
289 //=======================================================================
290 vec3 EvalBlinnReflection (in vec3 theWi, in vec3 theWo, in vec3 theFresnel, in float theRoughness)
292 // calculate the reflection half-vec
293 vec3 aH = normalize (theWi + theWo);
295 // roughness value -> Blinn exponent
296 float aPower = max (2.f / (theRoughness * theRoughness) - 2.f, 0.f);
298 // calculate microfacet distribution
299 float aD = (aPower + 2.f) * (1.f / M_2_PI) * pow (aH.z, aPower);
301 // calculate shadow-masking function
302 float aG = SmithG1 (theWo, aH, theRoughness) *
303 SmithG1 (theWi, aH, theRoughness);
305 // return total amount of reflection
306 return (theWi.z <= 0.f || theWo.z <= 0.f) ? ZERO :
307 aD * aG / (4.f * theWo.z) * fresnelMedia (dot (theWo, aH), theFresnel);
310 //=======================================================================
311 // function : EvalBsdfLayered
312 // purpose : Evaluates BSDF for specified material, with cos(N, PSI)
313 //=======================================================================
314 vec3 EvalBsdfLayered (in SBSDF theBSDF, in vec3 theWi, in vec3 theWo)
316 #ifdef TWO_SIDED_BXDF
317 theWi.z *= sign (theWi.z);
318 theWo.z *= sign (theWo.z);
321 vec3 aBxDF = theBSDF.Kd.rgb * EvalLambertianReflection (theWi, theWo);
323 if (theBSDF.Ks.w > FLT_EPSILON)
325 aBxDF += theBSDF.Ks.rgb * EvalBlinnReflection (theWi, theWo, theBSDF.FresnelBase, theBSDF.Ks.w);
328 aBxDF *= UNIT - fresnelMedia (theWo.z, theBSDF.FresnelCoat);
330 if (theBSDF.Kc.w > FLT_EPSILON)
332 aBxDF += theBSDF.Kc.rgb * EvalBlinnReflection (theWi, theWo, theBSDF.FresnelCoat, theBSDF.Kc.w);
338 //=======================================================================
339 // function : SampleLambertianReflection
340 // purpose : Samples Lambertian BRDF, W = BRDF * cos(N, PSI) / PDF(PSI)
341 //=======================================================================
342 vec3 SampleLambertianReflection (in vec3 theWo, out vec3 theWi, inout float thePDF)
344 float aKsi1 = RandFloat();
345 float aKsi2 = RandFloat();
347 theWi = vec3 (cos (M_2_PI * aKsi1),
348 sin (M_2_PI * aKsi1),
351 theWi.xy *= sqrt (aKsi2);
353 #ifdef TWO_SIDED_BXDF
354 theWi.z *= sign (theWo.z);
357 thePDF *= theWi.z * (1.f / M_PI);
359 #ifdef TWO_SIDED_BXDF
362 return UNIT * step (0.f, theWo.z);
366 //=======================================================================
367 // function : SampleGlossyBlinnReflection
368 // purpose : Samples Blinn BRDF, W = BRDF * cos(N, PSI) / PDF(PSI)
369 // The BRDF is a product of three main terms, D, G, and F,
370 // which is then divided by two cosine terms. Here we perform
371 // importance sample the D part of the Blinn model; trying to
372 // develop a sampling procedure that accounted for all of the
373 // terms would be complex, and it is the D term that accounts
374 // for most of the variation.
375 //=======================================================================
376 vec3 SampleGlossyBlinnReflection (in vec3 theWo, out vec3 theWi, in vec3 theFresnel, in float theRoughness, inout float thePDF)
378 float aKsi1 = RandFloat();
379 float aKsi2 = RandFloat();
381 // roughness value --> Blinn exponent
382 float aPower = max (2.f / (theRoughness * theRoughness) - 2.f, 0.f);
384 // normal from microface distribution
385 float aCosThetaM = pow (aKsi1, 1.f / (aPower + 2.f));
387 vec3 aM = vec3 (cos (M_2_PI * aKsi2),
388 sin (M_2_PI * aKsi2),
391 aM.xy *= sqrt (1.f - aCosThetaM * aCosThetaM);
393 // calculate PDF of sampled direction
394 thePDF *= (aPower + 2.f) * (1.f / M_2_PI) * pow (aCosThetaM, aPower + 1.f);
396 #ifdef TWO_SIDED_BXDF
397 bool toFlip = theWo.z < 0.f;
403 float aCosDelta = dot (theWo, aM);
405 // pick input based on half direction
406 theWi = -theWo + 2.f * aCosDelta * aM;
408 if (theWi.z <= 0.f || theWo.z <= 0.f)
413 // Jacobian of half-direction mapping
414 thePDF /= 4.f * aCosDelta;
416 // compute shadow-masking coefficient
417 float aG = SmithG1 (theWo, aM, theRoughness) *
418 SmithG1 (theWi, aM, theRoughness);
420 #ifdef TWO_SIDED_BXDF
425 return (aG * aCosDelta) / (theWo.z * aM.z) * fresnelMedia (aCosDelta, theFresnel);
428 //=======================================================================
429 // function : BsdfPdfLayered
430 // purpose : Calculates BSDF of sampling input knowing output
431 //=======================================================================
432 float BsdfPdfLayered (in SBSDF theBSDF, in vec3 theWo, in vec3 theWi, in vec3 theWeight)
434 float aPDF = 0.f; // PDF of sampling input direction
436 // We choose whether the light is reflected or transmitted
437 // by the coating layer according to the Fresnel equations
438 vec3 aCoatF = fresnelMedia (theWo.z, theBSDF.FresnelCoat);
440 // Coat BRDF is scaled by its Fresnel reflectance term. For
441 // reasons of simplicity we scale base BxDFs only by coat's
442 // Fresnel transmittance term
443 vec3 aCoatT = UNIT - aCoatF;
445 float aPc = dot (theBSDF.Kc.rgb * aCoatF, theWeight);
446 float aPd = dot (theBSDF.Kd.rgb * aCoatT, theWeight);
447 float aPs = dot (theBSDF.Ks.rgb * aCoatT, theWeight);
448 float aPt = dot (theBSDF.Kt.rgb * aCoatT, theWeight);
450 if (theWi.z * theWo.z > 0.f)
452 vec3 aH = normalize (theWi + theWo);
454 aPDF = aPd * abs (theWi.z / M_PI);
456 if (theBSDF.Kc.w > FLT_EPSILON)
458 float aPower = max (2.f / (theBSDF.Kc.w * theBSDF.Kc.w) - 2.f, 0.f); // roughness --> exponent
460 aPDF += aPc * (aPower + 2.f) * (0.25f / M_2_PI) * pow (abs (aH.z), aPower + 1.f) / dot (theWi, aH);
463 if (theBSDF.Ks.w > FLT_EPSILON)
465 float aPower = max (2.f / (theBSDF.Ks.w * theBSDF.Ks.w) - 2.f, 0.f); // roughness --> exponent
467 aPDF += aPs * (aPower + 2.f) * (0.25f / M_2_PI) * pow (abs (aH.z), aPower + 1.f) / dot (theWi, aH);
471 return aPDF / (aPc + aPd + aPs + aPt);
474 //! Tool macro to handle sampling of particular BxDF
475 #define PICK_BXDF_LAYER(p, k) aPDF = p / aTotalR; theWeight *= k / aPDF;
477 //=======================================================================
478 // function : SampleBsdfLayered
479 // purpose : Samples specified composite material (BSDF)
480 //=======================================================================
481 float SampleBsdfLayered (in SBSDF theBSDF, in vec3 theWo, out vec3 theWi, inout vec3 theWeight, inout bool theInside)
483 // NOTE: OCCT uses two-layer material model. We have base diffuse, glossy, or transmissive
484 // layer, covered by one glossy/specular coat. In the current model, the layers themselves
485 // have no thickness; they can simply reflect light or transmits it to the layer under it.
486 // We use actual BRDF model only for direct reflection by the coat layer. For transmission
487 // through this layer, we approximate it as a flat specular surface.
489 float aPDF = 0.f; // PDF of sampled direction
491 // We choose whether the light is reflected or transmitted
492 // by the coating layer according to the Fresnel equations
493 vec3 aCoatF = fresnelMedia (theWo.z, theBSDF.FresnelCoat);
495 // Coat BRDF is scaled by its Fresnel term. According to
496 // Wilkie-Weidlich layered BSDF model, transmission term
497 // for light passing through the coat at direction I and
498 // leaving it in O is T = ( 1 - F (O) ) x ( 1 - F (I) ).
499 // For reasons of simplicity, we discard the second term
500 // and scale base BxDFs only by the first term.
501 vec3 aCoatT = UNIT - aCoatF;
503 float aPc = dot (theBSDF.Kc.rgb * aCoatF, theWeight);
504 float aPd = dot (theBSDF.Kd.rgb * aCoatT, theWeight);
505 float aPs = dot (theBSDF.Ks.rgb * aCoatT, theWeight);
506 float aPt = dot (theBSDF.Kt.rgb * aCoatT, theWeight);
508 // Calculate total reflection probability
509 float aTotalR = (aPc + aPd) + (aPs + aPt);
511 // Generate random variable to select BxDF
512 float aKsi = aTotalR * RandFloat();
514 if (aKsi < aPc) // REFLECTION FROM COAT
516 PICK_BXDF_LAYER (aPc, theBSDF.Kc.rgb)
518 if (theBSDF.Kc.w < FLT_EPSILON)
522 theWi = vec3 (-theWo.x,
528 theWeight *= SampleGlossyBlinnReflection (theWo, theWi, theBSDF.FresnelCoat, theBSDF.Kc.w, aPDF);
531 aPDF = mix (aPDF, MAXFLOAT, theBSDF.Kc.w < FLT_EPSILON);
533 else if (aKsi < aTotalR) // REFLECTION FROM BASE
537 if (aKsi < aPc + aPd) // diffuse BRDF
539 PICK_BXDF_LAYER (aPd, theBSDF.Kd.rgb)
541 theWeight *= SampleLambertianReflection (theWo, theWi, aPDF);
543 else if (aKsi < (aPc + aPd) + aPs) // specular/glossy BRDF
545 PICK_BXDF_LAYER (aPs, theBSDF.Ks.rgb)
547 if (theBSDF.Ks.w < FLT_EPSILON)
549 theWeight *= fresnelMedia (theWo.z, theBSDF.FresnelBase);
551 theWi = vec3 (-theWo.x,
557 theWeight *= SampleGlossyBlinnReflection (theWo, theWi, theBSDF.FresnelBase, theBSDF.Ks.w, aPDF);
560 aPDF = mix (aPDF, MAXFLOAT, theBSDF.Ks.w < FLT_EPSILON);
562 else // specular transmission
564 PICK_BXDF_LAYER (aPt, theBSDF.Kt.rgb)
566 // refracted direction should exist if we are here
567 transmitted (theBSDF.FresnelCoat.y, theWo, theWi);
569 theInside = !theInside; aPDF = MAXFLOAT;
573 // path termination for extra small weights
574 theWeight = mix (ZERO, theWeight, step (FLT_EPSILON, aTotalR));
579 //////////////////////////////////////////////////////////////////////////////////////////////
580 // Handlers and samplers for light sources
581 //////////////////////////////////////////////////////////////////////////////////////////////
583 // =======================================================================
584 // function : Latlong
585 // purpose : Converts world direction to environment texture coordinates
586 // =======================================================================
587 vec2 Latlong (in vec3 thePoint)
589 float aPsi = acos (-thePoint.z);
591 float aPhi = atan (thePoint.y, thePoint.x) + M_PI;
593 return vec2 (aPhi * 0.1591549f,
597 //=======================================================================
598 // function : SampleLight
599 // purpose : General sampling function for directional and point lights
600 //=======================================================================
601 vec3 SampleLight (in vec3 theToLight, inout float theDistance, in bool isInfinite, in float theSmoothness, inout float thePDF)
603 SLocalSpace aSpace = buildLocalSpace (theToLight * (1.f / theDistance));
605 // for point lights smoothness defines radius
606 float aCosMax = isInfinite ? theSmoothness :
607 inversesqrt (1.f + theSmoothness * theSmoothness / (theDistance * theDistance));
609 float aKsi1 = RandFloat();
610 float aKsi2 = RandFloat();
612 float aTmp = 1.f - aKsi2 * (1.f - aCosMax);
614 vec3 anInput = vec3 (cos (M_2_PI * aKsi1),
615 sin (M_2_PI * aKsi1),
618 anInput.xy *= sqrt (1.f - aTmp * aTmp);
620 thePDF = (aCosMax < 1.f) ? (thePDF / M_2_PI) / (1.f - aCosMax) : MAXFLOAT;
622 return normalize (fromLocalSpace (anInput, aSpace));
625 //=======================================================================
626 // function : HandlePointLight
628 //=======================================================================
629 float HandlePointLight (in vec3 theInput, in vec3 theToLight, in float theRadius, in float theDistance, inout float thePDF)
631 float aCosMax = inversesqrt (1.f + theRadius * theRadius / (theDistance * theDistance));
633 float aVisibility = step (aCosMax, dot (theInput, theToLight));
635 thePDF *= step (-1.f, -aCosMax) * aVisibility * (1.f / M_2_PI) / (1.f - aCosMax);
640 //=======================================================================
641 // function : HandleDistantLight
643 //=======================================================================
644 float HandleDistantLight (in vec3 theInput, in vec3 theToLight, in float theCosMax, inout float thePDF)
646 float aVisibility = step (theCosMax, dot (theInput, theToLight));
648 thePDF *= step (-1.f, -theCosMax) * aVisibility * (1.f / M_2_PI) / (1.f - theCosMax);
653 // =======================================================================
654 // function: IntersectLight
655 // purpose : Checks intersections with light sources
656 // =======================================================================
657 vec3 IntersectLight (in SRay theRay, in int theDepth, in float theHitDistance, out float thePDF)
659 vec3 aTotalRadiance = ZERO;
661 thePDF = 0.f; // PDF of sampling light sources
663 for (int aLightIdx = 0; aLightIdx < uLightCount; ++aLightIdx)
665 vec4 aLight = texelFetch (
666 uRaytraceLightSrcTexture, LIGHT_POS (aLightIdx));
667 vec4 aParam = texelFetch (
668 uRaytraceLightSrcTexture, LIGHT_PWR (aLightIdx));
670 // W component: 0 for infinite light and 1 for point light
671 aLight.xyz -= mix (ZERO, theRay.Origin, aLight.w);
673 float aPDF = 1.f / uLightCount;
675 if (aLight.w != 0.f) // point light source
677 float aCenterDst = length (aLight.xyz);
679 if (aCenterDst < theHitDistance)
681 float aVisibility = HandlePointLight (
682 theRay.Direct, normalize (aLight.xyz), aParam.w /* radius */, aCenterDst, aPDF);
684 if (aVisibility > 0.f)
686 theHitDistance = aCenterDst;
687 aTotalRadiance = aParam.rgb;
693 else if (theHitDistance == MAXFLOAT) // directional light source
695 aTotalRadiance += aParam.rgb * HandleDistantLight (
696 theRay.Direct, aLight.xyz, aParam.w /* angle cosine */, aPDF);
702 if (thePDF == 0.f && theHitDistance == MAXFLOAT) // light source not found
704 if (theDepth + uSphereMapForBack == 0) // view ray and map is hidden
706 aTotalRadiance = BackgroundColor().rgb;
710 aTotalRadiance = FetchEnvironment (Latlong (theRay.Direct)).rgb;
712 #ifdef THE_SHIFT_sRGB
713 aTotalRadiance = pow (aTotalRadiance, vec3 (2.f));
717 return aTotalRadiance;
720 #define MIN_THROUGHPUT vec3 (1.0e-3f)
721 #define MIN_CONTRIBUTION vec3 (1.0e-2f)
723 #define MATERIAL_KC(index) (19 * index + 11)
724 #define MATERIAL_KD(index) (19 * index + 12)
725 #define MATERIAL_KS(index) (19 * index + 13)
726 #define MATERIAL_KT(index) (19 * index + 14)
727 #define MATERIAL_LE(index) (19 * index + 15)
728 #define MATERIAL_FRESNEL_COAT(index) (19 * index + 16)
729 #define MATERIAL_FRESNEL_BASE(index) (19 * index + 17)
730 #define MATERIAL_ABSORPT_BASE(index) (19 * index + 18)
732 //! Enables experimental Russian roulette sampling path termination.
733 //! In most cases, it provides faster image convergence with minimal
734 //! bias, so it is enabled by default.
735 #define RUSSIAN_ROULETTE
737 //! Frame step to increase number of bounces. This mode is used
738 //! for interaction with the model, when path length is limited
739 //! for the first samples, and gradually increasing when camera
741 #ifdef ADAPTIVE_SAMPLING
747 //=======================================================================
748 // function : IsNotZero
749 // purpose : Checks whether BSDF reflects direct light
750 //=======================================================================
751 bool IsNotZero (in SBSDF theBSDF, in vec3 theThroughput)
753 vec3 aGlossy = theBSDF.Kc.rgb * step (FLT_EPSILON, theBSDF.Kc.w) +
754 theBSDF.Ks.rgb * step (FLT_EPSILON, theBSDF.Ks.w);
756 return convolve (theBSDF.Kd.rgb + aGlossy, theThroughput) > FLT_EPSILON;
759 //=======================================================================
760 // function : PathTrace
761 // purpose : Calculates radiance along the given ray
762 //=======================================================================
763 vec4 PathTrace (in SRay theRay, in vec3 theInverse, in int theNbSamples)
765 float aRaytraceDepth = MAXFLOAT;
767 vec3 aRadiance = ZERO;
768 vec3 aThroughput = UNIT;
770 int aTransfID = 0; // ID of object transformation
771 bool aInMedium = false; // is the ray inside an object
776 for (int aDepth = 0; aDepth < NB_BOUNCES; ++aDepth)
778 SIntersect aHit = SIntersect (MAXFLOAT, vec2 (ZERO), ZERO);
780 ivec4 aTriIndex = SceneNearestHit (theRay, theInverse, aHit, aTransfID);
782 // check implicit path
783 vec3 aLe = IntersectLight (theRay, aDepth, aHit.Time, aExpPDF);
785 if (any (greaterThan (aLe, ZERO)) || aTriIndex.x == -1)
787 float aMIS = (aDepth == 0 || aImpPDF == MAXFLOAT) ? 1.f :
788 aImpPDF * aImpPDF / (aExpPDF * aExpPDF + aImpPDF * aImpPDF);
790 aRadiance += aThroughput * aLe * aMIS; break; // terminate path
793 vec3 aInvTransf0 = texelFetch (uSceneTransformTexture, aTransfID + 0).xyz;
794 vec3 aInvTransf1 = texelFetch (uSceneTransformTexture, aTransfID + 1).xyz;
795 vec3 aInvTransf2 = texelFetch (uSceneTransformTexture, aTransfID + 2).xyz;
797 // compute geometrical normal
798 aHit.Normal = normalize (vec3 (dot (aInvTransf0, aHit.Normal),
799 dot (aInvTransf1, aHit.Normal),
800 dot (aInvTransf2, aHit.Normal)));
802 theRay.Origin += theRay.Direct * aHit.Time; // get new intersection point
804 // evaluate depth on first hit
807 vec4 aNDCPoint = uViewMat * vec4 (theRay.Origin, 1.f);
809 float aPolygonOffset = PolygonOffset (aHit.Normal, theRay.Origin);
810 aRaytraceDepth = (aNDCPoint.z / aNDCPoint.w + aPolygonOffset * POLYGON_OFFSET_SCALE) * 0.5f + 0.5f;
815 // fetch BxDF weights
816 aBSDF.Kc = texelFetch (uRaytraceMaterialTexture, MATERIAL_KC (aTriIndex.w));
817 aBSDF.Kd = texelFetch (uRaytraceMaterialTexture, MATERIAL_KD (aTriIndex.w));
818 aBSDF.Ks = texelFetch (uRaytraceMaterialTexture, MATERIAL_KS (aTriIndex.w));
819 aBSDF.Kt = texelFetch (uRaytraceMaterialTexture, MATERIAL_KT (aTriIndex.w));
821 // fetch Fresnel reflectance for both layers
822 aBSDF.FresnelCoat = texelFetch (uRaytraceMaterialTexture, MATERIAL_FRESNEL_COAT (aTriIndex.w)).xyz;
823 aBSDF.FresnelBase = texelFetch (uRaytraceMaterialTexture, MATERIAL_FRESNEL_BASE (aTriIndex.w)).xyz;
825 vec4 anLE = texelFetch (uRaytraceMaterialTexture, MATERIAL_LE (aTriIndex.w));
827 // compute smooth normal (in parallel with fetch)
828 vec3 aNormal = SmoothNormal (aHit.UV, aTriIndex);
829 aNormal = normalize (vec3 (dot (aInvTransf0, aNormal),
830 dot (aInvTransf1, aNormal),
831 dot (aInvTransf2, aNormal)));
833 SLocalSpace aSpace = buildLocalSpace (aNormal);
836 if (aBSDF.Kd.w >= 0.0 || aBSDF.Kt.w >= 0.0 || anLE.w >= 0.0)
838 vec4 aTexCoord = vec4 (SmoothUV (aHit.UV, aTriIndex), 0.f, 1.f);
839 vec4 aTrsfRow1 = texelFetch (uRaytraceMaterialTexture, MATERIAL_TRS1 (aTriIndex.w));
840 vec4 aTrsfRow2 = texelFetch (uRaytraceMaterialTexture, MATERIAL_TRS2 (aTriIndex.w));
841 aTexCoord.st = vec2 (dot (aTrsfRow1, aTexCoord),
842 dot (aTrsfRow2, aTexCoord));
846 anLE.rgb *= textureLod (sampler2D (uTextureSamplers[int (anLE.w)]), aTexCoord.st, 0.0).rgb;
848 if (aBSDF.Kt.w >= 0.0)
850 vec2 aTexMetRough = textureLod (sampler2D (uTextureSamplers[int (aBSDF.Kt.w)]), aTexCoord.st, 0.0).bg;
851 float aPbrMetal = aTexMetRough.x;
852 float aPbrRough2 = aTexMetRough.y * aTexMetRough.y;
853 aBSDF.Ks.a *= aPbrRough2;
854 // when using metal-roughness texture, global metalness of material (encoded in FresnelBase) is expected to be 1.0 so that Kd will be 0.0
855 aBSDF.Kd.rgb = aBSDF.FresnelBase * (1.0 - aPbrMetal);
856 aBSDF.FresnelBase *= aPbrMetal;
858 if (aBSDF.Kd.w >= 0.0)
860 vec4 aTexColor = textureLod (sampler2D (uTextureSamplers[int (aBSDF.Kd.w)]), aTexCoord.st, 0.0);
861 vec3 aDiff = aTexColor.rgb * aTexColor.a;
862 aBSDF.Kd.rgb *= aDiff;
863 aBSDF.FresnelBase *= aDiff;
864 if (aTexColor.a != 1.0)
866 // mix transparency BTDF with texture alpha-channel
867 aBSDF.Ks.rgb *= aTexColor.a;
868 aBSDF.Kt.rgb = (UNIT - aTexColor.aaa) + aTexColor.a * aBSDF.Kt.rgb;
874 if (uLightCount > 0 && IsNotZero (aBSDF, aThroughput))
876 aExpPDF = 1.f / uLightCount;
878 int aLightIdx = min (int (floor (RandFloat() * uLightCount)), uLightCount - 1);
880 vec4 aLight = texelFetch (
881 uRaytraceLightSrcTexture, LIGHT_POS (aLightIdx));
882 vec4 aParam = texelFetch (
883 uRaytraceLightSrcTexture, LIGHT_PWR (aLightIdx));
885 // 'w' component is 0 for infinite light and 1 for point light
886 aLight.xyz -= mix (ZERO, theRay.Origin, aLight.w);
888 float aDistance = length (aLight.xyz);
890 aLight.xyz = SampleLight (aLight.xyz, aDistance,
891 aLight.w == 0.f /* is infinite */, aParam.w /* max cos or radius */, aExpPDF);
893 aImpPDF = BsdfPdfLayered (aBSDF,
894 toLocalSpace (-theRay.Direct, aSpace), toLocalSpace (aLight.xyz, aSpace), aThroughput);
896 // MIS weight including division by explicit PDF
897 float aMIS = (aExpPDF == MAXFLOAT) ? 1.f : aExpPDF / (aExpPDF * aExpPDF + aImpPDF * aImpPDF);
899 vec3 aContrib = aMIS * aParam.rgb /* Le */ * EvalBsdfLayered (
900 aBSDF, toLocalSpace (aLight.xyz, aSpace), toLocalSpace (-theRay.Direct, aSpace));
902 if (any (greaterThan (aContrib, MIN_CONTRIBUTION))) // check if light source is important
904 SRay aShadow = SRay (theRay.Origin + aLight.xyz * uSceneEpsilon, aLight.xyz);
906 aShadow.Origin += aHit.Normal * mix (
907 -uSceneEpsilon, uSceneEpsilon, step (0.f, dot (aHit.Normal, aLight.xyz)));
909 float aVisibility = SceneAnyHit (aShadow,
910 InverseDirection (aLight.xyz), aLight.w == 0.f ? MAXFLOAT : aDistance);
912 aRadiance += aVisibility * (aThroughput * aContrib);
916 // account for self-emission
917 aRadiance += aThroughput * anLE.rgb;
919 if (aInMedium) // handle attenuation
921 vec4 aScattering = texelFetch (uRaytraceMaterialTexture, MATERIAL_ABSORPT_BASE (aTriIndex.w));
923 aThroughput *= exp (-aHit.Time * aScattering.w * (UNIT - aScattering.rgb));
926 vec3 anInput = UNIT; // sampled input direction
928 aImpPDF = SampleBsdfLayered (aBSDF,
929 toLocalSpace (-theRay.Direct, aSpace), anInput, aThroughput, aInMedium);
931 float aSurvive = float (any (greaterThan (aThroughput, MIN_THROUGHPUT)));
933 #ifdef RUSSIAN_ROULETTE
934 aSurvive = aDepth < 3 ? aSurvive : min (dot (LUMA, aThroughput), 0.95f);
937 // here, we additionally increase path length for non-diffuse bounces
938 if (RandFloat() > aSurvive || all (lessThan (aThroughput, MIN_THROUGHPUT)) || aDepth >= theNbSamples / FRAME_STEP + step (1.f / M_PI, aImpPDF))
940 aDepth = INVALID_BOUNCES; // terminate path
943 #ifdef RUSSIAN_ROULETTE
944 aThroughput /= aSurvive;
947 anInput = normalize (fromLocalSpace (anInput, aSpace));
949 theRay = SRay (theRay.Origin + anInput * uSceneEpsilon +
950 aHit.Normal * mix (-uSceneEpsilon, uSceneEpsilon, step (0.f, dot (aHit.Normal, anInput))), anInput);
952 theInverse = InverseDirection (anInput);
955 gl_FragDepth = aRaytraceDepth;
957 return vec4 (aRadiance, aRaytraceDepth);