How to do it...

We'll define a function for each of the three terms in the specular BRDF. Use the following steps:

  1. Define a function for the Fresnel term using the Schlick approximation:
vec3 schlickFresnel( float lDotH ) {
vec3 f0 = vec3(0.04); // Dielectrics
if( Material.Metal ) {
f0 = Material.Color;
}
return f0 + (1 - f0) * pow(1.0 - lDotH, 5);
}
  1. Define a function for the geometry term G:  
float geomSmith( float dotProd ) {
float k = (Material.Rough + 1.0) * (Material.Rough + 1.0) / 8.0;
float denom = dotProd * (1 - k) + k;
return 1.0 / denom;
}

  1. The normal distribution function D, based on GGX/Trowbridge-Reitz:
float ggxDistribution( float nDotH ) {
float alpha2 = Material.Rough * Material.Rough * Material.Rough * Material.Rough;
float d = (nDotH * nDotH) * (alpha2 - 1) + 1;
return alpha2 / (PI * d * d);
}
  1. We'll now define a function that computes the entire model for a single light source:
vec3 microfacetModel( int lightIdx, vec3 position, vec3 n ) { 
vec3 diffuseBrdf = vec3(0.0); // Metallic
if( !Material.Metal ) {
diffuseBrdf = Material.Color;
}

vec3 l = vec3(0.0),
lightI = Light[lightIdx].L;
if( Light[lightIdx].Position.w == 0.0 ) { // Directional light
l = normalize(Light[lightIdx].Position.xyz);
} else { // Positional light
l = Light[lightIdx].Position.xyz - position;
float dist = length(l);
l = normalize(l);
lightI /= (dist * dist);
}

vec3 v = normalize( -position );
vec3 h = normalize( v + l );
float nDotH = dot( n, h );
float lDotH = dot( l, h );
float nDotL = max( dot( n, l ), 0.0 );
float nDotV = dot( n, v );
vec3 specBrdf = 0.25 * ggxDistribution(nDotH) *
schlickFresnel(lDotH) * geomSmith(nDotL) * geomSmith(nDotV);

return (diffuseBrdf + PI * specBrdf) * lightI * nDotL;
}
  1. We put this all together by summing over the light sources, applying Gamma correction, and writing out the result:
void main() {
vec3 sum = vec3(0), n = normalize(Normal);
for( int i = 0; i < 3; i++ ) {
sum += microfacetModel(i, Position, n);
}

// Gamma
sum = pow( sum, vec3(1.0/2.2) );

FragColor = vec4(sum, 1);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.229.113