Skip to content

Recitation 06 OpenGL Shader Programming

jijup edited this page Nov 3, 2026 · 2 revisions

Recitation 6: OpenGL Shader Programming

Objectives

Until now we made every image ourselves, one ray at a time, on the CPU. From this recitation on, the GPU draws for us. We hand OpenGL a few vertices and two small programs called shaders, written in GLSL (the OpenGL Shading Language):

  • the vertex shader runs once for every vertex. It decides where the vertex lands on the screen.
  • the fragment shader runs once for every pixel (fragment) a triangle covers. It decides the colour of that pixel.

Everything in between, such as finding which pixels a triangle covers and interpolating values across it, is done by the GPU.

This is your first shader program, so it is a small one. A happy Halloween to you all. In this recitation you will:

  1. Draw a triangle and give each vertex its own colour. The GPU interpolates the colours across the triangle.
  2. Put a texture on a quad: a carved pumpkin, and a bat drawn three times with the same quad. You throw away the transparent pixels around them and make the pumpkin flicker like a candle.
  3. Write translation and rotation matrices in the vertex shader, and make the bats fly around the pumpkin.

Figure 1 is what you will have at the end.

alt text


1. Getting the new exercise

You already have the repository. Do not clone it again. Open Git Bash inside your GraphicsLab2026 folder and run these four commands in order:

git add transformations
git commit -m "my transformations work"
git checkout -- CMakeLists.txt
git pull
  • git add transformations and git commit save last week's work into your own local history.
  • git checkout -- CMakeLists.txt restores my version of the top-level CMakeLists.txt, which has the line for this week's exercise.
  • git pull downloads this week's exercise, the shaders folder, and the GLFW and GLEW libraries in external/.

Be careful with the third command. Typing git checkout -- . with a dot discards your changes to every file.


2. Building

  1. Open the CMake GUI, point it at your GraphicsLab2026 folder and its build folder as before, and click Configure, then Generate. This makes the new shaders project appear.
  2. Click Open Project to open the solution in Visual Studio 2019.
  3. In the Solution Explorer, right-click shaders and choose Set as Startup Project.
  4. Build and run with Ctrl+F5. Debug and Release both work here, since the GPU does the heavy work.

The program opens a window (1024 x 768) and keeps drawing into it until you press Esc or close it. A console window opens too. Watch it: every time a shader is loaded, it prints

Compiling Vertex shader: Success
Compiling Fragment shader: Success
Linking shader program: Success

If you make a mistake in a shader, it prints Failed: and the GLSL compiler's error message with a line number instead, and the program closes. The C++ compiler never sees your shaders. They are compiled by the graphics driver when the program starts, so their errors appear only in this console.

The shaders and textures are copied next to the program (into build/shaders/Release or build/shaders/Debug) every time you build. So after you edit a .glsl file, build again (Ctrl+F5 does that) before you run.


3. The starter code

Build and run the starter code before you change anything. You should get Figure 2: a red triangle on a white background.

alt text

3.1 The files

File What it does Status
main.cpp Opens the window, then calls init() once and display() for every frame. task1 picks the triangle or the Halloween scene. given, you change task1
Helpers/ShaderHelper.h Reads the .glsl files, compiles and links them, and prints the messages above. Please read it. given
Helpers/lodepng.h, .cpp Loads PNG images. given
Triangle/Triangle.h Puts the triangle's vertices on the GPU and draws them. Task 1, TODO 1 and 2
Triangle/vshader.glsl The triangle's vertex shader. Task 1, TODO 3 and 4
Triangle/fshader.glsl The triangle's fragment shader. given
Quad/Quad.h A square with a texture on it. The pumpkin and the bats are both quads. Task 2, TODO 1 and 2
Quad/fshader.glsl The quad's fragment shader. Task 2, TODO 3 and 4
Quad/vshader.glsl The quad's vertex shader. Task 3, TODO 5, 6 and 7
Quad/pumpkin.png, Quad/bat.png The two textures, with transparent backgrounds. given

3.2 The libraries: GLFW and GLEW

OpenGL itself only draws. It cannot open a window, read the keyboard or even find its own functions on Windows. Two small libraries do that for us. Both are already in the external/ folder of the repository (external/glfw and external/glew), and CMake links them, so there is nothing to install.

