graphicsshaders

webgl + glsl

the pipeline from vertex to pixel, and fragment shaders from gradients to raymarching, with a playground.

report a mistake
.md

the gpu runs one small program per vertex and another per pixel, many at once. glsl is the language you write them in, and webgl is how the browser hands them over.

per vertex
vertex shader writes gl_Position
per pixel
fragment shader writes a color
line 1
#version 300 es nothing before it, not even a blank line
fullscreen
3 vertices one big triangle, clipped to the canvas
live contexts
16 in chromium, 8 on android
reach for it
  • backgrounds and gradients
  • procedural textures
  • image effects and transitions
  • particles and simulations
on this page
  1. the pipeline
  2. attributes, uniforms and varyings
  3. uv space
  4. fullscreen quad
  5. gradients
  6. noise
  7. signed distance functions
  8. raymarching
  9. dissolve
  10. distortion
  11. feedback buffers
  12. gpgpu particles
  13. shadermaterial in three.js
  14. pitfalls
  15. sources

webgl is the browser’s interface to the gpu. webgl 2 follows opengl es 3.0, and takes shaders written in glsl es 3.00 as well as the older 1.00. this page uses 3.00 throughout.1 you hand it two small programs, a vertex shader that runs once per vertex and a fragment shader that runs once per pixel, plus the data they run on. most of this sheet is fragment shaders on a rectangle that fills the canvas: that’s how gradients, noise, distance fields and raymarching get drawn.

0.0 s

compiles as you type

a glsl playground: a fragment shader editor and its output on a canvas, drawn with webgl 2. sixteen examples load from a menu, one or more for each section below: uv, three gradients, four kinds of noise, three distance fields, a raymarched sphere, a dissolve and three distortions. the shader gets three uniforms, u_resolution, u_time and u_pointer. time is paused at 0 until you press play, and a slider scrubs it. a compile error shows under the editor with its line number, and the last picture that compiled stays up.

edit the shader and the picture follows. drag on the picture to move u_pointer.

the shaders in the figures further down are all examples here, and each of those figures has a link to open its shader in the playground. the vertex shader is the fullscreen quad from further down, so only the fragment shader is yours. three uniforms come in: u_resolution is the canvas in pixels, u_time is seconds, paused at 0 until you press play, and u_pointer is where you last pressed or dragged, in pixels with y up.

the pipeline

a draw call sends vertices down a fixed chain. the vertex shader runs once per vertex and writes gl_Position, a point in clip space. the gpu groups the vertices into triangles, clips them to the visible volume, divides by w, and maps the result onto the canvas.2 the rasterizer then finds the pixels whose centers fall inside each triangle, and each of those is a fragment.3 the fragment shader runs once per fragment and writes its color, which can be depth tested and blended on its way into the framebuffer.

#version 300 es
// the vertex shader: one point in, its place in clip space out
layout(location = 0) in vec2 a_position;

void main() {
  gl_Position = vec4(a_position, 0.0, 1.0);
}
#version 300 es
precision highp float;
// the fragment shader: one pixel's color
out vec4 fragColor;

void main() {
  fragColor = vec4(0.13, 0.83, 0.93, 1.0);
}
const gl = canvas.getContext('webgl2');

function compile(type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(shader));
  return shader;
}

const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, vertexSource));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, fragmentSource));
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));

// three corners, two numbers each, into a buffer that attribute 0 reads
gl.bindVertexArray(gl.createVertexArray());
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-0.75, -0.6, 0.75, -0.6, 0, 0.7]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);

gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLES, 0, 3);

three vertices go in. the vertex shader runs once for each one and says where it lands.

drag a corner, or tab to one and use the arrow keys

a 16 by 10 grid of pixels with one triangle on it, in three steps. vertex shader: the three corners, cyan, amber and white. rasterizer: the 40 pixels whose centers fall inside the triangle are marked, so 40 fragments. fragment shader: each of those pixels is filled with the three corner colors, blended by how close its center is to each corner. dragging a corner changes which pixels are in.

a pixel is in when its center is inside. drag a corner across a row and whole pixels flip in or out.

attributes, uniforms and varyings

three ways data gets into a shader. an attribute is per vertex: the vertex shader reads one value per vertex from a buffer, declared with in. a uniform is per draw: one value, set from javascript, the same for every vertex and every fragment. a varying is written by the vertex shader with out and read by the fragment shader with in, and the gpu blends the three corners’ values across the triangle for each fragment, with perspective correction.4

