graphicsshaders
webgl + glsl
the pipeline from vertex to pixel, and fragment shaders from gradients to raymarching, with a playground.
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
- backgrounds and gradients
- procedural textures
- image effects and transitions
- particles and simulations
on this page
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.
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.
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 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 / widthfor 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.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);
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.
attributeandvaryingare from glsl es 1.00. in a#version 300 esshader they’re reserved words, and using one is a compile error. writeinandout.5flatswitches the blending off. every fragment then gets one vertex’s value, the provoking vertex, which for a triangle is its last.4,6- a typo in a uniform’s name fails quietly. a name that isn’t an active uniform has no location, so
getUniformLocationreturns null, and setting a null location is silently ignored. so does a uniform you declare but never use: it’s compiled away.7,8
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.
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_resolutionis the drawing buffer, not the css box. the drawing buffer’s size is the canvas’swidthandheightattributes.10 for sharp pixels on a dense screen, set them to the css size timesdevicePixelRatio, and pass those.- a resize doesn’t move the viewport. set it again after every resize, or the picture keeps its old size.11
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.
- 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.12
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);
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
smoothstepby swapping its edges is undefined. the spec requirese0 < e1. write1.0 - smoothstep(0.0, 1.0, x), notsmoothstep(1.0, 0.0, x).15
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
- 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.19 perlin’s 2002 fade curve,
6t⁵ - 15t⁴ + 10t³, is flat in slope and curvature at both ends of a cell, where the older3t² - 2t³left creases.20 - 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.21
- 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.22
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;
}
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. putprecision highp int;under the float precision line.23 - 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.22
- hashes built on
sin, likefract(sin(x) * 43758.5453), depend on how precisely the gpu computessin, which the spec leaves undefined.23 in jarzynski and olano’s tests their sine-based hash showed banding and repeated patterns.17
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;
}
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.24,25
- scale the distance back. to scale a shape, measure at
p / sand multiply the result bys:sdCircle(p / s, r) * s. without the* sthe edge lands in the right place, but every distance around it is off.24
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);
}
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.
open the 3d sphere in the playground: 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.24
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);
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.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);
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.xshows 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:
REPEATby default,CLAMP_TO_EDGEto smear the border instead.30
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);
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.
- 8 bits stall a fade. each value is rounded to the nearest byte as it’s stored,32 and once a channel is down to 10 of 255,
10 × 0.95 = 9.5rounds 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).30,33 - 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
blitFramebufferfor 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.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);
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.
- ask for the extension, and ask again after a lost context. webgl 2 can read
RGBA32Ftextures but can’t render into them withoutEXT_color_buffer_float, and a restored context comes back with no extensions turned on.34,35 - a float texture’s sampler is
lowpunless you say so. a texture read comes back at its sampler’s precision, and samplers default tolowp, so declareuniform highp sampler2Dfor data.23,36 - filter floats with
NEAREST.RGBA32Fcan’t be filtered linearly in webgl 2 withoutOES_texture_float_linear, and a linear filter on it leaves the texture incomplete. read it withtexelFetch, which takes whole texel coordinates and skips filtering.33,37 - step at a fixed rate. a fixed
dtkeeps 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.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;
- don’t declare what three.js declares. a
ShaderMaterialalready hasposition,uv,projectionMatrixand the rest, and declaring a name twice in a shader is a redeclaration error.38,40 - a uniform is
{ value }. three.js readsuniforms.name.valueevery frame, so setting.valueis all an animation needs.41 - with
RawShaderMaterial, don’t write#version 300 esyourself. three.js puts its own#definelines first, and the version line has to be line 1. setglslVersion: THREE.GLSL3and three.js writes it. you also write every declaration, precision included.38,42
pitfalls
- the
#versionline 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.42 - a fragment shader has no default float precision. start it with
precision highp float;, or every float declaration is an error.23 - no implicit conversions.
float x = 1;is an error, since1is an int. write1.0, orfloat(i)for a variable.43 - too many contexts. chromium allows 16 live webgl contexts, 8 on android, and drops the oldest past that with a console warning.44 when a canvas goes away for good, give its context back with
loseContext()from theWEBGL_lose_contextextension. the figures on this page give theirs back when they scroll far off screen, and get it again withrestoreContext()when they return.45 - lost contexts. a context can be lost at any time, from a power event on a phone to the limit above. call
preventDefault()onwebglcontextlostor it never comes back, then rebuild every buffer, texture, program and extension onwebglcontextrestored.35 - 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.46 - 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; awebglcontextcreationerrorevent may say why.47,48
sources
-
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. ↩
-
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). ↩
-
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). ↩
-
the glsl es 3.00 specification, section 4.3.9: with no qualifier a varying is interpolated, perspective correct, and
flattakes one provoking vertex’s value. ↩ ↩2 -
the glsl es 3.00 specification, section 3.8:
attributeandvaryingare reserved for future use, and using them is an error. ↩ -
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
flatcolor came out as the third vertex’s. ↩ -
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
GetUniformLocationreturns -1 for a name that isn’t an active uniform. ↩ -
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. ↩ -
the glsl es 3.00 specification, section 7.2:
gl_FragCoordholds 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), hasantialiasdefault to true. ↩ -
the webgl 1.0 specification, section 2.2 (opens in a new tab): the drawing buffer’s size is set by the canvas’s
widthandheightattributes. ↩ -
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. ↩
-
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
-
the opengl es 3.0.6 specification, section 2.18: primitives are clipped to the volume from
-wtowon each axis. ↩ -
the glsl es 3.00 specification, section 7.1:
gl_VertexIDholds the index of the vertex. checked in chromium: the one-triangle shader above links and fills the canvas with no buffers bound. ↩ -
the glsl es 3.00 specification, section 8.3:
mixis the linear blendx(1 - a) + ya,stepreturns 0 below the edge, andsmoothstepist * t * (3 - 2t)on the clamped ratio, with results undefined ifedge0 >= edge1. ↩ ↩2 -
inigo quilez, palettes (opens in a new tab):
color(t) = a + b ⋅ cos(2π(c⋅t + d)), where the cosine oscillatesctimes with phased, scaled and biased byaandb. ↩ -
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
-
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. ↩ -
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³. ↩ -
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, and6t⁵ - 15t⁴ + 10t³has zero first and second derivatives at both ends. ↩ -
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. ↩
-
inigo quilez, fbm (opens in a new tab): octaves at doubling frequency and a gain
Gusually 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 -
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
-
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,
opScalemeasuring atp / sand multiplying bys, and deformations that call for a smaller step). ↩ ↩2 ↩3 ↩4 -
inigo quilez, smooth minimum (opens in a new tab): the quadratic polynomial version used here, with
knormalized so it’s in distance units. ↩ -
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. ↩
-
inigo quilez, normals for an sdf (opens in a new tab): the normal as the gradient of the field, by central differences. ↩
-
the glsl es 3.00 specification, section 6.4:
discardabandons the fragment, and no buffers are updated. ↩ -
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. ↩ -
the opengl es 3.0.6 specification, section 3.8.14: a new texture starts with minification filter
NEAREST_MIPMAP_LINEAR, magnification filterLINEAR, and wrap modeREPEAT. ↩ ↩2 -
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. ↩ -
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
RGBA8texture stopped at 10 of 255. ↩ -
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
RGBA32Fas not filterable) and section 3.9.2.1 (sampling an incomplete texture returns (0, 0, 0, 1)). ↩ ↩2 -
the khronos EXT_color_buffer_float (opens in a new tab) extension:
R16FtoRGBA32Fbecome color-renderable. without it, table 3.13 of the opengl es 3.0.6 specification lists them as not color-renderable. ↩ ↩2 -
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 -
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). ↩ -
mdn on OES_texture_float_linear (opens in a new tab): it allows linear filtering of floating-point textures, in webgl 1 and 2. ↩
-
three.js r186, src/renderers/webgl/WebGLProgram.js (opens in a new tab): for a
ShaderMaterialit writes#version 300 es, precision lines, the#defines forattribute,varyingand (unlessglslVersionisGLSL3)gl_FragColor, then the built-in uniforms and attributes. for aRawShaderMaterialit writes only its#definelines, and the version line only whenglslVersionis set. ↩ ↩2 ↩3 -
three.js r186, src/materials/RawShaderMaterial.js (opens in a new tab): like
ShaderMaterial, without the built-in uniforms and attributes. ↩ -
the glsl es 3.00 specification, section 4.2.3: declaring a name again in the same scope is a redeclaration error. ↩
-
three.js r186, src/materials/ShaderMaterial.js (opens in a new tab): uniforms are
{ value }objects refreshed every frame, andglslVersiondefaults to null. ↩ -
the glsl es 3.00 specification, section 3.4:
#version 300 esis required for 3.00 and must be on the first line, and a shader without a version line is treated as 1.00. ↩ ↩2 -
the glsl es 3.00 specification, section 4.1: the language is type safe, with no implicit conversions between types. ↩
-
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”. ↩
-
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 untilrestoreContext(). checked in chromium: afterloseContext(),getContext('webgl2')returns the same lost context. ↩ -
the webgl 1.0 specification, section 5.2.1 (opens in a new tab):
premultipliedAlphadefaults to true, and then colors above their alpha composite as undefined. ↩ -
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. ↩
-
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,
getContextfires awebglcontextcreationerrorevent, optionally with a status message, and returns null. ↩