# Cg Programming/Unity/Shadows on Planes

This tutorial covers the **projection of shadows onto planes**.

It is not based on any particular tutorial; however, some understanding of Section “Vertex Transformations” is useful.

## Projecting Hard Shadows onto Planes[edit]

Computing realistic shadows in real time is difficult. However, there are certain cases that are a lot easier. Projecting a hard shadow (i.e. a shadow without penumbra; see Section “Soft Shadows of Spheres”) onto a plane is one of these cases. The idea is to render the shadow by rendering the shadow-casting object in the color of the shadow with the vertices projected just above the shadow-receiving plane.

## Projecting an Object onto a Plane[edit]

In order to render the projected shadow, we have to project the object onto a plane. In order to specify the plane, we will use the local coordinate system of the default plane game object. Thus, we can easily modify the position and orientation of the plane by editing the plane object. In the coordinate system of that game object, the actual plane is just the plane, which is spanned by the and axes.

Projecting an object in a vertex shader means to project each vertex. This could be done with a projection matrix similar to the one discussed in Section “Vertex Transformations”. However, those matrices are somewhat difficult to compute and debug. Therefore, we will take another approach and compute the projection with a bit of vector arithmetics. The illustration to the left shows the projection of a point **P** in the direction of light **L** onto a shadow-receiving plane. (Note that the vector **L** is in the opposite direction than the light vectors that are usually employed in lighting computations.) In order to move the point **P** to the plane, we add a scaled version of **L**. The scaling factor turns out to be the distance of **P** to the plane divided by the length of **L** in the direction of the normal vector of the plane (because of similar triangles as indicated by the gray lines). In the coordinate system of the plane, where the normal vector is just the axis, we can also use the ratio of the coordinate of the point **P** divided by the negated coordinate of the vector **L**.

Thus, the vertex shader could look like this:

```
uniform float4x4 _World2Receiver; // transformation from
// world coordinates to the coordinate system of the plane
[...]
float4 vert(float4 vertexPos : POSITION) : SV_POSITION
{
float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;
float4 lightDirection;
if (0.0 != _WorldSpaceLightPos0.w)
{
// point or spot light
lightDirection = normalize(
mul(modelMatrix, vertexPos - _WorldSpaceLightPos0));
}
else
{
// directional light
lightDirection = -normalize(_WorldSpaceLightPos0);
}
float4 vertexInWorldSpace = mul(modelMatrix, vertexPos);
float distanceOfVertex =
mul(_World2Receiver, vertexInWorldSpace).y
// = height over plane
float lengthOfLightDirectionInY =
mul(_World2Receiver, lightDirection).y
// = length in y direction
lightDirection = lightDirection
* (distanceOfVertex / (-lengthOfLightDirectionInY));
return mul(UNITY_MATRIX_VP,
vertexInWorldSpace + lightDirection));
}
```

The uniform `_World2Receiver`

is best set with the help of a small C# script that should be attached to the shadow-casting object:

```
using UnityEngine;
[ExecuteInEditMode, RequireComponent(typeof(Renderer))]
public class SetWorld2Receiver : MonoBehaviour {
public GameObject plane;
Renderer rend;
Renderer planeRend;
void Start() {
rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update () {
if (plane != null) {
planeRend = plane.GetComponent<Renderer>();
rend.sharedMaterial.SetMatrix("_World2Receiver",
planeRend.worldToLocalMatrix);
}
}
}
```

The script (which should be named `SetWorld2Receiver`

) requires the user to specify the shadow-receiving plane object and sets the uniform `_World2Receiver`

accordingly.

## Complete Shader Code[edit]

For the complete shader code we improve the performance by noting that the coordinate of a matrix-vector product is just the dot product of the second row (i.e. the first when starting with 0) of the matrix and the vector. Furthermore, we improve the robustness by not moving the vertex when it is below the plane, neither when the light is directed upwards. Additionally, we try to make sure that the shadow is on top of the plane with this instruction:

`Offset -1.0, -2.0`

This reduces the depth of the rasterized triangles a bit such that they always occlude other triangles of approximately the same depth.

