3. Gradients

When you started the GLSL shader tester in chapter 1, it showed a gradient covering the whole window.
In this chapter I take the shaders that draw that gradient apart line by line, and we figure out why every pixel gets a different color when there are only four vertices.
Then we add a color, move the color values into the shader, animate the colors from C, and finally build diagonal, radial and smoothstep gradients.

Gradients look boring, but games use them everywhere: skies, fog, UI, health bars, screen fades.
And the "interpolation" you learn here is the foundation for lighting and textures in later chapters.

The project you downloaded in chapter 1 already contains the final result of this chapter (the animated three-color gradient), except for the macOS fragment.mac.glsl, which is still the two-color version, so a Mac shows two colors until section 3.3. This chapter walks through the steps that lead there. If you want to type along, first put fragment.glsl and the uniform lines in main.c back to the two-color version shown in section 3.1.

3.1 Breaking down the shaders

Let's look at the code we already have.
The tester uses two shaders.
The vertex shader (vertex.glsl) runs once per vertex, and the fragment shader (fragment.glsl) runs once per pixel.
On macOS, vertex.mac.glsl and fragment.mac.glsl are loaded instead. They are identical except that the first line is #version 410 core.

vertex.glsl

#version 450 core

layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aUv;
out vec2 vUv;

void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition, 0.0, 1.0);
}

The first thing we see is #version 450 core.
It says that the shader uses GLSL version 4.50 with the core profile.
In the core profile, old deprecated features (like gl_FragColor) are not available, and in return the driver doesn't have to do extra compatibility work.
This line must always be the very first line of the file.

layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aUv;

These lines define the vertex shader's input attributes, which the C code provides.
In the C code, each vertex is four floats (position x, y and UV u, v):

  // set up the vertex data (fullscreen quad)
  float vertices[] = {
    -1.0f, -1.0f, 0.0f, 0.0f, // bottom left (position, UV)
     1.0f, -1.0f, 1.0f, 0.0f, // bottom right
     1.0f,  1.0f, 1.0f, 1.0f, // top right
    -1.0f,  1.0f, 0.0f, 1.0f  // top left
  };
  GLuint indices[] = { 0, 1, 2, 2, 3, 0 };
  ...
  // vertex attributes: position (location 0), UV (location 1)
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)0);
  glEnableVertexAttribArray(0);
  size_t offset = 2 * sizeof(float);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)offset);
  glEnableVertexAttribArray(1);

The layout(location = 0) and layout(location = 1) parts explicitly assign the binding location of each vertex attribute.
That number is the first argument of glVertexAttribPointer.
The 2D vector (vec2) aPosition goes to location 0 and holds the vertex position in X and Y.
Location 1 gets another 2D vector, aUv, which holds the texture coordinates (U and V).
The remaining arguments of glVertexAttribPointer mean "two floats", "don't normalize", "a new vertex starts every 4 * sizeof(float) bytes" and "this attribute starts this many bytes into the vertex".
Finally, the in keyword marks these as input variables that come from the vertex buffer into the shader.

The quad is made of two triangles (indices 0, 1, 2 and 2, 3, 0).
Notice that the UVs are placed so that the bottom left is (0,0) and the top right is (1,1).

out vec2 vUv;

This declares an output (out) variable vUv of type vec2, which is passed to the next stage of the pipeline (here, the fragment shader).
The fragment shader receives it with an in variable of the same name and the same type.

void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition, 0.0, 1.0);
}

This is the main function, the entry point of the vertex shader, and it runs once for each vertex.
vUv = aUv; copies the input texture coordinate aUv into the output variable vUv.
On its way to the fragment shader, this value goes through "interpolation", which I explain in the next section.

gl_Position = vec4(aPosition, 0.0, 1.0); sets the built-in variable gl_Position, the final position of the vertex in clip space.
aPosition is a vec2, so it only has X and Y. That's why we add z = 0.0 and w = 1.0.
Because w=1, this position is directly the normalized device coordinate (NDC, x and y from −1 to 1), and a square from −1 to 1 covers the whole window.

fragment.glsl

Here is the fragment shader in its starting state (two colors):

#version 450 core

in vec2 vUv;
out vec4 out_color;

uniform vec3 uColorA;
uniform vec3 uColorB;

void main() {
  vec3 blendedColor = mix(uColorA, uColorB, vUv.x);
  out_color = vec4(blendedColor, 1.0);
}

