Vertex shaders 2: lines, particles and moving meshes

glint · Examples · Tutorials · Gallery

After Vertex shaders, step by step: thick lines from triangles, an oscilloscope and spectrum bars from the audio, points that shrink with distance, billboards, a fountain and fireworks, instanced cubes turning and dancing to music, morphing, twisting and fixing normals, heights from another pass, a comet's tail, text from the font texture, shattering a mesh, and light per corner or per pixel.

A free interactive course of 20 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. Thick lines from triangles

WebGL's lines (Draw mode › Lines) are always 1 pixel wide. For lines of any width, glowing or tapering, make them out of triangles: cut the line into segments and draw each as a thin quad (2 triangles, 6 corners).

Each corner knows which segment it's in (gl_VertexID / 6), which end of it (CORNER[…].x) and which side (.y). It finds its point on the curve, the curve's direction there, and steps WIDTH to the side, at right angles. Neighbouring segments share their ends exactly, so the joins are seamless.

v_across (−1 to 1) goes to the fragment shader, which makes it glow brightest down the middle. The blending is additive, so where the line crosses itself it's brighter.

Your turn: Make it thick: const float WIDTH = 0.03;

2. An oscilloscope

Vertex shaders can read textures too. fft is the audio input as a 512 × 2 texture: row 0 the spectrum, row 1 the waveform, the sound's actual wiggle over the last moment (0.5 is silence).

So the line's height at each point along can come straight from the waveform: read row 1 (y = 0.75, the middle of the second row) at u. Every corner of the line reads its own bit of the sound: an oscilloscope.

Turn on audio in the Inputs panel and play something. With no audio the texture is empty (0, not 0.5), so the line just drops to the bottom; the check only wants the code.

Your turn: Draw the sound: float y = (texture(fft, vec2(u, 0.75)).r - 0.5) * 1.5;

3. Spectrum bars

Row 0 of fft is the spectrum: how loud each frequency is, bass on the left. 64 bars, one instance each, each reading its own frequency and setting its own height: the classic graphic equaliser, for the cost of 64 quads.

High frequencies are crowded into the right of the texture and usually quieter, so u * u * 0.6 spreads the bass out across more bars and leaves out the very top.

No audio? Try float h = 0.4 + 0.3 * sin(time * 4.0 + u * 20.0); to see them move.

Your turn: Read the spectrum: float h = texture(fft, vec2(u * u * 0.6, 0.25)).r;

4. Points that shrink with distance

3,000 stars flying at you, drawn as points (Draw mode › Points), with perspective done by hand: w is the distance, and the GPU divides the position by it, so far stars bunch up in the middle.

But every point is 4 pixels however far away: distant stars look as big as close ones, and nothing seems to come closer. A point's size isn't divided by w; that's left to you. 40.0 / gl_Position.w makes it shrink with distance like everything else.

The fragment shader makes each square point round: gl_PointCoord is where the pixel is inside the point, 0 to 1.

Your turn: Size them by distance: gl_PointSize = 40.0 / gl_Position.w;

5. Billboards: quads that face you

Points have limits: a maximum size, always square to the screen, gone the moment their middle leaves it. Particles in 3D are usually billboards: a quad per particle that always turns to face the camera.

Here each quad's corners are spread out in the world (corner * SIZE in x and y), so they're flat cards facing +z. As the camera goes round they turn edge-on and vanish.

The fix: move the centre into the camera's space first (viewMatrix * modelMatrix), where x is always the screen's right and y its up, and spread the corners there. Then only the projection is left to do.

Your turn: Spread the corners in the camera's space: replace the two lines making world and gl_Position with vec4 eye = viewMatrix * modelMatrix * vec4(centre, 1.0);, then eye.xy += corner * SIZE;, then gl_Position = projectionMatrix * eye;

6. A fountain: particles without memory

Particles usually need memory: each frame, move every particle a little from where it was. But simple motion has a formula: something thrown at speed v0 is at v0 * t + ½ * g * t² after t seconds. So each particle can work out where it is from its age alone, with nothing stored.

