SKP
Get in touch

JOURNAL 02

SHADERS FOR APP DEVELOPERS.

What I wish someone had told me before my first fragment shader. Not a tutorial — a list of the assumptions from application code that you need to put down.

Entry
02
Subject
GLSL
Assumes
You write JS
Difficulty
Conceptual
Glass sphere holding a miniature illuminated city, a whole world produced by one fragment shader
Concept render — a whole world inside one sphere

//You're writing one pixel's worth of code#

This is the mental shift everything else follows from. Your fragment shader doesn't draw a shape. It answers a single question — "given this pixel's coordinates, what colour are you?" — and the GPU asks it for every pixel simultaneously. You never loop over pixels because you're already inside the loop, and you have no idea what your neighbours decided.

That's why drawing a circle feels so strange at first. You don't draw it; you compute the distance from this pixel to a centre point and decide whether that distance is inside a radius. Shapes become distance functions, and once that clicks, a surprising amount of graphics work turns into arithmetic you can reason about.

//Branches are not free#

Pixels are processed in groups that execute in lockstep. If some pixels in a group take one side of an if and some take the other, the hardware may run both sides and throw half the results away. A conditional that costs nothing in JavaScript can double a shader's cost. You learn to replace branches with arithmetic — mix(), step(), smoothstep() — which produces the same result with no divergence.

//There is no debugger#

No console, no breakpoints, no stack trace. Your only output is a colour, so debugging means assigning the value you're suspicious about to the output and looking at the picture. Surface normals as RGB, depth as greyscale, UV coordinates as a red-green gradient. It sounds primitive and becomes a genuinely fast way to work, because you see the whole field of values at once rather than one sampled instance.

Last thing: precision differs between devices. A shader that's stable on a desktop card can band or shimmer badly on a phone using lower-precision floats. Test on the target hardware early, not at the end.

Fig. 31 — glsl, fragment shader, sdf