Library What it does Website
GLFW Opens the window, creates the OpenGL context (the "connection" to the GPU), runs the draw loop, reads the keyboard and mouse, and gives the time. Works the same on Windows, macOS and Linux. glfw.org
GLEW (OpenGL Extension Wrangler) Finds the addresses of the modern OpenGL functions, such as glGenBuffers and glVertexAttribPointer, when the program starts. On Windows, the system's OpenGL library only offers the functions of OpenGL 1.1 (from 1997); everything newer must be looked up at run time. glew.sourceforge.net

GLEW needs one line, glewInit(), called right after the window is created. You never call it again.

GLFW you meet in main() of main.cpp. Read main() once, and look up each GLFW call below in the GLFW documentation (the search box on that page finds a function by name). The Getting started guide walks through almost the same program as ours.

Call in our code What to look for in the documentation
glfwInit(), glfwTerminate() start and shut down the library
glfwWindowHint(...) why we ask for version 3.3 and the core profile
glfwCreateWindow(1024, 768, "Shaders", NULL, NULL) what each argument means
glfwMakeContextCurrent(window) why OpenGL calls need a current context
glfwSwapBuffers(window) why there are two buffers (front and back)
glfwPollEvents(), glfwGetKey(...), glfwWindowShouldClose(...) how the loop notices the Esc key and the close button
glfwGetTime() (in Quad::draw()) the clock that drives the animation in Task 3

You will use these same lines in every OpenGL program in this course, so it is worth knowing what each one does. This part is not marked.

3.3 How a shape gets to the screen

Triangle::init() and Quad::init() follow the same steps. They run once, before the first frame:

  1. Compile the shaders (load_shaders()) and make them current (glUseProgram()).
  2. Create a vertex array object (VAO) (glGenVertexArrays(), glBindVertexArray()). It remembers how the vertex data below is laid out.
  3. Copy the vertex data to the GPU in a vertex buffer object (VBO): glGenBuffers(), glBindBuffer(), glBufferData().
  4. Connect the data to an in variable of the vertex shader, called a vertex attribute: glGetAttribLocation() finds the variable by its name, glEnableVertexAttribArray() switches it on, and glVertexAttribPointer() says where it is in the VBO.

Then draw() runs every frame. It makes the shaders and the VAO current, sets the uniforms, and calls glDrawArrays(). A uniform is a value that is the same for every vertex and every pixel of one draw call, such as the time.


4. Task 1: Vertex colour interpolation (20%)

Keep task1 = true in main.cpp for this task.

The array vertices in Triangle::init() holds only the three vertex positions. We will give every vertex a colour too, and store the colours in the same array, right after each position:

         V1                      V2                      V3
| x  y  z  r  g  b | x  y  z  r  g  b | x  y  z  r  g  b |
  0  1  2  3  4  5   6  7  8  ...                            <- float index

This is called an interleaved layout. To read it, OpenGL needs two numbers for every attribute:

  • the stride: how many bytes from the start of one vertex to the start of the next. Here 6 floats, 6 * sizeof(float) bytes, for both attributes.
  • the offset: where the attribute starts inside a vertex. The position starts at 0, the colour after the 3 position floats, at 3 * sizeof(float) bytes.

These are the last two arguments of glVertexAttribPointer().

TODO 1 (Triangle.h): add an RGB colour (three values between 0 and 1) after each position in vertices, in the order V1 position, V1 colour, V2 position, V2 colour, and so on. Use red, green and blue to match Figure 3. Then fix the stride of the position attribute, vcoords: it is still 0, which means "the positions are packed one after another", and that is no longer true.

TODO 2 (Triangle.h): create the colour attribute, in the same three steps as the position attribute just above it. Its name in the shader is vcolor. It has 3 floats, the same stride, and an offset of 3 * sizeof(float). Write the offset as (void*)(3 * sizeof(float)), since OpenGL takes it as a pointer.

TODO 3 (Triangle/vshader.glsl): declare the colour input of the vertex shader: in vec3 vcolor;. The keyword in means one value per vertex, read from the VBO. The name must match the string you passed to glGetAttribLocation().

