Cg Programming/Unity/Shadows on Planes

< Cg Programming < Unity
A cartoon character with a drop shadow.

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

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.

Illustration of the projection of a point P in direction L onto a plane in the coordinate system of the plane.

Projecting an Object onto a Plane

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 = _Object2World;
            float4x4 modelMatrixInverse = _World2Object; 
 
            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 script that should be attached to the shadow-casting object:

@script ExecuteInEditMode()

public var plane : GameObject;

function Update () 
{
   if (null != plane)
   {
      GetComponent(Renderer).sharedMaterial.SetMatrix("_World2Receiver", 
         plane.GetComponent(Renderer).worldToLocalMatrix);
   }
}

The script requires the user to specify the shadow-receiving plane object and sets the uniform _World2Receiver accordingly.

Complete Shader Code

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 = _Object2World;
            float4x4 modelMatrixInverse = _World2Object; 
            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

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

Summary

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

Further Reading

If you still want to learn more


< Cg Programming/Unity

Unless stated otherwise, all example source code on this page is granted to the public domain.
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.