Skip to content

Recitation 08 Lighting Texturing and Water

jiju edited this page Nov 23, 2026 · 1 revision

Recitation 8: Lighting, Texturing and Water

Objectives

In Recitation 7 you built a terrain from noise and drew it as a topographic map. This week it becomes a place. We raise the terrain into an island in a round sea, light it with a low evening sun, paint it with sand, grass, rock and snow, and add a sea that moves.

The ideas behind this recitation come from four lectures and one recitation. Keep them open while you work:

  • The lecture on lighting and shading: the normal vector and the Blinn-Phong model, used in Task 1.
  • The OpenGL Textures lecture: texture coordinates, GL_REPEAT and mipmaps, used in Tasks 2 and 3.
  • Lecture 10.1 (Fractals): the noise terrain you finished in Recitation 7.
  • Lecture 11.1 (Ocean Waves): sine waves, sums of sines and their normals, used in Task 4.
  • Recitation 4: normal maps, used in Task 3.

In this recitation you will:

  1. Compute smooth normals from the noise by finite differences, and light the terrain with Blinn-Phong.
  2. Texture the terrain by height, with smooth blends between sand, grass, rock and snow.
  3. Make moving water: layered textures that drift with time, and ripples from a normal map.
  4. Add waves, a sum of sines that moves the water up and down, with exact normals (advanced).

This is the second of three recitations that build up to Assignment 2. The assignment asks for the same ideas in a different form: there the heights come from a texture made on the CPU, the normals come from that texture, the texturing also uses the slope, and the water is the flattened terrain. So reuse the ideas from today, not the code as it is.

Figure 1 is what you will have at the end.

alt text


1. Getting the new exercise (Routine Setup)

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 terrain
git commit -m "my terrain works"
git checkout -- CMakeLists.txt
git pull
  • git add terrain 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 island folder.

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 island project appear.
  2. Click Open Project to open the solution in Visual Studio 2019.
  3. In the Solution Explorer, right-click island and choose Set as Startup Project.
  4. Choose Release, then build and run with Ctrl+F5.

The program opens an 800 x 800 window called Recitation 08: Island. There are two shader programs this week, one for the terrain and one for the water, so the console shows the three lines twice:

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

If a shader has a mistake, it prints Failed: with the GLSL compiler's message and a line number, and the program closes. The first block is the terrain, the second is the water.

The shaders and the textures are copied next to the program (into build/island/Release) 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 flat, grey brown island in a plain blue sea. That is expected. Every normal points straight up, so every point of the land gets the same light, and you see only its outline.

alt text

3.1 The files

File What it does Status
main.cpp Opens the window, sets up the camera and reads the keys. given
Grid.h The grid mesh of Recitation 7, now used for both the terrain and the water. given
Terrain.h Draws the terrain. Holds the grid and noise settings, the sea level and the sun. given
Water.h Draws the water grid at sea level, see-through. given
Texture.h Loads a PNG file into an OpenGL texture. given
Shaders/terrain_vshader.glsl The noise of Recitation 7, the island, and the normal. Task 1a
Shaders/terrain_fshader.glsl Lighting and texturing of the terrain. Tasks 1b and 2
Shaders/water_vshader.glsl Moves the water vertices. Task 4
Shaders/water_fshader.glsl Colour, ripples and lighting of the water. Task 3
Textures/ Sand, grass, rock, snow, water colour and a water normal map. given
Helpers/ The same helpers as in Recitation 7. given

The textures were generated by a short program from random noise, so they tile with no seam and are free to use.

3.2 The keys

The keys are the same as in Recitation 7, plus W.

Key What it does
1, 2, 3 Perlin noise, fBm, ridged multifractal
Up, Down one more, or one fewer, octave (from 1 to 10)
Left, Right turn the terrain
Space spin on and off
W waves on and off (Task 4)
F wireframe on and off
P save a screenshot
Esc quit

P saves screenshot_000.png, then screenshot_001.png, and so on, next to the program in build/island/Release. Rename each one to the file name asked for in Sections 8 and 9.

