Tutorial: Procedural torus generation

Exercises

In this tutorial:

  1. Generate a torus from it's parametric equation
  2. Generate normals for the torus
  3. Do these calculations on the shader instead of the CPU
  4. Add specular highlights to the lighting calculation

1: Procedurally generate a torus

Download the base code. Extract, compile and run the sample. You should have a red teapot and basic camera controls. F1 toggles between fixed pipeline lighting and the given "torus.vert" shader.

Use the following parametric equation to generate a torus (not in the shader... yet):

	x = (R + r * cos(u)) * cos(v)
	y = (R + r * cos(u)) * sin(v)
	z = r * sin(u)
    

Where R is the torus outer radius and r is the inner radius and u and v are the angles θ and φ. You might want to create a function drawTorusVertex(u, v) to simplify the code.

2: Add the normals

Partial differentiation can be used to find the normal at any point on the given parametric surface:

	nx = cos(u) * cos(v)
	ny = cos(u) * sin(v)
	nz = sin(u)
      

Alter your drawTorusVertex function to supply a normal to OpenGL.

3: Generation on the vertex shader

Instead of passing in the final x, y and z positions to glVertex3f, just pass in the u and v parameters to the parametric equation.

Modify the given vertex shader to generate the (x, y, z) vertex position based on the input "vertex position" which actually contains u and v.

Similarly, add code to alter the normal (gl_Normal) based on the u and v parameters. Note that the vertex shader uses gl_Normal in the lighting calculations so it must be set beforehand.

4: Specular Lighting

Add specular highlights to the lighting calculation in the shader, as in last week's tutorial.