TODO 4 (Triangle/vshader.glsl): vertexColor is the shader's output, and it is hard coded to red. Set it to the vertex colour instead: vertexColor = vec4(vcolor, 1.0);. The fourth component is the alpha (opacity).

Run the program. You should get Figure 3.

alt text

You gave colours to three vertices only. Every other pixel got a mix of the three, weighted by how close it is to each vertex. These weights are the barycentric coordinates from the ray tracing lectures. The GPU interpolates every out variable of the vertex shader across the triangle in this way, and the fragment shader receives the result in its matching in variable (here vertexColor).


5. Task 2: Texturing the pumpkin and the bats (25%)

Set task1 = false in main.cpp for the rest of the recitation. The program now draws the Halloween scene on a night sky:

pumpkin.draw(0);  ///< id 0: the pumpkin
bat.draw(1);      ///< the same bat quad, drawn three times
bat.draw(2);
bat.draw(3);

There are only two quads, pumpkin and bat, each with its own texture. The bat is drawn three times. The number passed to draw() reaches both shaders as the uniform id, so the shaders can tell the pumpkin (id 0) from the three bats (id 1, 2 and 3).

Run the program. You get Figure 4: one black square.

alt text

There are two reasons. First, the vertex shader does not move anything yet (that is Task 3), so all four quads sit at the centre, on top of each other. Second, every pixel shows the colour of one corner of the texture. The texture coordinates never reach the GPU, so vtexcoord is (0, 0) for every vertex. That corner of the image is transparent, and a transparent texel is stored as black with alpha 0.

5.1 Texture coordinates

A texture coordinate (u, v) says which point of the image goes on a vertex. (0, 0) is the lower left corner of the image and (1, 1) the upper right. Quad::init() already has them in the array vtexcoord, one pair per vertex: the corners of the quad get the corners of the image.

TODO 1 (Quad.h): copy vtexcoord to the GPU in a second VBO, _vbo_vtexcoord, with the same three calls as the vertex positions above it.

TODO 2 (Quad.h): create the attribute vtexcoord in the same three steps as vpoint. A texture coordinate has 2 floats, not 3. The array holds nothing else, so the stride and offset are both 0.

The vertex shader passes the texture coordinate on to the fragment shader as uv, which the GPU interpolates across the quad like the colours in Task 1. The fragment shader then reads the texture at uv:

color = texture(tex, uv);

Run the program. You get Figure 5: the pumpkin and a bat, each inside a black box.

alt text

5.2 Throwing pixels away

The black boxes are the transparent parts of the textures. The texels there have alpha 0, but OpenGL ignores the alpha unless we tell it what to do with it.

TODO 3 (Quad/fshader.glsl): if the alpha of the texel is below 0.5, throw the fragment away:

if (color.a < 0.5)
    discard;

discard stops the fragment shader, and nothing is written to that pixel. Whatever was drawn there before (the sky, or the pumpkin under a bat) stays. Only the fragment shader can do this.

5.3 A candle inside the pumpkin

TODO 4 (Quad/fshader.glsl): make the pumpkin flicker. When id is 0, multiply its colour by a brightness that changes with time:

if (id == 0)
    color.rgb *= 0.85 + 0.15 * sin(20.0 * time) * sin(7.0 * time);

color.rgb means the first three components of color, so the alpha is left alone. The product of the two sines moves irregularly between 0.7 and 1.0, a bit like a candle. time and id are uniforms: Quad::draw() sets them once per draw call, and both shaders can read them.

You should get Figure 6, with the pumpkin flickering.

alt text


6. Task 3: Making the bats fly (25%)

The vertex shader in Quad/vshader.glsl places each quad on the screen, with the same kind of matrices as in Recitation 5. Here they are 4 x 4 matrices in GLSL, applied to the vertex vec4(vpoint, 1.0), a point with w = 1. The result goes in gl_Position. The screen runs from -1 to 1 in both x and y, with (0, 0) at its centre.

6.1 TODO 5 and 6: Translation and rotation in GLSL

S(sx, sy), the scaling matrix, is given. The matrices T() and R() still return the identity. That is why everything was at the centre in Task 2.