As mentioned above, the vertex shader passes data to the fragment shader.
So here, in vec2 vUv; comes in from the vertex shader.
There is also out vec4 out_color;, an output variable of type vec4 (a 4D vector) that holds the final color (RGBA).
This value is written to the framebuffer.
When a fragment shader has only one out variable, it automatically becomes output number 0 (the screen).

uniform vec3 uColorA;
uniform vec3 uColorB;

These two are uniform variables, each a 3D vector (vec3) that holds an RGB color.
Uniforms are global variables set from the C code, and they have the same value for every vertex and fragment during one draw call.
In main.c, these two lines set them right before drawing:

    glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), 1.0f, 0.0f, 0.0f); // red
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), 0.0f, 1.0f, 0.0f); // green

glGetUniformLocation looks up the number (location) of a variable by its name in the shader, and glUniform3f writes three floats to that location.
glUniform* works on the program currently bound with glUseProgram, so always call it after glUseProgram.

void main() {
  vec3 blendedColor = mix(uColorA, uColorB, vUv.x);
  out_color = vec4(blendedColor, 1.0);
}

This main function runs for each fragment (pixel) of the primitive being rendered.
vec3 blendedColor = mix(uColorA, uColorB, vUv.x); uses the mix function to linearly interpolate between uColorA and uColorB.
The interpolation factor is vUv.x, the x component of the UV coordinate (0 at the left edge of the window, 1 at the right edge).

mix(a, b, t) computes:

mix(𝐚,𝐛,t)=𝐚(1−t)+𝐛t=𝐚+t(𝐛−𝐚)

This is exactly the linear interpolation (lerp) from chapter 2 of the linear algebra series.
GLSL just calls it mix instead of lerp.
Used on a vec3, the same formula is applied to R, G and B separately (component-wise).

When vUv.x = 0, blendedColor = uColorA.
When vUv.x = 1, blendedColor = uColorB.
Values in between blend the two colors proportionally.
For example, a quarter of the way from the left (t=0.25):

mix((1,0,0),(0,1,0),0.25)=(1,0,0)×0.75+(0,1,0)×0.25=(0.75,0.25,0)

That's 75% red and 25% green, a red leaning slightly towards yellow.
In the middle (t=0.5) we get (0.5,0.5,0), a 50/50 blend.
The result is a smooth gradient from uColorA to uColorB.

out_color = vec4(blendedColor, 1.0); turns the blended RGB color (vec3) into a vec4 by adding an alpha value of 1.0 (fully opaque).
It is assigned to out_color and becomes the final color of the fragment.

A horizontal gradient from red to green

3.2 Interpolation: how the colors spread

The vertex shader only runs once per vertex.
For this quad that's 4 times (the indices reference vertices 6 times, but the GPU can reuse the result for a vertex it has already processed).
An 800×600 window, on the other hand, has 480,000 pixels, and the fragment shader runs for every one of them.
So how do the vUv values of 4 vertices turn into 480,000 different values?

