# Cg Programming/Unity/Diffuse Reflection

The light reflection from the surface of the moon is (in a good approximation) only diffuse.

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 can be computed using the surface normal vector N and the light vector L, i.e. the vector to the light source.

## 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 ${\displaystyle 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:

${\displaystyle \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 ${\displaystyle I_{\text{incoming}}}$ and a material constant ${\displaystyle k_{\text{diffuse}}}$ for the diffuse reflection: for a black surface, the material constant ${\displaystyle k_{\text{diffuse}}}$ is 0, for a white surface it is 1. The equation for the diffuse reflected intensity is then:

${\displaystyle 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 ${\displaystyle I_{\text{diffuse}}}$, ${\displaystyle I_{\text{incoming}}}$, and ${\displaystyle k_{\text{diffuse}}}$ denote color vectors and the multiplications are performed component-wise (which they are for vectors in Cg), 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 ${\displaystyle 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 ${\displaystyle 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 ${\displaystyle 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 vertex input parameter with semantic 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:

Shader "Cg per-vertex diffuse lighting" {
Properties {
_Color ("Diffuse Material Color", Color) = (1,1,1,1)
}
Pass {
Tags { "LightMode" = "ForwardBase" }
// make sure that all uniforms are correctly set

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : COLOR;
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

float3 normalDirection = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
// alternative:
// float3 normalDirection = UnityObjectToWorldNormal(input.normal);
float3 lightDirection = normalize(_WorldSpaceLightPos0.xyz);

float3 diffuseReflection = _LightColor0.rgb * _Color.rgb
* max(0.0, dot(normalDirection, lightDirection));

output.col = float4(diffuseReflection, 1.0);
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
return input.col;
}

ENDCG
}
}
Fallback "Diffuse"
}


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 > Light > Directional Light from the main menu.

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). 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.

## 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”. (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 output color 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:

Shader "Cg per-vertex diffuse lighting" {
Properties {
_Color ("Diffuse Material Color", Color) = (1,1,1,1)
}
Pass {
Tags { "LightMode" = "ForwardBase" }
// pass for first light source

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : COLOR;
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

float3 normalDirection = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
float3 lightDirection = normalize(_WorldSpaceLightPos0.xyz);

float3 diffuseReflection = _LightColor0.rgb * _Color.rgb
* max(0.0, dot(normalDirection, lightDirection));

output.col = float4(diffuseReflection, 1.0);
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
return input.col;
}

ENDCG
}

Pass {
Tags { "LightMode" = "ForwardAdd" }
// pass for additional light sources
Blend One One // additive blending

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : COLOR;
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

float3 normalDirection = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
float3 lightDirection = normalize(_WorldSpaceLightPos0.xyz);

float3 diffuseReflection = _LightColor0.rgb * _Color.rgb
* max(0.0, dot(normalDirection, lightDirection));

output.col = float4(diffuseReflection, 1.0);
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
return input.col;
}

ENDCG
}
}
Fallback "Diffuse"
}


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:

            float3 lightDirection;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
lightDirection = normalize(_WorldSpaceLightPos0.xyz
- mul(modelMatrix, input.vertex).xyz);
}


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:

            float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource = _WorldSpaceLightPos0.xyz
- mul(modelMatrix, input.vertex).xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}


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:

            float3 vertexToLightSource =
_WorldSpaceLightPos0.xyz - mul(modelMatrix,
input.vertex * _WorldSpaceLightPos0.w).xyz;
float one_over_distance =
1.0 / length(vertexToLightSource);
float attenuation =
lerp(1.0, one_over_distance, _WorldSpaceLightPos0.w);
float3 lightDirection =
vertexToLightSource * one_over_distance;


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:

Shader "Cg per-vertex diffuse lighting" {
Properties {
_Color ("Diffuse Material Color", Color) = (1,1,1,1)
}
Pass {
Tags { "LightMode" = "ForwardBase" }
// pass for first light source

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : COLOR;
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

float3 normalDirection = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource = _WorldSpaceLightPos0.xyz
- mul(modelMatrix, input.vertex).xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}

float3 diffuseReflection =
attenuation * _LightColor0.rgb * _Color.rgb
* max(0.0, dot(normalDirection, lightDirection));

output.col = float4(diffuseReflection, 1.0);
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
return input.col;
}

ENDCG
}

Pass {
Tags { "LightMode" = "ForwardAdd" }
// pass for additional light sources
Blend One One // additive blending

CGPROGRAM

#pragma vertex vert
#pragma fragment frag

#include "UnityCG.cginc"

uniform float4 _LightColor0;
// color of light source (from "Lighting.cginc")

struct vertexInput {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 col : COLOR;
};

vertexOutput vert(vertexInput input)
{
vertexOutput output;

float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;

float3 normalDirection = normalize(
mul(float4(input.normal, 0.0), modelMatrixInverse).xyz);
float3 lightDirection;
float attenuation;

if (0.0 == _WorldSpaceLightPos0.w) // directional light?
{
attenuation = 1.0; // no attenuation
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else // point or spot light
{
float3 vertexToLightSource = _WorldSpaceLightPos0.xyz
- mul(modelMatrix, input.vertex).xyz;
float distance = length(vertexToLightSource);
attenuation = 1.0 / distance; // linear attenuation
lightDirection = normalize(vertexToLightSource);
}

float3 diffuseReflection =
attenuation * _LightColor0.rgb * _Color.rgb
* max(0.0, dot(normalDirection, lightDirection));

output.col = float4(diffuseReflection, 1.0);
output.pos = UnityObjectToClipPos(input.vertex);
return output;
}

float4 frag(vertexOutput input) : COLOR
{
return input.col;
}

ENDCG
}
}
Fallback "Diffuse"
}


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 Cg 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.

## 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.