Game Development Reference
In-Depth Information
Overview of Vertex Shaders
In OpenGL ES 2.0, vertex shaders and fragment shaders are required to render 3D objects. The
general purpose of the vertex shader is to position vertices in the 3D world and to determine vertex
properties such as diffuse and specular lighting at that vertex. A simple vertex shader example is
given in Listing 4-3.
Listing 4-3. Simple Vertex Shader
// Vertex Shader
uniform mat4 uMVPMatrix;
attribute vec3 aPosition;
uniform vec3 vColor;
varying vec3 Color;
void main()
{
gl_Position = uMVPMatrix * vec4(aPosition,1);
Color = vColor;
}
The variable uMVPMatrix holds the 4-by-4 ModelViewProjection matrix that will be used to transform
the vertex. The ModelViewProjection matrix is simply the multiplication of the model matrix, the view
matrix, and the projection matrix into one single matrix. The uniform qualifier is used, because this
matrix does not change when the object is rendered. That is, that same matrix is used for all the
vertices on the object being rendered.
The aPosition variable is a vector that holds the (x,y,z) position of the vertex of the object in its initial
local object coordinates. The attribute qualifier indicates that this variable will receive input from the
main OpenGL ES 2.0 application. This is how a vertex shader program is sent vertex data.
The vColor variable is a vector that holds the (r,g,b) input color values of the object to be rendered.
The vColor is copied into the Color variable and is sent to the fragment shader for processing.
Variables that are linked to the fragment shader must be declared varying.
The main code itself is located within a main() block. The gl_Position variable is a reserved variable
that transforms the vertex by multiplying its position by the uMVPMatrix (ModelViewProjection
Matrix). This produces the projection of the 3D vertex on a 2D surface and puts the vertex in
clip coordinates. Also, note how a vec3 is converted to a vec4 by using the vec4(aPosition,1)
constructor.
A Complex Vertex Shader
The preceding vertex example shader is very simple. A more complex vertex shader is shown in
Figure 4-12 .
 
Search WWH ::




Custom Search