#version 300 es
layout(location = 0) in vec2 a_position; // attributes: one per vertex, from buffers
layout(location = 1) in vec3 a_color;
uniform float u_angle;                    // a uniform: one for the whole draw
uniform float u_aspect;
out vec3 v_color;                         // a varying: blended on its way to the fragment shader

void main() {
  float c = cos(u_angle);
  float s = sin(u_angle);
  vec2 p = mat2(c, s, -s, c) * a_position;
  gl_Position = vec4(p.x / u_aspect, p.y, 0.0, 1.0);
  v_color = a_color;
}
#version 300 es
precision highp float;
in vec3 v_color; // already blended for this pixel
out vec4 fragColor;

void main() {
  fragColor = vec4(v_color, 1.0);
}
// a second buffer for the colors, read by attribute 1: three floats per vertex
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 0, 0);

// a uniform belongs to a program: look it up once, set it while that program is in use
const angle = gl.getUniformLocation(program, 'u_angle');
gl.useProgram(program);
gl.uniform1f(angle, Math.PI / 6);
0°

a_position-0.75, -0.550.75, -0.550.00, 0.80

u_angle0.00 radians

drag a corner and only its attribute changes. the slider sets one uniform for all three. the colors between the corners are the varying, blended for each pixel

a webgl triangle with a cyan, an amber and a white corner, the colors blending across it. each corner can be dragged, which changes only that vertex's position attribute. a slider sets u_angle, one uniform for all three vertices, and turns the whole triangle. the blend between the corners is the varying, interpolated for every pixel.

two attributes per vertex, one uniform for the draw, and one varying blended in between.

uv space

gl_FragCoord.xy is the fragment’s position in pixels, from the bottom-left corner of the canvas, taken at the pixel’s center: the first pixel is at (0.5, 0.5). with antialiasing on, which is webgl’s default, the spec lets it be anywhere inside the pixel.9 divide by the canvas size and you get uv: 0 to 1 across and 0 to 1 up. for shapes that should stay round, center it and divide by the height instead.

// inside main()
vec2 uv = gl_FragCoord.xy / u_resolution;                         // 0..1 both ways, stretched on a wide canvas
vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y; // 0 in the middle, y from -0.5 to 0.5, square
// the drawing buffer at the screen's density, and the viewport to match, after every resize
canvas.width = Math.round(canvas.clientWidth * devicePixelRatio);
canvas.height = Math.round(canvas.clientHeight * devicePixelRatio);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);

// a pointer event in the shader's pixels: css to drawing buffer, and y flipped to point up
const rect = canvas.getBoundingClientRect();
const x = (event.clientX - rect.left) * (canvas.width / rect.width);
const y = canvas.height - (event.clientY - rect.top) * (canvas.height / rect.height);
gl.uniform2f(pointerLocation, x, y);

drag to move the white dot.

open this in the playground

the uv example: a canvas where red grows from left to right and green from bottom to top, black at the bottom-left corner and yellow at the top-right. a white dot marks u_pointer, which you can drag, and a readout shows gl_FragCoord, u_resolution and uv under it.

uv is gl_FragCoord over the size, so the middle reads 0.5, 0.5.

fullscreen quad

to run a fragment shader once for every pixel, draw something that covers all of clip space. two triangles do it: four corners as a strip, where each new vertex makes a triangle with the two before it.12 one bigger triangle does it too: with corners at (-1, -1), (3, -1) and (-1, 3) it covers the square, and clipping cuts off the rest.13 built from gl_VertexID, the index of the vertex being processed, it doesn’t need a buffer at all.14

#version 300 es
// one triangle over the whole canvas, from the vertex index alone
void main() {
  vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2); // (0, 0), (2, 0), (0, 2)
  gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);           // (-1, -1), (3, -1), (-1, 3)
}
// no buffers: an empty vertex array, three vertices
gl.bindVertexArray(gl.createVertexArray());
gl.drawArrays(gl.TRIANGLES, 0, 3);

// or the strip: bottom-left, bottom-right, top-left, top-right, into attribute 0
const corners = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

4 vertices drawn as a strip: two triangles that meet on the diagonal. the picture is the same either way.

clip space from -1.2 to 3.2 on both axes, with the canvas as the square from -1 to 1, showing uv colors. one option draws it with two triangles, four corners as a strip that meet on the diagonal. the other draws it with one triangle with corners at (-1, -1), (3, -1) and (-1, 3), most of it outside the canvas and clipped away. the picture inside the square is the same either way.