The answer is the rasterizer, which sits between the vertex shader and the fragment shader.
The rasterizer is fixed-function hardware on the GPU (a part you can't program), and it does this:

  1. It takes the gl_Position of the three vertices of a triangle and finds the triangle on the screen.
  2. It finds every pixel that the triangle covers.
  3. For the center of each pixel, it computes "weights" w0,w1,w2 for the three vertices. The weights are at least 0 and add up to 1 (these are called barycentric coordinates).
  4. It blends every out variable of the vertex shader with those weights and hands the result to the matching in variable of the fragment shader.

As a formula, this is exactly a linear combination from chapter 2 of the linear algebra series:

𝐯𝐔𝐯=w0𝐮𝐯0+w1𝐮𝐯1+w2𝐮𝐯2,w0+w1+w2=1

The two triangles of the quad and a fragment inside triangle 2. The numbers on the dashed lines are the weights of each vertex

The point in the picture lies inside triangle 2 (vertices v2,v3,v0).
Its weights are 0.5 for v0, 0.25 for v2 and 0.25 for v3, so:

0.5×(0,0)+0.25×(1,1)+0.25×(0,1)=(0.25,0.5)

We get the same value as the position of the point.
Because the UVs of this quad are laid out just like the positions, vUv tells us "where on the screen are we" as a number from 0 to 1.
To be precise, it is computed at the center of the pixel, so the 201st pixel from the left (x = 200) gets 200.5/800≈0.2506.
That also means no pixel ever gets vUv.x of exactly 0 or 1.

You can change how a value is interpolated by putting a qualifier in front of the out/in variables.

  • smooth (the default): perspective-correct interpolation. It corrects with the w of gl_Position so that things look right in 3D.
  • noperspective: plain linear interpolation on the screen.
  • flat: no interpolation. The value of one vertex of the triangle (the last one by default) is used for the whole triangle. Integer in variables of the fragment shader must be flat.

The quad in this chapter has w=1, so smooth and noperspective give the same result.
You'll see the difference in chapter 13, when we work in 3D.

3.3 Adding another color

Let's add a third color: blue.

First, add this line to main.c below the two lines:

    glUniform3f(glGetUniformLocation(shaderProgram, "uColorC"), 0.0f, 0.0f, 1.0f); // blue

This adds a new variable that the fragment shader can use.

In fragment.glsl, add this declaration:

uniform vec3 uColorC;

Next, in the main function, declare a vec3 called temp, move the value of blendedColor into it, and mix that with uColorC.
The second interpolation runs along the Y axis, and I hold it back a little so that blue doesn't take over completely.

void main() {
  vec3 temp = mix(uColorA, uColorB, vUv.x);
  vec3 blendedColor = mix(temp, uColorC, vUv.y * 0.95);
  out_color = vec4(blendedColor, 1.0);
}

On macOS, make the same change in fragment.mac.glsl too (keep #version 410 core as the first line).
The downloaded fragment.mac.glsl is still the two-color version, so this is where a Mac gets its third color.

The first mix paints the bottom edge from red to green, and the second mix pulls that towards blue the higher you go.
Because the factor is vUv.y * 0.95, even the very top is only 95% blue, and 5% of the bottom color remains.
Let's compute the four corners and the center:

vUv temp blendedColor
(0, 0) (1, 0, 0) (1, 0, 0) red
(1, 0) (0, 1, 0) (0, 1, 0) green
(0, 1) (1, 0, 0) (0.05, 0, 0.95)
(1, 1) (0, 1, 0) (0, 0.05, 0.95)
(0.5, 0.5) (0.5, 0.5, 0) (0.2625, 0.2625, 0.475)

In the center, t=0.5×0.95=0.475, so we get (0.5,0.5,0)×0.525+(0,0,1)×0.475.
If you check the center pixel of the screenshot, it is (67,67,121) in 8 bits, that is 0.2625×255≈67 and 0.475×255≈121, just as computed.

If you did everything right, the result looks like this:

A gradient with red at the bottom left, green at the bottom right and blue at the top

Before moving on, play with vUv.x, vUv.y and calculations on them to understand what happens.
For example, changing vUv.y * 0.95 to vUv.y * vUv.y pushes the blue up towards the top.

3.4 Moving the color values into the shader

The only problem with defining the colors in C is that you have to recompile the C code every time you try a color.
If we move uColorA, uColorB and uColorC into the fragment shader, though, we can test right away without compiling.
Shader files are read at run time, so restarting the program is enough.

So in main.c, comment out the three lines:

    // set the uniforms
    //glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), 1.0f, 0.0f, 0.0f); // red
    //glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), 0.0f, 1.0f, 0.0f); // green
    //glUniform3f(glGetUniformLocation(shaderProgram, "uColorC"), 0.0f, 0.0f, 1.0f); // blue

And in fragment.glsl:

#version 450 core

in vec2 vUv;
out vec4 out_color;

//uniform vec3 uColorA;
//uniform vec3 uColorB;
//uniform vec3 uColorC;

void main() {
  vec3 colorA = vec3(1.0, 0.0, 0.0); // red
  vec3 colorB = vec3(0.0, 1.0, 0.0); // green
  vec3 colorC = vec3(0.0, 0.0, 1.0); // blue

  vec3 temp = mix(colorA, colorB, vUv.x);
  vec3 blendedColor = mix(temp, colorC, vUv.y * 0.95);
  out_color = vec4(blendedColor, 1.0);
}

I use names without the u (colorA and so on) for the local variables.
A name starting with u marks a uniform, and using it for something that isn't a uniform gets confusing later.

Actually, it would work even if you didn't comment out the three lines in C.
When you look up a uniform that doesn't exist in the shader (or isn't used), glGetUniformLocation returns −1, and glUniform3f on location −1 silently does nothing.
Not getting an error is convenient, but it also means nobody tells you when you misspell a uniform name.
When "I set the value but nothing changes", suspect the spelling first.

Now you can see each color change by just restarting the program.
No compiling needed!

  • Windows: when you run with the debugger in Visual Studio (F5), the working directory is the project folder, so the files in the shader folder are read directly. Save the shader, close the window and press F5 again. main.c didn't change, so nothing gets recompiled. If you start glsltester.exe in x64\Debug directly by double-clicking, it can't find the shader folder, so in that case copy the exe to the project root and start it from there.
  • macOS: edit fragment.mac.glsl, not fragment.glsl. On every build, Xcode copies the .mac.glsl files into the shader folder of the build output (the Copy Files build phase), so save and press CMD + R, and it starts with the new shader without recompiling main.c.
  • Unix: build-unix.sh already writes the binary to the project root, so just run ./glsltester again from the project root. There is no need to run the build script again.

To check, let's change the colors.
Set colorA to vec3(1.0, 0.0, 1.0) (magenta), colorB to vec3(1.0, 1.0, 0.0) (yellow) and colorC to vec3(0.0, 1.0, 1.0) (cyan):

  vec3 colorA = vec3(1.0, 0.0, 1.0); // magenta
  vec3 colorB = vec3(1.0, 1.0, 0.0); // yellow
  vec3 colorC = vec3(0.0, 1.0, 1.0); // cyan

Restart the GLSL shader tester without compiling, and you get this:

A gradient with magenta at the bottom left, yellow at the bottom right and cyan at the top

3.5 Color animation

Finally, let's do something more fun.
So far the colors have been static, so let's rotate them over time.

There is a problem, though.
Our shader doesn't know what time it is.
The C program knows the time (glfwGetTime()), so the colors have to be computed in C and passed in as uniforms.
So let's undo the change from the previous section.
(In chapter 5 we'll pass the time itself as a uniform and animate inside the shader.)

In fragment.glsl:

#version 450 core

in vec2 vUv;
out vec4 out_color;

uniform vec3 uColorA;
uniform vec3 uColorB;
uniform vec3 uColorC;

void main() {
  vec3 temp = mix(uColorA, uColorB, vUv.x);
  vec3 blendedColor = mix(temp, uColorC, vUv.y * 0.95);
  out_color = vec4(blendedColor, 1.0);
}

And in main.c, uncomment the three lines:

    // set the uniforms
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), 1.0f, 0.0f, 0.0f); // red
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), 0.0f, 1.0f, 0.0f); // green
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorC"), 0.0f, 0.0f, 1.0f); // blue

