GameCrew AIEarly access
Sign in
Three.jsrenderingRevision 3 · By @maddmann

Chunked LOD Heightfield Terrain with Skirts & Procedural Slope/Altitude Materials in Three.js

Updated

A seeded landscape drawn as a grid of chunks that each swap between four mesh resolutions by distance, with skirts hiding the cracks and normals taken from the height function so seams light evenly. A textureless grass, dirt, rock and snow material is patched into MeshStandardMaterial, and gameplay queries the same height function.

  • terrain
  • heightfield
  • lod
  • chunks
  • skirts
  • procedural
  • landscape
  • mountains
  • open world
The demo of Chunked LOD Heightfield Terrain with Skirts & Procedural Slope/Altitude Materials in Three.js, as its check took it

Play the demo

Demo passed on r3 (kept from r2: its files are unchanged since): a small game that shows only this technique, built and checked by GameCrew AI's engine.

Play the demo

Chunked LOD heightfield terrain

When to use it

A game needs open ground bigger than one mesh can afford: hills to walk, a valley to fly, mountains on the horizon. This draws a landscape from one seeded height function, keeps the triangle count down by drawing far ground coarsely, and shades it as grass, dirt, rock and snow with no textures at all.

It is a heightfield, so it has no overhangs, caves or arches. The world here is a fixed square built around the origin; an endless world needs chunks made and freed as the player travels, which this does not do. The material is procedural colour, which reads well from a glider and plainly from a boot's height; a game that lives at ground level will want textured layers, and the library's hexagonal anti-tiling guide covers tiling those without repetition.

The idea

  1. One height function is the terrain. height(x, z) is layered gradient noise: four octaves of rolling country, plus ridged noise ((1 - |n|)^2, sharp where plain noise crosses zero) that is switched on only where the rolling country is already high, so mountains rise out of uplands and valleys stay smooth. A lattice hash built on Math.imul makes it identical on every machine for a given seed. Everything else samples this function: every mesh at every resolution, the normals, and gameplay.
  2. Chunks. The world is cut into square chunks (64 m here, 8 by 8 of them). Each chunk is a regular grid in world space, so there is no per-chunk transform to get wrong.
  3. Levels of detail by distance. Each chunk can be built at 64, 32, 16 or 8 cells per edge. Every frame each chunk measures the distance from the eye to its footprint (zero for the chunk underfoot) and takes the finest level whose range covers it: under 100 m, under 190 m, under 320 m, or the coarsest. A chunk steps down to a coarser mesh 8% later than it stepped up, so it does not flicker on a ring.
  4. Lazy, budgeted building. A mesh is built the first time its chunk wants that level, then cached. At most two are built per frame, nearest chunk first, and a chunk keeps drawing what it has until its new mesh exists. Every chunk starts with its coarsest mesh, so the whole world is visible from the first frame.
  5. Skirts hide cracks. Where a fine chunk meets a coarse one, the fine edge has vertices the coarse edge lacks, and they sit above or below the coarse edge's straight line: a crack. Instead of stitching, each chunk hangs a vertical strip from its four edges, two cells deep. The crack still exists, but what shows through it is skirt, shaded like the ground beside it.
  6. Normals from the function, not the mesh. Each vertex normal is a central difference of height at a fixed half-metre offset. A vertex shared by two chunks, or present at two levels, gets the same normal in all of them, so there is no lighting seam between chunks and little change in shading when a chunk swaps level.
  7. Material by slope and altitude. The fragment shader decides what the ground is from its world position and normal: rock where it is steep, a band of dirt where it is nearly steep, snow where it is high and not steep, grass elsewhere. Value noise moves every threshold so no boundary follows a contour line. Rock gets near-level strata from noise stretched along x and z. All of it is 3D noise sampled at the world position, so nothing stretches on a cliff the way a top-down texture would.
  8. Detail the mesh does not have. A fine noise adds albedo variation and a bump: the normal is bent by the screen-space derivatives of a per-pixel height, which needs no UVs or tangents. Both fade out between 40 and 140 m, before they can shimmer.

The material is a MeshStandardMaterial patched in onBeforeCompile, so the scene's lights, shadows, environment light and fog apply to the terrain exactly as to anything else.

