Cg Programming/Unity/Displacement Maps

This tutorial introduces displacement maps as an example of an application of texture lookups in vertex shaders.

This tutorial requires some knowledge about texture mapping as described in.

Texture Lookups in Vertex Shaders
Most tutorials in this wikibook use texture lookups only in fragment shaders because texture lookups in vertex shaders are a Shader Model 3.0 feature, i.e., it is not supported by all GPUs (see Unity's description of platform-specific rendering differences).

However, displacement mapping requires a lookup of a texture value for each vertex, which is used to displace, i.e., move, each vertex to a new position. For technical reasons, we cannot use the standard  command. Instead we have to use the command  with a four-dimensional vector specifying the texture coordinates where the 4th component is 0. (This makes sure that we always read the value from the finest mipmap level and we don't request an automatic computation of the mipmap level, which is impossible in a vertex shader.) The command could look like this: where  are the two texture coordinates.

Displacement of Vertices
The example below converts the resulting color  to a gray value and scales it with a user-specified uniform  : This displacement value is then used to move each vertex along its surface normal vector, i.e., we add the vertex position in object coordinates ( in the example) to the surface normal vector  multiplied with the displacement value. Note that  is a three-dimensional vector; thus, we have to append a 0.0 coordinate to form a four-dimensional vector before we can add it to the vertex position.

Shader Code
The rest of the code applies the standard vertex transformations and colors the surface with a unlit texture map. Make sure to use it on meshes with relatively many vertices - otherwise the displaced surface will appear quite "blocky." Note that edges of the surface mesh might not match up if the colors at the edges of the texture image do not match or if the surface normal vectors of corresponding vertices do not match.

Summary
Congratulations, you have reached the end of this tutorial. You saw:
 * How use texture mapping in vertex shaders.
 * How to move vertex positions along surface normal vectors.