GLSL stores a matrix column by column: M[c][r] is the entry in column c and row r. This is the opposite of the usual maths notation and of Eigen's A(row, col), so be careful.

TODO 5: complete T(tx, ty), the translation by (tx, ty). The amounts go in the last column, column 3:

| 1 0 0 tx |
| 0 1 0 ty |        M[3][0] = tx;
| 0 0 1 0  |        M[3][1] = ty;
| 0 0 0 1  |

TODO 6: complete R(degrees), the counterclockwise rotation about the z axis (the axis pointing out of the screen). GLSL's cos() and sin() take radians, so convert first with radians(degrees). Column 0 is where the x axis goes, (cos, sin), and column 1 is where the y axis goes, (-sin, cos):

| cos -sin 0 0 |
| sin  cos 0 0 |
|  0    0  1 0 |
|  0    0  0 1 |

Run the program. The pumpkin moves to the bottom of the screen, and the three bats wait in a row above it, the left one tilted 20 degrees counterclockwise and the right one 20 degrees clockwise (Figure 7). These placements are given in main() of the vertex shader.

alt text

The bats need a little more explanation. There is only one bat quad, drawn three times with id = 1, 2 and 3, and all three draws run the same vertex shader. So the shader must work out each bat's place from id:

float x = -0.6 + 0.6 * float(id - 1);       // id 1, 2, 3 -> x = -0.6, 0.0, 0.6
float tilt = 20.0 - 20.0 * float(id - 1);   // id 1, 2, 3 -> 20, 0, -20 degrees
gl_Position = T(x, 0.55) * R(tilt) * S(0.45, 0.45) * vec4(vpoint, 1.0);
  • id - 1 counts the bats from 0: it is 0, 1 and 2. float() turns it into a float, so the rest of the line is float arithmetic.
  • x starts at -0.6 and adds 0.6 for each bat: -0.6, 0.0 and 0.6. The bats are spaced 0.6 apart, centred on the screen.
  • tilt starts at 20 degrees and subtracts 20 for each bat: 20, 0 and -20. A positive angle turns counterclockwise, so the left bat tips up on its right side, and the right bat is its mirror image.
  • gl_Position: read the product from right to left, as in Recitation 5. S(0.45, 0.45) shrinks the unit quad to the bat's size, R(tilt) tilts it about its own centre (still at the origin), and T(x, 0.55) moves that centre to (x, 0.55), near the top of the screen.

Figure 8 shows the result for each id.

alt text

This is the same pattern as an array of positions, but computed from a number. In TODO 7 the formulas also depend on time, and the bats start to fly.

6.2 TODO 7: The flight

time is the number of seconds since the program started. Quad::draw() reads it with glfwGetTime() and sends it to the shaders every frame. Anything we compute from time in the vertex shader moves.

TODO 7: in the else branch (the bats), replace the three lines that place the bats in a row with these:

float t = time + 2.0 * float(id);              // each bat starts at a different point
float x = 0.75 * sin(0.9 * t);                 // left and right
float y = 0.45 + 0.2 * sin(1.8 * t);           // up and down twice as fast: a figure eight
float tilt = -20.0 * cos(0.9 * t);             // lean into the turn
float flap = 0.35 + 0.65 * abs(sin(10.0 * t)); // wings open and close
gl_Position = T(x, y) * R(tilt) * S(0.45 * flap, 0.45) * vec4(vpoint, 1.0);

Figure 9 shows what these lines do. Read it together with the list below.

alt text

Line by line:

  • t: all three bats run the same shader. If they all used time, they would sit on top of each other. So each bat gets its own clock, 2 seconds apart: bat 1 is 2 seconds into the loop, bat 2 is 4 seconds in, bat 3 is 6 seconds in. They follow the same path, one behind the other.
  • x: sin swings between -1 and 1, so x swings between -0.75 and 0.75: left and right across the screen. One full swing takes 2π / 0.9 ≈ 7 seconds.
  • y: the centre line is 0.45, and the bat goes 0.2 above and below it. The factor 1.8 is twice 0.9, so y goes up and down twice during one swing of x (Figure 9b). Up on the way out, down on the way back: that draws the figure eight (Figure 9a).
  • tilt: a bat should lean into its turn, like a plane. cos(0.9 * t) is positive while x is growing (flying right) and negative while it shrinks (flying left). With the minus sign, tilt is negative (clockwise) when flying right and positive (counterclockwise) when flying left. The bat leans at most 20 degrees.
  • flap: abs(sin(10.0 * t)) goes from 0 to 1 and back, about three times a second. So flap goes between 0.35 and 1. We multiply only the x scale by it, so the wings fold in and spread out while the body keeps its height (Figure 9c).
  • gl_Position: the same product as in the row, read from right to left: scale (with the flap), tilt, then move to (x, y). Only x, y, tilt and flap changed. The matrices are the ones you wrote.

