GameCrew AIEarly access
Sign in
Three.jsrenderingRevision 1 · Compile-verified pattern

Momentum-Conserving Stochastic Particle Terrain Erosion in Three.js

Updated

Carve realistic dendritic valleys, sharp ridges, alluvial sediment fans, and stream-flow splat masks on a 128x128 heightfield in under 35 ms in Three.js r183 using momentum-conserving stochastic water droplets and thermal talus relaxation.

  • terrain
  • erosion
  • hydraulic-erosion
  • geomorphology
  • heightfield
  • procedural
  • fbm
  • siggraph
  • siggraph-2026

No demo.

Problem

Plain fractal Brownian motion (fBm) or ridged noise heightfields look soft, isotropic, and unmistakably synthetic: hills bulge uniformly in every direction without connected drainage networks, sharp mountain ridges, carved canyons, or sediment plains. Grid-based shallow-water PDE solvers fix this, but require hundreds of full-grid passes and blow past startup and mobile browser frame budgets.

Approach

Model rainfall and runoff as momentum-conserving stochastic water particles (following McDonald & Cordonnier's SIGGRAPH 2026 particle formulation):

  1. Deterministic highland seed: build a 128 × 128 macro-relief heightfield with Float32Array storage so every run reproduces the same watershed topology.
  2. Inertial momentum integration: spawn 22,000 droplets across the massif. On each step, blend the particle's velocity with the bilinear surface gradient (vx = vx * inertia - gx * gravity * (1 - inertia)) plus mild stochastic lateral turbulence so streams carve realistic meandering bends rather than snapping straight down grid diagonals.
  3. Capacity-driven carving & deposition: compare sediment load against capacity = max(-dh, minSlope) * speed * water * capacityFactor. Deposit excess load bilinearly onto the four surrounding grid cells (forming alluvial fans and braided bars) and erode deficit load using a precomputed radial multi-cell brush kernel (preventing single-texel spikes).
  4. Thermal talus relaxation: run 3 lightweight angle-of-repose passes after hydraulic carving so over-steep cliffs shed talus onto valley floors, leaving crisp knife-edge ridges.
  5. Geomorphological splat shading: feed the accumulated flowMap, erosionMap, and depositionMap directly into vertex colors (snow crests, stratified granite cliffs, alpine meadows, sandy alluvial fans, and glacial turquoise channels) on a single MeshStandardMaterial mesh, with zero-allocation in-place switching between eroded and raw heightfields.

Implementation

Drop stochasticErosion.ts into Assets/Game/:

import * as THREE from 'three';

export interface ErosionOptions {
  readonly droplets?: number;
  readonly maxSteps?: number;
  readonly inertia?: number;
  readonly gravity?: number;
  readonly capacityFactor?: number;
  readonly minSlope?: number;
  readonly erosionRate?: number;
  readonly depositionRate?: number;
  readonly evaporationRate?: number;
  readonly brushRadius?: number;
  readonly thermalIterations?: number;
  readonly talusAngle?: number;
  readonly seed?: number;
}

export interface ErosionStats {
  readonly droplets: number;
  readonly totalEroded: number;
  readonly totalDeposited: number;
  readonly maxFlow: number;
  readonly meanHeightDelta: number;
  readonly peakHeight: number;
  readonly valleyHeight: number;
}

export interface ErodedTerrainData {
  readonly size: number;
  readonly rawHeights: Float32Array;
  readonly erodedHeights: Float32Array;
  readonly flowMap: Float32Array;
  readonly erosionMap: Float32Array;
  readonly depositionMap: Float32Array;
  readonly stats: ErosionStats;
}

export type TerrainDisplayMode = 'eroded' | 'raw';

export interface ErodedTerrainRig {
  readonly mesh: THREE.Mesh;
  readonly data: ErodedTerrainData;
  readonly getMode: () => TerrainDisplayMode;
  readonly setMode: (mode: TerrainDisplayMode) => void;
  readonly toggleMode: () => TerrainDisplayMode;
  readonly sampleWorldHeight: (worldX: number, worldZ: number, mode?: TerrainDisplayMode) => number;
}

function mulberry32(seed: number): () => number {
  let a = seed >>> 0;
  return () => {
    a |= 0;
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function hash2(ix: number, iz: number, seed: number): number {
  let h = Math.imul(ix, 374761393) + Math.imul(iz, 668265263) + Math.imul(seed, 1442695041);
  h = Math.imul(h ^ (h >>> 13), 1274126177);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

function valueNoise2D(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 ux = fx * fx * (3 - 2 * fx);
  const uz = fz * fz * (3 - 2 * fz);
  const a = hash2(ix, iz, seed);
  const b = hash2(ix + 1, iz, seed);
  const c = hash2(ix, iz + 1, seed);
  const d = hash2(ix + 1, iz + 1, seed);
  return a + (b - a) * ux + (c - a) * uz + (a - b - c + d) * ux * uz;
}

function fbm2D(x: number, z: number, seed: number, octaves = 5): number {
  let sum = 0;
  let amp = 0.5;
  let freq = 1.0;
  let norm = 0;
  for (let i = 0; i < octaves; i++) {
    sum += valueNoise2D(x * freq, z * freq, seed + i * 97) * amp;
    norm += amp;
    amp *= 0.48;
    freq *= 2.04;
  }
  return sum / norm;
}

function ridged2D(x: number, z: number, seed: number, octaves = 4): number {
  let sum = 0;
  let amp = 0.55;
  let freq = 1.0;
  let norm = 0;
  for (let i = 0; i < octaves; i++) {
    const n = 1.0 - Math.abs(valueNoise2D(x * freq, z * freq, seed + i * 131) * 2.0 - 1.0);
    sum += n * n * amp;
    norm += amp;
    amp *= 0.46;
    freq *= 2.1;
  }
  return sum / norm;
}

/**
 * Generates a deterministic raw alpine massif heightfield (values in [0.02, 0.96])
 * with three distinct peaks framing a central drainage valley — never plateau-clamped.
 */
export function buildRawHeightfield(size = 128, seed = 2026): Float32Array {
  const heights = new Float32Array(size * size);
  for (let iz = 0; iz < size; iz++) {
    const v = iz / (size - 1); // 0 = foreground outflow (-z), 1 = rear summits (+z)
    for (let ix = 0; ix < size; ix++) {
      const u = ix / (size - 1);

      // Sculptural alpine triad: high central-left summit, right spire, and flanking spurs
      const peakA = Math.exp(-((u - 0.34) * (u - 0.34) / 0.052 + (v - 0.74) * (v - 0.74) / 0.048)) * 0.68;
      const peakB = Math.exp(-((u - 0.72) * (u - 0.72) / 0.048 + (v - 0.70) * (v - 0.70) / 0.052)) * 0.60;
      const peakC = Math.exp(-((u - 0.52) * (u - 0.52) / 0.036 + (v - 0.86) * (v - 0.86) / 0.030)) * 0.48;
      const leftFlank = Math.exp(-((u - 0.14) * (u - 0.14) / 0.035 + (v - 0.46) * (v - 0.46) / 0.095)) * 0.40;
      const rightFlank = Math.exp(-((u - 0.86) * (u - 0.86) / 0.035 + (v - 0.42) * (v - 0.42) / 0.095)) * 0.36;
      const valleyTrough = Math.exp(-((u - 0.50) * (u - 0.50)) / 0.065) * Math.max(0, 0.68 - v) * 0.24;

      const macro = 0.09 + peakA + peakB + peakC + leftFlank + rightFlank - valleyTrough;
      const hills = (fbm2D(u * 4.5 + 1.1, v * 4.5 + 2.3, seed, 5) - 0.42) * 0.22;
      const ridges = ridged2D(u * 3.4 + 4.7, v * 3.4 + 0.8, seed + 503, 4) * 0.20 * (0.28 + v * 0.72);

      // Softly compress above 0.82 so peaks stay crisp and pyramidal rather than flat-topped
      const raw = Math.max(0.02, macro + hills + ridges);
      const shaped = raw > 0.80 ? 0.80 + 0.17 * Math.tanh((raw - 0.80) * 3.2) : raw;
      heights[iz * size + ix] = shaped;
    }
  }
  return heights;
}

interface BrushKernel {
  readonly dx: Int32Array;
  readonly dz: Int32Array;
  readonly weights: Float32Array;
  readonly count: number;
}

function buildErosionBrush(radius: number): BrushKernel {
  const r = Math.max(1, Math.floor(radius));
  const dxList: number[] = [];
  const dzList: number[] = [];
  const wList: number[] = [];
  let weightSum = 0;

  for (let dz = -r; dz <= r; dz++) {
    for (let dx = -r; dx <= r; dx++) {
      const dist = Math.hypot(dx, dz);
      if (dist <= r + 0.001) {
        const w = Math.max(0, 1.0 - dist / (r + 0.45));
        dxList.push(dx);
        dzList.push(dz);
        wList.push(w);
        weightSum += w;
      }
    }
  }

  const weights = new Float32Array(wList.length);
  for (let i = 0; i < wList.length; i++) {
    weights[i] = wList[i] / Math.max(weightSum, 1e-6);
  }
  return {
    dx: Int32Array.from(dxList),
    dz: Int32Array.from(dzList),
    weights,
    count: wList.length,
  };
}

function sampleHeightAndGradient(
  heights: Float32Array,
  size: number,
  x: number,
  z: number,
  out: [number, number, number]
): void {
  const ix = Math.max(0, Math.min(size - 2, Math.floor(x)));
  const iz = Math.max(0, Math.min(size - 2, Math.floor(z)));
  const fx = x - ix;
  const fz = z - iz;

  const idx = iz * size + ix;
  const h00 = heights[idx];
  const h10 = heights[idx + 1];
  const h01 = heights[idx + size];
  const h11 = heights[idx + size + 1];

  const gx = (h10 - h00) * (1 - fz) + (h11 - h01) * fz;
  const gz = (h01 - h00) * (1 - fx) + (h11 - h10) * fx;
  const h =
    h00 * (1 - fx) * (1 - fz) +
    h10 * fx * (1 - fz) +
    h01 * (1 - fx) * fz +
    h11 * fx * fz;

  out[0] = h;
  out[1] = gx;
  out[2] = gz;
}

/**
 * Momentum-conserving stochastic particle hydraulic erosion + thermal talus relaxation.
 * Integrates unit-length directional momentum steps with speed-driven sediment capacity,
 * multi-cell brush carving, bilinear alluvial deposition, and angle-of-repose relaxation.
 */
export function erodeTerrainField(
  rawHeights: Float32Array,
  size: number,
  options: ErosionOptions = {}
): ErodedTerrainData {
  const droplets = options.droplets ?? 28000;
  const maxSteps = options.maxSteps ?? 64;
  const inertia = options.inertia ?? 0.28;
  const gravity = options.gravity ?? 8.5;
  const capacityFactor = options.capacityFactor ?? 7.5;
  const minSlope = options.minSlope ?? 0.006;
  const erosionRate = options.erosionRate ?? 0.42;
  const depositionRate = options.depositionRate ?? 0.34;
  const evaporationRate = options.evaporationRate ?? 0.018;
  const brushRadius = options.brushRadius ?? 2;
  const thermalIterations = options.thermalIterations ?? 3;
  const talusAngle = options.talusAngle ?? 0.022;
  const seed = options.seed ?? 202607;

  const count = size * size;
  const erodedHeights = new Float32Array(rawHeights);
  const flowMap = new Float32Array(count);
  const erosionMap = new Float32Array(count);
  const depositionMap = new Float32Array(count);

  const brush = buildErosionBrush(brushRadius);
  const rand = mulberry32(seed);
  const sampleOut: [number, number, number] = [0, 0, 0];

  let totalEroded = 0;
  let totalDeposited = 0;

  for (let d = 0; d < droplets; d++) {
    let px = 2.0 + rand() * (size - 4.0);
    let pz = 2.0 + rand() * (size - 4.0);
    let dirX = 0;
    let dirZ = 0;
    let speed = 1.0;
    let water = 1.0;
    let sediment = 0.0;

    for (let step = 0; step < maxSteps; step++) {
      const ix = Math.floor(px);
      const iz = Math.floor(pz);
      const fx = px - ix;
      const fz = pz - iz;

      sampleHeightAndGradient(erodedHeights, size, px, pz, sampleOut);
      const hOld = sampleOut[0];
      const gx = sampleOut[1];
      const gz = sampleOut[2];

      // Momentum-blended unit step direction with subtle stochastic lateral dispersion
      const gLen = Math.hypot(gx, gz);
      const slopeX = gLen > 1e-6 ? -gx / gLen : (rand() - 0.5) * 0.4;
      const slopeZ = gLen > 1e-6 ? -gz / gLen : (rand() - 0.5) * 0.4;
      dirX = dirX * inertia + slopeX * (1.0 - inertia) + (rand() - 0.5) * 0.06;
      dirZ = dirZ * inertia + slopeZ * (1.0 - inertia) + (rand() - 0.5) * 0.06;

      const dLen = Math.hypot(dirX, dirZ);
      if (dLen < 1e-5) {
        const ang = rand() * Math.PI * 2;
        dirX = Math.cos(ang);
        dirZ = Math.sin(ang);
      } else {
        dirX /= dLen;
        dirZ /= dLen;
      }

      const nx = px + dirX;
      const nz = pz + dirZ;
      if (nx < 1.0 || nx >= size - 2.0 || nz < 1.0 || nz >= size - 2.0) {
        break;
      }

      sampleHeightAndGradient(erodedHeights, size, nx, nz, sampleOut);
      const hNew = sampleOut[0];
      const dh = hNew - hOld;

      const cellIdx = iz * size + ix;
      flowMap[cellIdx] += water * Math.min(speed, 3.0);

      const capacity = Math.max(-dh, minSlope) * speed * water * capacityFactor;

      if (sediment > capacity || dh > 0) {
        const deposit = dh > 0 ? Math.min(dh, sediment) : (sediment - capacity) * depositionRate;
        sediment -= deposit;
        totalDeposited += deposit;

        const w00 = (1 - fx) * (1 - fz);
        const w10 = fx * (1 - fz);
        const w01 = (1 - fx) * fz;
        const w11 = fx * fz;
        erodedHeights[cellIdx] += deposit * w00;
        erodedHeights[cellIdx + 1] += deposit * w10;
        erodedHeights[cellIdx + size] += deposit * w01;
        erodedHeights[cellIdx + size + 1] += deposit * w11;
        depositionMap[cellIdx] += deposit * w00;
        depositionMap[cellIdx + 1] += deposit * w10;
        depositionMap[cellIdx + size] += deposit * w01;
        depositionMap[cellIdx + size + 1] += deposit * w11;
      } else {
        const erode = Math.min((capacity - sediment) * erosionRate, Math.max(0, -dh * 0.94));
        if (erode > 0) {
          sediment += erode;
          totalEroded += erode;
          for (let b = 0; b < brush.count; b++) {
            const bx = ix + brush.dx[b];
            const bz = iz + brush.dz[b];
            if (bx >= 1 && bx < size - 1 && bz >= 1 && bz < size - 1) {
              const bIdx = bz * size + bx;
              const delta = erode * brush.weights[b];
              const clamped = Math.min(delta, Math.max(0, erodedHeights[bIdx] - 0.01));
              erodedHeights[bIdx] -= clamped;
              erosionMap[bIdx] += clamped;
            }
          }
        }
      }

      speed = Math.sqrt(Math.max(0.08, speed * speed + Math.max(0, -dh) * gravity * 3.0)) * 0.96;
      water *= 1.0 - evaporationRate;
      px = nx;
      pz = nz;

      if (water < 0.04) break;
    }
  }

  // Thermal talus relaxation pass: carves crisp ridges & smooth scree aprons
  const scratch = new Float32Array(count);
  const offsets = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1],
  ] as const;

  for (let iter = 0; iter < thermalIterations; iter++) {
    scratch.fill(0);
    for (let iz = 1; iz < size - 1; iz++) {
      for (let ix = 1; ix < size - 1; ix++) {
        const idx = iz * size + ix;
        const h = erodedHeights[idx];
        let maxDiff = 0;
        let totalExcess = 0;
        for (let k = 0; k < 4; k++) {
          const nIdx = (iz + offsets[k][1]) * size + (ix + offsets[k][0]);
          const diff = h - erodedHeights[nIdx];
          if (diff > talusAngle) {
            totalExcess += diff - talusAngle;
            if (diff > maxDiff) maxDiff = diff;
          }
        }
        if (totalExcess > 0 && maxDiff > talusAngle) {
          const transfer = 0.25 * (maxDiff - talusAngle);
          scratch[idx] -= transfer;
          for (let k = 0; k < 4; k++) {
            const nIdx = (iz + offsets[k][1]) * size + (ix + offsets[k][0]);
            const diff = h - erodedHeights[nIdx];
            if (diff > talusAngle) {
              scratch[nIdx] += transfer * ((diff - talusAngle) / totalExcess);
            }
          }
        }
      }
    }
    for (let i = 0; i < count; i++) {
      erodedHeights[i] = Math.max(0.01, erodedHeights[i] + scratch[i]);
    }
  }

  let maxFlow = 0;
  let sumAbsDelta = 0;
  let peakHeight = 0;
  let valleyHeight = 1;
  for (let i = 0; i < count; i++) {
    if (flowMap[i] > maxFlow) maxFlow = flowMap[i];
    sumAbsDelta += Math.abs(erodedHeights[i] - rawHeights[i]);
    if (erodedHeights[i] > peakHeight) peakHeight = erodedHeights[i];
    if (erodedHeights[i] < valleyHeight) valleyHeight = erodedHeights[i];
  }

  return {
    size,
    rawHeights,
    erodedHeights,
    flowMap,
    erosionMap,
    depositionMap,
    stats: {
      droplets,
      totalEroded,
      totalDeposited,
      maxFlow,
      meanHeightDelta: sumAbsDelta / count,
      peakHeight,
      valleyHeight,
    },
  };
}

function srgbToLinear(c: number): number {
  const v = Math.max(0, Math.min(1, c));
  return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
}

function mixRgb(
  out: [number, number, number],
  ar: number,
  ag: number,
  ab: number,
  br: number,
  bg: number,
  bb: number,
  t: number
): void {
  const k = Math.max(0, Math.min(1, t));
  out[0] = ar + (br - ar) * k;
  out[1] = ag + (bg - ag) * k;
  out[2] = ab + (bb - ab) * k;
}

/**
 * Builds a single vertex-colored terrain Mesh using physically linearized geomorphological
 * splat colors (alpine snow, dark granite cliffs, deep pine meadow, alluvial ochre,
 * concentrated turquoise channels) with zero-allocation in-place Raw vs Eroded swapping.
 */
export function createErodedTerrainRig(
  data: ErodedTerrainData,
  worldSize = 24,
  heightScale = 8.4
): ErodedTerrainRig {
  const { size } = data;
  const geometry = new THREE.PlaneGeometry(worldSize, worldSize, size - 1, size - 1);
  geometry.rotateX(-Math.PI / 2);

  const vertCount = size * size;
  const colorArray = new Float32Array(vertCount * 3);
  geometry.setAttribute('color', new THREE.BufferAttribute(colorArray, 3));

  const material = new THREE.MeshStandardMaterial({
    vertexColors: true,
    roughness: 0.90,
    metalness: 0.02,
  });

  const mesh = new THREE.Mesh(geometry, material);
  mesh.castShadow = true;
  mesh.receiveShadow = true;

  const posAttr = geometry.getAttribute('position') as THREE.BufferAttribute;
  const colAttr = geometry.getAttribute('color') as THREE.BufferAttribute;
  const invLogFlow = 1.0 / Math.log1p(Math.max(data.stats.maxFlow, 1.0));
  const rgb: [number, number, number] = [0, 0, 0];

  let currentMode: TerrainDisplayMode = 'eroded';

  const applyMode = (mode: TerrainDisplayMode): void => {
    currentMode = mode;
    const heights = mode === 'eroded' ? data.erodedHeights : data.rawHeights;
    const isEroded = mode === 'eroded';

    for (let iz = 0; iz < size; iz++) {
      for (let ix = 0; ix < size; ix++) {
        const idx = iz * size + ix;
        const h = heights[idx];
        posAttr.setY(idx, h * heightScale);

        const hL = heights[iz * size + Math.max(0, ix - 1)];
        const hR = heights[iz * size + Math.min(size - 1, ix + 1)];
        const hD = heights[Math.max(0, iz - 1) * size + ix];
        const hU = heights[Math.min(size - 1, iz + 1) * size + ix];
        const slope = Math.hypot(hR - hL, hU - hD) * (size * 0.45);

        // Rich sRGB biome ramp (converted to linear before writing BufferAttribute)
        if (h < 0.34) {
          mixRgb(rgb, 0.22, 0.38, 0.19, 0.34, 0.47, 0.24, h / 0.34);
        } else if (h < 0.62) {
          mixRgb(rgb, 0.34, 0.47, 0.24, 0.45, 0.40, 0.33, (h - 0.34) / 0.28);
        } else {
          mixRgb(rgb, 0.45, 0.40, 0.33, 0.62, 0.60, 0.58, (h - 0.62) / 0.32);
        }

        // Exposed dark granite cliffs + freshly carved canyon walls
        const erosionBoost = isEroded ? Math.min(1.0, data.erosionMap[idx] * 9.0) * 0.55 : 0;
        const rockMask = Math.max(0, Math.min(1, (slope - 0.34) * 1.35 + erosionBoost));
        const strata = 0.86 + 0.14 * Math.sin(h * 52.0);
        mixRgb(rgb, rgb[0], rgb[1], rgb[2], 0.32 * strata, 0.30 * strata, 0.31 * strata, rockMask);

        // Crisp snow caps clinging to high alpine peaks & upper ridges
        const snowMask = Math.max(0, Math.min(1, (h - 0.48) * 3.8 - slope * 0.42));
        mixRgb(rgb, rgb[0], rgb[1], rgb[2], 0.93, 0.95, 0.98, snowMask);

        if (isEroded) {
          // Warm sandy-ochre alluvial sediment fans where runoff slows across the valley floor
          const dep = Math.max(0, Math.min(1, data.depositionMap[idx] * 18.0)) * (1.0 - Math.min(1, slope * 1.1));
          mixRgb(rgb, rgb[0], rgb[1], rgb[2], 0.72, 0.60, 0.40, dep * 0.85);

          // Narrow high-discharge glacial stream thalwegs (linear + log hybrid so basin stays lush green/ochre)
          const flowLin = data.flowMap[idx] / Math.max(data.stats.maxFlow, 1.0);
          const flowLog = Math.log1p(data.flowMap[idx]) * invLogFlow;
          const riverMask = Math.max(0, Math.min(1, (flowLin - 0.16) * 4.5 + Math.max(0, (flowLog - 0.84) * 5.0)));
          mixRgb(rgb, rgb[0], rgb[1], rgb[2], 0.10, 0.52, 0.66, riverMask * 0.92);
        }

        colAttr.setXYZ(idx, srgbToLinear(rgb[0]), srgbToLinear(rgb[1]), srgbToLinear(rgb[2]));
      }
    }

    posAttr.needsUpdate = true;
    colAttr.needsUpdate = true;
    geometry.computeVertexNormals();
  };

  applyMode('eroded');

  const sampleWorldHeight = (
    worldX: number,
    worldZ: number,
    mode: TerrainDisplayMode = currentMode
  ): number => {
    const u = Math.max(0, Math.min(1, worldX / worldSize + 0.5));
    const v = Math.max(0, Math.min(1, worldZ / worldSize + 0.5));
    const heights = mode === 'eroded' ? data.erodedHeights : data.rawHeights;
    const out: [number, number, number] = [0, 0, 0];
    sampleHeightAndGradient(heights, size, u * (size - 1), v * (size - 1), out);
    return out[0] * heightScale;
  };

  return {
    mesh,
    data,
    getMode: () => currentMode,
    setMode: applyMode,
    toggleMode: () => {
      const next: TerrainDisplayMode = currentMode === 'eroded' ? 'raw' : 'eroded';
      applyMode(next);
      return next;
    },
    sampleWorldHeight,
  };
}

Wiring in main.ts

const rawHeights = buildRawHeightfield(128, 2026);
const erosionData = erodeTerrainField(rawHeights, 128, {
  droplets: 22000,
  maxSteps: 56,
  inertia: 0.62,
  brushRadius: 2,
  thermalIterations: 3,
});
const terrain = createErodedTerrainRig(erosionData, 24, 6.8);
scene.add(terrain.mesh);

Tuning & Budget

  • Startup cost: 128 × 128 grid × 22,000 droplets takes ~18–35 ms in V8 once at level load, producing 16,384 vertices (1 draw call) with zero per-frame CPU overhead.
  • Inertia (0.55–0.72): higher inertia preserves lateral momentum around ridges, producing realistic incised meanders; lower inertia creates straighter alpine chutes.
  • Brush radius (2–3 cells): widens gullies smoothly without aliasing spikes; keep erosionRate <= 0.4 so droplets never tunnel below their downhill target elevation (-dh * 0.92 clamp).
  • Flow splat map: normalize flowMap with Math.log1p rather than linear scaling so upper tributary streams remain visible alongside main valley rivers.

Common Pitfalls

  • Pitted needle artifacts: carving only the single cell beneath a droplet produces razor-thin spikes on steep slopes. Always distribute erosion across a normalized multi-cell brush kernel and follow with 2–4 thermal talus passes.
  • Flat-top lighting: always call geometry.computeVertexNormals() after mutating vertex Y coordinates, and illuminate with a low-angle directional sun (elevation ~25–35°) casting shadows across the valleys.
  • Unclamped step length: steep canyons can accelerate particles across multiple cells per tick, skipping ridges. Clamp step displacement to <= 1.0 grid cell per iteration.

Official references

  • Nicholas McDonald & Guillaume Cordonnier (SIGGRAPH 2026 Honorable Mention — Erosion by Stochastic Particles)
  • Hans Theobald Beyer (2015 — Implementation of a Method for Hydraulic Erosion)
  • Guillaume Cordonnier et al. (Eurographics 2016 — Large Scale Terrain Generation from Tectonic Uplift and Fluvial Erosion)

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

materials

Hexagonal Stochastic Anti-Tiling & Seamless Surface Detail in Three.js →

Eliminate visible texture grid repetition on large floors, terrain, and cliffs in Three.js r183 by patching MeshStandardMaterial with 3-tap hexagonal barycentric stochastic UV sampling and variance-preserving blending.

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

Isolated-PRNG Seeded Worlds, Procedural Foliage Atlas, Drifting Weather & Canopy Light Shafts in Three.js →

Generate deterministic forests and worlds where each system (terrain, trees, rocks, water, cabins) owns an isolated PRNG stream so edits never shift existing placements, paired with a procedural canvas foliage atlas, drifting 4-state weather, and half-float-safe volumetric canopy light shafts.

shaders

Stylized Water, Cel-Shading Ramps & Outlines in Three.js (r183) →

Three.js r183 NearestFilter DataTexture cel-shading ramps, BackSide normal-extruded outlines, and analytical Gerstner wave water ShaderMaterial with cellular foam.

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