Implementation

import * as THREE from 'three';

export interface TerrainOptions {
  seed: number;
  /** World extent in metres along x and z; the terrain is centred on the origin. A multiple of `chunk`. */
  size: number;
  /** Chunk edge in metres. */
  chunk: number;
  /** Height scale in metres. Summits come out near it and hollows dip below zero. */
  maxHeight: number;
  /** Grid cells per chunk edge at each LOD, finest first. Each a power of two, so coarse vertices land on fine ones. */
  segments: number[];
  /** Distance in metres at which LOD i hands over to LOD i + 1; one fewer entry than `segments`. */
  ranges: number[];
}

export const TERRAIN_DEFAULTS: TerrainOptions = { seed: 7, size: 512, chunk: 64, maxHeight: 70, segments: [64, 32, 16, 8], ranges: [100, 190, 320] };

// ---- the height function ----

/** A lattice point's random number in 0..1, the same on every machine. */
function lattice(ix: number, iz: number, seed: number): number {
  let h = (Math.imul(ix, 374761393) + Math.imul(iz, 668265263) + Math.imul(seed, 1274126177)) | 0;
  h = Math.imul(h ^ (h >>> 13), 1103515245);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

function corner(ix: number, iz: number, fx: number, fz: number, seed: number): number {
  const a = lattice(ix, iz, seed) * 6.283185307179586;
  return Math.cos(a) * fx + Math.sin(a) * fz;
}

/** 2D gradient noise, about -1..1. */
function gradient(x: number, z: number, seed: number): number {
  const ix = Math.floor(x);
  const iz = Math.floor(z);
  const fx = x - ix;
  const fz = z - iz;
  const u = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
  const v = fz * fz * fz * (fz * (fz * 6 - 15) + 10);
  const a = corner(ix, iz, fx, fz, seed);
  const b = corner(ix + 1, iz, fx - 1, fz, seed);
  const c = corner(ix, iz + 1, fx, fz - 1, seed);
  const d = corner(ix + 1, iz + 1, fx - 1, fz - 1, seed);
  return (a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v) * 1.4142;
}

function fbm(x: number, z: number, octaves: number, seed: number): number {
  let sum = 0;
  let amp = 0.5;
  for (let i = 0; i < octaves; i++) {
    sum += gradient(x, z, seed + i) * amp;
    x *= 2;
    z *= 2;
    amp *= 0.5;
  }
  return sum;
}

/** Ridged noise, 0..1: sharp crests where the plain noise crosses zero. */
function ridged(x: number, z: number, octaves: number, seed: number): number {
  let sum = 0;
  let amp = 0.5;
  for (let i = 0; i < octaves; i++) {
    const r = 1 - Math.abs(gradient(x, z, seed + i));
    sum += r * r * amp;
    x *= 2;
    z *= 2;
    amp *= 0.5;
  }
  return sum;
}

function smooth(a: number, b: number, x: number): number {
  const t = Math.min(Math.max((x - a) / (b - a), 0), 1);
  return t * t * (3 - 2 * t);
}

// ---- the material ----

const FRAG_HEAD = /* glsl */ `
uniform float uSnowLine;
uniform vec3 uGrassA;
uniform vec3 uGrassB;
uniform vec3 uDirt;
uniform vec3 uRockA;
uniform vec3 uRockB;
uniform vec3 uSnow;
uniform vec3 uLodTint;
varying vec3 vTerrainPos;
varying vec3 vTerrainNormal;

float tRand(vec3 c) { return fract(sin(dot(c, vec3(127.1, 311.7, 74.7))) * 43758.5453); }

// 3D value noise sampled at the world position: nothing is projected, so nothing stretches on a cliff.
float tNoise(vec3 x) {
  vec3 i = floor(x);
  vec3 f = fract(x);
  f = f * f * (3.0 - 2.0 * f);
  float a = mix(tRand(i), tRand(i + vec3(1.0, 0.0, 0.0)), f.x);
  float b = mix(tRand(i + vec3(0.0, 1.0, 0.0)), tRand(i + vec3(1.0, 1.0, 0.0)), f.x);
  float c = mix(tRand(i + vec3(0.0, 0.0, 1.0)), tRand(i + vec3(1.0, 0.0, 1.0)), f.x);
  float d = mix(tRand(i + vec3(0.0, 1.0, 1.0)), tRand(i + vec3(1.0, 1.0, 1.0)), f.x);
  return mix(mix(a, b, f.y), mix(c, d, f.y), f.z);
}

float tFbm(vec3 p) {
  return tNoise(p) * 0.5 + tNoise(p * 2.03) * 0.3 + tNoise(p * 4.1) * 0.2;
}

struct TerrainSurface {
  vec3 albedo;
  float roughness;
  float bump; // metres
  float bumpStrength;
};

TerrainSurface terrainSurface(vec3 p, vec3 n) {
  float dist = length(p - cameraPosition);
  float closeUp = 1.0 - smoothstep(40.0, 140.0, dist); // fine detail fades out before it can shimmer
  float broad = tNoise(p * 0.035); // patches tens of metres across
  float fine = mix(0.5, tFbm(p * 0.9), closeUp);
  float slope = 1.0 - n.y;

  // Where each layer lives. Noise moves every threshold, so no boundary is a contour line.
  float rock = smoothstep(0.22, 0.42, slope + (broad - 0.5) * 0.18);
  float dirt = smoothstep(0.12, 0.22, slope + (fine - 0.5) * 0.1) * (1.0 - rock);
  float snow = smoothstep(-5.0, 5.0, p.y - uSnowLine + (broad - 0.5) * 14.0) * (1.0 - smoothstep(0.30, 0.55, slope));

  vec3 grass = mix(uGrassA, uGrassB, smoothstep(0.25, 0.75, broad)) * (0.65 + 0.7 * fine);
  float strata = tNoise(vec3(p.x * 0.05, p.y * 0.9 + broad * 3.0, p.z * 0.05)); // near-level bands
  vec3 stone = mix(uRockA, uRockB, strata) * (0.75 + 0.5 * fine);

  vec3 col = mix(grass, uDirt * (0.8 + 0.4 * fine), dirt * 0.7);
  col = mix(col, stone, rock);
  col = mix(col, uSnow, snow);

  TerrainSurface s;
  s.albedo = col;
  s.roughness = mix(mix(0.95, 0.85, rock), 0.55, snow);
  s.bump = (fine * mix(0.12, 0.35, rock) + strata * rock * 0.25) * (1.0 - snow * 0.8);
  s.bumpStrength = closeUp;
  return s;
}

// Bends a view-space normal by a height given per pixel, from screen-space derivatives (no tangents, no UVs).
vec3 terrainBump(vec3 n, vec3 p, float h, float strength) {
  vec3 dpdx = dFdx(p);
  vec3 dpdy = dFdy(p);
  float dhdx = dFdx(h);
  float dhdy = dFdy(h);
  vec3 r1 = cross(dpdy, n);
  vec3 r2 = cross(n, dpdx);
  float det = dot(dpdx, r1);
  vec3 grad = sign(det) * (dhdx * r1 + dhdy * r2);
  return normalize(abs(det) * n - strength * grad);
}
`;

type Shared = {
  uSnowLine: { value: number };
  uGrassA: { value: THREE.Color };
  uGrassB: { value: THREE.Color };
  uDirt: { value: THREE.Color };
  uRockA: { value: THREE.Color };
  uRockB: { value: THREE.Color };
  uSnow: { value: THREE.Color };
};

function terrainMaterial(shared: Shared, tint: { value: THREE.Color }): THREE.MeshStandardMaterial {
  const material = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1, metalness: 0 });
  material.onBeforeCompile = (shader) => {
    Object.assign(shader.uniforms, shared, { uLodTint: tint });
    shader.vertexShader = shader.vertexShader
      .replace('#include <common>', 'varying vec3 vTerrainPos;\nvarying vec3 vTerrainNormal;\n#include <common>')
      .replace(
        '#include <begin_vertex>',
        '#include <begin_vertex>\nvTerrainPos = (modelMatrix * vec4(transformed, 1.0)).xyz;\nvTerrainNormal = normalize(mat3(modelMatrix) * objectNormal);',
      );
    shader.fragmentShader = shader.fragmentShader
      .replace('#include <common>', `${FRAG_HEAD}\n#include <common>`)
      .replace(
        '#include <color_fragment>',
        '#include <color_fragment>\nTerrainSurface terrainS = terrainSurface(vTerrainPos, normalize(vTerrainNormal));\ndiffuseColor.rgb = terrainS.albedo * uLodTint;',
      )
      .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = terrainS.roughness;')
      .replace(
        '#include <normal_fragment_maps>',
        '#include <normal_fragment_maps>\nnormal = terrainBump(normal, -vViewPosition, terrainS.bump, terrainS.bumpStrength);',
      );
  };
  // every terrain material compiles to the same program
  material.customProgramCacheKey = () => 'chunked-terrain';
  return material;
}