the canvas is the part of clip space from -1 to 1. whatever is drawn past it is clipped.

gradients

mix(a, b, t) is a * (1 - t) + b * t, a straight blend. step(edge, x) is 0 below the edge and 1 from it on, a hard cut. smoothstep(e0, e1, x) is 0 up to e0, 1 from e1, and an s-curve between, t * t * (3 - 2 * t).15 feed them uv and you get gradients; feed them a distance and you get a soft circle. inigo quilez’s cosine palette turns any number into a smooth run of colors: a is the middle color, b how far it swings, c how many times each channel cycles as t goes from 0 to 1, and d where each channel starts.16

vec3 palette(float t) { // after inigo quilez
  vec3 a = vec3(0.5), b = vec3(0.5), c = vec3(1.0), d = vec3(0.0, 0.33, 0.67);
  return a + b * cos(6.283185 * (c * t + d));
}

// inside main()
vec3 linear = mix(CYAN, AMBER, uv.x);                          // left to right
float glow = 1.0 - smoothstep(0.0, 0.45, distance(p, center)); // bright at the center, gone 0.45 out
vec3 ramp = palette(uv.x);

drag sideways: the white line marks where you are on the blend.

open this in the playground

three gradients. linear: cyan on the left blending to amber on the right, with a white line you drag to mark the blend factor. radial: a cyan glow fading out from a center you drag. palette: inigo quilez's cosine palette across the canvas, with more cycles as you drag up.

noise

there’s no random() in glsl, and a shader has to give the same answer for the same pixel every time, so noise starts from a hash: integers in, well-mixed integers out. jarzynski and olano tested 27 gpu hash functions, and recommend pcg3d as a good default for three numbers in and three out.17 a grid cell’s coordinates go through int on the way in, since uint() of a negative float is undefined.18

uvec3 pcg3d(uvec3 v) { // jarzynski and olano, 2020
  v = v * 1664525u + 1013904223u;
  v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
  v ^= v >> 16u;
  v.x += v.y * v.z; v.y += v.z * v.x; v.z += v.x * v.y;
  return v;
}

// three numbers in [0, 1) for a grid cell. through int first: uint() of a negative float is undefined
vec3 hash2(vec2 cell) {
  uvec3 h = pcg3d(uvec3(ivec3(ivec2(cell), 0)));
  return vec3(h) / 4294967296.0;
}

float valueNoise(vec2 p) {
  vec2 i = floor(p);
  vec2 f = fract(p);
  vec2 u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0); // perlin's fade
  float a = hash2(i).x;
  float b = hash2(i + vec2(1.0, 0.0)).x;
  float c = hash2(i + vec2(0.0, 1.0)).x;
  float d = hash2(i + vec2(1.0, 1.0)).x;
  return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

float fbm(vec2 p) {
  float sum = 0.0, amplitude = 1.0, total = 0.0;
  for (int i = 0; i < 5; i++) {
    sum += amplitude * valueNoise(p);
    total += amplitude; // 1.9375 after five
    p *= 2.0;
    amplitude *= 0.5;
  }
  return sum / total;
}

drag sideways to change the frequency.

open this in the playground

four kinds of noise in gray: value noise, gradient noise, simplex noise, and fbm made of five octaves of gradient noise. dragging sideways changes how many cells fit across. value noise shows its square grid, gradient noise is smoother, simplex noise has no grid direction, and fbm adds finer and finer detail on top.

value noise is blocky, gradient noise is smoother, simplex has no grain, fbm stacks octaves for detail.

signed distance functions

a signed distance function takes a point and returns how far it is from a shape’s edge: negative inside, 0 on the edge, positive outside. shapes are small formulas, and a circle is length(p) - r. moving a shape means moving the point you measure from: sdCircle(p - center, r). the minimum of two distances is their union, the maximum their intersection, and max(-a, b) cuts a out of b. subtract a number from any distance and the shape grows by that much, with round corners.24

float sdCircle(vec2 p, float r) { return length(p) - r; }

float sdBox(vec2 p, vec2 b) { // b is half the size
  vec2 d = abs(p) - b;
  return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
}

float opUnion(float a, float b) { return min(a, b); }
float opSubtract(float a, float b) { return max(-a, b); } // b with a cut out
float opIntersect(float a, float b) { return max(a, b); }