Handling the colors as nine loose floats is hard to read, so we use vector.h from the project's include directory.
This header defines small types called Vector2, Vector3 and Vector4.
They are unions, so you can call the same values v.x, v.y, v.z or v.r, v.g, v.b. It's the same idea as swizzling in GLSL.

typedef union {
  struct {
    float x;
    float y;
    float z;
  };
  struct {
    float r;
    float g;
    float b;
  };
} Vector3;

Add the vector.h and math.h headers to main.c, and change the uniform part of the while loop like this:

#include <vector.h>
#include <math.h>
...
    // animate the colors over time
    float time = (float)glfwGetTime();
    float speed = 1.0f; // animation speed
    float phase = 2.0f * 3.14159f / 3.0f; // 120 degree phase offset (for 3 colors)

    // uColorA: red -> green -> blue
    Vector3 colorA;
    colorA.r = sin(time * speed + 0.0f) * 0.5f + 0.5f; // 0.0 to 1.0
    colorA.g = sin(time * speed + phase) * 0.5f + 0.5f;
    colorA.b = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;

    // uColorB: green -> blue -> red
    Vector3 colorB;
    colorB.r = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;
    colorB.g = sin(time * speed + 0.0f) * 0.5f + 0.5f;
    colorB.b = sin(time * speed + phase) * 0.5f + 0.5f;

    // uColorC: blue -> red -> green
    Vector3 colorC;
    colorC.r = sin(time * speed + phase) * 0.5f + 0.5f;
    colorC.g = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;
    colorC.b = sin(time * speed + 0.0f) * 0.5f + 0.5f;

    // set the uniforms
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), colorA.r, colorA.g, colorA.b);
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), colorB.r, colorB.g, colorB.b);
    glUniform3f(glGetUniformLocation(shaderProgram, "uColorC"), colorC.r, colorC.g, colorC.b);