// ---- the chunks ----

export interface TerrainChunk {
  readonly mesh: THREE.Mesh;
  /** The LOD it is drawn at now (0 is finest). */
  lod: number;
  readonly x0: number;
  readonly z0: number;
  readonly cache: (THREE.BufferGeometry | undefined)[];
  distance: number;
}

const LOD_TINTS = ['#ff6b5e', '#ffd166', '#5ed6a0', '#6aa9ff', '#c58bff', '#aaaaaa'];

export class Terrain {
  readonly options: TerrainOptions;
  /** Add this to the scene. */
  readonly group = new THREE.Group();
  readonly chunks: TerrainChunk[] = [];
  readonly materials: THREE.MeshStandardMaterial[];
  readonly colors: Shared = {
    uSnowLine: { value: 42 },
    uGrassA: { value: new THREE.Color('#3b5f2c') },
    uGrassB: { value: new THREE.Color('#6f8540') },
    uDirt: { value: new THREE.Color('#7a6248') },
    uRockA: { value: new THREE.Color('#5d5a57') },
    uRockB: { value: new THREE.Color('#948b80') },
    uSnow: { value: new THREE.Color('#dde5ee') },
  };

  private readonly tints: { value: THREE.Color }[];
  private readonly indices: THREE.BufferAttribute[];
  private readonly order: TerrainChunk[];
  private readonly n = new THREE.Vector3();
  private tinted = false;