// inigo quilez's quadratic smooth minimum: where the two are within 4k, a join that dips k below min
float smin(float a, float b, float k) {
  k *= 4.0;
  float h = max(k - abs(a - b), 0.0) / k;
  return min(a, b) - h * h * k * 0.25;
}

drag to move the circle. each ring is 0.1 further from its edge.

open this in the playground

distance fields drawn as color: cyan inside a shape, amber outside, darker further from the edge, a ring every 0.1 and a white line on the edge itself. the first is a circle you drag. the second is a rounded box and the circle joined with min, the union. the third joins them with a smooth minimum, which grows a bridge between the two as they get close.

raymarching

to draw a 3d distance field, shoot a ray from the camera through each pixel and walk along it. the sdf says how far the nearest surface is, so a step that long can’t pass through anything. that walk is sphere tracing, john hart’s name for it.26 stop when the distance gets tiny, a hit, or the ray has gone too far, a miss, and cap the steps. the surface normal is the sdf’s gradient, taken by central differences.27

#version 300 es
precision highp float;
uniform vec2 u_resolution;
out vec4 fragColor;

float map(vec3 p) { // the scene: a unit sphere on a floor at y = -1
  return min(length(p) - 1.0, p.y + 1.0);
}

float march(vec3 origin, vec3 dir) {
  float t = 0.0;
  for (int i = 0; i < 64; i++) {
    float d = map(origin + dir * t);
    if (d < 0.001) return t; // close enough: a hit
    t += d;                  // nothing is nearer than d, so this step is safe
    if (t > 20.0) break;     // too far: a miss
  }
  return -1.0;
}

vec3 normalAt(vec3 p) {
  vec2 h = vec2(0.0001, 0.0);
  return normalize(vec3(map(p + h.xyy) - map(p - h.xyy),
                        map(p + h.yxy) - map(p - h.yxy),
                        map(p + h.yyx) - map(p - h.yyx)));
}

void main() {
  vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;
  vec3 origin = vec3(0.0, 0.5, 4.0);
  vec3 dir = normalize(vec3(p, -1.6)); // the camera looks down -z, through this pixel
  float t = march(origin, dir);
  vec3 color = vec3(0.0);
  if (t > 0.0) {
    vec3 n = normalAt(origin + dir * t);
    float light = max(dot(n, normalize(vec3(1.0, 1.5, 1.0))), 0.0);
    color = vec3(0.13, 0.83, 0.93) * (0.08 + 0.92 * light);
  }
  fragColor = vec4(color, 1.0);
}
0.60

hit after 5 steps, 2.20 along the ray.

each ring is the distance the sdf read at that step. no surface is inside a ring, so a step to its edge can't jump over one

sphere tracing in two dimensions: a cyan circle, and a ray from an eye on the left at a height set by a slider. each step is drawn as a ring around the point the ray reached, its radius the distance to the circle from there. at height 0 the ray hits in 2 steps. at 0.99, just under the top edge, it takes 24 small steps. above 1 it misses and walks off past the far limit of 20.

head on, two steps. grazing the edge, two dozen.

open the 3d sphere in the playground: drag to move the camera, play to move the light.

dissolve

a dissolve throws away the pixels whose noise is below a threshold, and raises the threshold over time. discard ends the fragment without writing anything.28 the band just above the threshold gets an edge color, so the cut glows.

// inside main(), with fbm from the noise section
float threshold = fract(u_time / 6.0); // 0 to 1, every 6 seconds
float n = fbm(p * 6.0);
if (n < threshold) discard;            // gone: nothing is written for this pixel

float glow = 1.0 - smoothstep(threshold, threshold + 0.08, n); // 1 at the cut, 0 past the band
color = mix(color, AMBER, glow);
2.4 s

time raises the threshold. drag up for a finer edge.

open this in the playground

a rounded box with a cyan to white gradient, dissolving. pixels whose noise is below a threshold are discarded, and the band just above the threshold glows amber. it starts 2.4 seconds in, with the threshold at 0.4. a u_time slider raises the threshold from 0 to 1, and dragging up makes the edge finer.

distortion

distortion moves where the picture is read, not the picture. add an offset to uv before you look the color up: a sine of y shifts rows sideways, a sine of the distance from a point makes ripples, and noise fed into its own input warps the space. that last one is domain warping, after inigo quilez.29

// inside main(), before the picture is looked up at uv
uv.x += sin(uv.y * 3.0 * 6.2832 + u_time * 2.0) * 0.05; // wave: rows slide sideways

