GLSL Programming/GLUT/Multiple Lights

This tutorial covers lighting by multiple light sources.

This tutorial is an extension of the tutorial on smooth specular highlights. If you haven't read that tutorial, you should read it first.

Multiple Lights
In the previous tutorials on diffuse reflection, etc., we have only used one light source, which was specified by the variable. However, we could handle an array of light sources.

Here, we take a certain number of these lights into account and add their contributions to the total lighting. This can be computed with a for-loop in the fragment shader of the tutorial on smooth specular highlights. The structure is this:

The total lighting by all lights is accumulated in  by initializing it to the ambient lighting and then adding the diffuse and specular reflection of each light to the previous value of   at the end of the for-loop. A for-loop should be familiar to any C/C++/Java/JavaScript programmer. Note that for-loops in GLSL are usually severely limited. Often (e.g. in OpenGL ES 2.0) the limits (here: 0 and ) have to be constants, i.e. you cannot even use uniforms to determine the limits. (The technical reason for the limitation is that the limits have to be known at compile time in order to “un-roll” the loop.)

Complete Shader Code
The vertex shader is the same as in the tutorial on smooth specular highlights: The only tricky thing about the fragment shader is that the nesting of loops and conditionals appears to be limited on some GPUs and/or graphics drivers. In fact, I had to reduce the nesting by avoiding if-else-statements in order to compile the shader on my computer (the OpenGL API reported an internal error). In principle, nesting of conditionals and loops is allowed in GLSL; however, it is probably a good idea to test shaders that make extensive use of nested loops and conditionals on several systems.

Summary
Congratulations, you have reached the end of this tutorial. We have seen:
 * How a for-loop can be used in GLSL to compute the lighting of multiple lights in a fragment shader.