  constructor(options: Partial<TerrainOptions> = {}) {
    const o = { ...TERRAIN_DEFAULTS, ...options };
    if (o.ranges.length !== o.segments.length - 1) throw new Error('Terrain: ranges needs one fewer entry than segments');
    this.options = o;
    this.group.name = 'Terrain';
    this.tints = o.segments.map(() => ({ value: new THREE.Color('#ffffff') }));
    this.materials = this.tints.map((tint) => terrainMaterial(this.colors, tint));
    this.indices = o.segments.map((n) => gridIndex(n));

    const coarsest = o.segments.length - 1;
    const per = Math.round(o.size / o.chunk);
    for (let cz = 0; cz < per; cz++) {
      for (let cx = 0; cx < per; cx++) {
        const x0 = -o.size / 2 + cx * o.chunk;
        const z0 = -o.size / 2 + cz * o.chunk;
        const cache: (THREE.BufferGeometry | undefined)[] = o.segments.map(() => undefined);
        const geometry = this.build(x0, z0, coarsest);
        cache[coarsest] = geometry;
        const mesh = new THREE.Mesh(geometry, this.materials[coarsest]);
        mesh.name = `chunk-${cx}-${cz}`;
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        this.group.add(mesh);
        this.chunks.push({ mesh, lod: coarsest, x0, z0, cache, distance: 0 });
      }
    }
    this.order = [...this.chunks];
  }

  /** The ground's height at a point, in metres. The meshes are sampled from this, so gameplay can ask it directly. */
  height(x: number, z: number): number {
    const s = this.options.seed;
    const f = 1 / 256;
    const base = fbm(x * f, z * f, 4, s); // rolling country, about -0.7..0.7
    const mountains = smooth(-0.15, 0.45, base); // only the high country grows ridges
    const ridge = ridged(x * f * 2.1 + 31.7, z * f * 2.1 - 12.4, 4, s + 101);
    const detail = fbm(x * 0.045, z * 0.045, 3, s + 211);
    return this.options.maxHeight * (0.3 * base + 0.85 * mountains * ridge + 0.025 * detail);
  }

