Multiple-lights.html (13580B)
1 <h1 id="content-title">Multiple lights</h1> 2 <h1 id="content-url" style='display:none;'>Lighting/Multiple-lights</h1> 3 <p> 4 In the previous chapters we learned a lot about lighting in OpenGL. We learned about Phong shading, materials, lighting maps and different types of light casters. In this chapter we're going to combine all the previously obtained knowledge by creating a fully lit scene with 6 active light sources. We are going to simulate a sun-like light as a directional light source, 4 point lights scattered throughout the scene and we'll be adding a flashlight as well. 5 </p> 6 7 <p> 8 To use more than one light source in the scene we want to encapsulate the lighting calculations into GLSL <def>functions</def>. The reason for that is that the code quickly gets nasty when we do lighting computations with multiple light types, each requiring different computations. If we were to do all these calculations in the <fun>main</fun> function only, the code quickly becomes difficult to understand. 9 </p> 10 11 <p> 12 Functions in GLSL are just like C-functions. We have a function name, a return type and we need to declare a prototype at the top of the code file if the function hasn't been declared yet before the main function. We'll create a different function for each of the light types: directional lights, point lights and spotlights. 13 </p> 14 15 <p> 16 When using multiple lights in a scene the approach is usually as follows: we have a single color vector that represents the fragment's output color. For each light, the light's contribution to the fragment is added to this output color vector. So each light in the scene will calculate its individual impact and contribute that to the final output color. A general structure would look something like this: 17 </p> 18 19 <pre><code> 20 out vec4 FragColor; 21 22 void main() 23 { 24 // define an output color value 25 vec3 output = vec3(0.0); 26 // add the directional light's contribution to the output 27 output += someFunctionToCalculateDirectionalLight(); 28 // do the same for all point lights 29 for(int i = 0; i < nr_of_point_lights; i++) 30 output += someFunctionToCalculatePointLight(); 31 // and add others lights as well (like spotlights) 32 output += someFunctionToCalculateSpotLight(); 33 34 FragColor = vec4(output, 1.0); 35 } 36 </code></pre> 37 38 <p> 39 The actual code will likely differ per implementation, but the general structure remains the same. We define several functions that calculate the impact per light source and add its resulting color to an output color vector. If for example two light sources are close to the fragment, their combined contribution would result in a more brightly lit fragment compared to the fragment being lit by a single light source. 40 </p> 41 42 <h2>Directional light</h2> 43 <p> 44 We want to define a function in the fragment shader that calculates the contribution a directional light has on the corresponding fragment: a function that takes a few parameters and returns the calculated directional lighting color. 45 </p> 46 47 <p> 48 First we need to set the required variables that we minimally need for a directional light source. We can store the variables in a struct called <fun>DirLight</fun> and define it as a uniform. The struct's variables should be familiar from the <a href="https://learnopengl.com/Lighting/Light-casters" target="_blank">previous</a> chapter: 49 </p> 50 51 <pre><code> 52 struct DirLight { 53 vec3 direction; 54 55 vec3 ambient; 56 vec3 diffuse; 57 vec3 specular; 58 }; 59 uniform DirLight dirLight; 60 </code></pre> 61 62 <p> 63 We can then pass the <var>dirLight</var> uniform to a function with the following prototype: 64 </p> 65 66 <pre><code> 67 vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir); 68 </code></pre> 69 70 <note> 71 Just like C and C++, when we want to call a function (in this case inside the <fun>main</fun> function) the function should be defined somewhere before the caller's line number. In this case we'd prefer to define the functions below the <fun>main</fun> function so this requirement doesn't hold. Therefore we declare the function's prototypes somewhere above the <fun>main</fun> function, just like we would in C. 72 </note> 73 74 <p> 75 You can see that the function requires a <fun>DirLight</fun> struct and two other vectors required for its computation. If you successfully completed the previous chapter then the content of this function should come as no surprise: 76 </p> 77 78 <pre><code> 79 vec3 CalcDirLight(DirLight light, vec3 normal, vec3 viewDir) 80 { 81 vec3 lightDir = normalize(-light.direction); 82 // diffuse shading 83 float diff = max(dot(normal, lightDir), 0.0); 84 // specular shading 85 vec3 reflectDir = reflect(-lightDir, normal); 86 float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); 87 // combine results 88 vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); 89 vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords)); 90 vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords)); 91 return (ambient + diffuse + specular); 92 } 93 </code></pre> 94 95 <p> 96 We basically copied the code from the previous chapter and used the vectors given as function arguments to calculate the directional light's contribution vector. The resulting ambient, diffuse and specular contributions are then returned as a single color vector. 97 </p> 98 99 <h2>Point light</h2> 100 <p> 101 Similar to directional lights we also want to define a function that calculates the contribution a point light has on the given fragment, including its attenuation. Just like directional lights we want to define a struct that specifies all the variables required for a point light: 102 </p> 103 104 <pre><code> 105 struct PointLight { 106 vec3 position; 107 108 float constant; 109 float linear; 110 float quadratic; 111 112 vec3 ambient; 113 vec3 diffuse; 114 vec3 specular; 115 }; 116 #define NR_POINT_LIGHTS 4 117 uniform PointLight pointLights[NR_POINT_LIGHTS]; 118 </code></pre> 119 120 <p> 121 As you can see we used a pre-processor directive in GLSL to define the number of point lights we want to have in our scene. We then use this <var>NR_POINT_LIGHTS</var> constant to create an array of <fun>PointLight</fun> structs. Arrays in GLSL are just like C arrays and can be created by the use of two square brackets. Right now we have 4 <fun>PointLight</fun> structs to fill with data. 122 </p> 123 124 <!--<note> 125 We could also simply define <strong>one</strong> large struct (instead of different structs per light type) that contains all the necessary variables for <strong>all</strong> the different light types and use that struct for each function, and simply ignore the variables we don't need. However, I personally find the current approach more intuitive and aside from a few extra lines of code it could save up some memory since not all light types need all variables. 126 </note>--> 127 128 <p> 129 The prototype of the point light's function is as follows: 130 </p> 131 132 <pre><code> 133 vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir); 134 </code></pre> 135 136 <p> 137 The function takes all the data it needs as its arguments and returns a <code>vec3</code> that represents the color contribution that this specific point light has on the fragment. Again, some intelligent copy-and-pasting results in the following function: 138 </p> 139 140 <pre><code> 141 vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir) 142 { 143 vec3 lightDir = normalize(light.position - fragPos); 144 // diffuse shading 145 float diff = max(dot(normal, lightDir), 0.0); 146 // specular shading 147 vec3 reflectDir = reflect(-lightDir, normal); 148 float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); 149 // attenuation 150 float distance = length(light.position - fragPos); 151 float attenuation = 1.0 / (light.constant + light.linear * distance + 152 light.quadratic * (distance * distance)); 153 // combine results 154 vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); 155 vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords)); 156 vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords)); 157 ambient *= attenuation; 158 diffuse *= attenuation; 159 specular *= attenuation; 160 return (ambient + diffuse + specular); 161 } 162 </code></pre> 163 164 <p> 165 Abstracting this functionality away in a function like this has the advantage that we can easily calculate the lighting for multiple point lights without the need for duplicated code. In the <fun>main</fun> function we simply create a loop that iterates over the point light array that calls <fun>CalcPointLight</fun> for each point light. 166 </p> 167 168 <h2>Putting it all together</h2> 169 <p> 170 Now that we defined both a function for directional lights and a function for point lights we can put it all together in the <fun>main</fun> function. 171 </p> 172 173 <pre><code> 174 void main() 175 { 176 // properties 177 vec3 norm = normalize(Normal); 178 vec3 viewDir = normalize(viewPos - FragPos); 179 180 // phase 1: Directional lighting 181 vec3 result = CalcDirLight(dirLight, norm, viewDir); 182 // phase 2: Point lights 183 for(int i = 0; i < NR_POINT_LIGHTS; i++) 184 result += CalcPointLight(pointLights[i], norm, FragPos, viewDir); 185 // phase 3: Spot light 186 //result += CalcSpotLight(spotLight, norm, FragPos, viewDir); 187 188 FragColor = vec4(result, 1.0); 189 } 190 </code></pre> 191 192 <p> 193 Each light type adds its contribution to the resulting output color until all light sources are processed. The resulting color contains the color impact of all the light sources in the scene combined. We leave the <fun>CalcSpotLight</fun> function as an exercise for the reader. 194 </p> 195 196 <note> 197 There are lot of duplicated calculations in this approach spread out over the light type functions (e.g. calculating the reflect vector, diffuse and specular terms, and sampling the material textures) so there's room for optimization here. 198 </note> 199 200 <p> 201 Setting the uniforms for the directional light struct shouldn't be too unfamiliar, but you may be wondering how to set the uniform values of the point lights since the point light uniform is actually an array of <fun>PointLight</fun> structs. This isn't something we've discussed before. 202 </p> 203 204 <p> 205 Luckily for us, it isn't too complicated. Setting the uniform values of an array of structs works just like setting the uniforms of a single struct, although this time we also have to define the appropriate index when querying the uniform's location: 206 </p> 207 208 <pre><code> 209 lightingShader.setFloat("pointLights[0].constant", 1.0f); 210 </code></pre> 211 212 <p> 213 Here we index the first <fun>PointLight</fun> struct in the <var>pointLights</var> array and internally retrieve the location of its <var>constant</var> variable, which we set to <code>1.0</code>. 214 </p> 215 216 <p> 217 Let's not forget that we also need to define a position vector for each of the 4 point lights so let's spread them up a bit around the scene. We'll define another <code>glm::vec3</code> array that contains the pointlights' positions: 218 </p> 219 220 <pre><code> 221 glm::vec3 pointLightPositions[] = { 222 glm::vec3( 0.7f, 0.2f, 2.0f), 223 glm::vec3( 2.3f, -3.3f, -4.0f), 224 glm::vec3(-4.0f, 2.0f, -12.0f), 225 glm::vec3( 0.0f, 0.0f, -3.0f) 226 }; 227 </code></pre> 228 229 <p> 230 Then we index the corresponding <fun>PointLight</fun> struct from the <var>pointLights</var> array and set its <var>position</var> attribute as one of the positions we just defined. Also be sure to now draw 4 light cubes instead of just 1. Simply create a different model matrix for each of the light objects just like we did with the containers. 231 </p> 232 233 <p> 234 If you'd also use a flashlight, the result of all the combined lights looks something like this: 235 </p> 236 237 <img src="/img/lighting/multiple_lights_combined.png" class="clean"/> 238 239 <p> 240 As you can see there appears to be some form of a global light (like a sun) somewhere in the sky, we have 4 lights scattered throughout the scene and a flashlight is visible from the player's perspective. Looks pretty neat doesn't it? 241 </p> 242 243 <p> 244 You can find the full source code of the final application <a href="/code_viewer_gh.php?code=src/2.lighting/6.multiple_lights/multiple_lights.cpp" target="_blank">here</a>. 245 </p> 246 247 <p> 248 The image shows all the light sources set with the default light properties we've used in the previous chapters, but if you play around with these values you can get pretty interesting results. Artists and level designers generally tweak all these lighting variables in a large editor to make sure the lighting matches the environment. Using our simple environment you can already create some pretty interesting visuals simply by tweaking the lights' attributes: 249 </p> 250 251 <img src="/img/lighting/multiple_lights_atmospheres.png" class="clean" style="border-radius: 0px;"/> 252 253 <p> 254 We also changed the clear color to better reflect the lighting. You can see that by simply adjusting some of the lighting parameters you can create completely different atmospheres. 255 </p> 256 257 <p> 258 By now you should have a pretty good understanding of lighting in OpenGL. With the knowledge so far we can already create interesting and visually rich environments and atmospheres. Try playing around with all the different values to create your own atmospheres. 259 </p> 260 261 <h2>Exercises</h2> 262 <p> 263 <ul> 264 <li>Can you (sort of) re-create the different atmospheres of the last image by tweaking the light's attribute values? <a href="/code_viewer_gh.php?code=src/2.lighting/6.multiple_lights_exercise1/multiple_lights_exercise1.cpp" target="_blank">solution</a>.</li> 265 </ul> 266 </p> 267 268 </div> 269