# GLSL Programming/Unity/Diffuse Reflection

This tutorial covers per-vertex diffuse reflection.
It's the first in a series of tutorials about basic lighting in Unity. In this tutorial, we start with diffuse reflection from a single directional light source and then include point light sources and multiple light sources (using multiple passes). Further tutorials cover extensions of this, in particular specular reflection, per-pixel lighting, and two-sided lighting.

### Diffuse Reflection

The moon exhibits almost exclusively diffuse reflection (also called Lambertian reflection), i.e. light is reflected into all directions without specular highlights. Other examples of such materials are chalk and matte paper; in fact, any surface that appears dull and matte.
In the case of perfect diffuse reflection, the intensity of the observed reflected light depends on the cosine of the angle between the surface normal vector and the ray of the incoming light. As illustrated in the figure to the left, it is common to consider normalized vectors starting in the point of a surface, where the lighting should be computed: the normalized surface normal vector N is orthogonal to the surface and the normalized light direction L points to the light source.
For the observed diffuse reflected light $I_{\text{diffuse}}$, we need the cosine of the angle between the normalized surface normal vector N and the normalized direction to the light source L, which is the dot product N·L because the dot product a·b of any two vectors a and b is:
$\mathbf {a} \cdot \mathbf {b} =\left\vert \mathbf {a} \right\vert \left\vert \mathbf {b} \right\vert \cos \measuredangle (\mathbf {a} ,\mathbf {b} )$.
In the case of normalized vectors, the lengths |a| and |b| are both 1.
If the dot product N·L is negative, the light source is on the “wrong” side of the surface and we should set the reflection to 0. This can be achieved by using max(0, N·L), which makes sure that the value of the dot product is clamped to 0 for negative dot products. Furthermore, the reflected light depends on the intensity of the incoming light $I_{\text{incoming}}$ and a material constant $k_{\text{diffuse}}$ for the diffuse reflection: for a black surface, the material constant $k_{\text{diffuse}}$ is 0, for a white surface it is 1. The equation for the diffuse reflected intensity is then:
$I_{\text{diffuse}}=I_{\text{incoming}}\,k_{\text{diffuse}}\max(0,\mathbf {N} \cdot \mathbf {L} )$
For colored light, this equation applies to each color component (e.g. red, green, and blue). Thus, if the variables $I_{\text{diffuse}}$, $I_{\text{incoming}}$, and $k_{\text{diffuse}}$ denote color vectors and the multiplications are performed component-wise (which they are for vectors in GLSL), this equation also applies to colored light. This is what we actually use in the shader code.

### Shader Code for One Directional Light Source

If we have only one directional light source, the shader code for implementing the equation for $I_{\text{diffuse}}$ is relatively small. In order to implement the equation, we follow the questions about implementing equations, which were discussed in Section “Silhouette Enhancement”:
* Should the equation be implemented in the vertex shader or the fragment shader? We try the vertex shader here. In Section “Smooth Specular Highlights”, we will look at an implementation in the fragment shader.
* In which coordinate system should the equation be implemented? We try world space by default in Unity. (Which turns out to be a good choice here because Unity provides the light direction in world space.)
* Where do we get the parameters from? The answer to this is a bit longer:
We use a shader property (see Section “Shading in World Space”) to let the user specify the diffuse material color $k_{\text{diffuse}}$. We can get the direction to the light source in world space from the Unity-specific uniform _WorldSpaceLightPos0 and the light color $I_{\text{incoming}}$ from the Unity-specific uniform _LightColor0. As mentioned in Section “Shading in World Space”, we have to tag the shader pass with Tags {"LightMode" = "ForwardBase"} to make sure that these uniforms have the correct values. (Below we will discuss what this tag actually means.) We get the surface normal vector in object coordinates from the attribute gl_Normal. Since we implement the equation in world space, we have to convert the surface normal vector from object space to world space as discussed in Section “Silhouette Enhancement”.
The shader code then looks like this:
When you use this shader, make sure that there is only one light source in the scene, which has to be directional. If there is no light source, you can create a directional light source by selecting Game Object > Create Other > Directional Light from the main menu. Also, make sure that the “Forward Rendering Path” is active by selecting Edit > Project Settings > Player and then in the Inspector View the Per-Platform Settings > Other Settings > Rendering > Rendering Path should be set to Forward. (See below for more details about the “Forward Rendering Path”.)

### Fallback Shaders

The line Fallback "Diffuse" in the shader code defines a built-in fallback shader in case Unity doesn't find an appropriate subshader. For our example, Unity would use the fallback shader if it doesn't use the “forward rendering path” (see below) or if it couldn't compile the shader code. By choosing the specific name “_Color” for our shader property, we make sure that this built-in fallback shader can also access it. The source code of the built-in shaders is available at Unity's website. Inspection of this source code appears to be the only way to determine a suitable fallback shader and the names of the properties that it is using.
As mentioned, Unity will also use the fallback shader if there is a compile error in the shader code. In this case, the error is only be reported in the Inspector View of the shader; thus, it might be difficult to understand that the fallback shader is being used. Therefore, it is usually a good idea to comment the fallback instruction out during development of a shader but include it in the final version for better compatibility.