The program starts in mode 3, the ridged multifractal, with waves on.

3.3 The settings

At the top of Terrain.h you find the grid and noise settings of Recitation 7, unchanged, and two new things:

const float SEA_LEVEL = 0.0f;    ///< height of the water surface

struct Light {
    Vec3 sunDir = Vec3(-0.78f, 0.50f, 0.42f).normalized();   ///< direction TO the sun: low, in the west
    Vec3 I = Vec3(1.00f, 0.84f, 0.64f);                      ///< I: sunlight, warm
    Vec3 I_a = Vec3(0.32f, 0.36f, 0.46f);                    ///< I_a: ambient light from the sky, cool
};

The sun is a directional light: it is so far away that its light comes from the same direction sunDir everywhere. Both shader programs get sunDir, I, I_a and the camera position viewPos as uniforms. The sun is low and warm, as in the evening, and the ambient light from the sky is a little blue.

The constants of the shading, the texturing and the water are at the top of each shader.

3.4 How the island is drawn

The world is z-up, as in Recitation 7.

  1. The terrain vertex shader computes the height of every vertex with terrainHeight(xy). This is your noise from Recitation 7, raised in the middle of the grid and pushed under the sea near the edges by islandShape(), so the land forms an island. Both are given.
  2. The terrain fragment shader chooses the colour of the ground, lights it, and makes it bluer and darker under the sea.
  3. The water is a second grid of the same size, at SEA_LEVEL. It is drawn after the terrain, with blending on (see Water::draw()). Each water pixel is mixed with the terrain pixel behind it: alpha * water + (1 - alpha) * terrain. So you see the sandy shallows through the water, and the deep sea looks dark.
  4. Near the border of the grid, both the ground and the water fade into the sky colour. The world becomes a round island in a round sea.

4. Task 1: Normals and Blinn-Phong shading (25%)

To light a surface we need its normal, the unit vector perpendicular to it. The grid starts flat, so its normal is (0, 0, 1) everywhere. Once the vertices move up and down, that is wrong. The starter still uses it, which is why the island looks flat.

In Recitation 7 the topographic map used the normal of each triangle, from dFdx and dFdy. That gives flat facets. Today we compute one normal per vertex, from the noise itself. The GPU interpolates it across each triangle, so the lighting is smooth.

4.1 TODO Task 1a: The normal, by finite differences

Open Shaders/terrain_vshader.glsl and find ///TODO Task 1a, about line 105.

Below, h(x, y) is short for terrainHeight(xy).

The tangents of a height field

The terrain is a height field: one height for each point (x, y). Its surface is the set of points

S(x, y) = (x, y, h(x, y))

A tangent is a direction along the surface. To find one, walk on the surface along x, keeping y fixed, and ask how the point S moves. Its derivative with respect to x is

dS/dx = (1, 0, dh/dx)

Move one unit in x: you stay at the same y, and you go up by the slope dh/dx. This is the exact tangent along x. Along y, in the same way, it is (0, 1, dh/dy).

So we need the slopes dh/dx and dh/dy. We have a function for the height, but not for its slope. So we estimate the slope from heights.

Estimating the slope: the central finite difference

The derivative is a limit: the slope of a line through two points of the curve, as the two points move together. On a computer we cannot take the limit, so we stop at a small step eps. That is a finite difference.

We use the central difference: one point a step to the left of x and one a step to the right, so the two points are centred on x:

dh/dx  ≈  [h(x + eps) - h(x - eps)] / (2 eps)

This is the slope of the line from the left point to the right point.

How good is it? Write the Taylor series of both neighbours:

h(x + eps) = h + eps h' + (eps^2 / 2) h'' + (eps^3 / 6) h''' + ...
h(x - eps) = h - eps h' + (eps^2 / 2) h'' - (eps^3 / 6) h''' + ...

Subtract them. The terms h and h'' have the same sign in both lines, so they cancel:

[h(x + eps) - h(x - eps)] / (2 eps)  =  h'  +  (eps^2 / 6) h'''  +  ...

So the error is about (eps^2 / 6) h'''. It shrinks like eps^2: halve the step and the error drops to a quarter. Because the points sit on both sides of x, the curvature on the left and on the right balance out. Figure 3 shows the line through the two points next to the true tangent at x. The step in the figure is large, so that the small difference is easy to see.

We use a step of one grid cell: eps = gridStep.

alt text

The tangent from two points

Now put the two ideas together. Take the two neighbours of the vertex on the surface, one step to the left and one to the right:

P- = (x - eps, y, h(x - eps, y))
P+ = (x + eps, y, h(x + eps, y))

Both lie on the terrain, so the vector from one to the other lies along the terrain. That is our tangent along x:

tx = P+ - P- = (2 eps,  0,  h(x + eps, y) - h(x - eps, y))
  • The x part is 2 eps, because the two points are 2 eps apart in x.
  • The y part is 0, because both points have the same y.
  • The z part is how much higher P+ is than P-.

Divide it by 2 eps and you get (1, 0, central difference). That is the exact tangent (1, 0, dh/dx), with the central difference in place of the slope. So tx is the tangent along x, scaled by 2 eps. The scale does not matter, because we normalize the normal at the end. In code:

tx = (2 eps,  0,  terrainHeight(xy + (eps, 0)) - terrainHeight(xy - (eps, 0)))

In the same way, the vector from the point one step below in y to the point one step above is the tangent along y:

ty = (0,  2 eps,  terrainHeight(xy + (0, eps)) - terrainHeight(xy - (0, eps)))

The normal is perpendicular to both tangents, so it is their cross product:

normal = normalize(cross(tx, ty));

The order matters. On flat ground, tx = (2 eps, 0, 0) and ty = (0, 2 eps, 0), and cross(tx, ty) points along +z, up. cross(ty, tx) would point down, and the lighting would look inside out.

Write the three lines. Use vec3(...) for the tangents and vec2(eps, 0.0) for the steps.

The noise is now computed five times per vertex: once for the height and four times for the normal. With 66,049 vertices that is about 330,000 noise values per frame. The GPU does them all in parallel.

4.2 TODO Task 1b: Blinn-Phong

Open Shaders/terrain_fshader.glsl and find ///TODO Task 1b, about line 34, in the function blinnPhong(). We use the same notation as in the lectures and in Assignment 1:

L = k_a I_a  +  k_d I max(0, n . l)  +  k_s I max(0, n . h)^p
  • n is the unit normal. main() normalizes the interpolated normal before it calls blinnPhong(), because interpolation makes it a little shorter than 1.
  • l is the unit direction to the light: normalize(sunDir). For a directional light it is the same at every point.
  • v is the unit direction from the point to the camera: normalize(viewPos - fragPos).
  • h is the half vector, halfway between l and v: normalize(l + v).
  • k_a and k_d are the colour of the ground. They are passed in. Until Task 2 they are a plain grey brown.
  • k_s and p are constants at the top of the file: 0.1 and 16. The ground is a little shiny, not much.
  • I and I_a are uniforms, from Terrain.h.

Write the three terms and return their sum. GLSL multiplies two vec3s component by component, so k_d * I is the ground colour in the colour of the sunlight.

Run the program. You should get Figure 4: the slopes that face the sun, on the left, are bright and warm. The slopes that face away get only the cool ambient light. The ridges of the ridged multifractal are sharp, but the light on them is smooth.

alt text

If the island is dark where it should be bright, check the order in the cross product. If it is lit evenly, with no hills, check that the tangents use + eps and - eps, and that normal is set.


5. Task 2: Texturing by height (15%)

Real islands have sand at the water, grass on the low land, bare rock higher up and snow on the peaks. We pick the texture of each fragment from its height h = fragPos.z.

Open Shaders/terrain_fshader.glsl and find ///TODO Task 2, about line 49, in terrainColor(). The four texture colours are already read for you, at the texture coordinates uv:

vec3 sand = texture(sandTex, uv).rgb;
// grass, rock and snow the same way

Texture coordinates. To read a texture, each pixel needs a texture coordinate (u, v): which point of the picture to use. Usually the mesh stores one per vertex. Our grid does not, so we make them from the position: the x and y of the ground become u and v, and the texture lies flat on the island, like a carpet seen from above. In main(): uv = fragPos.xy * TEX_REPEAT.

The scale. The grid is 8 units wide. With TEX_REPEAT = 1.5, u runs over 12 units, so each texture repeats 12 times across the island. A larger value makes the pattern smaller.

Repeating. A texture only covers u from 0 to 1. The textures are loaded with GL_REPEAT (see Texture.h), so OpenGL keeps only the fractional part: u = 2.3 reads the same point as u = 0.3. The picture repeats like floor tiles, and since each texture's edges match, you do not see the joins.

Far away. In the distance, one pixel covers many texels. Reading just one of them makes the ground flicker as the camera moves. Mipmaps are smaller, pre-averaged copies of the texture (recall our discussion of Mipmaps, Lecture 5.2), and OpenGL reads from them far away, so the distant ground stays calm.

The levels are constants at the top of the file:

const float SAND_TOP = 0.10;   ///< sand below, grass above
const float GRASS_TOP = 0.52;  ///< grass below, rock above
const float SNOW_LINE = 0.80;  ///< rock below, snow above
const float BLEND = 0.05;      ///< half width of the blend between two layers

Why not a hard switch?

The simplest rule is an if: if (h < SAND_TOP) c = sand; else c = grass;. Every fragment then gets exactly one texture. Where the height crosses SAND_TOP, the texture jumps from sand to grass in one pixel. The result is a sharp line around the island, as if someone had drawn it with a ruler. Nature does not change at an exact height. Sand thins out into grass over some distance. So we want a gradual change: a little grass in the sand near the level, a little sand in the grass, more and more grass as we go up.

One level: smoothstep gives a weight, mix uses it

We do this in two steps.

  1. A weight between 0 and 1. w = smoothstep(SAND_TOP - BLEND, SAND_TOP + BLEND, h) says how much grass we want at the height h. Below the band it is 0. Above the band it is 1. Inside the band, which is 0.1 units wide, it rises smoothly from 0 to 1, and it is exactly 0.5 at SAND_TOP.
  2. A weighted average of the two colours. mix(sand, grass, w) computes (1 - w) * sand + w * grass. With w = 0 it is pure sand. With w = 1 it is pure grass. With w = 0.25 it is three parts sand and one part grass. The two weights always add up to 1, so the colour never gets brighter or darker than the two textures.

Figure 5 shows both steps for the sand and grass border. The top panel is the weight. The middle strip is what mix makes of it, with the real textures. The bottom strip is the hard switch, for comparison. Read it from left to right as walking uphill from the beach.

alt text

Why smoothstep and not a straight ramp from 0 to 1? A straight ramp starts and stops with a corner. The eye notices a sudden change in the rate of change, so the start and the end of the band would show as faint lines. smoothstep uses the cubic 3t^2 - 2t^3, which starts and ends with zero slope, the same idea as the fade curve of Recitation 7. The band then has no visible edges.

Three levels: stacking the mix lines

We have four textures and three levels. We start with sand everywhere and apply one mix line per level, from the bottom up:

vec3 c = sand;
c = mix(c, grass, smoothstep(SAND_TOP - BLEND, SAND_TOP + BLEND, h));
c = mix(c, rock,  ________);   // the same pattern, at GRASS_TOP
c = mix(c, snow,  ________);   // the same pattern, at SNOW_LINE

Think of it as painting in layers. Each line takes the colour so far, c, and paints the next texture over it, but only above its own level. Below the level its weight is 0, so it leaves c alone. Above the level its weight is 1, so it covers everything painted before. Figure 6 shows the colour after each line.

alt text

This is why the order matters. If the snow line came first, the grass line would paint grass over the snow on every peak, because the peaks are also above SAND_TOP.

The levels are far apart compared with BLEND, so the bands never overlap. At any height, at most two textures are mixed.

Figure 7 puts it on a hill, cut through the middle. The colour of the ground depends only on its height. On the left, with a hard switch, each border is a sharp line. On the right, each border is a soft band, 2 BLEND high.

alt text

TODO Task 2: in terrainColor(), write these four lines, fill in the two blanks, and return c.

Run the program. You should get Figure 8: a sandy shore, green slopes, grey brown rock on the high ground and snow on the highest peaks. Under the sea, the sand turns blue and dark with depth.

alt text

Look at a steep cliff. It has grass or snow on it if its height says so, though nothing would stay there in nature. Assignment 2 fixes that with a rule for the slope. Today we use the height only.


6. Task 3: Moving water (20%)

6.0 The idea: moving water without moving the water

Look at a lake or the sea. Three things tell you it is water:

  1. Its colour moves. Patterns of light and dark drift across it, never quite the same twice.
  2. It glitters. Thousands of tiny ripples catch the sun, each for a moment.
  3. Its shape moves. Swells rise and fall.

The obvious way to get all three is to build a very fine mesh and move every vertex like real water. That is expensive, and the ripples are far smaller than our grid cells: our 256 x 256 grid could not show them anyway.

So we fake the first two, and leave only the third to geometry:

What you see How we make it Where Do vertices move?
Colour that drifts Layered textures, moved with time (Task 3a) fragment shader no
Glitter of small ripples Normal map, moved with time (Task 3b) fragment shader no
Swells that rise and fall Waves, a sum of sines (Task 4) vertex shader yes

In Task 3 the water grid stays perfectly flat. No vertex moves. Every effect happens per pixel, in the fragment shader:

  • Texturing changes what colour each pixel reads. Move the texture coordinates with time and the pattern moves, though the surface does not.
  • Normal mapping changes which way each pixel seems to face. Lighting only looks at the normal, so a flat surface with tilted normals is lit as if it were bumpy. This is the same trick as in Recitation 4.

Think of the two as what you see in the water (its colour) and what you see on the water (the glitter of the sun). Colour alone looks like a moving painting. Glitter alone looks like sparkles on a plain blue sheet. Together they read as water.

The water grid has the texture coordinates uv = xy / WATER_TILE from its vertex shader, so the water textures repeat every 2 world units. All of Task 3 is in Shaders/water_fshader.glsl. The uniform time holds the seconds since the start.

6.1 TODO Task 3a: Layered textures (the colour)

The idea. water.png is a picture of water: blue green with bright lines. The simplest way to animate it is to slide it: add time * speed to uv. But then the whole pattern moves as one piece, like a printed sheet being pulled across the sea. Real water moves in many directions at once.

So we read the same picture three times, each copy shifted by its own offset, and average the three. Each offset changes with time in its own way, so the copies drift against each other. Where they overlap, the bright lines cross, merge and split. The pattern keeps changing shape instead of just sliding.

The mechanism. Find ///TODO Task 3a, about line 23. The offsets are:

vec2 uv1 = uv + vec2(0.2  * (1.0 + sin(time / 5.0)), 0.2  * (1.0 + sin(time / 10.0)));
vec2 uv2 = uv + vec2(0.1  * (1.0 + sin(time / 2.0)), 0.1  * (1.0 + sin(time / 5.0)));
vec2 uv3 = uv + vec2(0.05 * (1.0 + sin(time)),       0.05 * (1.0 + sin(time / 2.0)));

Each offset swings back and forth with a sine, so the water sloshes rather than flows away. The three layers have different amplitudes and different periods, so they never move together (Figure 9). The first layer is large and slow, the last is small and fast.

alt text

Replace the plain colour with the weighted sum of the three reads:

vec3 waterColor = 0.5 * texture(waterTex, uv1).rgb + 0.3 * /* uv2 */ + 0.2 * /* uv3 */;

The weights add up to 1, so the result is as bright as the texture.

6.2 TODO Task 3b: Ripples (the light)

The idea. Water is shiny. Much of what makes it look like water is the specular highlight: the reflection of the sun. A flat surface has the same normal everywhere, so it gives one smooth, dull highlight. Real water is covered in tiny ripples. Each one faces a slightly different direction, so only some of them reflect the sun toward you at any moment. That is the glitter.

We do not move any vertex to make these ripples. We only tilt the normal at each pixel. Blinn-Phong uses the normal, not the position, so a pixel with a tilted normal is lit as if the surface there were tilted. The surface stays flat; its lighting is bumpy.

The mechanism. Find ///TODO Task 3b, about line 33. The tilts come from a normal map, as in Recitation 4. normalTex does not store a colour. It stores a unit vector in each texel, with each component moved from [-1, 1] into the colour range [0, 1]. Three steps:

  1. Read it, drifting slowly with time so the glitter moves, and turn the colour back into a vector:
    vec3 ripple = texture(normalTex, uv * 3.0 + time * vec2(0.04, 0.03)).rgb * 2.0 - 1.0;
  2. Tilt the normal of the water by the sideways part of the ripple:
    n = normalize(n + RIPPLE * vec3(ripple.xy, 0.0));
    Until Task 4, n is (0, 0, 1). RIPPLE (0.5) sets how strong the ripples are.
  3. Light the water with Blinn-Phong, as in Task 1b, with k_a = k_d = waterColor and the k_s and p at the top of the file: 0.9 and 300. Store the result in c. The water is dark and very shiny: its highlight is small and bright.

One normal map layer is enough today.

Run the program. You should get Figure 10: the sea has a texture and bright sparkles where it reflects the sun. Watch it for a few seconds: the colour drifts and the sparkles move. Press F for wireframe: the water grid is still flat.

alt text


7. Task 4: Waves (advanced) (15%)

So far the water is flat. The layered textures change its colour and the ripples change its normal, but no vertex has moved. Now we change its shape, the third row of the table in Section 6.0: we move the water vertices up and down with waves, in the vertex shader. Open Shaders/water_vshader.glsl and find ///TODO Task 4, about line 28.

This task follows Lecture 11.1 (Ocean Waves). Keep its slides on sine waves, sums of sines and their normals open while you work.

One wave that travels in the direction D (a unit vector) is a sine:

z(x, y, t) = A sin(k (D . (x, y)) - w t)
  • A is the amplitude, the height of the crests above the middle.
  • k = 2 pi / wavelength is the wave number. The sine repeats every wavelength along D.
  • w = speed * k is the angular frequency. With - w t, the crests move along D at speed units per second.
  • D . (x, y) is the distance along D. Points on a line perpendicular to D have the same phase: they form one crest.

One sine looks like a machine. The sea looks natural when several waves with different directions and sizes are added (Figure 11). The four waves are given as constant arrays at the top of the shader: DIR, WAVELENGTH, AMPLITUDE and SPEED.

alt text

The normal. For the terrain we measured the slope with finite differences, because we had only a function for the height. For the waves we know the formula, so we can take the derivative exactly. The derivative of a sum is the sum of the derivatives, and the derivative of sin(k (D . xy) - w t) along x is k D.x cos(...). So

dz/dx = sum of  A k D.x cos(phase)
dz/dy = sum of  A k D.y cos(phase)
n     = normalize(-dz/dx, -dz/dy, 1)

The vector (-dz/dx, -dz/dy, 1) is the cross product of the two tangents (1, 0, dz/dx) and (0, 1, dz/dy), the same construction as in Task 1a.

TODO Task 4: when waves == 1, loop over the NUM_WAVES waves. For each one, compute D, k, w and phase, add the sine to z, and add the two derivatives to dzdx and dzdy (declare both as 0.0 before the loop). After the loop, set n. Remember normalize(DIR[i]): the directions in the array are not unit vectors.

Run the program. You should get Figure 12. The sea is now covered with crossing swells, and the sun makes a wide glitter on the waves that face it. Press W to switch the waves off and on. Watch the shore: the water moves up and down the beach.

alt text

Here is a close look at the water, with the waves and the drifting textures over a few seconds:

alt text

Take two screenshots with P: one as the program starts, and one after pressing W to switch the waves off. Rename them island.png and no_waves.png. You need them for the submission.


8. Check yourself

  • The island project appears in your solution and builds with no errors.
  • The console shows Success six times when the program starts.
  • Your starter output matches Figure 2.
  • After Task 1, the island has smooth hills, bright on the side of the sun and dark on the other side (Figure 4).
  • After Task 2, you see sand, grass, rock and snow, with soft borders between them (Figure 8).
  • After Task 3, the sea has a texture that drifts, and bright sparkles from the sun (Figure 10).
  • After Task 4, the sea has moving waves, and W switches them off and on (Figure 12).
  • You have saved island.png and no_waves.png, answered the five questions in Section 9 and saved their screenshots.

9. Questions (20%, 4% each)

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

  • take a screenshot with P and rename it to the file name given;
  • answer the question in a few sentences in answers.txt.

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

Question 1: The fade curve, again. In terrain_vshader.glsl, make fade() return t (the line is there, as a comment). Press 1 for plain Perlin noise. What do you see in the lighting that was hard to see on the topographic map of Recitation 7? Then try the cubic (no screenshot). Why do the lines go away? Hint: the normal comes from the slope of the noise. What happens to the slope of the noise at a cell border with each fade curve? (save as no_fade.png)

Question 2: A bigger step. In terrain_vshader.glsl, change float eps = gridStep; to float eps = 10.0 * gridStep;. Compare with your island.png. What happens to the small bumps on the hills? Why? Hint: look at Figure 3. With this step, P- and P+ are 20 grid cells apart. What happens to a small bump that lies between them? (save as big_eps.png)

Question 3: Hard borders. In terrain_fshader.glsl, set BLEND to 0.001. What do the borders between the textures look like, and what shape do they follow? Then set it to 0.2 (no screenshot). What goes wrong with a wide blend? Hint: what is the set of points where h = GRASS_TOP? Do not set BLEND to exactly 0: smoothstep(a, b, h) is not defined when a = b. (save as hard_edges.png)

Question 4: A dull sea. In water_fshader.glsl, change p from 300 to 20. What happens to the size of the highlight on the water? Why does water need a large p? Hint: think of the sun on a mirror and on a plastic ball. Which one gives a small, sharp highlight? (save as low_p.png)

Question 5: Waves without normals. In water_vshader.glsl, after the loop, replace the line that sets n with n = vec3(0.0, 0.0, 1.0);. The vertices still move. Compare with your island.png. Why are the waves so hard to see now? From which view would you still notice them? Hint: which term of the shading changes when only the height of a point changes? Press Left a few times and watch the shore. (save as flat_waves.png)


10. Submission

Submit through the Recitation 8 assignment in MS Teams by Monday 30 November, 11:59pm.

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: normals and Blinn-Phong (Section 4) 25%
Task 2: texturing by height (Section 5) 15%
Task 3: moving water (Section 6) 20%
Task 4: waves (Section 7) 15%
Questions, with their screenshots (Section 9) 20% (4% each)
island.png and no_waves.png 5%
Total 100%

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

lastname_rec8/
├── code/      your four shaders: Shaders/terrain_vshader.glsl, terrain_fshader.glsl,
│              water_vshader.glsl and water_fshader.glsl
└── output/    seven screenshots and your answers:
               island.png         after Task 4, as the program starts
               no_waves.png       after Task 4, waves off (key W)
               no_fade.png        Question 1, key 1
               big_eps.png        Question 2, eps = 10 * gridStep
               hard_edges.png     Question 3, BLEND = 0.001
               low_p.png          Question 4, p = 20
               flat_waves.png     Question 5
               answers.txt        your answers to the five questions in Section 9

Do not include the build folder.


11. If something goes wrong

  • The island project is not in the solution. You have not rerun Configure and Generate since pulling. Go back to Section 2.
  • The console shows Could not load Textures/sand.png. The program cannot find its textures. Build again, and run it from Visual Studio with Ctrl+F5.
  • The console shows Failed: and the program closes. A shader did not compile. The message names the line, for example ERROR: 0:42: ... is line 42. The first Failed: after the first Compiling Vertex shader is the terrain, after the second it is the water. Common causes in this recitation:
    • xy + vec2(eps, 0) is fine, but vec3(2 * eps, 0, ...) with the int 2 fails on some drivers. Write 2.0.
    • sin(time / 5): an int in a float expression. Write 5.0.
    • texture(waterTex, uv1) is a vec4. Add .rgb to get a vec3.
    • dzdx used before it is declared, or declared inside the loop.
    • a missing ;, or a misspelled variable name.
  • You changed a shader but nothing changed. Build again before you run.
  • The island is still flat and evenly lit after Task 1. normal is still (0, 0, 1), or blinnPhong() still returns k_d.
  • The lighting is inside out: bright on the far side, dark on the side of the sun. The normal points down. Swap the arguments of cross().
  • Black patches, or flickering black pixels. A vector with length 0 was normalized, or a pow() got a negative base. Use max(dot(...), 0.0) inside pow().
  • The specular highlight is in the wrong place, or moves with the camera in a strange way. v must go from fragPos to viewPos, not the other way, and both l and v must be unit vectors before you add them.
  • Sharp lines between the textures. You used if or step(), or BLEND is 0.
  • Snow everywhere, or only sand. The mix() lines are in the wrong order, or use the wrong level. Sand first, snow last.
  • The water is bright white or very washed out. The weights of the three layers do not add up to 1, or the normal map was not turned back with * 2.0 - 1.0.
  • The water does not move. time is not used, or you wrote time / 5 with ints.
  • The waves are a regular grid, or a single sine. You used DIR[0] or WAVELENGTH[0] for every wave instead of [i].
  • The waves are huge spikes. D is not normalized, or k is the wavelength instead of 2 pi / wavelength.
  • The waves move but look flat. n is not set from dzdx and dzdy, or the signs are wrong: it is (-dz/dx, -dz/dy, 1).
  • You cannot find your screenshots. They are next to the program, in build/island/Release.
  • 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 the lectures on lighting and shading, on OpenGL textures, on ocean waves and on fractals:

  • Lighting and shading: the normal vector and the Blinn-Phong model, used in Tasks 1 and 3.
  • OpenGL Textures: texture coordinates, repeating textures and mipmaps, used in Tasks 2 and 3.
  • Lecture 10.1 (Fractals): the noise terrain from Recitation 7.
  • Lecture 11.1 (Ocean Waves): sine waves, sums of sines and their normals, used in Task 4.

References:

  1. J. F. Blinn. 1977. Models of light reflection for computer synthesized pictures. SIGGRAPH Computer Graphics 11, 2, 192 to 198.
  2. K. Perlin. 2002. Improving noise. ACM Transactions on Graphics 21, 3, 681 to 682.
  3. M. Finch. 2004. Effective water simulation from physical models. In R. Fernando (Ed.), GPU Gems, chapter 1. Addison-Wesley.
  4. S. Marschner and P. Shirley. 2021. Fundamentals of Computer Graphics (5th ed.). CRC Press. Chapters on shading and texture mapping.

The exercise is adapted from the terrain and water recitation of the previous offering of this course: the grid mesh, the finite difference normals and the layered water texture come from there. The textures were generated procedurally for this recitation. An AI assistant (Claude) was used to help write the code, and to help draft the text of this recitation. All content was reviewed, edited and tested by the course instructor.

Clone this wiki locally