vec2 toPixel = (uv - center) * vec2(aspect, 1.0);         // ripple: round on a wide canvas too
float d = length(toPixel);
uv += normalize(toPixel) * sin(d * 62.83 - u_time * 4.0) * 0.03 * exp(-3.0 * d) / vec2(aspect, 1.0);

vec2 q = vec2(fbm(p), fbm(p + vec2(5.2, 1.3)));          // warp: noise moves noise
float n = fbm(p + 4.0 * q);
0.0 s

drag sideways for a stronger wave. time moves it.

open this in the playground

a grid of lines, cyan to amber, read from moved positions. wave: rows shift sideways by a sine wave whose strength you drag. ripple: rings spread from a point you drag. domain warp: fbm noise whose input is moved by more noise, after inigo quilez. a u_time slider moves the waves and the rings.

feedback buffers

a feedback effect reads the last frame, changes it a little, and draws the next frame from it: trails, smoke, reaction-diffusion. the frame lives in a texture you render into through a framebuffer. you can’t read a texture while you draw into it: webgl makes that an INVALID_OPERATION.31 so keep two and swap them every frame, which is called ping-pong.

function makeTarget(width, height) {
  const texture = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); // no mipmaps, or it reads as black
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  const framebuffer = gl.createFramebuffer();
  gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  return { texture, framebuffer };
}

const targets = [makeTarget(w, h), makeTarget(w, h)];
let read = 0;

function frame() {
  const write = 1 - read;
  gl.bindFramebuffer(gl.FRAMEBUFFER, targets[write].framebuffer); // draw into one
  gl.bindTexture(gl.TEXTURE_2D, targets[read].texture);           // while reading the other
  gl.useProgram(fadeProgram);
  gl.drawArrays(gl.TRIANGLES, 0, 3);

  gl.bindFramebuffer(gl.FRAMEBUFFER, null);                       // then show what was drawn
  gl.bindTexture(gl.TEXTURE_2D, targets[write].texture);
  gl.useProgram(showProgram);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
  read = write;
}
// the fade program's fragment shader, inside main()
vec3 last = texture(u_previous, gl_FragCoord.xy / u_resolution).rgb;
fragColor = vec4(max(last * 0.95 - 1.0 / 255.0, 0.0), 1.0);
paused: paint, then play

a plain fade never reaches black in 8 bits. each value is rounded to a byte after the multiply, and 10 × 0.95 = 9.5 rounds back to 10, so a trail stops at a dim gray, about a second in.

drag to paint, or hold an arrow key. shown brightened, so the last few values of a trail stay visible

a black canvas with a cyan wave painted on it, and a brush to paint more. each frame reads the last one from a texture, multiplies it by 0.95 and draws into a second texture, then the two swap, so strokes leave fading trails. nothing moves until you press play. with the plain multiply, trails stop at a dim gray, 10 of 255, because 10 times 0.95 is 9.5, which rounds back to 10 in an 8-bit texture. with one more byte taken off each frame they fade all the way to black, in under a second.

press play and the wave fades to a gray ghost that never leaves. switch the fade and play again to clear it.

gpgpu particles

the same trick can compute instead of paint. keep every particle’s state in a float texture, one texel each: position in red and green, velocity in blue and alpha. an update pass draws a quad over the whole texture, so each fragment is one particle working out its next step, written into the other texture. a draw pass then draws one point per particle, and its vertex shader reads that particle’s texel with texelFetch. rendering into a float texture needs the EXT_color_buffer_float extension.34

#version 300 es
precision highp float;
// update pass, fragment shader: one fragment per particle
uniform highp sampler2D u_state;
uniform vec2 u_target; // the middle of the grid they settle into
uniform float u_dt;    // a fixed 1/60
out vec4 next;

const float PULL = 12.0; // the figure gives each particle its own, from a hash of its id

void main() {
  ivec2 texel = ivec2(gl_FragCoord.xy);
  vec4 state = texelFetch(u_state, texel, 0); // x, y, vx, vy
  vec2 home = u_target + (vec2(texel) + 0.5) / 64.0 * 1.4 - 0.7;
  vec2 a = (home - state.xy) * PULL - state.zw * 4.0; // a spring home, and some drag
  vec2 v = state.zw + a * u_dt;                       // velocity first, then position
  next = vec4(state.xy + v * u_dt, v);
}
#version 300 es
// draw pass, vertex shader: no attributes, gl_VertexID picks the particle
uniform highp sampler2D u_state;