### Shader Code for Multiple Directional (Pixel) Lights

So far, we have only considered a single light source. In order to handle multiple light sources, Unity chooses various techniques depending on the rendering and quality settings. In the tutorials here, we will only cover the “Forward Rendering Path”. In order to choose it, select Edit > Project Settings > Player and then in the Inspector View set Per-Platform Settings > Other Settings > Rendering > Rendering Path to Forward. (Moreover, all cameras should be configured to use the player settings, which they are by default.)
In this tutorial we consider only Unity's so-called pixel lights. For the first pixel light (which always is a directional light), Unity calls the shader pass tagged with Tags { "LightMode" = "ForwardBase" } (as in our code above). For each additional pixel light, Unity calls the shader pass tagged with Tags { "LightMode" = "ForwardAdd" }. In order to make sure that all lights are rendered as pixel lights, you have to make sure that the quality settings allow for enough pixel lights: Select Edit > Project Settings > Quality and then increase the number labeled Pixel Light Count in any of the quality settings that you use. If there are more light sources in the scene than pixel light count allows for, Unity renders only the most important lights as pixel lights. Alternatively, you can set the Render Mode of all light sources to Important in order to render them as pixel lights. (See Section “Multiple Lights” for a discussion of the less important vertex lights.)
Our shader code so far is OK for the ForwardBase pass. For the ForwardAdd pass, we need to add the reflected light to the light that is already stored in the framebuffer. To this end, we just have to configure the blending to add the new fragment color (gl_FragColor) to the color in the framebuffer. As discussed in Section “Transparency”, this is achieved by an additive blend equation, which is specified by this line:
Blend One One
Blending automatically clamps all results between 0 and 1; thus, we don't have to worry about colors or alpha values greater than 1.
All in all, our new shader for multiple directional lights becomes:
This appears to be a rather long shader; however, both passes are identical apart from the tag and the Blend setting in the ForwardAdd pass.

### Changes for a Point Light Source

In the case of a directional light source _WorldSpaceLightPos0 specifies the direction from where light is coming. In the case of a point light source (or a spot light source), however, _WorldSpaceLightPos0 specifies the position of the light source in world space and we have to compute the direction to the light source as the difference vector from the position of the vertex in world space to the position of the light source. Since the 4th coordinate of a point is 1 and the 4th coordinate of a direction is 0, we can easily distinguish between the two cases:
While there is no attenuation of light for directional light sources, we should add some attenuation with distance to point and spot light source. As light spreads out from a point in three dimensions, it's covering ever larger virtual spheres at larger distances. Since the surface of these spheres increases quadratically with increasing radius and the total amount of light per sphere is the same, the amount of light per area decreases quadratically with increasing distance from the point light source. Thus, we should divide the intensity of the light source by the squared distance to the vertex.
Since a quadratic attenuation is rather rapid, we use a linear attenuation with distance, i.e. we divide the intensity by the distance instead of the squared distance. The code could be:
The factor attenuation should then be multiplied with _LightColor0 to compute the incoming light; see the shader code below. Note that spot light sources have additional features, which are beyond the scope of this tutorial.
Also note that this code is unlikely to give you the best performance because any if is usually quite costly. Since _WorldSpaceLightPos0.w is either 0 or 1, it is actually not too hard to rewrite the code to avoid the use of if and optimize a bit further:
However, we will use the version with if for clarity. (“Keep it simple, stupid!”)
The complete shader code for multiple directional and point lights is:
Note that the light source in the ForwardBase pass always is a directional light; thus, the code for the first pass could actually be simplified. On the other hand, using the same GLSL code for both passes, makes it easier to copy & paste the code from one pass to the other in case we have to edit the shader code.
If there is a problem with the shader, remember to activate the “Forward Rendering Path” by selecting Edit > Project Settings > Player and then in the Inspector View set Per-Platform Settings > Other Settings > Rendering > Rendering Path to Forward.

### Changes for a Spotlight

Unity implements spotlights with the help of cookie textures as described in Section “Cookies”; however, this is somewhat advanced. Here, we treat spotlights as if they were point lights.

### Summary

Congratulations! You just learned how Unity's per-pixel lights work. This is essential for the following tutorials about more advanced lighting. We have also seen:
* What diffuse reflection is and how to describe it mathematically.
* How to implement diffuse reflection for a single directional light source in a shader.
* How to extend the shader for point light sources with linear attenuation.
* How to further extend the shader to handle multiple per-pixel lights.

### Further Reading

If you still want to know more
* about transforming normal vectors into world space, you should read Section “Shading in World Space”.
* about uniform variables provided by Unity and shader properties, you should read Section “Shading in World Space”.
* about (additive) blending, you should read Section “Transparency”.
* about pass tags in Unity (e.g. ForwardBase or ForwardAdd), you should read Unity's ShaderLab reference about pass tags.
* about how Unity processes light sources in general, you should read Unity's manual about rendering paths.
< GLSL Programming/Unity