# webgl + glsl

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

source: https://learning.anthnydas.com/graphics/webgl-glsl/

## tl;dr

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

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.[^webgl2] 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.

> **interactive figure:** 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.

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.[^coords] the rasterizer then finds the pixels whose centers fall inside each triangle, and each of those is a fragment.[^raster] the fragment shader runs once per fragment and writes its color, which can be depth tested and blended on its way into the framebuffer.

```glsl
#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);
}
```

```glsl
#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);
}
```

```js
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);
```

> **interactive figure:** 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 counts by its center.** a sliver of a triangle that passes between two pixel centers draws nothing at all.
- **clip space is -1 to 1 on both axes, whatever the canvas's shape.** on a wide canvas a square in clip space comes out wide. scale x by `height / width` for shapes that shouldn't stretch.

## 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.[^interpolation]

```glsl
#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;
}
```

```glsl
#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);
}
```

```js
// 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);
```

> **interactive figure:** 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.

- **`attribute` and `varying` are from glsl es 1.00.** in a `#version 300 es` shader they're reserved words, and using one is a compile error. write `in` and `out`.[^keywords]
- **`flat` switches the blending off.** every fragment then gets one vertex's value, the provoking vertex, which for a triangle is its last.[^interpolation][^provoking]
- **a typo in a uniform's name fails quietly.** a name that isn't an active uniform has no location, so `getUniformLocation` returns null, and setting a null location is silently ignored. so does a uniform you declare but never use: it's compiled away.[^active][^null]

## 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.[^fragcoord] 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.

```glsl
// 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
```

```js
// 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);
```

> **interactive figure:** 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.

- **y points up.** the dom's y points down, so a pointer's y gets flipped on its way in, as in the code above.
- **`u_resolution` is the drawing buffer, not the css box.** the drawing buffer's size is the canvas's `width` and `height` attributes.[^buffer] for sharp pixels on a dense screen, set them to the css size times `devicePixelRatio`, and pass those.
- **a resize doesn't move the viewport.** set it again after every resize, or the picture keeps its old size.[^viewport]

## 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.[^strip] 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.[^clip] built from `gl_VertexID`, the index of the vertex being processed, it doesn't need a buffer at all.[^vertexid]

```glsl
#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)
}
```

```js
// 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);
```

> **interactive figure:** 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.

- **a strip's order matters.** going round the square, (-1, -1), (1, -1), (1, 1), (-1, 1), makes two triangles that overlap on the right and leave a wedge on the left empty. the order is bottom-left, bottom-right, top-left, top-right.[^strip]

## 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)`.[^builtins] 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.[^palettes]

```glsl
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);
```

> **interactive figure:** 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.

- **flipping `smoothstep` by swapping its edges is undefined.** the spec requires `e0 < e1`. write `1.0 - smoothstep(0.0, 1.0, x)`, not `smoothstep(1.0, 0.0, x)`.[^builtins]

## 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.[^hash] a grid cell's coordinates go through `int` on the way in, since `uint()` of a negative float is undefined.[^convert]

- **value noise** puts a random value at every corner of a square grid and blends them across each cell. it shows its grid: blobs that line up with the axes.
- **gradient noise**, perlin's, puts a random direction at every corner instead. each corner contributes a ramp that rises along its direction and is 0 at the corner, so the noise is 0 at every lattice point and looks less blocky.[^perlin1985] perlin's 2002 fade curve, `6t⁵ - 15t⁴ + 10t³`, is flat in slope and curvature at both ends of a cell, where the older `3t² - 2t³` left creases.[^perlin2002]
- **simplex noise** uses a grid of triangles instead of squares, so a point gets three corners instead of four (n + 1 instead of 2ⁿ in n dimensions), each a round bump that's summed rather than blended. it has no visible grid direction.[^simplex]
- **fbm** (fractional brownian motion) adds octaves, each at twice the frequency and half the amplitude of the last. five octaves add up to 1.9375 times the first one's amplitude, so divide by that to stay in range.[^fbm]

```glsl
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;
}
```

> **interactive figure:** 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.

- **the hash needs 32-bit integers.** a fragment shader's integers default to `mediump`, which may be as narrow as 16 bits, and then the multiplies wrap early and the noise breaks. put `precision highp int;` under the float precision line.[^precision]
- **gradient noise is 0 at every integer point, and so is its fbm.** every octave's grid lines up on the integers when the frequency exactly doubles. a slightly detuned step, like 2.01, or a small rotation per octave breaks that up.[^fbm]
- **hashes built on `sin`, like `fract(sin(x) * 43758.5453)`, depend on how precisely the gpu computes `sin`,** which the spec leaves undefined.[^precision] in jarzynski and olano's tests their sine-based hash showed banding and repeated patterns.[^hash]

