Back to index

Tutorial 5: Introduction to the use of shaders

Shaders are specialized programs to override fixed pipeline functionality and perform certain stages of the graphics pipeline.

A number of shader types exist in OpenGL, each operating in a different stage of the graphics pipeline: vertex, fragments, geometry and tessellation shaders. There are also compute shaders, but this tutorial will focus on the first two.

Exercises:

In this tutorial:

Note that we use OpenGL Shading Language (GLSL) in this subject but others exist.

Build and run the Orange book brick and particle demos

Create your own shader

Red sphere

Create two files, shader.vert and shader.frag:

//shader.vert
void main(void)
{
  // os - object space, es - eye space, cs - clip space
  vec4 osVert = gl_Vertex;
  vec4 esVert = gl_ModelViewMatrix * osVert;
  vec4 csVert = gl_ProjectionMatrix * esVert;
  gl_Position = csVert;
  // Equivalent to: gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex
}

//shader.frag
void main (void)
{
  gl_FragColor = vec4(1, 0, 0, 1);
}

The vertex shader transforms the vertex by both modelview and projection matrices. This is what allows you to move objects with glTranslatef and also applies the perspective projection from gluPerspective.

The fragment program will colour each pixel rendered red. gl_FragColor is the main output from fragment programs.

Run the program and make sure the geometry draws with its colour being generated in the fragment shader. Change the color to green to check it works as expected.

Now in the fragment shader set the color to the fragment depth:

//shader.frag
void main (void)
{
  float depth = gl_FragCoord.z;
  gl_FragColor = vec4(vec3(depth), 1);
}

You should see something like:

Depth sphere

OpenGL maps the depth values into the range [0,1] by default. Does the image make sense?

Try setting the color to 1-depth. Does the resulting image also make sense?

Now add an interactive control for using shaders or the fixed pipeline: use render_state.useShaders to control whether shaders are used via the glUseProgram setting - a value of 0 disables use of shaders. Also add the appropriate code to update_renderstate and to the keyboard event handling.

Visual Debugging

red green sphere

There are many ways to shade objects. A common method is to use pre-computed geometry normals for lighting calculations. This will be covered in next weeks tutorial.

Axes

Try adding a set of r,g,b axes. Hint: use gl_FragColor = gl_Color.

Resources