The first pass of the shader renders the shadow-casting object while the second pass renders the projected shadow. In an actual application, the first pass could be replaced by one or more passes to compute the lighting of the shadow-casting object.

```
Shader "Cg planar shadow" {
Properties {
_Color ("Object's Color", Color) = (0,1,0,1)
_ShadowColor ("Shadow's Color", Color) = (0,0,0,1)
}
SubShader {
Pass {
Tags { "LightMode" = "ForwardBase" } // rendering of object
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// User-specified properties
uniform float4 _Color;
float4 vert(float4 vertexPos : POSITION) : SV_POSITION
{
return mul(UNITY_MATRIX_MVP, vertexPos);
}
float4 frag(void) : COLOR
{
return _Color;
}
ENDCG
}
Pass {
Tags { "LightMode" = "ForwardBase" }
// rendering of projected shadow
Offset -1.0, -2.0
// make sure shadow polygons are on top of shadow receiver
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
// User-specified uniforms
uniform float4 _ShadowColor;
uniform float4x4 _World2Receiver; // transformation from
// world coordinates to the coordinate system of the plane
float4 vert(float4 vertexPos : POSITION) : SV_POSITION
{
float4x4 modelMatrix = unity_ObjectToWorld;
float4x4 modelMatrixInverse = unity_WorldToObject;
float4x4 viewMatrix =
mul(UNITY_MATRIX_MV, modelMatrixInverse);
float4 lightDirection;
if (0.0 != _WorldSpaceLightPos0.w)
{
// point or spot light
lightDirection = normalize(
mul(modelMatrix, vertexPos - _WorldSpaceLightPos0));
}
else
{
// directional light
lightDirection = -normalize(_WorldSpaceLightPos0);
}
float4 vertexInWorldSpace = mul(modelMatrix, vertexPos);
float4 world2ReceiverRow1 =
float4(_World2Receiver[1][0], _World2Receiver[1][1],
_World2Receiver[1][2], _World2Receiver[1][3]);
float distanceOfVertex =
dot(world2ReceiverRow1, vertexInWorldSpace);
// = (_World2Receiver * vertexInWorldSpace).y
// = height over plane
float lengthOfLightDirectionInY =
dot(world2ReceiverRow1, lightDirection);
// = (_World2Receiver * lightDirection).y
// = length in y direction
if (distanceOfVertex > 0.0 && lengthOfLightDirectionInY < 0.0)
{
lightDirection = lightDirection
* (distanceOfVertex / (-lengthOfLightDirectionInY));
}
else
{
lightDirection = float4(0.0, 0.0, 0.0, 0.0);
// don't move vertex
}
return mul(UNITY_MATRIX_VP,
vertexInWorldSpace + lightDirection);
}
float4 frag(void) : COLOR
{
return _ShadowColor;
}
ENDCG
}
}
}
```

## Further Improvements of the Fragment Shader[edit]

There are a couple of things that could be improved, in particular in the fragment shader:

- Fragments of the shadow that are outside of the rectangular plane object could be removed with the
`discard`

instruction, which was discussed in Section “Cutaways”. - If the plane is textured, this texturing could be integrated by using only local vertex coordinates for the texture lookup (also in the shader of the plane object) and specifying the texture of the plane as a shader property of the shadow-casting object.
- Soft shadows could be faked by computing the lighting of the plane in this shader and attenuating it depending on the angle of the surface normal vector of the shadow-casting object to the light direction similar to the approach in Section “Silhouette Enhancement”.

## Summary[edit]

Congratulations, this is the end of this tutorial. We have seen:

- How to project a vertex in the direction of light onto a plane.
- How to implement this technique to project a shadow onto a plane.

## Further reading[edit]

If you still want to learn more

- about the model transformation, the view transformation, and the projection, you should read the description in Section “Vertex Transformations”.
- about setting up a projection matrix to project the shadow, you could read Section 9.4.1 of the SIGGRAPH '98 Course “Advanced Graphics Programming Techniques Using OpenGL” organized by Tom McReynolds, which is available online.