  /** The ground's unit normal at a point, from the height function (the same at every LOD). */
  normal(x: number, z: number, target: THREE.Vector3): THREE.Vector3 {
    const e = 0.5;
    return target.set(this.height(x - e, z) - this.height(x + e, z), 2 * e, this.height(x, z - e) - this.height(x, z + e)).normalize();
  }

  /** The chunk over a point, or undefined off the edge of the world. */
  chunkAt(x: number, z: number): TerrainChunk | undefined {
    const o = this.options;
    const per = Math.round(o.size / o.chunk);
    const cx = Math.floor((x + o.size / 2) / o.chunk);
    const cz = Math.floor((z + o.size / 2) / o.chunk);
    if (cx < 0 || cz < 0 || cx >= per || cz >= per) return undefined;
    return this.chunks[cz * per + cx];
  }

  /** How many chunks are drawn at each LOD now. */
  counts(): number[] {
    const counts = this.options.segments.map(() => 0);
    for (const c of this.chunks) counts[c.lod]++;
    return counts;
  }

  /** Colour each chunk by its LOD (to see the rings) or back to plain. */
  set tint(on: boolean) {
    this.tinted = on;
    this.tints.forEach((t, i) => t.value.set(on ? LOD_TINTS[Math.min(i, LOD_TINTS.length - 1)] : '#ffffff'));
  }
  get tint(): boolean {
    return this.tinted;
  }

  set wireframe(on: boolean) {
    for (const m of this.materials) m.wireframe = on;
  }
  get wireframe(): boolean {
    return this.materials[0].wireframe;
  }

  /**
   * Picks each chunk's LOD for an eye position. Call it every frame. A chunk whose mesh at the wanted LOD isn't built
   * yet keeps its current one until it is; at most `budget` meshes are built per call, nearest chunks first. Returns
   * how many it built.
   */
  update(eye: THREE.Vector3, budget = 2): number {
    const o = this.options;
    for (const c of this.chunks) {
      // distance to the chunk's footprint, not its centre: the chunk underfoot is at distance 0
      const dx = Math.max(c.x0 - eye.x, 0, eye.x - (c.x0 + o.chunk));
      const dz = Math.max(c.z0 - eye.z, 0, eye.z - (c.z0 + o.chunk));
      c.distance = Math.hypot(dx, dz);
    }
    this.order.sort((a, b) => a.distance - b.distance);
    let built = 0;
    for (const c of this.order) {
      let want = o.ranges.length;
      for (let i = 0; i < o.ranges.length; i++) {
        // a chunk steps down to a coarser mesh a little later than it stepped up, so it doesn't flicker at the ring
        const range = c.lod <= i ? o.ranges[i] * 1.08 : o.ranges[i];
        if (c.distance < range) {
          want = i;
          break;
        }
      }
      if (want === c.lod) continue;
      let geometry = c.cache[want];
      if (!geometry) {
        if (built >= budget) continue;
        geometry = this.build(c.x0, c.z0, want);
        c.cache[want] = geometry;
        built++;
      }
      c.mesh.geometry = geometry;
      c.mesh.material = this.materials[want];
      c.lod = want;
    }
    return built;
  }

  dispose(): void {
    for (const c of this.chunks) for (const g of c.cache) g?.dispose();
    for (const m of this.materials) m.dispose();
  }