## 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.[^sdf]

```glsl
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;
}
```

> **interactive figure:** 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.

- **only some results are true distances.** the union of two exact distances is exact outside the shapes, but subtraction, intersection and the smooth blends give a bound: never more than the true distance, often less. that's fine for drawing and for raymarching, but the rings spread unevenly.[^sdf][^smin]
- **scale the distance back.** to scale a shape, measure at `p / s` and multiply the result by `s`: `sdCircle(p / s, r) * s`. without the `* s` the edge lands in the right place, but every distance around it is off.[^sdf]

## 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.[^hart] 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.[^normals]

```glsl
#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);
}
```

> **interactive figure:** 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.

[open the 3d sphere in the playground](#playground=raymarch): drag to move the camera, play to move the light.

- **edges are the slow part.** a ray that grazes a surface takes many small steps, so cap the steps (64 here) and treat running out as a miss.
- **a distance that overestimates makes holes.** twisting, bending or squashing space breaks the distance, and the march can jump through a surface. step a fraction of the distance, like `t += d * 0.7`.[^sdf]

## 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.[^discard] the band just above the threshold gets an edge color, so the cut glows.

```glsl
// 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);
```

> **interactive figure:** 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.

- **the edge uses the same noise as the cut,** so it hugs it exactly. measure the band in noise units, `smoothstep(t, t + 0.08, n)`, not in pixels.

## 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.[^warp]

```glsl
// 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);
```

> **interactive figure:** 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.

- **an offset moves the picture the other way.** adding 0.1 to `uv.x` shows what's 0.1 to the right, so the picture shifts left.
- **offsets near the edge read outside 0 to 1.** with a texture, the wrap mode decides what comes back there: `REPEAT` by default, `CLAMP_TO_EDGE` to smear the border instead.[^texstate]

## 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`.[^loop] so keep two and swap them every frame, which is called ping-pong.

```js
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;
}
```

```glsl
// 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);
```

> **interactive figure:** 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.

- **8 bits stall a fade.** each value is rounded to the nearest byte as it's stored,[^unorm] and once a channel is down to 10 of 255, `10 × 0.95 = 9.5` rounds back to 10. the trail stops there for good. take a byte off as well, or use a float texture.
- **a new texture reads as black until you set its filter.** the default minification filter, `NEAREST_MIPMAP_LINEAR`, needs mipmaps the texture doesn't have, and sampling a texture that isn't complete returns (0, 0, 0, 1).[^texstate][^completeness]
- **a fade per frame runs twice as fast at 120 hz.** step the effect at a fixed rate instead of once per frame: this figure runs 60 steps a second whatever the screen does.
- **a resize needs new textures.** copy the old frame across, with `blitFramebuffer` for example, or the trail starts over.

## 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.[^float-render]

```glsl
#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);
}
```

```glsl
#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;
}
```

```js
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);
```

> **interactive figure:** 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.

- **ask for the extension, and ask again after a lost context.** webgl 2 can read `RGBA32F` textures but can't render into them without `EXT_color_buffer_float`, and a restored context comes back with no extensions turned on.[^float-render][^lost]
- **a float texture's sampler is `lowp` unless you say so.** a texture read comes back at its sampler's precision, and samplers default to `lowp`, so declare `uniform highp sampler2D` for data.[^precision][^sampler]
- **filter floats with `NEAREST`.** `RGBA32F` can't be filtered linearly in webgl 2 without `OES_texture_float_linear`, and a linear filter on it leaves the texture incomplete. read it with `texelFetch`, which takes whole texel coordinates and skips filtering.[^completeness][^float-linear]
- **step at a fixed rate.** a fixed `dt` keeps the simulation the same on a 60 hz and a 120 hz screen.

## 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.[^three-program] a `RawShaderMaterial` adds none of it.[^three-raw] the [three.js sheet](/graphics/three-js/) has the scenes; this is the shader side.

```js
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;
```

- **don't declare what three.js declares.** a `ShaderMaterial` already has `position`, `uv`, `projectionMatrix` and the rest, and declaring a name twice in a shader is a redeclaration error.[^three-program][^redeclare]
- **a uniform is `{ value }`.** three.js reads `uniforms.name.value` every frame, so setting `.value` is all an animation needs.[^three-material]
- **with `RawShaderMaterial`, don't write `#version 300 es` yourself.** three.js puts its own `#define` lines first, and the version line has to be line 1. set `glslVersion: THREE.GLSL3` and three.js writes it. you also write every declaration, precision included.[^three-program][^version]

## pitfalls

- **the `#version` line must be line 1.** nothing may come before `#version 300 es`, not a comment and not a blank line. a shader without it is read as glsl es 1.00.[^version]
- **a fragment shader has no default float precision.** start it with `precision highp float;`, or every float declaration is an error.[^precision]
- **no implicit conversions.** `float x = 1;` is an error, since `1` is an int. write `1.0`, or `float(i)` for a variable.[^types]
- **too many contexts.** chromium allows 16 live webgl contexts, 8 on android, and drops the oldest past that with a console warning.[^chromium] when a canvas goes away for good, give its context back with `loseContext()` from the `WEBGL_lose_context` extension. the figures on this page give theirs back when they scroll far off screen, and get it again with `restoreContext()` when they return.[^lose]
- **lost contexts.** a context can be lost at any time, from a power event on a phone to the limit above. call `preventDefault()` on `webglcontextlost` or it never comes back, then rebuild every buffer, texture, program and extension on `webglcontextrestored`.[^lost]
- **alpha is premultiplied.** by default the page assumes the drawing buffer's colors are already multiplied by their alpha, and a color brighter than its alpha composites as undefined. write premultiplied colors, or ask for `{ alpha: false }` when the canvas doesn't need to be see-through.[^premultiplied]
- **webgl 2 is in every major browser.** chrome 56, firefox 51 and safari 15 added it, and mdn counts it as available across browsers since september 2021. still show a message when `getContext('webgl2')` returns null, which it does when the browser can't make a drawing buffer; a `webglcontextcreationerror` event may say why.[^support][^creation]

[^webgl2]: the khronos [webgl 2.0 specification](https://registry.khronos.org/webgl/specs/latest/2.0/): 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](https://registry.khronos.org/webgl/specs/latest/2.0/#5.3) (it accepts glsl es 3.00 shaders as well as 1.00). the [glsl es 3.00 specification](https://registry.khronos.org/OpenGL/specs/es/3.0/GLSL_ES_Specification_3.00.pdf), revision 6, is the shading language.

[^coords]: the [opengl es 3.0.6 specification](https://registry.khronos.org/OpenGL/specs/es/3.0/es_spec_3.0.pdf), section 2.13 (coordinate transformations: perspective division, then the viewport) and section 2.18 (primitive clipping).

[^raster]: 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).

[^interpolation]: 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.

[^provoking]: 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.

[^keywords]: the glsl es 3.00 specification, section 3.8: `attribute` and `varying` are reserved for future use, and using them is an error.

[^active]: 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.

[^null]: the [webgl 1.0 specification](https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.10), section 5.14.10: if the location passed to a `uniform*` call is null, the data is silently ignored.

[^fragcoord]: 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](https://registry.khronos.org/webgl/specs/latest/1.0/#5.2), has `antialias` default to true.

[^buffer]: the webgl 1.0 specification, [section 2.2](https://registry.khronos.org/webgl/specs/latest/1.0/#2.2): the drawing buffer's size is set by the canvas's `width` and `height` attributes.

[^viewport]: the webgl 1.0 specification, [section 2.3](https://registry.khronos.org/webgl/specs/latest/1.0/#2.3): the viewport starts at the drawing buffer's size, and resizing the canvas doesn't change it.

[^strip]: 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.

[^clip]: the opengl es 3.0.6 specification, section 2.18: primitives are clipped to the volume from `-w` to `w` on each axis.

[^vertexid]: 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.

[^builtins]: 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`.

[^palettes]: inigo quilez, [palettes](https://iquilezles.org/articles/palettes/): `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`.

[^hash]: mark jarzynski and marc olano, [hash functions for gpu rendering](https://jcgt.org/published/0009/03/02/), 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.

[^perlin1985]: ken perlin, an image synthesizer, siggraph 1985, [doi 10.1145/325165.325247](https://doi.org/10.1145/325165.325247). 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³`.

[^perlin2002]: ken perlin, improving noise, acm transactions on graphics 21(3), 2002, [doi 10.1145/566654.566636](https://doi.org/10.1145/566654.566636), open copy [on his site](https://mrl.cs.nyu.edu/~perlin/paper445.pdf): `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.

[^simplex]: stefan gustavson, [simplex noise demystified](https://itn-web.it.liu.se/~stegu76/simplexnoise/simplexnoise.pdf), 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.

[^fbm]: inigo quilez, [fbm](https://iquilezles.org/articles/fbm/): 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.

[^sdf]: inigo quilez, [2d distance functions](https://iquilezles.org/articles/distfunctions2d/) (the circle, the box, the segment, and rounding by subtracting a radius) and [3d distance functions](https://iquilezles.org/articles/distfunctions/) (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).

[^smin]: inigo quilez, [smooth minimum](https://iquilezles.org/articles/smin/): the quadratic polynomial version used here, with `k` normalized so it's in distance units.

[^hart]: 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](https://doi.org/10.1007/s003710050084). inigo quilez's [raymarching sdfs](https://iquilezles.org/articles/raymarchingdf/) tells the history, and how hart named the technique.

[^normals]: inigo quilez, [normals for an sdf](https://iquilezles.org/articles/normalsSDF/): the normal as the gradient of the field, by central differences.

[^discard]: the glsl es 3.00 specification, section 6.4: `discard` abandons the fragment, and no buffers are updated.

[^warp]: inigo quilez, [domain warping](https://iquilezles.org/articles/warp/): `fbm(p + fbm(p))`, with the offsets (5.2, 1.3) and the factor 4 the warp example uses.

[^texstate]: 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`.

[^completeness]: 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)).

[^loop]: the webgl 1.0 specification, [section 6.27](https://registry.khronos.org/webgl/specs/latest/1.0/#6.27): 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.

[^unorm]: 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.

[^float-render]: the khronos [EXT_color_buffer_float](https://registry.khronos.org/webgl/extensions/EXT_color_buffer_float/) 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.

[^float-linear]: mdn on [OES_texture_float_linear](https://developer.mozilla.org/en-US/docs/Web/API/OES_texture_float_linear): it allows linear filtering of floating-point textures, in webgl 1 and 2.

[^sampler]: 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).

[^precision]: 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).

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

[^convert]: 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.

[^version]: 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.

[^redeclare]: the glsl es 3.00 specification, section 4.2.3: declaring a name again in the same scope is a redeclaration error.

[^three-program]: three.js r186, [src/renderers/webgl/WebGLProgram.js](https://github.com/mrdoob/three.js/blob/r186/src/renderers/webgl/WebGLProgram.js): for a `ShaderMaterial` it writes `#version 300 es`, precision lines, the `#define`s 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.

[^three-raw]: three.js r186, [src/materials/RawShaderMaterial.js](https://github.com/mrdoob/three.js/blob/r186/src/materials/RawShaderMaterial.js): like `ShaderMaterial`, without the built-in uniforms and attributes.

[^three-material]: three.js r186, [src/materials/ShaderMaterial.js](https://github.com/mrdoob/three.js/blob/r186/src/materials/ShaderMaterial.js): uniforms are `{ value }` objects refreshed every frame, and `glslVersion` defaults to null.

[^chromium]: chromium 149.0.7827.238: [webgraphicscontext3d_provider_impl.cc](https://chromium.googlesource.com/chromium/src/+/refs/tags/149.0.7827.238/content/renderer/webgraphicscontext3d_provider_impl.cc) in content/renderer sets 16 active webgl contexts, 8 on android, and blink's [webgl_rendering_context_base.cc](https://chromium.googlesource.com/chromium/src/+/refs/tags/149.0.7827.238/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc) loses the oldest past that, with "too many active webgl contexts".

[^lose]: the khronos [WEBGL_lose_context](https://registry.khronos.org/webgl/extensions/WEBGL_lose_context/) 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.

[^lost]: the webgl 1.0 specification, [section 5.14.13](https://registry.khronos.org/webgl/specs/latest/1.0/#5.14.13) (power events on mobile devices can lose the context at any time), [section 5.15.2](https://registry.khronos.org/webgl/specs/latest/1.0/#5.15.2) and [section 5.15.3](https://registry.khronos.org/webgl/specs/latest/1.0/#5.15.3): 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.

[^premultiplied]: the webgl 1.0 specification, [section 5.2.1](https://registry.khronos.org/webgl/specs/latest/1.0/#5.2.1): `premultipliedAlpha` defaults to true, and then colors above their alpha composite as undefined.

[^creation]: the webgl 1.0 specification, [section 2.1](https://registry.khronos.org/webgl/specs/latest/1.0/#2.1) and [section 5.15.4](https://registry.khronos.org/webgl/specs/latest/1.0/#5.15.4): if the drawing buffer can't be created, `getContext` fires a `webglcontextcreationerror` event, optionally with a status message, and returns null.

[^support]: mdn on [WebGL2RenderingContext](https://developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext) and its browser compatibility data: chrome 56, firefox 51, safari 15, and available across browsers since september 2021.

## related

- https://learning.anthnydas.com/graphics/three-js.md
- https://learning.anthnydas.com/graphics/cg-fundamentals.md