Run the program. The bats should fly as in Figure 1. Figure 10 is one frame of it.

alt text

Notice that the C++ code did not change at all for the animation. Every frame, the CPU only sends one number, the time. The positions of all the vertices are computed on the GPU.


7. Check yourself

  • The shaders project appears in your solution and builds with no errors.
  • The console shows Success three times for every shader program that is loaded.
  • Your starter output matches Figure 2.
  • After Task 1, your triangle matches Figure 3: red, green and blue corners with smooth blends.
  • After Task 2, your image matches Figure 6: no black boxes, and the pumpkin flickers.
  • After TODO 5 and 6, your image matches Figure 7.
  • After Task 3, the three bats fly a figure eight over the pumpkin, lean into their turns and flap, as in Figure 1.
  • You have answered the five questions in Section 8 and saved the six screenshots.

8. Questions (25%, 5% each)

Each question asks you to make one small change, run the program and look at the result. Then:

  • take a screenshot of the window (Win+Shift+S, then Window mode) and save it with the file name given;
  • answer the question in one or two sentences in answers.txt.

Start every question from your final code, and undo the change before the next one. Remember to build again after you edit a .glsl file.

Question 1: A yellow corner. Set task1 = true in main.cpp, so the triangle comes back. In Triangle.h, change the colour of the top vertex (V3) from blue 0.0f, 0.0f, 1.0f to yellow 1.0f, 1.0f, 0.0f. What happens to the colour in the middle of the triangle, and why didn't you have to change any other pixel? Hint: you only set three colours. Who works out the colour of all the pixels in between? (save as yellow.png)

Question 2: Bats hang upside down. In Quad/vshader.glsl, change the last line from uv = vtexcoord; to

uv = vec2(vtexcoord.x, 1.0 - vtexcoord.y);

What happens to the pumpkin and the bats? Did they move, or did only the picture on them change? Hint: in a texture, v = 0 is the bottom of the image and v = 1 is the top. What does 1.0 - v do to 0 and to 1? (save as upside_down.png)

Question 3: A green pumpkin. In Quad/fshader.glsl, add these two lines at the end of main():

if (id == 0)
    color.rgb *= vec3(0.4, 1.0, 0.4);

Why does only the pumpkin turn green, and not the bats? Hint: look at what pumpkin.draw(0) and bat.draw(1) pass to the shader. (save as green.png)

Question 4: Rolling the pumpkin. In Quad/vshader.glsl, the pumpkin is placed with T(0.0, -0.4) * S(1.2, 1.2). Make two versions, one at a time:

  • (a) T(0.0, -0.4) * R(45.0) * S(1.2, 1.2) (save as tilt_inplace.png)
  • (b) R(45.0) * T(0.0, -0.4) * S(1.2, 1.2) (save as tilt_swing.png)

The two lines use the same three matrices. In which version does the pumpkin stay where it was, and in which does it move? Why? Hint: read each product from right to left. R() always turns about the origin, the centre of the screen. Where is the pumpkin when R() is applied?

Question 5: A fourth bat. In main.cpp, add one line, bat.draw(4);, after bat.draw(3);. You did not change the shader. Where did the fourth bat come from, and why does it follow the same path as the others? Hint: look at the line float t = time + 2.0 * float(id);. Which time does bat 4 use? (save as four_bats.png)


9. Submission

Submit through the Recitation 6 assignment in MS Teams by Monday 16 November, 11:59pm. The deadline runs past fall break, so you can take the break off and finish afterwards.

Marks are based on attendance and a completed submission. The TA reviews a sample of submissions in detail. The weightings below show how the work is distributed and what the TA looks at.

Part Weight
Task 1: vertex colour interpolation (Section 4) 20%
Task 2: texturing the pumpkin and the bats (Section 5) 25%
Task 3: making the bats fly (Section 6) 25%
Questions, with their screenshots (Section 8) 25% (5% each)
triangle.png and halloween.png 5%
Total 100%

Submit one zip file named lastname_rec6.zip, laid out like this:

lastname_rec6/
├── code/      your main.cpp, and the Triangle and Quad folders
│              (with Triangle.h, Quad.h and the four .glsl files)
└── output/    eight screenshots and your answers:
               triangle.png       the triangle after Task 1 (Figure 3)
               halloween.png      the scene after Task 3 (like Figure 10)
               yellow.png         Question 1
               upside_down.png    Question 2
               green.png          Question 3
               tilt_inplace.png   Question 4 (a)
               tilt_swing.png     Question 4 (b)
               four_bats.png      Question 5
               answers.txt        your answers to the five questions in Section 8

Do not include the build folder.


10. If something goes wrong

  • The shaders project is not in the solution. You have not rerun Configure and Generate since pulling. Go back to Section 2.
  • Cannot open include file: 'GL/glew.h' (or 'GLFW/glfw3.h'), but CMake shows the right paths. Visual Studio is still using an old project from your build folder. Close Visual Studio, delete the whole build folder (everything in it is generated, so you lose nothing), then click Configure, Generate and Open Project in the CMake GUI again.
  • The console shows Failed: and the program closes. A shader did not compile. The message names the line, for example ERROR: 0:12: ... is line 12 of that shader. Common causes: a missing ;, a misspelled variable name, or a vec3 where a vec4 is needed (such as vertexColor = vcolor; in Task 1).
  • The console shows Could not open file: Quad/vshader.glsl, or decoder error 78. The program cannot find the shader or texture files. They are copied into build/shaders/Release (or Debug) when you build, and the program must run from that folder. Run it from Visual Studio with Ctrl+F5, not by double-clicking an old copy of the program.
  • You changed a shader but nothing changed. Build again before you run. The shaders are copied only when you build.
  • The triangle is red, or white, or has strange colours after Task 1. Check the stride and offset of both attributes. Check that the name in glGetAttribLocation() is exactly vcolor, the name in the shader.
  • One black square in the Halloween scene. The texture coordinates do not reach the shader yet. Finish TODO 1 and 2 of Task 2, and check that the attribute has 2 floats.
  • Black boxes around the pumpkin and the bats. Add the discard of TODO 3.
  • Everything is still at the centre. T() still returns the identity. Finish TODO 5.
  • The bats are in the wrong places, or swing around the centre of the screen. Check the order of the product. T() must be at the left (see Question 4).
  • The bats spin far too fast, or barely tilt. R() must convert degrees to radians with radians() before cos() and sin().
  • The three bats fly on top of each other. The time is not shifted per bat. Check the line float t = time + 2.0 * float(id);.
  • The window does not open and the console mentions OpenGL 3.3. The graphics driver is too old. Update it, or use a lab machine.

Acknowledgements

The material in this recitation follows our OpenGL discussions (Lectures 9.1 and 10.1) and the course textbook, Fundamentals of Computer Graphics by Steve Marschner and Peter Shirley:

  • Chapter 8: the graphics pipeline, and the interpolation of vertex attributes across a triangle with barycentric coordinates, used in Task 1.
  • Chapter 11: texture mapping and texture coordinates, used in Task 2.
  • Sections 6.1 and 6.3: 2D transformations, their composition, and translation with homogeneous coordinates, used in Task 3.
  • Chapter 17: using graphics hardware, vertex buffers and shaders, used throughout.

OpenGL references: docs.gl and the Khronos OpenGL reference pages. The OpenGL Programming Guide (8th edition) covers the same material in more depth.

The starter code is adapted from the previous offering of this course. AI tools were used to help write the code, the textures and the figures, and to help draft the text of this recitation. All content was reviewed, edited and tested by the course instructor.

Clone this wiki locally