  /** One chunk's mesh at one LOD: an (n+1) x (n+1) grid in world space, then a skirt hanging from each edge. */
  private build(x0: number, z0: number, lod: number): THREE.BufferGeometry {
    const o = this.options;
    const n = o.segments[lod];
    const row = n + 1;
    const cell = o.chunk / n;
    const drop = cell * 2; // deep enough to cover the gap to a neighbour one or two LODs away
    const count = row * row + 4 * row;
    const position = new Float32Array(count * 3);
    const normal = new Float32Array(count * 3);
    let min = Infinity;
    let max = -Infinity;

    for (let j = 0; j < row; j++) {
      for (let i = 0; i < row; i++) {
        const x = x0 + i * cell;
        const z = z0 + j * cell;
        const y = this.height(x, z);
        const k = (j * row + i) * 3;
        position[k] = x;
        position[k + 1] = y;
        position[k + 2] = z;
        this.normal(x, z, this.n);
        normal[k] = this.n.x;
        normal[k + 1] = this.n.y;
        normal[k + 2] = this.n.z;
        if (y < min) min = y;
        if (y > max) max = y;
      }
    }
    // skirts: each edge vertex again, lower, with the same normal so the lighting carries on down it
    let s = row * row;
    const hang = (from: number): void => {
      position[s * 3] = position[from * 3];
      position[s * 3 + 1] = position[from * 3 + 1] - drop;
      position[s * 3 + 2] = position[from * 3 + 2];
      normal[s * 3] = normal[from * 3];
      normal[s * 3 + 1] = normal[from * 3 + 1];
      normal[s * 3 + 2] = normal[from * 3 + 2];
      s++;
    };
    for (let i = 0; i < row; i++) hang(i); // z = z0
    for (let i = 0; i < row; i++) hang(n * row + i); // z = z0 + chunk
    for (let j = 0; j < row; j++) hang(j * row); // x = x0
    for (let j = 0; j < row; j++) hang(j * row + n); // x = x0 + chunk

    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute('position', new THREE.BufferAttribute(position, 3));
    geometry.setAttribute('normal', new THREE.BufferAttribute(normal, 3));
    geometry.setIndex(this.indices[lod]);
    const half = o.chunk / 2;
    const midY = (min + max) / 2 - drop / 2;
    geometry.boundingSphere = new THREE.Sphere(new THREE.Vector3(x0 + half, midY, z0 + half), Math.hypot(half, half, (max - min + drop) / 2));
    return geometry;
  }
}

/** The triangle list every chunk of n x n cells shares: the grid, then four skirts facing outwards. */
function gridIndex(n: number): THREE.BufferAttribute {
  const row = n + 1;
  const index = new Uint16Array(n * n * 6 + 4 * n * 6);
  let k = 0;
  for (let j = 0; j < n; j++) {
    for (let i = 0; i < n; i++) {
      const a = j * row + i;
      const b = a + 1;
      const c = a + row;
      const d = c + 1;
      index[k++] = a;
      index[k++] = c;
      index[k++] = b;
      index[k++] = b;
      index[k++] = c;
      index[k++] = d;
    }
  }
  const base = row * row;
  const skirt = (top: (i: number) => number, first: number, flip: boolean): void => {
    for (let i = 0; i < n; i++) {
      const t0 = top(i);
      const t1 = top(i + 1);
      const s0 = first + i;
      const s1 = s0 + 1;
      if (flip) {
        index[k++] = t0;
        index[k++] = s0;
        index[k++] = t1;
        index[k++] = t1;
        index[k++] = s0;
        index[k++] = s1;
      } else {
        index[k++] = t0;
        index[k++] = t1;
        index[k++] = s0;
        index[k++] = t1;
        index[k++] = s1;
        index[k++] = s0;
      }
    }
  };
  skirt((i) => i, base, false); // z = z0, faces -z
  skirt((i) => n * row + i, base + row, true); // z = z0 + chunk, faces +z
  skirt((j) => j * row, base + 2 * row, true); // x = x0, faces -x
  skirt((j) => j * row + n, base + 3 * row, false); // x = x0 + chunk, faces +x
  return new THREE.BufferAttribute(index, 1);
}

In start(game):

const terrain = new Terrain({ seed: 7 });
game.scene.add(terrain.group);

// Every step, paused or not, so the rings follow whatever the camera does.
game.onAlways(() => {
  terrain.update(game.camera.position);
});

// Gameplay asks the same function the meshes were sampled from.
player.position.y = terrain.height(player.position.x, player.position.z);

A still frame taken straight after a camera cut (a capture view, a cutscene) should pass a large budget, terrain.update(camera.position, 1000), so every chunk reaches its level in that one call instead of over the next second.