glfwGetTime() returns the number of seconds since GLFW was initialized.
Every channel is computed with the same kind of formula:

c(t)=0.5+0.5sin(st+φ)

s is speed and φ (phi) is the phase, how far the wave is shifted.
sin swings between −1 and 1, so multiplying by 0.5 and adding 0.5 gives the range 0 to 1, which we can use directly as a color.
The three phases are 0, 2π3 (120°) and 4π3 (240°), so the R, G and B waves are shifted by exactly a third of a period.
That's why, when red is at its brightest, green and blue are darker, and over time the brightest channel moves "red → green → blue".
The three colors are the same values in a different order, so the three corners always show different colors.

Let's compute colorA at t=0:

r=0.5+0.5sin0=0.5g=0.5+0.5sin2π3=0.5+0.5×0.866=0.933b=0.5+0.5sin4π3=0.5−0.5×0.866=0.067

Three sines shifted by 120° always add up to 0, so r+g+b is always 1.5.
That's why the brightness stays roughly the same while only the hue rotates.

On Unix, sin lives in the math library, so you need -lm when linking (build-unix.sh already has it).

Now, here's some homework: play with the values.
Change speed, phase and 0.5f and figure out what each one does.

The final result looks like this (a 5-second recording):

One frame of the animation after 2 seconds

3.6 Other gradient shapes

Every gradient so far used vUv.x or vUv.y directly as the mix factor.
Just by changing how we build the factor t, we can give a gradient any shape we like.
Try the shaders in this section by replacing the whole fragment.glsl (they don't use the uniforms, so the C side can stay as it is).

Diagonal gradients

For a gradient from the bottom left to the top right, use the average of x and y as the factor:

#version 450 core

in vec2 vUv;
out vec4 out_color;

void main() {
  vec3 colorA = vec3(0.1, 0.1, 0.4); // navy
  vec3 colorB = vec3(1.0, 0.6, 0.2); // orange

  // 0 at the bottom left, 1 at the top right
  float t = (vUv.x + vUv.y) * 0.5;
  out_color = vec4(mix(colorA, colorB, t), 1.0);
}

For a gradient at any angle, use the dot product from chapter 4 of the linear algebra series.
The dot product with a unit vector 𝐝^ tells us "how far along that direction we are", so we use that value, measured from the center of the screen, as the factor:

t=(𝐮𝐯−(0.5,0.5))⋅𝐝^+0.5,𝐝^=(cosθ,sinθ)

#version 450 core

in vec2 vUv;
out vec4 out_color;

void main() {
  vec3 colorA = vec3(0.1, 0.1, 0.4); // navy
  vec3 colorB = vec3(1.0, 0.6, 0.2); // orange

  float angle = radians(30.0);              // direction of the gradient
  vec2 dir = vec2(cos(angle), sin(angle));  // direction vector of length 1
  float t = dot(vUv - 0.5, dir) + 0.5;      // distance from the center along dir
  t = clamp(t, 0.0, 1.0);
  out_color = vec4(mix(colorA, colorB, t), 1.0);
}

Subtracting a float from a vec2, like vUv - 0.5, subtracts it from every component.
radians converts degrees to radians (degrees×π/180).

clamp(t, 0.0, 1.0) keeps t in the range 0 to 1.
Why do we need it?
With 30°, the top right corner gives (0.5,0.5)⋅(0.866,0.5)+0.5=1.183, which is more than 1.
mix doesn't limit t, so at t=1.183 we get 𝐚+1.183(𝐛−𝐚)=(1.165,0.692,0.163), a color that has "overshot" the orange.
Anything above 1 gets cut off when it's written to the screen, but it isn't the color we wanted.
If you want a gradient to stop at its two end colors, the standard move is to limit the factor with clamp.

Left: the diagonal gradient (x + y) / 2. Right: a 30 degree gradient

Radial gradients

If we use the distance from the center as the factor, we get a circular (radial) gradient.
The distance is the vector length from chapter 3 of the linear algebra series, called length in GLSL:

length(𝐩)=‖𝐩‖=px2+py2

#version 450 core

in vec2 vUv;
out vec4 out_color;

void main() {
  vec3 inner = vec3(1.0, 0.9, 0.5); // color in the center
  vec3 outer = vec3(0.2, 0.0, 0.3); // color outside

  vec2 p = vUv - 0.5;          // put the center at (0, 0)
  p.x *= 800.0 / 600.0;        // so that it stays a circle on a wide window
  float t = length(p) * 2.0;   // 0 in the center, 1 at the top and bottom edges
  t = clamp(t, 0.0, 1.0);
  out_color = vec4(mix(inner, outer, t), 1.0);
}

Without the line p.x *= 800.0 / 600.0;, you get an ellipse instead of a circle.
UVs go from 0 to 1 both horizontally and vertically, but the window is 800 pixels wide and 600 pixels tall, so 0.1 in UV is 80 pixels horizontally and 60 pixels vertically.
Multiplying x by the aspect ratio of the window, 800/600≈1.333, gives x and y the same unit.
I wrote the numbers directly here, which breaks as soon as the window size changes.
In chapter 5 we'll receive the window size as a uniform and fix this properly.

Let's check with numbers.
In the center of the screen, 𝐩=(0,0), so t=0.
In the middle of the top edge, 𝐩=(0,0.5), so t=0.5×2=1.
In the middle of the right edge, 𝐩=(0.5×1.333,0)=(0.667,0), so t=1.333, and clamp turns it into 1.

Left: an ellipse without the aspect ratio fix. Right: a circle with the fix

Smoothing with smoothstep

A linear gradient starts and stops changing abruptly, so you can sometimes see a faint "crease" at its ends.
smoothstep is an S-shaped curve whose slope is 0 at both ends, and it fixes that:

smoothstep(e0,e1,x)=t2(3−2t),t=clamp(x−e0e1−e0,0,1)

If x is at most e0 the result is 0, if it's at least e1 the result is 1, and in between it goes smoothly from 0 to 1.
For example, smoothstep(0,1,0.25) has t=0.25, so it is 0.0625×2.5=0.15625.
A linear ramp would be at 0.25 there, but smoothstep has only moved 0.156.
In the middle, x=0.5, it gives 0.25×2=0.5, the same as linear.

Graph of linear and smoothstep. Smoothstep flattens out at both ends

Let's compare them with the top half of the screen linear and the bottom half smoothstep:

#version 450 core

in vec2 vUv;
out vec4 out_color;

void main() {
  vec3 colorA = vec3(0.1, 0.1, 0.4); // navy
  vec3 colorB = vec3(1.0, 0.6, 0.2); // orange

  float t;
  if (vUv.y > 0.5) {
    t = vUv.x;                         // top half: linear
  } else {
    t = smoothstep(0.0, 1.0, vUv.x);   // bottom half: smoothstep
  }
  vec3 color = mix(colorA, colorB, t);

  // draw a thin line where the halves meet
  if (abs(vUv.y - 0.5) < 0.002) color = vec3(1.0);
  out_color = vec4(color, 1.0);
}

abs is the absolute value.
abs(vUv.y - 0.5) < 0.002 means "vUv.y is within 0.002 of 0.5", which draws a line 2 to 3 pixels tall across the middle of the window.

The top half is a linear gradient, the bottom half a smoothstep gradient

In the bottom half, the end colors stay longer at the left and right, and the change happens quickly in the middle.
If you move e0 and e1 of smoothstep close together (for example smoothstep(0.45, 0.55, vUv.x)), you get a sharp gradient that is almost a hard edge.
This property is extremely useful in chapter 6 for smoothing the edges of shapes (anti-aliasing).

Chaining several colors

By stacking mix calls, you can chain as many colors as you like.
Let's make a sunset with three colors: ground, horizon and sky:

#version 450 core

in vec2 vUv;
out vec4 out_color;

void main() {
  vec3 ground  = vec3(0.05, 0.04, 0.08);
  vec3 horizon = vec3(1.0, 0.55, 0.25);
  vec3 sky     = vec3(0.15, 0.2, 0.5);

  vec3 color = mix(ground, horizon, smoothstep(0.25, 0.32, vUv.y));
  color = mix(color, sky, smoothstep(0.32, 0.9, vUv.y));
  out_color = vec4(color, 1.0);
}

The first mix switches from the ground to the horizon color in the narrow range where vUv.y is 0.25 to 0.32, and the second mix fades to the sky color over the wide range 0.32 to 0.9.
A narrow smoothstep range gives a crisp boundary, a wide one gives a soft one.

A sunset gradient with dark ground, an orange horizon and a blue sky

3.7 GLSL features used in this chapter

  • mix(a, b, t): a(1−t)+bt. Linear interpolation. Works component-wise on vectors and does not limit t.
  • clamp(x, lo, hi): min(max(x,lo),hi). Keeps a value inside a range.
  • smoothstep(e0, e1, x): t2(3−2t), where t is x mapped from e0 to e1 onto 0 to 1 and clamped.
  • length(v): the length of a vector, x2+y2 (plus z2 in 3D).
  • dot(a, b): the dot product axbx+ayby. The dot product with a unit vector is the component along that direction.
  • sin(x), cos(x): take the angle in radians. radians(deg) converts degrees to radians.
  • abs(x): the absolute value.
  • in/out: pass values between stages. Names and types must match.
  • smooth/noperspective/flat: qualifiers that change how values are interpolated.
  • uniform: a value set from C with glUniform* that stays constant during a draw. Setting a uniform that doesn't exist is silently ignored.

3.8 How games and engines use this

Gradients and interpolation hide in almost every part of a game's screen.

  • Skies: many games draw the sky as a two- or three-color gradient. Use the y component of the view direction as the factor, and looking up gives you the sky color, looking down the horizon color.
  • Fog: use the distance from the camera as the factor and mix the object's color towards the fog color. It's an old technique that makes distant things slowly melt into the air.
  • Vertex colors: games from the PlayStation era often stored colors on the vertices instead of using textures, and let the rasterizer's interpolation paint the faces. Even today, engines put non-color data on vertices (terrain blend weights, how much grass sways) and let it interpolate.
  • UI: buttons, health bars, text shadows. The "remaining amount" of a bar is classically made with step or smoothstep.
  • Screen effects: a fade in or out is just "mix the screen color towards black". The red flash when you take damage is the same thing.
  • Values that move over time: the sine formula from this chapter drives blinking items, UI that glows as if breathing, wobbling water and every other "wiggle" in a game.

3.9 Summary

  • The vertex shader runs once per vertex, the fragment shader once per pixel.
  • The rasterizer interpolates the vertex shader's out variables with barycentric weights and passes them to the fragment shader's in variables.
  • mix(a, b, t) is a(1−t)+bt, the same as lerp from linear algebra.
  • By changing how the factor t is built you get horizontal, vertical, diagonal (dot), radial (length) and other gradients.
  • mix doesn't limit t, so clamp it when it can leave the range.
  • smoothstep is an S-curve with zero slope at both ends, used for smooth transitions.
  • Shaders are read at run time, so shader-only changes can be tested without recompiling C.
  • Values that change over time can be computed in C and passed as uniforms (in chapter 5 we pass the time itself).

3.10 Challenges

  1. ★ In the two-color shader (red to green), compute by hand the color of the pixel where vUv.x = 0.75. Then, in the three-color shader, compute the colors at vUv = (0.5, 0) and vUv = (0.5, 1).
  2. ★ Compute smoothstep(0.0, 1.0, 0.75) and smoothstep(2.0, 4.0, 3.0) by hand (hint: for the second one, find t first).
  3. ★★ Make the gradient vertical. Red should be at the bottom and green at the top, with no change in color horizontally.
  4. ★★ Write a shader with a different color in each corner (for example red bottom left, green bottom right, blue top left, white top right). Hint: mix along the bottom edge and the top edge separately, then mix those two with vUv.y. Each corner should be exactly its color, and the center should be the average of the four, the gray (0.5,0.5,0.5).
  5. ★★ Turn the radial gradient into a "ring". Only the places at distance 0.3 from the center should be bright, getting darker the farther you are from that distance (hint: abs(length(p) - 0.3)).
  6. ★★ Predict what happens when you set phase to 0.0f in main.c, then try it. All channels get the same value, so the whole screen should stay gray and pulse between black and white.
  7. ★★★ The middle of the red-to-green mix, (0.5,0.5,0), looks like a slightly dark, muddy yellow. Find out why (keywords: sRGB, gamma). Then convert the colors into "linear space" with pow(color, vec3(2.2)) before the mix, convert back with pow(result, vec3(1.0 / 2.2)), and compare how the middle changes. Chapter 10 covers gamma in detail.

Download the diff

ファイル: a/main.c | b/main.c

前新
@@ -9,6 +9,8 @@
9 #include <GLFW/glfw3.h> 9 #include <GLFW/glfw3.h>
10 #include <stdio.h> 10 #include <stdio.h>
11 #include <stdlib.h> 11 #include <stdlib.h>
    12 #include <vector.h>
    13 #include <math.h>
12   14  
13 // ファイルパスを構築(プラットフォームに応じて) 15 // ファイルパスを構築(プラットフォームに応じて)
14 char *constructFilePath(const char *basePath) { 16 char *constructFilePath(const char *basePath) {
@@ -229,9 +231,33 @@ int main(int argc, char **argv) {
229 // シェーダープログラムを使用 231 // シェーダープログラムを使用
230 glUseProgram(shaderProgram); 232 glUseProgram(shaderProgram);
231   233  
    234 // 時間に基づいて色をアニメーション
    235 float time = (float)glfwGetTime();
    236 float speed = 1.0f; // アニメーションの速度
    237 float phase = 2.0f * 3.14159f / 3.0f; // // 120度の位相差(3色用)
    238  
    239 // uColorA: 赤 -> 緑 -> 青
    240 Vector3 colorA;
    241 colorA.r = sin(time * speed + 0.0f) * 0.5f + 0.5f; // 0.0 to 1.0
    242 colorA.g = sin(time * speed + phase) * 0.5f + 0.5f;
    243 colorA.b = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;
    244  
    245 // uColorB: 緑 -> 青 -> 赤
    246 Vector3 colorB;
    247 colorB.r = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;
    248 colorB.g = sin(time * speed + 0.0f) * 0.5f + 0.5f;
    249 colorB.b = sin(time * speed + phase) * 0.5f + 0.5f;
    250  
    251 // uColorC: 青 -> 赤 -> 緑
    252 Vector3 colorC;
    253 colorC.r = sin(time * speed + phase) * 0.5f + 0.5f;
    254 colorC.g = sin(time * speed + 2.0f * phase) * 0.5f + 0.5f;
    255 colorC.b = sin(time * speed + 0.0f) * 0.5f + 0.5f;
    256  
232 // ユニフォームを設定 257 // ユニフォームを設定
233 glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), 1.0f, 0.0f, 0.0f); // 赤 258 glUniform3f(glGetUniformLocation(shaderProgram, "uColorA"), colorA.r, colorA.g, colorA.b); // 赤
234 glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), 0.0f, 1.0f, 0.0f); // 緑 259 glUniform3f(glGetUniformLocation(shaderProgram, "uColorB"), colorB.r, colorB.g, colorB.b); // 緑
    260 glUniform3f(glGetUniformLocation(shaderProgram, "uColorC"), colorC.r, colorC.g, colorC.b); // 青
