Shaders From Zero · Episode 02

GLSL Essentials

GLSL Essentials is Episode 02 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 02 · Shaders From Zero

Episode 01 showed you the structure: vertex shader, fragment shader, three kinds of input, one output each. This episode shows you the language. By the end of it you can open any shader on Shadertoy, read it line by line, and know what every symbol means — no more squinting at v.xxyz wondering whether that's a typo.

GLSL is small. The whole language fits in a single afternoon. We're going to cover its types, its one weird trick (swizzles), the half-dozen built-in functions you'll use forever, and the strictness rules that catch every beginner. The demo below visualises five of those functions one at a time, on the same flat quad, so you can see exactly what each one does to a coordinate.

Open it. Step through the five stages while you read.

0 fps
ShaderMaterial · GLSL
mix(a, b, vUv.x) — the linear blend that powers every gradient.

Types — the GLSL number tower

GLSL has a very small set of primitive types. You will use the same five or six over and over for the rest of your shading life:

TypeWhat it holdsConstructor
floatA single 32-bit number.float t = 0.5;
intA signed integer. Rare in pixel math.int i = 3;
boolA true/false value.bool hit = true;
vec2Two floats. UVs, screen positions, 2D vectors.vec2(0.5, 0.25)
vec3Three floats. RGB colors, 3D positions, normals.vec3(1.0, 0.4, 0.1)
vec4Four floats. RGBA colors, homogeneous positions.vec4(0.0, 0.0, 0.0, 1.0)
mat2, mat3, mat4Square matrices. We'll use them in later episodes.mat2(1.0, 0.0, 0.0, 1.0)

Vector constructors are flexible. You can pass a single scalar to fill every component, or pass smaller vectors to build a bigger one:

vec2 a = vec2(0.5);                // (0.5, 0.5)
vec3 b = vec3(1.0, 0.4, 0.1);       // (1.0, 0.4, 0.1)
vec4 c = vec4(b, 1.0);              // (1.0, 0.4, 0.1, 1.0)
vec4 d = vec4(a, a);                // (0.5, 0.5, 0.5, 0.5)
vec3 e = vec3(0.0);                // black

Arithmetic on vectors is component-wise. vec3(1.0, 2.0, 3.0) * 2.0 is vec3(2.0, 4.0, 6.0). vec3(1.0, 2.0, 3.0) + vec3(10.0) is vec3(11.0, 12.0, 13.0). This is half of why GLSL is so terse.

Takeaway: if you can read those five vector lines fluently, half of every shader you'll ever see is already legible.

Swizzles — the GLSL superpower

The other half is swizzles. Every vec2, vec3, and vec4 exposes its components as fields you can read in any order, repeating allowed:

vec4 p = vec4(1.0, 2.0, 3.0, 4.0);

p.x          // 1.0
p.y          // 2.0
p.zw         // vec2(3.0, 4.0)
p.xyz        // vec3(1.0, 2.0, 3.0)
p.wzyx       // vec4(4.0, 3.0, 2.0, 1.0) — reversed
p.xxx        // vec3(1.0, 1.0, 1.0) — repeated

There are three sets of names for the same four slots — pick whichever reads best for the situation:

SetSlotsBest for
.x .y .z .wpositionsgeometry, math
.r .g .b .acolorscolor tweaks
.s .t .p .qtexture coordstexture sampling (rare in practice)

The sets are aliases. p.x and p.r are the same memory. You'll see color.rgb and position.xyz used in the same file all the time — that's normal, and the reader's brain just absorbs which set fits which context.

You can also write with swizzles, as long as you don't repeat a component on the left side:

vec3 color = vec3(0.5);
color.rg = vec2(1.0, 0.0);   // red=1, green=0, blue still 0.5
color.bgr = color.rgb;          // flips R and B channels

That last line is the entire implementation of a "swap red and blue" effect. Swizzles are pure syntactic sugar, but they're the difference between shader code that reads like poetry and shader code that reads like a tax form.

Takeaway: .xy, .xyz, .rgb, and .xxx account for 90% of all swizzles you'll ever see. Recognize them on sight.

The three I/O kinds (quick recap)

Episode 01 covered the three flavors of input — quick reminder, because every line of GLSL below has to be one of them:

  • attribute — per-vertex, e.g. position, uv. Auto-declared by ShaderMaterial.
  • uniform — per-draw, e.g. uTime, a color, a matrix. You add these from JS.
  • varying — bridge from vertex to fragment, smoothly interpolated. Most commonly vUv.

If you need to refresh, jump back to Episode 01. Everything below assumes you can sort GLSL declarations into those three buckets at a glance.