Tuning

| Setting | Default | Effect | | --- | --- | --- | | seed | 7 | A different landscape per integer | | size, chunk | 512, 64 | World and chunk edge in metres; 64 chunks here | | maxHeight | 70 | Height scale; summits come out near it | | segments | 64, 32, 16, 8 | Cells per chunk edge per level; 1 m cells at the finest | | ranges | 100, 190, 320 | Where each level hands over to the next, in metres | | colors.uSnowLine | 42 | Altitude of the snow line in metres | | colors.uGrassA ... uSnow | see code | The six layer colours |

Performance traps

  • Building is the cost, drawing is not. A finest-level chunk is 4,225 grid vertices, each needing five height samples (one for position, four for the normal) of eleven noise octaves each. That is why builds are budgeted per frame and cached. Raising the budget makes the rings settle sooner and risks a hitch; the demo uses 2.
  • The cache only grows. A chunk keeps every level it has ever built. For this world that is bounded and small. A much larger world needs old levels of far chunks disposed.
  • Ranges against world size. In a 512 m world seen from the middle, no chunk is further than 320 m, so the coarsest level only appears from near an edge or corner. Size the ranges for the world and the camera's far plane.
  • 16-bit indices. A chunk at 64 cells is 4,485 vertices with its skirts. 128 cells per edge still fits a 16-bit index; 256 does not, and needs a Uint32Array.
  • Skirts are not stitching. They hide the crack from most angles. Looking along a seam at a grazing angle, with a steep slope and two levels of difference, a sliver of skirt can read as a small step. Narrower gaps between ranges make that rarer.
  • Shadows. The chunks cast and receive. A directional light's shadow box has to follow the camera to cover the ground around it; one fixed box will not cover the world at a useful resolution.
  • Derivative bump is per pixel quad. dFdx and dFdy are constant over a 2 by 2 pixel block, so the bump is slightly blocky under magnification. It is detail for the mid-ground, and it fades with distance.
  • The fragment shader takes five noise lookups per pixel near the camera (one broad, three fine, one strata), each of eight hashes. On a weak GPU the fine noise is the first thing to drop.

How to check it

  • On the function: any grid vertex's y equals height(x, z) at its x and z, and its normal equals normal(x, z).
  • Repeatable: two terrains with the same seed return the same height at the same point; a different seed does not.
  • Rings: with terrain.tint = true, chunks are coloured by level (red finest, then yellow, green, blue). The colours form rings around the camera and follow it.
  • Level counts: terrain.counts() after the camera has been still for a second: the chunk underfoot is level 0, and far corners are coarser.
  • Seams: with terrain.wireframe = true, a fine chunk beside a coarse one shows twice the edge vertices and a skirt below both. With it off, no sky shows through the seam.
  • Layers: steep faces are rock with near-level bands, high gentle ground is snow, and the boundaries wander instead of following contour lines.

Official references

  • three.js manual: BufferGeometry, Material.onBeforeCompile and Material.customProgramCacheKey
  • Morten S. Mikkelsen, Bump Mapping Unparametrized Surfaces on the GPU (2010)
  • Ken Perlin, Improving Noise (SIGGRAPH 2002)
  • F. Kenton Musgrave, Procedural Fractal Terrains, in Texturing and Modeling: A Procedural Approach

Who made it

This guide is by @maddmann.

More Three.js games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.

More Three.js techniques

optimization

Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →

Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

atmosphere

Baked 3D Volumetric Cloud Sea, World-Anchored Marching & TAA in Three.js →

Endless fly-above volumetric cloud sea in Three.js r183 WebGL 2 using a GPU-baked WebGL3DRenderTarget SDF and lighting volume, anti-boiling world-anchored z-plane marching, 3-octave Henyey-Greenstein scattering, and variance-clamped depth-packed TAA.

optimization

Octahedral Impostor Forests & Procedural Trees in Three.js →

Render thousands of 3D trees or distant props in a single Three.js r183 InstancedMesh draw call by baking an NxN hemisphere octahedral atlas at startup from a procedural ez-tree-style branching tree mesh.

atmosphere

Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →

Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP