LearnOpenGL

Translation in progress of learnopengl.com.
git clone https://git.mtkn.jp/LearnOpenGL
Log | Files | Refs

Lighting.html (21595B)


      1     <h1 id="content-title">Lighting</h1>
      2 <h1 id="content-url" style='display:none;'>PBR/Lighting</h1>
      3 <p>
      4   In the <a href="https://learnopengl.com/PBR/Theory" target="_blank">previous</a> chapter we laid the foundation for getting a realistic physically based renderer off the ground. In this chapter we'll focus on translating the previously discussed theory into an actual renderer that uses direct (or analytic) light sources: think of point lights, directional lights, and/or spotlights. 
      5 </p>
      6 
      7 <p>
      8   Let's start by re-visiting the final reflectance equation from the previous chapter:
      9 </p>
     10 
     11  \[
     12     L_o(p,\omega_o) = \int\limits_{\Omega} 
     13     	(k_d\frac{c}{\pi} + \frac{DFG}{4(\omega_o \cdot n)(\omega_i \cdot n)})
     14     	L_i(p,\omega_i) n \cdot \omega_i  d\omega_i
     15  \]
     16 
     17 <p>
     18   We now know mostly what's going on, but what still remained a big unknown is how exactly we're going to represent irradiance, the total radiance \(L\), of the scene. We know that radiance \(L\) (as interpreted in computer graphics land) measures the radiant flux \(\phi\) or light energy of a light source over a given solid angle  \(\omega\). In our case we assumed the solid angle \(\omega\) to be infinitely small in which case radiance measures the flux of a light source over a single light ray or direction vector.
     19 </p>
     20 
     21 <p>
     22   Given this knowledge, how do we translate this into some of the lighting knowledge we've accumulated from previous chapters? Well, imagine we have a single point light (a light source that shines equally bright in all directions) with a radiant flux of <code>(23.47, 21.31, 20.79)</code> as translated to an RGB triplet. The radiant intensity of this light source equals its radiant flux at all outgoing direction rays. However, when shading a specific point \(p\) on a surface, of all possible incoming light directions over its hemisphere \(\Omega\), only one incoming direction vector \(w_i\) directly comes from the point light source. As we only have a single light source in our scene, assumed to be a single point in space, all other possible incoming light directions have zero radiance observed over the surface point \(p\):
     23 </p>
     24 
     25 <img src="/img/pbr/lighting_radiance_direct.png" class="clean" alt="Radiance on a point p of a non-attenuated point light source only returning non-zero at the infitely small solid angle Wi or light direction vector Wi"/>
     26 
     27 <p>
     28   If at first, we assume that light attenuation (dimming of light over distance) does not affect the point light source, the radiance of the incoming light ray is the same regardless of where we position the light (excluding scaling the radiance by the incident angle \(\cos  \theta\)). This, because the point light has the same radiant intensity regardless of the angle we look at it, effectively modeling its radiant intensity as its radiant flux: a constant vector <code>(23.47, 21.31, 20.79)</code>.
     29 </p>
     30 
     31 <p>
     32   However, radiance also takes a position \(p\) as input and as any realistic point light source takes light attenuation into account, the radiant intensity of the point light source is scaled by some measure of the distance between point \(p\) and the light source. Then, as extracted from the original radiance equation, the result is scaled by the dot product between the surface normal \(n\) and the incoming light direction \(w_i\).
     33 </p>
     34 
     35 <p>
     36   To put this in more practical terms: in the case of a direct point light the radiance function \(L\)  measures the light color, attenuated over its distance to \(p\) and scaled by \(n \cdot w_i\), but only over the single light ray \(w_i\) that hits \(p\) which equals the light's direction vector from \(p\).
     37   In code this translates to:
     38 </p>
     39 
     40 <pre><code>
     41 vec3  lightColor  = vec3(23.47, 21.31, 20.79);
     42 vec3  wi          = normalize(lightPos - fragPos);
     43 float cosTheta    = max(dot(N, Wi), 0.0);
     44 float attenuation = calculateAttenuation(fragPos, lightPos);
     45 vec3  radiance    = lightColor * attenuation * cosTheta;
     46 </code></pre>
     47   
     48 <p>
     49   Aside from the different terminology, this piece of code should be awfully familiar to you: this is exactly how we've been doing diffuse lighting so far. When it comes to direct lighting, radiance is calculated similarly to how we've calculated lighting before as only a single light direction vector contributes to the surface's radiance. 
     50 </p>
     51   
     52 <note>
     53   Note that this assumption holds as point lights are infinitely small and only a single point in space. If we were to model a light that has area or volume, its radiance would be non-zero in more than one incoming light direction.
     54 </note>
     55   
     56 <p>
     57   For other types of light sources originating from a single point we calculate radiance similarly. For instance, a directional light source has a constant \(w_i\) without an attenuation factor. And a spotlight would not have a constant radiant intensity, but one that is scaled by the forward direction vector of the spotlight. 
     58 </p>
     59   
     60 <p>
     61   This also brings us back to the integral \(\int\) over the surface's hemisphere \(\Omega\) . As we know beforehand the single locations of all the contributing light sources while shading a single surface point, it is not required to try and solve the integral. We can directly take the (known) number of light sources and calculate their total irradiance, given that each light source has only a single light direction that influences the surface's radiance. This makes PBR on direct light sources relatively simple as we effectively only have to loop over the contributing light sources. When we later take environment lighting into account in the <a href="https://learnopengl.com/PBR/IBL/Diffuse-irradiance" target="_blank">IBL</a> chapters we do have to take the integral into account as light can come from any direction.
     62 </p>
     63   
     64 <h2>A PBR surface model</h2>
     65 <p>
     66   Let's start by writing a fragment shader that implements the previously described PBR models. First, we need to take the relevant PBR inputs required for shading the surface:
     67 </p>
     68   
     69 <pre><code>
     70 #version 330 core
     71 out vec4 FragColor;
     72 in vec2 TexCoords;
     73 in vec3 WorldPos;
     74 in vec3 Normal;
     75   
     76 uniform vec3 camPos;
     77   
     78 uniform vec3  albedo;
     79 uniform float metallic;
     80 uniform float roughness;
     81 uniform float ao;
     82 </code></pre>
     83   
     84 <p>
     85   We take the standard inputs as calculated from a generic vertex shader and a set of constant material properties over the surface of the object. 
     86 </p>
     87   
     88 <p>
     89   Then at the start of the fragment shader we do the usual calculations required for any lighting algorithm:
     90 </p>
     91   
     92 <pre><code>
     93 void main()
     94 {
     95     vec3 N = normalize(Normal); 
     96     vec3 V = normalize(camPos - WorldPos);
     97     [...]
     98 }
     99 </code></pre>
    100   
    101 <h3>Direct lighting</h3>
    102 <p>
    103   In this chapter's example demo we have a total of 4 point lights that together represent the scene's irradiance. To satisfy the reflectance equation we loop over each light source, calculate its individual radiance and sum its contribution scaled by the BRDF and the light's incident angle. We can think of the loop as solving the integral \(\int\) over \(\Omega\) for direct light sources. First, we calculate the relevant per-light variables:
    104 </p>
    105   
    106 <pre><code>
    107 vec3 Lo = vec3(0.0);
    108 for(int i = 0; i &lt; 4; ++i) 
    109 {
    110     vec3 L = normalize(lightPositions[i] - WorldPos);
    111     vec3 H = normalize(V + L);
    112   
    113     float distance    = length(lightPositions[i] - WorldPos);
    114     float attenuation = 1.0 / (distance * distance);
    115     vec3 radiance     = lightColors[i] * attenuation; 
    116     [...]  
    117 </code></pre>
    118   
    119 <p>
    120   As we calculate lighting in linear space (we'll <a href="https://learnopengl.com/Advanced-Lighting/Gamma-Correction" target="_blank">gamma correct</a> at the end of the shader) we attenuate the light sources by the more physically correct <def>inverse-square law</def>. 
    121 </p>
    122   
    123 <note>
    124   While physically correct, you may still want to use the constant-linear-quadratic attenuation equation that (while not physically correct) can offer you significantly more control over the light's energy falloff.
    125 </note>
    126   
    127 <p>
    128   Then, for each light we want to calculate the full Cook-Torrance specular BRDF term:
    129 </p>
    130 
    131   \[
    132   	\frac{DFG}{4(\omega_o \cdot n)(\omega_i \cdot n)}
    133   \]
    134   
    135 <p>
    136   The first thing we want to do is calculate the ratio between specular and diffuse reflection, or how much the surface reflects light versus how much it refracts light. We know from the <a href="https://learnopengl.com/PBR/Theory" target="_blank">previous</a> chapter that the Fresnel equation calculates just that (note the <code>clamp</code> here to prevent black spots):
    137 </p>
    138   
    139 <pre><code>
    140 vec3 fresnelSchlick(float cosTheta, vec3 F0)
    141 {
    142     return F0 + (1.0 - F0) * pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);
    143 }  
    144 </code></pre>
    145   
    146 <p>
    147   The Fresnel-Schlick approximation expects a <var>F0</var> parameter which is known as the <em>surface reflection at zero incidence</em> or how much the surface reflects if looking directly at the surface. The <var>F0</var> varies per material and is tinted on metals as we find in large material databases. In the PBR metallic workflow we make the simplifying assumption that most dielectric surfaces look visually correct with a constant <var>F0</var> of <code>0.04</code>, while we do specify <var>F0</var> for metallic surfaces as then given by the albedo value. This translates to code as follows:
    148 </p>
    149   
    150 <pre><code>
    151 vec3 F0 = vec3(0.04); 
    152 F0      = mix(F0, albedo, metallic);
    153 vec3 F  = fresnelSchlick(max(dot(H, V), 0.0), F0);
    154 </code></pre>
    155   
    156 <p>
    157   As you can see, for non-metallic surfaces <var>F0</var> is always <code>0.04</code>. For metallic surfaces, we vary <var>F0</var> by linearly interpolating between the original <var>F0</var> and the albedo value given the <var>metallic</var> property. 
    158 </p>
    159   
    160 <p>
    161   Given \(F\), the remaining terms to calculate are the normal distribution function \(D\) and the geometry function \(G\).
    162 </p>
    163   
    164 <p>
    165   In a direct PBR lighting shader their code equivalents are:
    166 </p>
    167   
    168 <pre><code>
    169 float DistributionGGX(vec3 N, vec3 H, float roughness)
    170 {
    171     float a      = roughness*roughness;
    172     float a2     = a*a;
    173     float NdotH  = max(dot(N, H), 0.0);
    174     float NdotH2 = NdotH*NdotH;
    175 	
    176     float num   = a2;
    177     float denom = (NdotH2 * (a2 - 1.0) + 1.0);
    178     denom = PI * denom * denom;
    179 	
    180     return num / denom;
    181 }
    182 
    183 float GeometrySchlickGGX(float NdotV, float roughness)
    184 {
    185     float r = (roughness + 1.0);
    186     float k = (r*r) / 8.0;
    187 
    188     float num   = NdotV;
    189     float denom = NdotV * (1.0 - k) + k;
    190 	
    191     return num / denom;
    192 }
    193 float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness)
    194 {
    195     float NdotV = max(dot(N, V), 0.0);
    196     float NdotL = max(dot(N, L), 0.0);
    197     float ggx2  = GeometrySchlickGGX(NdotV, roughness);
    198     float ggx1  = GeometrySchlickGGX(NdotL, roughness);
    199 	
    200     return ggx1 * ggx2;
    201 }
    202 </code></pre>
    203   
    204 <p>
    205   What's important to note here is that in contrast to the <a href="https://learnopengl.com/PBR/Theory" target="_blank">theory</a> chapter, we pass the roughness parameter directly to these functions; this way we can make some term-specific modifications to the original roughness value. Based on observations by Disney and adopted by Epic Games, the lighting looks more correct squaring the roughness in both the geometry and normal distribution function.
    206 </p>
    207   
    208 <p>
    209   With both functions defined, calculating the NDF and the G term in the reflectance loop is straightforward: 
    210 </p>
    211   
    212 <pre><code>
    213 float NDF = DistributionGGX(N, H, roughness);       
    214 float G   = GeometrySmith(N, V, L, roughness);       
    215 </code></pre>
    216   
    217 <p>
    218   This gives us enough to calculate the Cook-Torrance BRDF:
    219 </p>
    220   
    221 <pre><code>
    222 vec3 numerator    = NDF * G * F;
    223 float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0)  + 0.0001;
    224 vec3 specular     = numerator / denominator;  
    225 </code></pre>
    226   
    227 <p>
    228   Note that we add <code>0.0001</code> to the denominator to prevent a divide by zero in case any dot product ends up <code>0.0</code>.
    229 </p>
    230   
    231 <p>
    232   Now we can finally calculate each light's contribution to the reflectance equation. As the Fresnel value directly corresponds to \(k_S\) we can use <var>F</var> to denote the specular contribution of any light that hits the surface. From \(k_S\) we can then calculate the ratio of refraction \(k_D\):
    233 </p>
    234   
    235 <pre><code>
    236 vec3 kS = F;
    237 vec3 kD = vec3(1.0) - kS;
    238   
    239 kD *= 1.0 - metallic;	
    240 </code></pre>
    241   
    242 <p>
    243   Seeing as <var>kS</var> represents the energy of light that gets reflected, the remaining ratio of light energy is the light that gets refracted which we store as <var>kD</var>. Furthermore, because metallic surfaces don't refract light and thus have no diffuse reflections we enforce this property by nullifying <var>kD</var> if the surface is metallic.  This gives us the final data we need to calculate each light's outgoing reflectance value:
    244 </p>
    245   
    246 <pre><code>
    247     const float PI = 3.14159265359;
    248   
    249     float NdotL = max(dot(N, L), 0.0);        
    250     Lo += (kD * albedo / PI + specular) * radiance * NdotL;
    251 }
    252 </code></pre>
    253   
    254 <p>
    255   The resulting <var>Lo</var> value, or the outgoing radiance, is effectively the result of the reflectance equation's integral \(\int\) over \(\Omega\).  We don't really have to try and solve the integral for all possible incoming light directions as we know exactly the 4 incoming light directions that can influence the fragment. Because of this, we can directly loop over these incoming light directions e.g. the number of lights in the scene.
    256 </p>
    257   
    258 <p>
    259   What's left is to add an (improvised) ambient term to the direct lighting result <var>Lo</var> and we have the final lit color of the fragment:
    260 </p>
    261 
    262 <pre><code>
    263 vec3 ambient = vec3(0.03) * albedo * ao;
    264 vec3 color   = ambient + Lo;  
    265 </code></pre>
    266   
    267 <h3>Linear and HDR rendering</h3>
    268 <p>
    269   So far we've assumed all our calculations to be in linear color space and to account for this we need to <a href="https://learnopengl.com/Advanced-Lighting/Gamma-Correction" target="_blank">gamma correct</a> at the end of the shader. Calculating lighting in linear space is incredibly important as PBR requires all inputs to be linear. Not taking this into account will result in incorrect lighting. Additionally, we want light inputs to be close to their physical equivalents such that their radiance or color values can vary wildly over a high spectrum of values. As a result, <var>Lo</var> can rapidly grow really high which then gets clamped between <code>0.0</code> and <code>1.0</code> due to the default low dynamic range (LDR) output. We fix this by taking <var>Lo</var> and tone or exposure map the <a href="https://learnopengl.com/Advanced-Lighting/HDR" target="_blank">high dynamic range</a> (HDR) value correctly to LDR before gamma correction: 
    270 </p>
    271   
    272 <pre><code>
    273 color = color / (color + vec3(1.0));
    274 color = pow(color, vec3(1.0/2.2)); 
    275 </code></pre>
    276   
    277 <p>
    278   Here we tone map the HDR color using the Reinhard operator, preserving the high dynamic range of a possibly highly varying irradiance, after which we gamma correct the color. We don't have a separate framebuffer or post-processing stage so we can directly apply both the tone mapping and gamma correction step at the end of the forward fragment shader. 
    279 </p>
    280   
    281   <img src="/img/pbr/lighting_linear_vs_non_linear_and_hdr.png" alt="The difference linear and HDR rendering makes in an OpenGL PBR renderer."/>
    282   
    283 <p>
    284   Taking both linear color space and high dynamic range into account is incredibly important in a PBR pipeline. Without these it's impossible to properly capture the high and low details of varying light intensities and your calculations end up incorrect and thus visually unpleasing.
    285 </p>
    286   
    287 <h3>Full direct lighting PBR shader</h3>
    288 <p>
    289   All that's left now is to pass the final tone mapped and gamma corrected color to the fragment shader's output channel and we have ourselves a direct PBR lighting shader. For completeness' sake, the complete <fun>main</fun> function is listed below:
    290 </p>
    291   
    292 <pre><code>
    293 #version 330 core
    294 out vec4 FragColor;
    295 in vec2 TexCoords;
    296 in vec3 WorldPos;
    297 in vec3 Normal;
    298 
    299 // material parameters
    300 uniform vec3  albedo;
    301 uniform float metallic;
    302 uniform float roughness;
    303 uniform float ao;
    304 
    305 // lights
    306 uniform vec3 lightPositions[4];
    307 uniform vec3 lightColors[4];
    308 
    309 uniform vec3 camPos;
    310 
    311 const float PI = 3.14159265359;
    312   
    313 float DistributionGGX(vec3 N, vec3 H, float roughness);
    314 float GeometrySchlickGGX(float NdotV, float roughness);
    315 float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness);
    316 vec3 fresnelSchlick(float cosTheta, vec3 F0);
    317 
    318 void main()
    319 {		
    320     vec3 N = normalize(Normal);
    321     vec3 V = normalize(camPos - WorldPos);
    322 
    323     vec3 F0 = vec3(0.04); 
    324     F0 = mix(F0, albedo, metallic);
    325 	           
    326     // reflectance equation
    327     vec3 Lo = vec3(0.0);
    328     for(int i = 0; i &lt; 4; ++i) 
    329     {
    330         // calculate per-light radiance
    331         vec3 L = normalize(lightPositions[i] - WorldPos);
    332         vec3 H = normalize(V + L);
    333         float distance    = length(lightPositions[i] - WorldPos);
    334         float attenuation = 1.0 / (distance * distance);
    335         vec3 radiance     = lightColors[i] * attenuation;        
    336         
    337         // cook-torrance brdf
    338         float NDF = DistributionGGX(N, H, roughness);        
    339         float G   = GeometrySmith(N, V, L, roughness);      
    340         vec3 F    = fresnelSchlick(max(dot(H, V), 0.0), F0);       
    341         
    342         vec3 kS = F;
    343         vec3 kD = vec3(1.0) - kS;
    344         kD *= 1.0 - metallic;	  
    345         
    346         vec3 numerator    = NDF * G * F;
    347         float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0) + 0.0001;
    348         vec3 specular     = numerator / denominator;  
    349             
    350         // add to outgoing radiance Lo
    351         float NdotL = max(dot(N, L), 0.0);                
    352         Lo += (kD * albedo / PI + specular) * radiance * NdotL; 
    353     }   
    354   
    355     vec3 ambient = vec3(0.03) * albedo * ao;
    356     vec3 color = ambient + Lo;
    357 	
    358     color = color / (color + vec3(1.0));
    359     color = pow(color, vec3(1.0/2.2));  
    360    
    361     FragColor = vec4(color, 1.0);
    362 }  
    363 </code></pre>
    364   
    365 <p>
    366   Hopefully, with the <a href="https://learnopengl.com/PBR/Theory" target="_blank">theory</a> from the previous chapter and the knowledge of the reflectance equation this shader shouldn't be as daunting anymore. If we take this shader, 4 point lights, and quite a few spheres where we vary both their metallic and roughness values on their vertical and horizontal axis respectively, we'd get something like this:
    367 </p>
    368   
    369   <img src="/img/pbr/lighting_result.png" alt="Render of PBR spheres with varying roughness and metallic values in OpenGL."/>
    370   
    371 <p>
    372   From bottom to top the metallic value ranges from <code>0.0</code> to <code>1.0</code>, with roughness increasing left to right from <code>0.0</code> to <code>1.0</code>. You can see that by only changing these two simple to understand parameters we can already display a wide array of different materials.
    373 </p>
    374 
    375 <iframe src="https://oneshader.net/embed/6b8a7c6363" style="width:80%; height:440px; border:0;margin-left:10.0%; margin-right:12.5%;" frameborder="0" allowfullscreen></iframe>
    376   
    377 <p>
    378   You can find the full source code of the demo <a href="/code_viewer_gh.php?code=src/6.pbr/1.1.lighting/lighting.cpp" target="_blank">here</a>.
    379 </p>
    380       
    381 <h2>Textured PBR</h2>
    382 <p>
    383   Extending the system to now accept its surface parameters as textures instead of uniform values gives us per-fragment control over the surface material's properties:
    384 </p>
    385 
    386 <pre><code>
    387 [...]
    388 uniform sampler2D albedoMap;
    389 uniform sampler2D normalMap;
    390 uniform sampler2D metallicMap;
    391 uniform sampler2D roughnessMap;
    392 uniform sampler2D aoMap;
    393   
    394 void main()
    395 {
    396     vec3 albedo     = pow(texture(albedoMap, TexCoords).rgb, 2.2);
    397     vec3 normal     = getNormalFromNormalMap();
    398     float metallic  = texture(metallicMap, TexCoords).r;
    399     float roughness = texture(roughnessMap, TexCoords).r;
    400     float ao        = texture(aoMap, TexCoords).r;
    401     [...]
    402 }
    403 </code></pre>
    404   
    405 <p>
    406   Note that the albedo textures that come from artists are generally authored in sRGB space which is why we first convert them to linear space before using albedo in our lighting calculations. Based on the system artists use to generate ambient occlusion maps you may also have to convert these from sRGB to linear space as well. Metallic and roughness maps are almost always authored in linear space.
    407 </p>
    408   
    409 <p>
    410   Replacing the material properties of the previous set of spheres with textures, already shows a major visual improvement over the previous lighting algorithms we've used:
    411 </p>
    412   
    413   <img src="/img/pbr/lighting_textured.png" alt="Render of PBR spheres with a textured PBR material in OpenGL."/>
    414   
    415 <p>
    416   You can find the full source code of the textured demo <a href="/code_viewer_gh.php?code=src/6.pbr/1.2.lighting_textured/lighting_textured.cpp" target="_blank">here</a> and the texture set used <a href="http://freepbr.com/materials/rusted-iron-pbr-metal-material-alt/" target="_blank">here</a> (with a white ao map). Keep in mind that metallic surfaces tend to look too dark in direct lighting environments as they don't have diffuse reflectance. They do look more correct when taking the environment's specular ambient lighting into account, which is what we'll focus on in the next chapters.
    417 </p>
    418   
    419 <p>
    420   While not as visually impressive as some of the PBR render demos you find out there, given that we don't yet have <a href="https://learnopengl.com/PBR/IBL/Diffuse-irradiance" target="_blank">image based lighting</a> built in, the system we have now is still a physically based renderer, and even without IBL you'll see your lighting look a lot more realistic.
    421 </p>       
    422 
    423     </div>
    424