void main() {
  int side = textureSize(u_state, 0).x;
  vec4 state = texelFetch(u_state, ivec2(gl_VertexID % side, gl_VertexID / side), 0);
  gl_Position = vec4(state.xy, 0.0, 1.0);
  gl_PointSize = 2.0;
}
if (!gl.getExtension('EXT_color_buffer_float')) throw new Error('no float render targets');
// two 64 x 64 RGBA32F textures for the state, then each frame:
gl.viewport(0, 0, 64, 64);
// ...update pass into the other texture, swap, then
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
gl.drawArrays(gl.POINTS, 0, 64 * 64);
paused

4,096 particles, one texel each in a 64 × 64 float texture. a fragment shader moves them all at once, 60 steps a second; white ones are still moving.

drag to move the grid they settle into

4,096 particles, each one texel of a 64 by 64 float texture holding its position and velocity. a fragment shader updates them all at once, 60 steps a second, and a second pass draws one point per particle. they start scattered across the canvas, and once you press play they spring into a square grid around a point you drag, settling in two or three seconds. moving particles are white and settled ones cyan.

4,096 particles, no particle loop in javascript: the whole step is one draw call.

shadermaterial in three.js

three.js wraps all of the above. a ShaderMaterial takes your two shaders and a uniforms object, and three.js adds the rest: #version 300 es, precision lines, its matrices (projectionMatrix, modelViewMatrix and others) and the mesh’s attributes (position, normal, uv). it also defines attribute, varying and gl_FragColor, so shaders in the older style compile.38 a RawShaderMaterial adds none of it.39 the three.js sheet has the scenes; this is the shader side.

import * as THREE from 'three';

