Why CPU Vertex Loops Stall the Main Thread
Most WebGL terrain tutorials start with the same pattern: create a subdivided THREE.PlaneGeometry, loop over geometry.attributes.position.array inside requestAnimationFrame, evaluate a JavaScript noise function for each vertex, call computeVertexNormals(), and set position.needsUpdate = true. On a small 32 by 32 grid that approach looks effortless. Scale the mesh to a crisp 160 by 160 surface (25,921 vertices and 51,200 triangles) and frame pacing collapses on laptops and mobile devices.
The bottleneck is not just JavaScript arithmetic. Every time you flag needsUpdate = true on a buffer attribute, Three.js schedules a gl.bufferSubData transfer across the CPU to GPU boundary. For a 160 by 160 plane storing positions and normals as 32-bit floats, each frame pushes roughly 622 KB of dynamic vertex memory over the bus before the rasterizer can even start. Worse, computeVertexNormals() traverses every triangle index on the main thread, accumulating cross products and normalizing vectors in a single synchronous sweep that competes directly with DOM layout, input events, and garbage collection.
A procedural terrain mesh rarely needs to mutate its topology on the CPU. If the height at any point (x, z) is a deterministic function of world coordinates and time, the entire displacement belongs in the vertex shader. The geometry buffers stay static in VRAM after the first upload, draw calls stay pinned at one, and the CPU spends less than 0.2 milliseconds per frame updating a handful of uniform floats.
Designing a Frame-Stable Heightfield in GLSL
Writing terrain noise directly in GLSL lets hundreds of shader cores evaluate vertex elevations in parallel. The key is choosing a noise primitive that avoids texture lookups (which can trigger cache misses on mobile GPUs) and avoids dynamic branching inside the octave loop. A lightweight hash-based value noise combined with a quintic Hermite interpolation curve (u * u * u * (u * (u * 6.0 - 15.0) + 10.0)) gives C2-continuous derivatives with minimal ALU cost.
Four octaves of fractional Brownian motion (fBm) strike the right balance between broad mountain ridges and fine micro-relief. Rotating the domain by a fixed 2 by 2 orthonormal matrix between octaves breaks up the subtle axis-aligned grid artifacts that standard value noise can produce when viewed from a low oblique camera angle. Because the loop bound is a compile-time constant, the GLSL compiler unrolls all four iterations into straight-line vector instructions.
uniform float uTime;
uniform float uAmplitude;
uniform float uFrequency;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
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);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
float terrainHeight(vec2 xz) {
const mat2 rot = mat2(0.80, -0.60, 0.60, 0.80);
vec2 p = xz * uFrequency + vec2(uTime * 0.12, uTime * 0.08);
float sum = 0.0;
float gain = 0.52;
for (int i = 0; i < 4; i++) {
sum += gain * (valueNoise(p) * 2.0 - 1.0);
p = rot * p * 2.04;
gain *= 0.5;
}
return sum * uAmplitude;
}
Notice how terrainHeight accepts a 2D coordinate in the horizontal plane and returns a scalar displacement centered around zero. Keeping the heightfield purely a function of vec2 makes it trivial to sample neighboring offsets when computing smooth surface normals in the next step.
Interactive Mesh & Shader Sandbox
Below is a live Three.js 0.170.0 viewport running the exact vertex displacement shader from this post on a 96 by 96 terrain mesh. Toggle wireframe rendering to inspect the underlying triangle topology, adjust the vertex noise amplitude to stress-test slope lighting, or change the camera orbit speed. The code inspector beneath the canvas reflects your active uniform values in real time.
// Live vertex shader uniforms synced with controls
uniform float uAmplitude = 0.85;
uniform float uRotationSpeed = 0.35;
// Material state: wireframe = true
void main() {
vec3 pos = position;
float h = terrainHeight(pos.xz);
pos.y += h;
vElevation = h;
vNormal = computeNormal(pos.xz, 0.08);
gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
}
Analytical Normals vs. Screen-Space Derivatives
Once vertices move on the GPU, the original upward-facing normals in PlaneGeometry are stale. Lighting a displaced mesh with flat (0, 1, 0) normals hides every ridge and valley. Developers usually reach for one of two fixes: screen-space partial derivatives in the fragment shader, or finite-difference tangent sampling in the vertex shader.
Screen-space derivatives via normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos))) are compact and require zero extra noise evaluations. However, because dFdx and dFdy measure differences across 2 by 2 pixel quads on a flat triangle face, the resulting normal is constant across each triangle. That gives a crisp low-poly faceted look, which works for stylized terrain, yet visibly breaks smooth specular highlights when wireframe mode is turned off.
For smooth shading without a second render pass, evaluate terrainHeight at two small orthogonal offsets along +X and +Z right inside the vertex shader. Constructing the tangent vectors and taking their cross product produces a smooth per-vertex normal that interpolates cleanly across every fragment. Pairing those normals with an emerald elevation contour line in the fragment shader makes subtle height gradients legible even in dark charcoal scenes.
// Vertex shader: finite-difference normal from two neighbor samples
vec3 computeNormal(vec2 xz, float eps) {
float hC = terrainHeight(xz);
float hX = terrainHeight(xz + vec2(eps, 0.0));
float hZ = terrainHeight(xz + vec2(0.0, eps));
vec3 tangentX = vec3(eps, hX - hC, 0.0);
vec3 tangentZ = vec3(0.0, hZ - hC, eps);
return normalize(cross(tangentZ, tangentX));
}
// Fragment shader: slope shading + anti-aliased contour lines
vec3 lightDir = normalize(vec3(0.55, 0.80, 0.35));
float ndl = clamp(dot(normalize(vNormal), lightDir), 0.0, 1.0);
float band = abs(fract(vElevation * 4.5) - 0.5);
float contour = 1.0 - smoothstep(0.02, 0.06, band);
vec3 surface = mix(uValleyColor, uRidgeColor, ndl);
gl_FragColor = vec4(mix(surface, uContourColor, contour * 0.55), 1.0);
DPR Capping and Frame-Loop Discipline
A fast shader still wastes battery if the renderer runs unchecked on a 3x HiDPI display or keeps spinning while the reader scrolls down to the comments. Three small lifecycle guards keep embedded WebGL scenes polite inside long-form articles:
- Cap devicePixelRatio at 2. On 3x mobile displays, rendering at native resolution multiplies fragment shading work by 2.25x compared to 2x with almost no perceptible gain on soft procedural surfaces.
- Gate the loop with IntersectionObserver and visibilitychange. Pause
requestAnimationFramethe instant the sandbox leaves the viewport or the browser tab moves to the background. - Respect reduced motion preferences. When
prefers-reduced-motion: reduceis active, render one crisp static frame on load and only re-render on direct user interaction with the sliders or wireframe button.
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: 'high-performance',
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
let isVisible = true;
let rafId = 0;
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function syncLoop() {
const shouldRun = isVisible && !document.hidden && !reducedMotion;
if (shouldRun && !rafId) {
rafId = requestAnimationFrame(tick);
} else if (!shouldRun && rafId) {
cancelAnimationFrame(rafId);
rafId = 0;
}
}
new IntersectionObserver(([entry]) => {
isVisible = entry.isIntersecting;
syncLoop();
}, { threshold: 0.05 }).observe(canvas);
document.addEventListener('visibilitychange', syncLoop);
Frame-Time Budget Benchmarks
We profiled all three pipelines on an Apple M2 MacBook Air at 1440 by 900 (DPR capped at 2) and a mid-tier Android phone over a 30-second orbit. Moving noise and normal evaluation into the vertex shader cuts CPU frame time by more than 94% on dense meshes and eliminates frame-time spikes completely.
| Pipeline Strategy | Grid Size | CPU / Frame | GPU / Frame | 99th Percentile |
|---|---|---|---|---|
CPU Loop + computeVertexNormals |
96 × 96 | 7.8 ms | 1.4 ms | 18.9 ms |
CPU Loop + computeVertexNormals |
160 × 160 | 21.4 ms | 2.6 ms | 34.2 ms |
GLSL Vertex Noise + dFdx/dFdy |
160 × 160 | 0.18 ms | 1.9 ms | 2.4 ms |
| GLSL Vertex Noise + Finite-Diff Normals | 160 × 160 | 0.19 ms | 2.3 ms | 2.9 ms |
Takeaway: For interactive WebGL articles and map editors, reserve CPU geometry mutation for topology changes or physics queries. Keep continuous displacement, normal calculation, and contour styling inside a single shader pass so your main thread remains free for UI responsiveness.
Rotating the domain matrix between octaves fixed the diagonal striping we were seeing in our map previewer. Capping DPR at 2 also dropped GPU frame time on iPhone Safari from 9.1 ms down to 4.4 ms.
Quick tip for anyone using WebGL1 fallbacks: keep the finite-difference epsilon tied to your mesh grid spacing (roughly one half of a cell width) so steep ridges do not alias at low subdivision counts.