pburke.dev — Blog

Shaders (Part 1)

Shaders are great. They can make beautiful images, from fills, patterns, and basic graphics through stylized or realistic three-dimensional scenes, fractals, and dynamical systems.

A shader is just a program that runs on a GPU. Shader programs are written in a C-like language such as GLSL.

When creating some sort of graphic, usually the shader implements a pure function like this: F(x,y) = (r,g,b)

which is saying, for some point (x,y), define the colour of that pixel in terms of (r,g,b) (red green and blue).

First Shader - Red Screen

This function returns red for every pixel. You can also modify it to see what the change does for yourself.

vec3 mainImage(vec2 p) {
    return vec3(1.0, 0.0, 0.0);
}

You will note that it doesn't use p at all - there is no variation with what space on the screen it is. You can change the colour to blue, cyan, dark red, etc and see that it works. Congratulations, shader programmer.

Second Shader - Gradient

This function returns a sweep along the x axis for green and along the y axis for blue. Since p is -1.0...1.0 by convention you will observe that the negative quadrant is simply black.

vec3 mainImage(vec2 p) {
    return vec3(0.0, p.x, p.y);
}

You can change the sign of p.x / p.y, or if you are feeling ambitious see what abs(p.x) does, etc.

Third Shader - Flag thing

This just demonstrates cutting the space into pieces with math. The diagonal seapration? p.x > p.y. The circle? The circle formula: x^2 + y^2 = r^2.

// p is normalized to between -1.0 and 1.0.
vec3 mainImage(vec2 p) {
    vec3 green_white = p.x > p.y
        ? vec3(0.0, 1.0, 0.0)
        : vec3(1.0, 1.0, 1.0);
    return sqrt(p.x*p.x + p.y*p.y) < 0.5
        ? green_white
        : vec3(1.0, 0.0, 0.0);
}

Change any of the colours or parameters and see the results.

Fourth Shader - With time

A host program can bind other variables, such as time (t in this example).

uniform float t;
const float speed = 5.0;

// p is normalized to between -1.0 and 1.0.
vec3 mainImage(vec2 p) {
    float p_r = length(p);
    float p_theta = atan(p.y, p.x);
    p_theta += t * speed;
    vec2 p_rotated = p_r * vec2(cos(p_theta), sin(p_theta));
    vec3 green_white = p_rotated.x > p_rotated.y
        ? vec3(0.0, 1.0, 0.0)
        : vec3(1.0, 1.0, 1.0);
    return sqrt(p.x*p.x + p.y*p.y) < 0.5
        ? green_white
        : vec3(1.0, 0.0, 0.0);
}

Edit speed and see the results