Vertex shaders, step by step
glint · Examples · Tutorials · Gallery
The other half of a pass: triangles from gl_VertexID, clip space, draw modes, handing values to the fragment shader (smooth and flat), instancing and random copies, additive glow, 3D meshes and the camera's matrices, depth, lighting, displacement, meshes built in code, then triangles with a glow pass and neon wireframes.
A free interactive course of 21 steps in glint, a live shader editor in the browser: each step changes a running shader, and ticks itself when you've done its task.
1. The two halves of a pass
Every pass is two programs. The vertex shader runs once for each corner of the shape being drawn, and its one job is to say where that corner goes on screen, in gl_Position. The GPU then fills in the triangles between the corners and runs the fragment shader once for every pixel inside them.
Everything so far in the other courses drew the same thing: a rectangle covering the screen (Pass panel › Geometry › Full-screen quad), with all the work done per pixel. That rectangle is two triangles sharing a diagonal: four corners, and a_position is this corner's position, from the mesh.
Corners are placed in clip space: −1 to 1 across the screen and −1 to 1 up it, whatever its size. The quad's corners are (−1, −1) to (1, 1), so it fills the screen exactly.
The colour comes from gl_FragCoord, the pixel's place on screen, so shrinking the rectangle doesn't shrink the picture: it crops it, like a window. (Pass panel › Draw mode › Lines draws just the edges, diagonal included.)
Your turn: In the Vertex tab, shrink the rectangle to half size: change a_position.xy * 1.0 to a_position.xy * 0.5.
2. One triangle from nothing
A vertex shader doesn't need a mesh. This pass has none (Pass panel › Geometry › Vertices only) and asks for 3 corners. The vertex shader runs three times, and gl_VertexID says which run this is: 0, 1, then 2.
So the corners can simply be written down: a constant array of three positions, and each run picks its own with CORNERS[gl_VertexID]. Then gl_Position puts it on screen. The Draw mode is Triangles, so every three corners make one filled triangle.
The fragment shader only colours what's inside: here, all orange.
Your turn: Make the triangle lean: move its top corner, e.g. to vec2(0.4, 0.8).
3. Three triangles
More triangles is just more corners: every three make one. With 9 corners gl_VertexID runs from 0 to 8, and two little sums turn it into which triangle and which corner of it:
ID 0 1 2 3 4 5 6 7 8
ID / 3 0 0 0 1 1 1 2 2 2 which triangle
ID % 3 0 1 2 0 1 2 0 1 2 which corner(/ between whole numbers drops the remainder; % is the remainder.) The corner picks a point of the triangle's shape, SHAPE, around its own centre; the triangle number picks where that centre goes, PLACE. Adding them puts the corner in the right place.
The pass only asks for 3 corners, so only triangle 0 is drawn, the one in the middle. This is the whole trick for drawing a handful of shapes: no maths per pixel to decide what's inside what, the GPU fills them.
Your turn: In the Pass panel (opened on the right), set Geometry › Vertex count to 9.
4. Clip space, and the screen's shape
Now each triangle spins round its own centre: rot(angle) turns the shape before it's moved into place. Watch them: they stretch and squash as they turn.
That's clip space. x runs −1 to 1 across the screen and y −1 to 1 up it, so on a wide screen one unit across is longer than one unit up. Fragment shaders fix it by dividing by resolution.y; here it's the same idea backwards, squeezing x by the screen's height over its width.
And why vec4(p, 0.0, 1.0)? The third number is depth (for which of two things is in front, later). The fourth, w, divides the others: the GPU shows (x / w, y / w). With w = 1 they're used as they are; perspective (far things smaller) is made by putting the distance in w, as two later steps do.
Your turn: Keep their shape: before gl_Position, add p.x *= resolution.y / resolution.x;
5. Draw modes
The same 9 corners can be joined up in different ways: Pass panel › Geometry › Draw mode.
Triangles every 3 corners: one triangle
Lines every 2: a line
Line strip a line through all of them
Points a dot at each corner
Triangle strip each corner + the 2 beforePoints are squares gl_PointSize pixels wide (set here in the vertex shader; it does nothing in other modes). The fragment shader runs for every pixel of a point, and gl_PointCoord says where in the square it is, which is how particles get drawn as round dots.
Lines are always 1 pixel wide in WebGL. For thick or glowing lines, draw thin triangles (or a quad) and do the line in the fragment shader: step 7 shows how.
Your turn: Set the Draw mode to something other than Triangles, and try each.
6. Varyings: handing values on
The vertex shader can hand values to the fragment shader: declare out vec3 v_color; in the vertex shader and in vec3 v_color; in the fragment shader, same name and type. They're called varyings.
Each corner sets its own value, but the fragment shader runs for pixels between corners. So the GPU blends: a pixel halfway along an edge gets half of each end's value, and one in the middle gets a third of each corner's. That's why the classic first triangle is a smooth rainbow.
Here the corners are red, green and blue, and v_color is already handed on, but the fragment shader still ignores it and paints orange.
Your turn: In the Fragment tab, use it: fragColor = vec4(v_color, 1.0);
7. Each triangle's own coordinates
Blending works for any value, positions included. Each corner hands on its position in its triangle's own shape, v_local, before it's turned and moved. In the fragment shader that gives every pixel its place inside its own triangle, with (0, 0) at the centre, however the triangle moves.
Which means everything from the 2D courses works inside a triangle: distance functions, outlines, glows. sdTri is the distance to a triangle's edge (negative inside). The triangle drawn is twice the size of that shape, leaving room round it for a glow.
For now the colour shows v_local itself: red across, green up, the same in all three however they turn.
The glow is the neon trick: 0.03 / abs(d) is very bright where d is near 0 (on the edge) and fades away smoothly either side.
Your turn: In the Fragment tab, draw the neon outline: vec3 col = v_tint * 0.03 / abs(d);
8. flat: one colour per triangle
This is a sheet of squares, each two triangles: 16 × 10 squares × 6 corners = 960 corners, all worked out from gl_VertexID (the square, then which of its six corners). The inner points drift, so it ripples like a low-poly poster.
Each corner gets its own colour and the GPU blends them, so it's soft. For the faceted low-poly look each triangle should be one colour: put flat before the varying, in both shaders (they have to match, or the pass won't link: change both before it recompiles, or expect an error in between). Then nothing is blended: the whole triangle takes the value from one of its corners (in WebGL, its last).
flat is also the only way to hand on whole numbers (int, uint): there's no halfway between 3 and 4.
Your turn: Make it faceted: flat out vec3 v_color; in the Vertex tab and flat in vec3 v_color; in the Fragment tab.
9. Moving corners is cheap
Work in the vertex shader runs once per corner: 960 times a frame here. The same work per pixel would run about 2 million times. So anything that moves whole shapes (positions, sizes, turning) belongs in the vertex shader, and the fragment shader only colours.
push moves every corner outwards by its own random amount, and brightens it. It's 0 now. Make it follow the music: spectrum.x is the bass, 0 to 1, with audio on (Inputs panel). Without audio, try 0.5 + 0.5 * sin(time * 3.0).
Your turn: Set push to something that moves: float push = spectrum.x; (or the sine).
10. Instancing: hundreds of copies
Drawing the same shape many times doesn't need more corners: Pass panel › Geometry › Instances draws the whole thing again and again, in one go. In each copy gl_InstanceID says which copy it is (0, 1, 2 …) and instanceCount how many there are.
This is one triangle, 3 corners. With Instances at 1 there's just copy 0, in the middle. Each copy uses its number to find its place on a sunflower spiral (each one turned by the golden angle from the last and a little further out) and its colour.
Instances are the fast way to draw particles, crowds, grass or confetti: one small shape, one draw, thousands of copies.
Your turn: In the Pass panel, set Instances to 300.
11. Something random for each copy
Copies that are all the same look fake. A hash turns each copy's number into random-looking numbers that stay the same every frame: hash(id * 4u), hash(id * 4u + 1u)… are four different ones for the same copy.
This hash works on whole numbers (uint, the u on the end), mixing their bits. The fract(sin(x) * 43758.5) hash you'll see in many shaders falls apart on real GPUs once x gets big: thousands of copies would all get the same number.
Here h2 picks where across, h3 where it starts falling, h4 its colour and spin. But they all fall at the same speed, like a sheet.
Your turn: Give each its own speed: float speed = 0.1 + 0.3 * h;
12. Blending: glow for free
2,000 soft stars, each a triangle with a fuzzy dot drawn in it (v_local again). But each triangle paints over whatever was there, dark corners and all, so the galaxy is a mess of black edges.
Pass panel › Render › Blending decides how a new pixel combines with the one already there. Off replaces it. Alpha mixes by the alpha. Additive adds the colours: black adds nothing, so the corners vanish, and where stars overlap they get brighter.
Additive blending is the cheapest glow there is: no raymarching, no blur, just light adding up. Order doesn't matter either, so nothing needs sorting.
Your turn: Set Pass panel › Render › Blending to Additive.
13. 3D meshes
Now 3D. Pass panel › Geometry › Shape has ready-made meshes: plane, cube, sphere, torus. Each corner comes in as attributes: a_position (where), a_normal (which way the surface faces) and a_texcoord (a 0..1 position across it).
mvp (model-view-projection) is the camera from Pass panel › Camera: one matrix that turns a 3D point into a place on screen, with perspective. So the whole vertex shader is gl_Position = mvp * a_position;.
The fragment shader shows the normal as a colour: red where the surface faces right, green up, blue towards you. Depth test is on (two steps on says why). Draw mode › Lines shows the triangles.
Your turn: Pick another Shape: Sphere, Torus or Plane.
14. The camera's three matrices
mvp is three matrices multiplied together, and here they're used one at a time so you can step in between.
modelMatrix object -> world
viewMatrix world -> camera
projectionMatrix camera -> screenThe model matrix places and turns the object in the world (here it's the Camera panel's tilt and spin). The view matrix moves the world so the camera is at the centre looking down −z. The projection matrix adds perspective: it puts the distance into w, and the GPU divides by w, so far things shrink.
Between them, world is the corner's position in the world, and you can move it there: anything added is in world units, up is up, whatever the object's turned to.
Your turn: Make it bob: after the world line, add world.y += 0.3 * sin(time * 2.0);
15. Something's wrong: the depth test
Look closely at this torus: as it turns, the far side of the ring shows through the near side. Triangles are drawn in the order they come in the mesh, and each one simply paints over what was there.
The fix is a depth buffer: a second picture holding, for every pixel, how far away the thing drawn there is. With the depth test on, a pixel is only drawn if it's nearer than what's already there, so the order stops mattering. (The fragment's depth comes from gl_Position's z over w.)
Raymarching never needs this: each pixel's ray finds the nearest surface itself. For triangles it's the first thing to switch on in 3D. Don't use it with additive blending, where everything should show.
Your turn: Turn on Pass panel › Render › Depth test.
16. Lighting a mesh
Light depends on which way the surface faces: dot(n, light) is 1 facing the light, 0 side-on. Watch the torus: the bright patch turns with it, as if the lamp were glued on.
That's because a_normal is the mesh's own normal, in the object's space. When the model matrix turns the object, its normals must turn too, or the light sees the object as it was before turning.
normalMatrix does it: the model matrix's turning part (inverted and transposed, which keeps normals at right angles to the surface even when an object is stretched).
Your turn: Turn the normals with the object: v_normal = normalMatrix * a_normal;
17. Displacement: moving every corner
A flat plane of 64 × 64 squares (Shape: Plane, Segments 64). The vertex shader lays it flat and lifts each corner by h, a height worked out from where it is: one wave, rolling along x. Draw mode is Lines, so you see the grid.
This is how terrain, water and flags are done: a fine flat mesh, and a height (or any push) per corner. A sphere pushed out by noise times spectrum.x makes a blob that swells with the bass.
v_h hands the height on so the fragment shader can colour by it.
Your turn: Add a second wave across the first: float h = 0.15 * sin(p.x * 3.0 + time) + 0.1 * sin(p.z * 5.0 - time * 1.3);
18. Building your own mesh
The ready-made shapes run out quickly, but any mesh that's a grid can be built from gl_VertexID. This is a tube following a knot: segments squares along it, SIDES squares round it, 6 corners each, all from one number.
For each corner: t is how far along the knot, a how far round the tube. T points along the curve; two directions at right angles to it (N, B, from cross products) make a little circle, and the corner goes out from the centre line along cos(a) * N + sin(a) * B. That direction is also the surface's normal, for free.
With 3 sides the tube is a twisted triangular bar: the lighting is smooth (normals blend) but the outline is jagged.
Your turn: Make it round: raise SIDES to 12. (The vertex count stays 36,000, so it uses fewer squares along.)
19. Triangles, then a glow pass
A tunnel of triangle outlines: 60 instances, each pushed further away (z) and divided by it, which is perspective by hand. They're drawn with additive blending, and fade with distance: fog, with no raymarching at all.
Pass 1, Glow (the one open), is a full-screen quad that reads Shapes' picture. Glow spreading round bright things is a blur, and blurs are cheap from mipmaps: smaller and smaller copies of the picture the GPU makes for us (the prevPass sampler is set to mipmap in this pass). blurred(…, float(i)) reads copy i (2, 4, 8… times smaller, so blurrier) with textureLod, at six points round a little circle so its big pixels don't show as blocks.
Adding the copies on top of the sharp picture is bloom. Right now GLOW is 0.
Your turn: In the Glow pass, turn it up: const float GLOW = 1.5;
20. Neon wireframe
A synthwave road, built from a 60 × 60 grid in the vertex shader: rows slide towards you, hills rise either side, and perspective is by hand again (w = z). Pass 1 lays it over a sunset and adds bloom.
Wireframe lines from Draw mode › Lines are 1 pixel and can't glow. Instead, give each triangle's corners (1,0,0), (0,1,0) and (0,0,1). Blended, a value near 0 means near the edge across from that corner. The smallest of them is the distance to the nearest edge, and fwidth turns that into a line about a pixel wide, at any distance.
BARY is arranged so that the diagonal of each square never counts, so you get squares, not triangles. The line is worked out already; it isn't drawn yet.
Your turn: In the Ground pass's Fragment tab, add the neon: col += vec3(1.0, 0.2, 0.8) * line; before the haze line.
21. Pull it apart: three neon triangles
Everything together: three triangles in a triangle, spinning, breathing with the bass and jumping on the beat (with no audio, a pulse every second), with neon edges and a glow pass. This is the kind of thing that's hard work per pixel and easy with corners.
But it's broken: there are no edges, just three dim blobs. Something the fragment shader needs isn't arriving. Read both tabs of the Shapes pass and find what.
Hint: the fragment shader draws the outline from v_local, each pixel's place in its triangle. What does the vertex shader set it to?
Your turn: Fix it, so the neon outlines come back.
Other courses: Basics · Medium · Advanced · Maths for shaders · Raymarching, step by step · Matrices, from scratch · Sound you can see · Noise from scratch · Colour and light · Passes and feedback · Skies and reflections · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Raymarching 4: modelling, materials and motion · Fractals, step by step · Vertex shaders 2: lines, particles and moving meshes · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow