TExcelTAD

GLSL Basics

GLSL (the OpenGL Shading Language) looks like C: semicolons, braces, if, for, functions with typed parameters. What makes it different is that vectors and matrices are built-in types, math functions work on whole vectors at once, and the compiler is strict about types. The playgrounds use GLSL ES 3.00, the version in WebGL2. Desktop OpenGL uses GLSL 3.30–4.60, and Vulkan accepts GLSL 4.50+ compiled to SPIR-V; the core syntax is the same.

Types

Type What it holds Example
float, int, uint, bool scalars float speed = 2.0; uint mask = 3u;
vec2, vec3, vec4 2–4 floats vec3 color = vec3(1.0, 0.5, 0.0);
ivec2..4, uvec2..4, bvec2..4 int, uint and bool vectors ivec2 cell = ivec2(3, 4);
mat2, mat3, mat4 (and mat2x3 …) column-major float matrices mat2 rot = mat2(c, s, -s, c);
sampler2D, samplerCube … texture handles (uniforms only) uniform sampler2D uAlbedo;
arrays and struct fixed-size groups float weights[5]; struct Hit { float t; vec3 n; };

Constructors are flexible: they take any mix of scalars and vectors as long as the component count adds up.

glsl
vec4 a = vec4(1.0);                 // (1, 1, 1, 1): one scalar fills every component
vec4 b = vec4(vec2(0.1, 0.2), 0.3, 1.0);
vec3 c = vec3(b);                   // drops the extra component: (0.1, 0.2, 0.3)
mat2 m = mat2(1.0);                 // identity matrix
float f = float(7);                 // explicit int -> float conversion

Swizzling

Vector components can be read and written by name, in any order and with repeats. The three name sets are interchangeable aliases: xyzw (positions), rgba (colors) and stpq (texture coordinates). You can't mix sets in one swizzle (v.xg is an error).

glsl
vec4 v = vec4(1.0, 2.0, 3.0, 4.0);
vec2 p = v.xy;      // (1, 2)
vec3 r = v.zyx;     // (3, 2, 1)
vec4 d = v.xxyy;    // (1, 1, 2, 2)
v.rg = vec2(0.0);   // write two components at once

Swizzles cost nothing on GPUs; use them freely. This shader builds one gradient and shows it four ways by swizzling:

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    vec3 base = vec3(uv, 0.25);                   // (x, y, constant)

    vec3 color;
    if (uv.x < 0.25)      color = base.xyz;
    else if (uv.x < 0.5)  color = base.zxy;       // rotate the channels
    else if (uv.x < 0.75) color = base.yyy;       // grey from the y component
    else                  color = base.bgr;       // same data, rgba names, reversed

    fragColor = vec4(color, 1.0);
}

Operators work on vectors

Arithmetic is component-wise: vec3 * vec3 multiplies x by x, y by y, z by z, and a scalar applies to every component. The one exception is matrices: mat * vec and mat * mat are true linear-algebra products, and component-wise matrix products need matrixCompMult.

glsl
vec3 a = vec3(1.0, 2.0, 3.0);
vec3 b = a * 2.0;              // (2, 4, 6)
vec3 c = a * vec3(0.5);        // (0.5, 1, 1.5)
float d = dot(a, vec3(1.0));   // 6: dot product is a function, not an operator
mat2 rot = mat2(0.0, 1.0, -1.0, 0.0);   // columns (0,1) and (-1,0): 90° rotation
vec2 e = rot * vec2(1.0, 0.0);          // (0, 1)

The built-in function toolbox

These functions accept floats or vectors (component-wise) and are fast, many of them single GPU instructions. You will see them in nearly every shader:

Function Meaning
abs sign floor ceil fract mod min max the usual; fract(x) = x - floor(x), mod(x, y) is the floored remainder (positive for negative x)
clamp(x, lo, hi) limit to a range
mix(a, b, t) linear interpolation a*(1-t) + b*t (GLSL's lerp)
step(edge, x) 0.0 if x < edge, else 1.0
smoothstep(e0, e1, x) smooth 0→1 ramp between e0 and e1 (Hermite 3t² - 2t³)
length distance dot cross normalize reflect refract vector geometry
sin cos tan asin acos atan pow exp log sqrt inversesqrt math; atan(y, x) is the two-argument form
dFdx dFdy fwidth how fast a value changes to the neighboring pixel (fragment shaders only)

step and smoothstep replace most if statements in shader code. Here three horizontal bands show step, smoothstep and mix applied to the same x:

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    float x = uv.x;
    float edge = 0.5 + 0.3 * sin(iTime);

    float v;
    if (uv.y > 0.66)      v = step(edge, x);                       // hard edge
    else if (uv.y > 0.33) v = smoothstep(edge - 0.2, edge + 0.2, x); // soft edge
    else                  v = x;                                   // a plain ramp

    vec3 color = mix(vec3(0.1, 0.1, 0.3), vec3(1.0, 0.8, 0.3), v);
    fragColor = vec4(color, 1.0);
}

Functions and parameter qualifiers

Functions must be declared before they are called (or prototyped), and recursion is not allowed. Parameters are copied in by default. out parameters are written by the function, and inout ones are both read and written. That is why mainImage declares out vec4 fragColor: it is the function's result.

glsl
void polar(in vec2 p, out float radius, out float angle) {
    radius = length(p);
    angle = atan(p.y, p.x);
}

void wrapAngle(inout float a) {
    a = mod(a, 6.2831853);
}

Strict types: no implicit int → float

GLSL ES does not convert an int to a float for you. 1 is an int and 1.0 is a float, and assigning one to the other is a compile error. (Desktop GLSL 4.x allows a few implicit conversions, which is why shaders copied from a desktop project sometimes fail in WebGL.) Run this:

glsl · try it yourself
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    vec2 uv = fragCoord / iResolution.xy;
    float brightness = 1;
    fragColor = vec4(uv * brightness, 0.0, 1.0);
}
Shader compile error:
ERROR: line 3: '=' : cannot convert from 'const int' to 'highp float'

Write 1.0 (or float(1)) and it compiles. The same rule applies to calls and operators: pow(x, 2) and color * 2 are errors when x and color are floats. Constructors are the exception: vec3(1, 0, 0) converts its int arguments. The habit that avoids all of this is simple: write float literals with a decimal point.

Precision qualifiers

GLSL ES has highp, mediump and lowp. Fragment shaders have no default float precision, so a complete ES shader must say precision highp float; (or mediump) at the top; the Shadertoy-style playground adds it for you. On desktop GPUs all three behave as 32-bit floats. On many mobile GPUs mediump is 16-bit, about 3 decimal digits, which is faster and enough for colors, but too little for positions, time and UVs on big textures. The Field Notes lesson shows the classic failure.

A complete ES shader, annotated

glsl
#version 300 es              // must be the very first line: WebGL2 = GLSL ES 3.00
precision highp float;       // required default precision in fragment shaders

uniform float uTime;         // set by the host each draw
in vec2 vUv;                 // interpolated from the vertex shader
out vec4 outColor;           // the color written to the framebuffer (location 0)

void main() {
    outColor = vec4(vUv, 0.5 + 0.5 * sin(uTime), 1.0);
}

Test yourself

What is vec4(1.0, 2.0, 3.0, 4.0).wzx?

  1. (1, 2, 3)
  2. (4, 3, 1)
  3. (4, 3, 2)
  4. A compile error

Why does float k = 2; fail to compile in GLSL ES 3.00?

  1. k is a reserved word
  2. Integer literals are not implicitly converted to float
  3. Floats must be declared const
  4. Missing precision

What does smoothstep(0.4, 0.6, x) return for x = 0.7?

  1. 0.0
  2. 0.5
  3. 1.0
  4. 0.7