Each one launches at its own moment (fract(time / LIFE + h): its age, wrapping round every LIFE seconds, offset by its own random h) with its own speed, mostly upwards.

With no gravity they fly off in straight lines. Earth's is 9.8 down; at this scale 2.5 looks right.

Your turn: Add gravity: const vec3 GRAVITY = vec3(0.0, -2.5, 0.0);

7. Lifetimes: fading out

Each particle pops into existence at full size and brightness, and vanishes the same way when its time is up and it starts again. Watch the bottom: drops blinking out.

life should run from 1 when it's launched down to 0 at the end. The size and the colour already use it (0.05 * (0.4 + 0.6 * life), * life), so with it worked out, drops shrink and fade as they fall, and nobody sees them restart.

Your turn: Count it down: float life = 1.0 - age / LIFE;

8. Fireworks

Groups of particles: 1,200 instances as 8 bursts of 150 sparks. id / SPARKS is the burst, and everything about a burst (when it goes off, where) comes from hashing that number, so all its sparks agree. Each spark adds its own direction: a random point on a sphere.

They fly out fast and slow down (1 - exp(-age * 3) levels off), fall, and fade with life * life. The same recipe makes explosions, sparks off a grinder, or confetti cannons.

All bursts are the same gold. Give each its own colour, from its own number.

Your turn: Colour each burst: vec3 colour = 0.6 + 0.4 * cos(6.2832 * (hash(b * 7u + 4u) + vec3(0.0, 0.33, 0.67)));

9. A field of cubes

Instancing works with meshes too: Shape › Cube with 400 instances draws 400 cubes in one go. Here they're all in the same place, on top of each other.

Lay them out in a 20 × 20 grid from the instance number: i % 20 is the column, i / 20 the row. Subtracting 9.5 centres the grid, and 0.13 spaces them a little more than a cube's width apart.

Your turn: Spread them out: vec3 offset = vec3(float(i % 20) - 9.5, 0.0, float(i / 20) - 9.5) * 0.13;

10. Each copy turned

Each copy can be turned as well as moved. R is a rotation matrix (here about the vertical axis): applied to the mesh's corners before they're moved into place, it turns each cube round its own middle.

The normals must turn the same way, or the lighting stays put while the cube turns: that's why R is applied to a_normal too. Give every cube its own angle, from its hash, plus time to set them spinning.

Your turn: Turn each cube: mat3 R = rotY(time * 2.0 + h * 6.2832);

11. A floor that dances

Now the height. level is already worked out per cube: the spectrum (row 0 of fft) at a frequency picked by the cube's distance from the middle, so bass in the centre and treble at the edges, plus a ripple running outwards so it moves without audio too.

Each cube is stood on the floor ((a_position.y + 0.5) * height: its bottom at 0, its top at height), so making height follow level grows them upwards. Turn on audio (Inputs panel) to see the music.

Your turn: Follow the music: float height = 0.1 + 1.2 * level;

12. Morphing one mesh into another

A vertex shader can move every corner anywhere, including into a completely different shape. Each corner of this sphere knows its direction from the middle; pushing it out along that direction until it meets a cube's surface (divide by its largest part) gives the same corner on a cube.

Mixing the two positions by m morphs between them, and the normals are mixed too so the light follows. Any two shapes can morph like this as long as each corner has a sensible place on both.

Your turn: Morph back and forth: float m = 0.5 + 0.5 * sin(time);

13. Twisting

Deforming a mesh is a function from each corner to where it goes. shape makes a tall square column from the sphere mesh, then twists it: each corner is turned round the vertical axis by an angle that grows with its height, p.y * twist.

Bends, tapers, waves and wobbles all work the same way: a turn, scale or shift that depends on where the corner is. Notice the lighting, though: it still lights a smooth sphere, not a twisted column. The next step fixes that.

Your turn: Twist it, back and forth: float twist = 2.0 * sin(time * 0.7);

14. Normals after bending