235   261  
236 // クアッドを描画 262 // クアッドを描画
237 glBindVertexArray(VAO); 263 glBindVertexArray(VAO);

ファイル: a/shader/fragment.glsl | b/shader/fragment.glsl

前新
@@ -5,8 +5,10 @@ out vec4 out_color;
5   5  
6 uniform vec3 uColorA; 6 uniform vec3 uColorA;
7 uniform vec3 uColorB; 7 uniform vec3 uColorB;
    8 uniform vec3 uColorC;
8   9  
9 void main() { 10 void main() {
10 vec3 blendedColor = mix(uColorA, uColorB, vUv.x); 11 vec3 temp = mix(uColorA, uColorB, vUv.x);
    12 vec3 blendedColor = mix(temp, uColorC, vUv.y * 0.95);
11 out_color = vec4(blendedColor, 1.0); 13 out_color = vec4(blendedColor, 1.0);
12 } 14 }

ファイル: a/shader/fragment.mac.glsl | b/shader/fragment.mac.glsl

前新
@@ -5,8 +5,10 @@ out vec4 out_color;
5   5  
6 uniform vec3 uColorA; 6 uniform vec3 uColorA;
7 uniform vec3 uColorB; 7 uniform vec3 uColorB;
    8 uniform vec3 uColorC;
8   9  
9 void main() { 10 void main() {
10 vec3 blendedColor = mix(uColorA, uColorB, vUv.x); 11 vec3 temp = mix(uColorA, uColorB, vUv.x);
    12 vec3 blendedColor = mix(temp, uColorC, vUv.y * 0.95);
11 out_color = vec4(blendedColor, 1.0); 13 out_color = vec4(blendedColor, 1.0);
12 } 14 }


コメント(0)

まだコメントはありません。