The five functions that appear in 90% of all shaders

GLSL has a long list of built-ins — sines, cosines, exponentials, geometric operations, all the math you'd expect. But five functions show up in essentially every shader, and once you've internalized them you can read 90% of the code on Shadertoy without looking anything up.

mix(a, b, t) — linear interpolation

The single most useful function in graphics. mix blends between two values: when t = 0.0 you get a, when t = 1.0 you get b, anything in between is a straight linear blend.

// signature: genType mix(genType a, genType b, float t)
// equivalent to: a * (1.0 - t) + b * t

vec3 warm = vec3(0.95, 0.4, 0.2);
vec3 cool = vec3(0.2, 0.5, 0.95);
vec3 col  = mix(warm, cool, vUv.x);  // horizontal gradient

Stage 1 in the demo is exactly this. Two colors, one blend factor, an entire gradient in one line. mix works on float, every vec type, and even matrices — anywhere you have "two things and a number between them," it's the right tool.

step(edge, x) — hard cutoff

Returns 0.0 if x < edge and 1.0 otherwise. No anti-aliasing, no smoothing — it's a switch.

// signature: genType step(genType edge, genType x)

float mask = step(0.5, vUv.x);      // 0 on left half, 1 on right half
gl_FragColor = vec4(vec3(mask), 1.0); // black-white split

Stage 2 in the demo. Look closely at the edge: it's jagged. That's not a bug, that's how step works — for every pixel, either you cross the threshold or you don't, and there's no in-between. Useful as a building block, terrible as a final output.

smoothstep(e0, e1, x) — Hermite-smoothed cutoff

The anti-aliased cousin of step. Returns 0.0 below e0, 1.0 above e1, and a Hermite-smoothed S-curve in between. The transition has continuous derivatives at both ends, so edges look soft and natural.

// signature: genType smoothstep(genType e0, genType e1, genType x)
// note the argument order: e0 first, e1 second, x THIRD

float mask = smoothstep(0.45, 0.55, vUv.x);  // 10%-wide soft edge
gl_FragColor = vec4(vec3(mask), 1.0);

Stage 3 in the demo. Same cutoff as Stage 2, but now the edge has a soft band where the value ramps from 0 to 1. The width of that band is e1 - e0. Make it wider, the edge feathers more; make it narrower, you approach the look of step.

This is the function you reach for whenever you need a visible edge in a shader. Circles, rectangles, fades, glows — they all live on top of smoothstep.

fract(x) — fractional part

Returns just the bit after the decimal point. fract(3.7) = 0.7, fract(0.25) = 0.25, fract(5.0) = 0.0.

// signature: genType fract(genType x)

float band = fract(vUv.x * 6.0);     // six ramps from 0 to 1 across the surface
gl_FragColor = vec4(vec3(band), 1.0);

Stage 4 in the demo. vUv.x goes 0 to 1; multiplying by 6 stretches it to 0 to 6; fract takes only the after-decimal part, so it ramps from 0 to 1, six times. Add uTime inside and the bands slide.

This is the basis of every tiled, repeating, or "scrolling stripes" effect you've ever seen. Anytime you want something to repeat in a shader, fract is the first thing you reach for.

mod(x, y) — modulo

The remainder after dividing x by y. mod(7.0, 3.0) = 1.0. mod(0.5, 0.3) = 0.2.

// signature: genType mod(genType x, genType y)

float band = mod(vUv.y * 4.0, 0.7);    // repeats every 0.7

For integer y, mod(x, y) looks identical to fract(x / y) * y. But for non-integer y they differ — mod gives you a configurable period, fract always wraps at 1.0.

Power-user note: GLSL's mod uses floored division, so mod(-0.5, 1.0) = 0.5 — positive, even for negative inputs. JavaScript's % operator uses truncated division and returns -0.5 for the same inputs. Same name, different sign convention. If you're porting a math formula from JS to GLSL and it works for positive inputs but breaks at the edges of your screen, this is why.

Stage 5 shows the two side by side: fract on the left half, mod with a 0.7 period on the right. Notice the right side has a hard discontinuity at vUv.y * 4.0 = 0.7, 1.4, 2.1... — that's the modulo wrapping.

Takeaway: mix blends, step cuts hard, smoothstep cuts soft, fract repeats at 1.0, mod repeats at any period. Five tools, infinite combinations.

Other built-ins worth knowing

Past the big five, a second tier of functions shows up constantly. You don't need to memorize them — just know they exist so you can search efficiently:

FunctionWhat it does
length(v)Magnitude of a vector. sqrt(dot(v, v)).
distance(a, b)Same as length(a - b).
normalize(v)Divides by length, returns a unit vector.
dot(a, b)Dot product. Workhorse of lighting and projections.
cross(a, b)Cross product. vec3 only.
abs(x)Absolute value. Component-wise on vectors.
sign(x)-1, 0, or +1 depending on sign of x.
floor(x), ceil(x)Round down, round up.
min(a, b), max(a, b)Smaller / larger, component-wise.
clamp(x, lo, hi)min(max(x, lo), hi). Locks x into a range.
pow(x, y)x to the power y. Gamma curves, falloffs.
sin(x), cos(x)Trig in radians. Always in radians.
exp(x), log(x)Natural exponent / log.

Every one of these is component-wise on vectors. abs(vec3(-1.0, 2.0, -3.0)) is vec3(1.0, 2.0, 3.0). sin(vec2(0.0, 3.14)) is vec2(0.0, 0.0). This is the second big reason GLSL is so terse.

Takeaway: most "math you'd want" is already a one-call built-in. Before you write a loop or a helper, check whether the function you want already exists — it usually does.

Type strictness — the most common compile error

GLSL is stricter about types than JavaScript or Python. The compiler will happily reject your shader for the most innocent-looking expressions, and the error messages can be cryptic. The single most common cause: integer literals where floats are expected.

vec3 c = vec3(1, 0, 0);    // sometimes errors: int args to a float ctor
float t = 1;                // usually errors: int → float without cast
float u = 1.0;              // always fine

vec3 c1 = vec3(1.0, 0.0, 0.0); // always fine
float r = vec3(1.0).r * 2;       // risky — "2" is an int
float r2 = vec3(1.0).r * 2.0;     // safe

WebGL2's GLSL is slightly more forgiving than WebGL1's, but Three.js's ShaderMaterial targets WebGL1 by default and auto-upgrades only parts of it. Treat every numeric literal in your shader as needing a decimal point. If your shader won't compile, search for missing dots first.

The other strictness rule worth knowing: you cannot mix int and float in an expression without an explicit cast. 1 + 1.0 is an error. float(1) + 1.0 is fine. So is 1.0 + 1.0. Most beginners avoid the issue by never using int at all in their pixel math.

Takeaway: when in doubt, add a .0. Cost is one keystroke, payoff is hours of saved debugging.

Common first-day pitfalls

  • Mixing int and float without explicit conversion. float t = 1; is an error. So is 2 * vUv.x in many contexts. Write 1.0, 2.0, 0.5 — never bare integers in numeric expressions.
  • Using % instead of mod(). GLSL does not have a % operator on floats — it only exists for ints in GLSL 3.00, and even then it behaves like C, not like JS. Use mod(x, y) and remember its sign convention.
  • Forgetting that step has no anti-aliasing. It gives perfectly jagged edges. Beautiful for masks you'll combine later, ugly for anything you show the user. If you can see the edge, smoothstep almost always wins.
  • Confused smoothstep argument order. It's smoothstep(e0, e1, x) — edges first, value last. The very common mistake is smoothstep(x, e0, e1), which compiles fine and gives you garbage. If a soft-edged shape looks wrong, this is the first thing to check.
  • Swizzle typos. .xyz, .zyx, .xxz — they all compile. A typo silently swaps your color channels or your axes. If the output is wrong but plausible, suspect a swizzle.
  • Returning a vec3 to gl_FragColor. gl_FragColor is a vec4. gl_FragColor = col; where col is a vec3 is an error — wrap it: gl_FragColor = vec4(col, 1.0);.

Exercises

  1. Modify Stage 1 to use vUv.y instead of vUv.x as the mix factor. Predict what you'll see before you switch.
  2. Stage 3 has a 10%-wide soft edge. Change it to a 40%-wide edge, then a 1%-wide edge. Notice how a 1% edge looks almost identical to step — smoothstep is step when the edges are close together.
  3. In Stage 4, replace fract(vUv.x * 6.0) with abs(fract(vUv.x * 6.0) - 0.5) * 2.0. You should get triangle waves (ramp up, ramp down) instead of sawtooth (ramp up, jump to zero). Why does that formula work? Walk through it for vUv.x * 6.0 = 2.3.

What's next

Episode 03 — UVs Are Everything. We've been treating vUv as a "two numbers from 0 to 1" since the start. Next episode we take it seriously: centering it on the origin, converting it to polar coordinates, tiling it, scaling it, warping it. Almost every shader you'll ever write is, at heart, a function from vUv to a color — and knowing how to bend that input is more than half the battle.