a_normal is the original sphere's normal. Once the corners have been moved into a twisted column, it's wrong: the faces of the column are flat, but they're lit as a smooth ball.

The surface's real direction can be measured: work out the shape a tiny step along u and a tiny step along v from this corner (du, dv, already done). Both lie in the bent surface, so their cross product is at right angles to it: the new normal. (The tiny bit of a_normal only matters at the poles, where a step along u goes nowhere.)

Any deformation can get its normals this way, at the cost of two more calls of the shape.

Your turn: Use the real normal: vec3 n = normalize(cross(du, dv) + 1e-7 * a_normal);

15. Heights from another pass

Pass 0, Height, is an ordinary fragment shader drawing ripples, but not to look at: its red channel is a height, 0 to 1. Pass 1, Sheet, is a plane of 128 × 128 squares, and its vertex shader can read Height's picture (pass0) like any texture.

Each corner reads the height at its own place on the plane (a_texcoord, 0 to 1 across it) and lifts itself by that much. Anything a fragment shader can draw (noise, a simulation, a webcam) becomes a moving surface.

Your turn: In the Sheet pass's Vertex tab, read the height: float h = texture(pass0, a_texcoord).r;

16. A comet's tail

A trail is a line through where something has been. Nothing needs storing if the motion is a formula: the comet's head is at head(time), so a moment ago it was at head(time - 0.1). Make the thick line from step 1 follow the head's path into the past: its start is now, its end TRAIL seconds ago.

It also tapers (the width shrinks towards the end) and fades along v_along. For now TRAIL is 0.1: only a tenth of a second of the past, so the comet is a short stub with no tail to speak of.

Your turn: Give it a tail: const float TRAIL = 1.5;

17. Text from a font texture

The stock font texture holds every ASCII character in a 16 × 16 grid, as a distance field (alpha under 0.5 inside a letter). One instance per letter: each looks up its character in MSG, finds that character's cell in the grid, and hands the fragment shader where its corners are in the texture.

The fragment shader reads the distance field and draws the letter, plus a glow (the distance field makes outlines and glows free). Because each letter is its own instance, each can move on its own.

Your turn: Make the letters wave: float y = 0.08 * sin(time * 3.0 + float(i) * 0.6);

18. Shattering a mesh

To blow a mesh apart, each triangle has to move as one piece: all three corners by the same amount, in the same direction. But a vertex shader only sees its own corner.

So build the mesh in code (Vertices only, as in the first course), and let every corner work out its whole triangle: all three corners' positions, so it knows the triangle's middle and its normal. Moving by the middle's direction keeps each triangle whole, and the triangle's own normal makes it flat-shaded.

Your turn: Blow it apart, and back: float burst = 0.35 * max(sin(time), 0.0);

19. Light per corner, or per pixel

This torus has few corners (Segments 12). The lighting, a soft diffuse plus a sharp highlight, is worked out in the vertex shader, once per corner, and the colours blended across each triangle (Gouraud shading, how games lit everything around 2000).

It's cheap, but look at the highlight: blotchy, star-shaped, jumping from corner to corner, because a sharp highlight that falls between corners is simply missed. Hand on the normal instead and light each pixel (Phong shading): smooth whatever the mesh.

The fragment tab already has lit; it only needs the normal, normalised again (blending shortens it).

Your turn: In the Fragment tab, light per pixel: fragColor = vec4(lit(normalize(v_normal)), 1.0);

20. Pull it apart: a fountain that hiccups

The fountain again, with lifetimes, billboards, additive glow and a spray of colour. But it hiccups: every couple of seconds the whole fountain vanishes at once and starts again from the bottom, instead of flowing.

Every particle is on the same clock. Read how age is worked out, and what makes each particle different from the next.

Your turn: Fix it so the fountain flows.

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 · Vertex shaders, step by step · Raymarching 2: glow, fog and light · Raymarching 3: worlds · Raymarching 4: modelling, materials and motion · Fractals, step by step · Fractals 2: further in · Vertex shaders 3: living geometry · Post-processing · Surfaces: from vertex to fragment · Blur and glow