const material = new THREE.ShaderMaterial({
  uniforms: {
    u_time: { value: 0 },
    u_color: { value: new THREE.Color(0x22d3ee) },
  },
  vertexShader: /* glsl */ `
    varying vec2 vUv;
    void main() {
      vUv = uv; // uv, position and the matrices come from three.js
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: /* glsl */ `
    uniform float u_time;
    uniform vec3 u_color;
    varying vec2 vUv;
    void main() {
      float band = 0.5 + 0.5 * sin(vUv.x * 20.0 - u_time * 2.0);
      gl_FragColor = vec4(u_color * band, 1.0);
    }
  `,
});
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(2, 1), material);

// before each render: set the value, and three.js sends it
material.uniforms.u_time.value = performance.now() / 1000;

pitfalls

sources

  1. the khronos webgl 2.0 specification (opens in a new tab): its abstract (a context that conforms closely to the opengl es 3.0 api, described as differences from webgl 1.0) and section 5.3 (opens in a new tab) (it accepts glsl es 3.00 shaders as well as 1.00). the glsl es 3.00 specification (opens in a new tab), revision 6, is the shading language. ↩

  2. the opengl es 3.0.6 specification (opens in a new tab), section 2.13 (coordinate transformations: perspective division, then the viewport) and section 2.18 (primitive clipping). ↩

  3. the opengl es 3.0.6 specification, the introduction to chapter 3 (a fragment’s center is offset by a half from its corner) and section 3.6.1 (point sampling: the fragments whose centers lie inside the polygon, and exactly one of two triangles gets a center on their shared edge). ↩

  4. the glsl es 3.00 specification, section 4.3.9: with no qualifier a varying is interpolated, perspective correct, and flat takes one provoking vertex’s value. ↩ ↩2

  5. the glsl es 3.00 specification, section 3.8: attribute and varying are reserved for future use, and using them is an error. ↩

  6. the opengl es 3.0.6 specification, section 2.17 and table 2.12: for independent triangles the provoking vertex is the third. checked in chromium: a flat color came out as the third vertex’s. ↩

  7. the opengl es 3.0.6 specification, section 2.12.6: a uniform is active only if the compiler and linker find it is used, and GetUniformLocation returns -1 for a name that isn’t an active uniform. ↩

  8. the webgl 1.0 specification (opens in a new tab), section 5.14.10: if the location passed to a uniform* call is null, the data is silently ignored. ↩

  9. the glsl es 3.00 specification, section 7.2: gl_FragCoord holds the fragment’s window coordinates, and with multisampling it can be any location within the pixel. the opengl es 3.0.6 specification’s chapter 3 puts fragment centers on half-integer coordinates, and the webgl 1.0 specification, section 5.2 (opens in a new tab), has antialias default to true. ↩

  10. the webgl 1.0 specification, section 2.2 (opens in a new tab): the drawing buffer’s size is set by the canvas’s width and height attributes. ↩

  11. the webgl 1.0 specification, section 2.3 (opens in a new tab): the viewport starts at the drawing buffer’s size, and resizing the canvas doesn’t change it. ↩

  12. the opengl es 3.0.6 specification, section 2.7.1: in a triangle strip the first three vertices make the first triangle, and each later vertex makes a new one with two vertices from the triangle before. ↩ ↩2

  13. the opengl es 3.0.6 specification, section 2.18: primitives are clipped to the volume from -w to w on each axis. ↩

  14. the glsl es 3.00 specification, section 7.1: gl_VertexID holds the index of the vertex. checked in chromium: the one-triangle shader above links and fills the canvas with no buffers bound. ↩

  15. the glsl es 3.00 specification, section 8.3: mix is the linear blend x(1 - a) + ya, step returns 0 below the edge, and smoothstep is t * t * (3 - 2t) on the clamped ratio, with results undefined if edge0 >= edge1. ↩ ↩2

  16. inigo quilez, palettes (opens in a new tab): color(t) = a + b ⋅ cos(2π(c⋅t + d)), where the cosine oscillates c times with phase d, scaled and biased by a and b. ↩

  17. mark jarzynski and marc olano, hash functions for gpu rendering (opens in a new tab), journal of computer graphics techniques 9(3), 2020: their tests of gpu hashes for quality and speed, pcg3d’s code in section 6.1, pcg3d as a good default for multidimensional input, and figure 1, where the sine-based “trig” hash shows banding, linear artifacts and repeated patterns. ↩ ↩2

  18. the glsl es 3.00 specification, section 5.4.1: converting a negative float to a uint is undefined, and uint(int) keeps the bit pattern. ↩

  19. ken perlin, an image synthesizer, siggraph 1985, doi 10.1145/325165.325247 (opens in a new tab). his 2002 paper dates noise to it and his 1984 siggraph course, and describes the original: a pseudo-random gradient at each lattice point, blended by 3t² - 2t³. ↩

  20. ken perlin, improving noise, acm transactions on graphics 21(3), 2002, doi 10.1145/566654.566636 (opens in a new tab), open copy on his site (opens in a new tab): 3t² - 2t³ has a second derivative that isn’t zero at 0 and 1, which shows as creases, and 6t⁵ - 15t⁴ + 10t³ has zero first and second derivatives at both ends. ↩

  21. stefan gustavson, simplex noise demystified (opens in a new tab), 2005, on ken perlin’s simplex noise from 2001: a simplex has n + 1 corners where a hypercube has 2ⁿ, each corner adds a radially symmetric kernel times its gradient ramp, and the 2d code (the skew factors, the 0.5 kernel radius, the final scale of 70) that the noise example follows. ↩

  22. inigo quilez, fbm (opens in a new tab): octaves at doubling frequency and a gain G usually hardcoded to 0.5, and detuning the 2.0 to values like 2.01, or rotating each 2d octave, so the octaves’ zeros and peaks don’t line up. ↩ ↩2

  23. the glsl es 3.00 specification, section 4.5.1 (mediump integers may be as narrow as 16 bits, and trigonometric functions have undefined precision) and section 4.5.4 (the fragment language has no default float precision and defaults integers to mediump; a precision statement for int covers signed and unsigned). ↩ ↩2 ↩3 ↩4

  24. inigo quilez, 2d distance functions (opens in a new tab) (the circle, the box, the segment, and rounding by subtracting a radius) and 3d distance functions (opens in a new tab) (union, subtraction and intersection, which only the union keeps exact outside the shapes, the smooth versions as bounds, opScale measuring at p / s and multiplying by s, and deformations that call for a smaller step). ↩ ↩2 ↩3 ↩4

  25. inigo quilez, smooth minimum (opens in a new tab): the quadratic polynomial version used here, with k normalized so it’s in distance units. ↩

  26. john c. hart, sphere tracing: a geometric method for the antialiased ray tracing of implicit surfaces, the visual computer 12(10), 527 to 545, 1996, doi 10.1007/s003710050084 (opens in a new tab). inigo quilez’s raymarching sdfs (opens in a new tab) tells the history, and how hart named the technique. ↩

  27. inigo quilez, normals for an sdf (opens in a new tab): the normal as the gradient of the field, by central differences. ↩

  28. the glsl es 3.00 specification, section 6.4: discard abandons the fragment, and no buffers are updated. ↩

  29. inigo quilez, domain warping (opens in a new tab): fbm(p + fbm(p)), with the offsets (5.2, 1.3) and the factor 4 the warp example uses. ↩

  30. the opengl es 3.0.6 specification, section 3.8.14: a new texture starts with minification filter NEAREST_MIPMAP_LINEAR, magnification filter LINEAR, and wrap mode REPEAT. ↩ ↩2

  31. the webgl 1.0 specification, section 6.27 (opens in a new tab): an operation that would make a feedback loop between a texture and the framebuffer generates INVALID_OPERATION. checked in chromium: drawing into a texture while it’s bound for reading raised it, reading a second texture didn’t. ↩

  32. the opengl es 3.0.6 specification, section 2.1.6.2: a float stored into an 8-bit normalized channel becomes one of the two nearest bytes, with the nearest preferred. checked in chromium: a fade by 0.95 in an RGBA8 texture stopped at 10 of 255. ↩

  33. the opengl es 3.0.6 specification, section 3.8.13 (a texture is incomplete if its filter needs mipmaps it doesn’t have, or if a format that isn’t texture-filterable gets a linear filter; table 3.13 lists RGBA32F as not filterable) and section 3.9.2.1 (sampling an incomplete texture returns (0, 0, 0, 1)). ↩ ↩2

  34. the khronos EXT_color_buffer_float (opens in a new tab) extension: R16F to RGBA32F become color-renderable. without it, table 3.13 of the opengl es 3.0.6 specification lists them as not color-renderable. ↩ ↩2

  35. the webgl 1.0 specification, section 5.14.13 (opens in a new tab) (power events on mobile devices can lose the context at any time), section 5.15.2 (opens in a new tab) and section 5.15.3 (opens in a new tab): without preventDefault() on the lost event the context isn’t restored, and after a restore the old resources are invalid and extensions are not turned back on. ↩ ↩2

  36. the glsl es 3.00 specification, section 4.5.4 (samplers default to lowp) and section 12.5 (texture functions return at the precision of their sampler). ↩

  37. mdn on OES_texture_float_linear (opens in a new tab): it allows linear filtering of floating-point textures, in webgl 1 and 2. ↩

  38. three.js r186, src/renderers/webgl/WebGLProgram.js (opens in a new tab): for a ShaderMaterial it writes #version 300 es, precision lines, the #defines for attribute, varying and (unless glslVersion is GLSL3) gl_FragColor, then the built-in uniforms and attributes. for a RawShaderMaterial it writes only its #define lines, and the version line only when glslVersion is set. ↩ ↩2 ↩3

  39. three.js r186, src/materials/RawShaderMaterial.js (opens in a new tab): like ShaderMaterial, without the built-in uniforms and attributes. ↩

  40. the glsl es 3.00 specification, section 4.2.3: declaring a name again in the same scope is a redeclaration error. ↩

  41. three.js r186, src/materials/ShaderMaterial.js (opens in a new tab): uniforms are { value } objects refreshed every frame, and glslVersion defaults to null. ↩

  42. the glsl es 3.00 specification, section 3.4: #version 300 es is required for 3.00 and must be on the first line, and a shader without a version line is treated as 1.00. ↩ ↩2

  43. the glsl es 3.00 specification, section 4.1: the language is type safe, with no implicit conversions between types. ↩

  44. chromium 149.0.7827.238: webgraphicscontext3d_provider_impl.cc (opens in a new tab) in content/renderer sets 16 active webgl contexts, 8 on android, and blink’s webgl_rendering_context_base.cc (opens in a new tab) loses the oldest past that, with “too many active webgl contexts”. ↩

  45. the khronos WEBGL_lose_context (opens in a new tab) extension: loseContext() is the recommended way to stop using webgl, and the context stays lost until restoreContext(). checked in chromium: after loseContext(), getContext('webgl2') returns the same lost context. ↩

  46. the webgl 1.0 specification, section 5.2.1 (opens in a new tab): premultipliedAlpha defaults to true, and then colors above their alpha composite as undefined. ↩

  47. mdn on WebGL2RenderingContext (opens in a new tab) and its browser compatibility data: chrome 56, firefox 51, safari 15, and available across browsers since september 2021. ↩

  48. the webgl 1.0 specification, section 2.1 (opens in a new tab) and section 5.15.4 (opens in a new tab): if the drawing buffer can’t be created, getContext fires a webglcontextcreationerror event, optionally with a status message, and returns null. ↩