Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Shaders and Post-processing

Vertex Shaders, Displacement and onBeforeCompile

Move vertices on the GPU in Three.js: wave and noise displacement, custom attributes, shader-driven particles with Points, and extending MeshStandardMaterial with onBeforeCompile.

In the previous lesson most of the creativity happened in the fragment shader. The vertex shader is just as powerful: because it decides where every vertex ends up, it can bend flags, ripple water, grow grass, morph a sphere into a cube and animate a hundred thousand particles, all without touching the CPU after setup.

This lesson shows vertex displacement, per-vertex custom attributes, a GPU particle field, and a very practical technique, onBeforeCompile, that adds your custom vertex code to a built-in material and keeps its lighting and shadows.

Displacing vertices

The vertex shader receives position (an attribute) and may change it before projecting:

GLSL
vec3 p = position;
p.z += sin(p.x * 4.0 + uTime) * 0.2;      // a travelling wave
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);

Two consequences matter:

  1. You need enough vertices. A plane made of two triangles cannot ripple; use PlaneGeometry(w, h, 128, 128). Displacement changes only the vertices you have.
  2. Normals do not follow automatically. The geometry's normal attribute still describes the flat surface, so lighting looks flat. Either recompute normals in the shader (by sampling the height function at neighbours) or derive a face normal in the fragment shader from screen-space derivatives, as the example below does.

Noise functions give natural-looking height. GLSL has no built-in random, so a compact hash is the usual starting point:

GLSL
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
float noise(vec2 p) {            // value noise: smooth blend between random lattice values
  vec2 i = floor(p), f = fract(p);
  f = f * f * (3.0 - 2.0 * f);   // smoothstep curve
  return mix(mix(hash(i), hash(i + vec2(1, 0)), f.x),
             mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), f.x), f.y);
}
A rolling terrain displaced on the GPU

The 25,921 vertices are moved every frame by the GPU, while the CPU only updates one number. Doing the same loop in JavaScript would work for a few thousand vertices but not for millions.

One caveat: because displacement happens on the GPU, the CPU does not know about it. Raycasting and bounding boxes use the original geometry, so picking a displaced mesh finds the flat plane. If you need accurate picking, compute the height on the CPU too, or raycast a proxy.

Custom attributes: per-vertex data

Any array you attach to a BufferGeometry can become an attribute in the vertex shader. That is how you give every particle its own random phase, color or size. With THREE.Points, each vertex is one square sprite whose size is set by gl_PointSize, and gl_PointCoord gives the 0 to 1 position inside that square, which is enough to cut a round shape.

GPU particles with a custom attribute

Note uPixelRatio: gl_PointSize is measured in device pixels, so on a retina screen you scale it or the dots shrink. Additive blending makes overlapping particles brighten, which is what gives the glow.

Extending built-in materials with onBeforeCompile

Writing a full ShaderMaterial means you lose what MeshStandardMaterial gives you: PBR lighting, shadows, fog, environment maps, color management. Often you only want a small change, such as "wobble the vertices" or "tint by height". For that, Three.js lets you edit the generated shader source just before it compiles.

Built-in shaders are assembled from named chunks, referenced as #include <chunkname>. You hook into one by replacing its include with the include plus your own code:

JavaScript
material.onBeforeCompile = (shader) => {
  shader.uniforms.uTime = timeUniform;                      // add your uniforms
  shader.vertexShader = shader.vertexShader
    .replace('#include <common>', '#include <common>\nuniform float uTime;')
    .replace('#include <begin_vertex>', `
      #include <begin_vertex>
      transformed.y += sin(position.x * 3.0 + uTime) * 0.15;
    `);
};

Useful chunks: begin_vertex (the variable transformed holds the vertex position before projection), beginnormal_vertex (modify objectNormal), color_fragment and map_fragment (adjust diffuseColor), emissivemap_fragment (add glow to totalEmissiveRadiance), and output_fragment (final color). Because you only add to the pipeline, lights, shadows, fog and tone mapping all keep working.

A lit, shadowed material with custom wobble

Notice that the cylinder still receives a real shadow on the floor and is lit by the hemisphere light. One catch: the shadow pass uses a different (depth) material, so the shadow does not wobble with the mesh unless you also set mesh.customDepthMaterial with the same displacement. For anything big, consider the dedicated node materials (TSL), covered in WebGPU and TSL, which make this kind of extension cleaner.

Practical advice

  • Prefer onBeforeCompile when you only tweak a standard material; prefer ShaderMaterial when the look is entirely custom.
  • Dump the real shader to see chunk names: console.log(shader.vertexShader) inside the hook.
  • Keep all per-frame work in uniforms; rebuilding geometry attributes each frame defeats the purpose.
  • Never call Math.random() in GLSL (it does not exist). Hash functions, textures of noise, or attributes you generate once on the CPU are the options.
  • Set frustumCulled = false on meshes that your shader moves far from their bounding sphere, otherwise they vanish when their original position leaves the screen.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a displaced two-triangle plane not ripple?

    Vertex displacement moves vertices. A plane with four corners can only move four points, so use many segments.
  2. 2. What is gl_PointCoord used for?

    In the fragment shader of a Points material it gives each pixel's location inside the point's square.
  3. 3. What is the main advantage of onBeforeCompile over a plain ShaderMaterial?

    You only inject small pieces into chunks of the existing shader, so the rest of the PBR pipeline continues to work.
  4. 4. A mesh displaced in the vertex shader is hard to click with a Raycaster. Why?

    The displacement exists only in the GPU, so the raycaster tests the undisplaced triangles.

Summary

  • The vertex shader can displace positions, animate with a time uniform, and pass data to the fragment shader through varyings.
  • Displacement needs dense geometry; normals must be recomputed or derived (for example with dFdx and dFdy).
  • Custom BufferAttributes become attribute variables; Points with gl_PointSize and gl_PointCoord make GPU particle systems.
  • onBeforeCompile injects code into a built-in material's chunks (begin_vertex, color_fragment, ...) while keeping its lighting and shadows.
  • Displacement is invisible to the CPU: raycasts and bounding boxes use the original geometry.

Next: Post-processing with EffectComposer