Three.js Fractal Mountains (Ray-Marched Terrain)

Infinite procedural mountains ray-marched in a Three.js shader using derivative-damped fBm for eroded ridges, with snow, water, soft sun shadows, aerial perspective and an automatic fly-through.

Key topics: three.js terrain, ray marching terrain, procedural mountains, fbm, heightfield, glsl landscape

What this code does

- Heightfield Marching: the ray advances by a fraction of its height above the terrain, which is fast and stable for height maps.
- Eroded fBm: each noise octave is damped by the accumulated gradient, so slopes stay smooth and ridges sharpen.
- Analytic Derivatives: value noise returns its gradient too, which drives the damping without extra samples.
- Materials: rock, grass on flat low ground and snow on high, gentle slopes are chosen from height and normal.
- Shadows & Fog: a coarse march toward the sun gives soft shadows, and exponential fog adds aerial perspective.
- Controls: octaves, derivative damping, sun angle, snow line, water level, fly-through toggle and speed.

Continue Learning

JavaScript Implementation

ES6+
// Heightfield ray marching: step along the ray by a fraction of the height above the terrain
const fragmentShader = `
  uniform vec3 uCamPos; uniform mat4 uCamWorld; uniform mat4 uInvProj; varying vec2 vUv;
  float hash (vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
  float noise (vec2 p) { vec2 i = floor(p), f = fract(p), u = f * f * (3.0 - 2.0 * f);
    return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y); }
  float terrain (vec2 p) { float h = 0.0, a = 1.0; p *= 0.006; for (int i = 0; i < 8; i++) { h += a * noise(p); a *= 0.5; p *= 2.0; } return h * 90.0 - 20.0; }
  void main () {
    vec4 v = uInvProj * vec4(vUv * 2.0 - 1.0, 1.0, 1.0);
    vec3 rd = normalize((uCamWorld * vec4(v.xyz / v.w, 0.0)).xyz);
    float t = 1.0;
    for (int i = 0; i < 250; i++) { vec3 p = uCamPos + rd * t; float h = p.y - terrain(p.xz); if (h < 0.002 * t || t > 1500.0) break; t += 0.45 * h; }
    vec3 sky = vec3(0.6, 0.72, 0.9);
    gl_FragColor = vec4(t < 1500.0 ? mix(vec3(0.3, 0.27, 0.22), sky, 1.0 - exp(-t * 0.002)) : sky, 1.0);
  }`
// Render it on a fullscreen quad, updating uCamPos / uCamWorld / uInvProj from the camera every frame.