TExcelTAD
Home › Math for Games › Value and Perlin Noise

Value and Perlin Noise

Plain random numbers are white noise: every sample is unrelated to its neighbor, so a terrain built from them looks like static. Nature is smoother: a hill's height at one step is close to its height one step away. Coherent noise gives random-looking values that change smoothly with position. It is behind terrain, clouds, fire, wood grain, camera shake, wandering AI, and grass that sways in the wind.

Step 1: a hash instead of a sequence

Noise must give the same value for the same position, in any order. So instead of a generator stream, use a hash of the integer grid coordinates and a seed (the stateless approach from the Seeded RNG lesson):

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cstdint>

// Hash two integers and a seed into a float in [0, 1).
double hash01(int x, int y, uint32_t seed) {
    uint32_t h = seed * 3266489917u + uint32_t(x) * 374761393u + uint32_t(y) * 668265263u;
    h ^= h >> 16; h *= 0x85EBCA6Bu;           // MurmurHash3's finalizer mixes the bits
    h ^= h >> 13; h *= 0xC2B2AE35u;
    h ^= h >> 16;
    return (h & 0xFFFFFF) / 16777216.0;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::cout << "hash(3, 4) = " << hash01(3, 4, 1) << ", again = " << hash01(3, 4, 1) << "\n";
    std::cout << "neighbors:";
    for (int x = 0; x < 6; x++) std::cout << " " << hash01(x, 0, 1);
    std::cout << "\n";
}
hash(3, 4) = 0.267, again = 0.267
neighbors: 0.319 0.901 0.656 0.581 0.453 0.941

Same input, same output, and neighboring values are unrelated. That is white noise again; the next step smooths it.

Value noise

Value noise puts a random value at each integer grid point and interpolates between them. Interpolating with smoothstep instead of linear lerp hides the grid's corners.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <cmath>
#include <string>

double hash01(int x, int y, uint32_t seed) {
    uint32_t h = seed * 3266489917u + uint32_t(x) * 374761393u + uint32_t(y) * 668265263u;
    h ^= h >> 16; h *= 0x85EBCA6Bu;           // MurmurHash3's finalizer mixes the bits
    h ^= h >> 13; h *= 0xC2B2AE35u;
    h ^= h >> 16;
    return (h & 0xFFFFFF) / 16777216.0;
}
double smooth(double t) { return t * t * (3 - 2 * t); }
double lerp(double a, double b, double t) { return a + (b - a) * t; }

double valueNoise1D(double x, uint32_t seed) {
    int i = int(std::floor(x));
    double f = x - i;
    return lerp(hash01(i, 0, seed), hash01(i + 1, 0, seed), smooth(f));
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    // Sample between grid points 0 and 3: smooth hills instead of static.
    for (int i = 0; i <= 12; i++) {
        double x = i * 0.25;
        double v = valueNoise1D(x, 7);
        std::cout << "x=" << x << " " << v << " |" << std::string(int(v * 40), ' ') << "#\n";
    }
}
x=0.000 0.112 |    #
x=0.250 0.186 |       #
x=0.500 0.350 |              #
x=0.750 0.514 |                    #
x=1.000 0.589 |                       #
x=1.250 0.625 |                        #
x=1.500 0.705 |                            #
x=1.750 0.784 |                               #
x=2.000 0.821 |                                #
x=2.250 0.795 |                               #
x=2.500 0.738 |                             #
x=2.750 0.681 |                           #
x=3.000 0.655 |                          #

Perlin (gradient) noise

Value noise has a blocky look: peaks and valleys sit exactly on the grid. Ken Perlin's gradient noise (1985, improved in 2002) stores a random gradient direction at each grid point instead of a value. The noise at a point blends the dot products of each corner's gradient with the offset from that corner. The result is zero at every grid point and has its features between them, which looks much more natural. Simplex noise (also Perlin's) uses a triangular grid instead of squares: fewer corners per sample, fewer directional artifacts, and it scales better to 3D and 4D.

cpp · try it yourself
#include <iostream>
#include <cstdint>
#include <cmath>
#include <string>
#include <algorithm>

uint32_t hash(int x, int y, uint32_t seed) {
    uint32_t h = seed * 3266489917u + uint32_t(x) * 374761393u + uint32_t(y) * 668265263u;
    h ^= h >> 16; h *= 0x85EBCA6Bu;
    h ^= h >> 13; h *= 0xC2B2AE35u;
    return h ^ (h >> 16);
}
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }      // smootherstep
double lerp(double a, double b, double t) { return a + (b - a) * t; }

// Dot product of a hashed corner gradient (one of 8 directions) with the offset (dx, dy).
double grad(int ix, int iy, double dx, double dy, uint32_t seed) {
    static const double G[8][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {0.7071, 0.7071}, {-0.7071, 0.7071}, {0.7071, -0.7071}, {-0.7071, -0.7071}};
    const double* g = G[hash(ix, iy, seed) & 7];
    return g[0] * dx + g[1] * dy;
}

double perlin(double x, double y, uint32_t seed) {      // roughly in [-0.7, 0.7]
    int x0 = int(std::floor(x)), y0 = int(std::floor(y));
    double fx = x - x0, fy = y - y0;
    double n00 = grad(x0, y0, fx, fy, seed), n10 = grad(x0 + 1, y0, fx - 1, fy, seed);
    double n01 = grad(x0, y0 + 1, fx, fy - 1, seed), n11 = grad(x0 + 1, y0 + 1, fx - 1, fy - 1, seed);
    double u = fade(fx), v = fade(fy);
    return lerp(lerp(n00, n10, u), lerp(n01, n11, u), v);
}

int main() {
    const std::string shades = " .:-=+*#%@";
    for (int row = 0; row < 12; row++) {
        std::string line;
        for (int col = 0; col < 48; col++) {
            double n = perlin(col * 0.12, row * 0.2, 3);     // stretch x: terminal cells are tall
            int idx = std::clamp(int((n + 0.7) / 1.4 * 10), 0, 9);
            line += shades[idx];
        }
        std::cout << line << "\n";
    }
}
++*++=-==+*#%##*+==---===++++***++=--::--=++***+
++*++====+*###*+==---=+*****####**++====++**####
+***++===++****+==--=+*#%%%%%%%####******####%%#
*****++++==++***++===+*#%%%%########%%%%########
+++++**++====+***+===++*****+++++**##%%##**+++**
+===++*++=--==+++==---===+===---==+**##**+====+*
----=+**+==-======--:::-----:::--==+***+==---=++
:.::-++**+++=======-::...::::---===++++=--::::=+
:.::-=+*****++++++++=-:..::-=++++++++===--:..:-=
------=++****+++++**+=----=+**#**+++======-::::-
+===---==++++====++++====++*###*++====++++==-:::
**+==---==+===---=======++**##**+=--==+***+=--::

Fractal noise (fBm): octaves

One layer of noise gives smooth, rolling blobs. Real terrain has big mountains and small rocks. Add several layers (octaves), each with double the frequency (lacunarity 2) and half the amplitude (gain or persistence 0.5). The sum is called fractal Brownian motion (fBm):

text
fbm(p) = Σ  amplitude_i * noise(p * frequency_i)      frequency doubles, amplitude halves

Move the sliders: the left half is value noise, the right half Perlin noise, both summed over the chosen number of octaves.

html · try it yourself
<canvas id="c" width="320" height="160" style="image-rendering:pixelated;width:100%;max-width:640px;display:block"></canvas>
<div style="font:13px system-ui;color:#555;margin-top:4px">
  scale <input id="scale" type="range" min="2" max="24" value="8">
  octaves <input id="oct" type="range" min="1" max="6" value="1">
  seed <input id="seed" type="number" value="1" style="width:4em"> <span id="lbl"></span>
</div>
<script>
  const c = document.getElementById('c'), ctx = c.getContext('2d');
  const ui = ['scale', 'oct', 'seed'].map((id) => document.getElementById(id));
  function hash(x, y, s) {
    let h = (Math.imul(s, 3266489917) + Math.imul(x, 374761393) + Math.imul(y, 668265263)) >>> 0;
    h = Math.imul(h ^ (h >>> 16), 0x85ebca6b) >>> 0;
    h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35) >>> 0;
    return (h ^ (h >>> 16)) >>> 0;
  }
  const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
  const lerp = (a, b, t) => a + (b - a) * t;
  const G = [[1, 0], [-1, 0], [0, 1], [0, -1], [0.7071, 0.7071], [-0.7071, 0.7071], [0.7071, -0.7071], [-0.7071, -0.7071]];
  function value(x, y, s) {
    const x0 = Math.floor(x), y0 = Math.floor(y), u = fade(x - x0), v = fade(y - y0);
    const h = (i, j) => (hash(i, j, s) & 0xffffff) / 16777216;
    return lerp(lerp(h(x0, y0), h(x0 + 1, y0), u), lerp(h(x0, y0 + 1), h(x0 + 1, y0 + 1), u), v) * 2 - 1;
  }
  function perlin(x, y, s) {
    const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;
    const g = (i, j, dx, dy) => { const d = G[hash(i, j, s) & 7]; return d[0] * dx + d[1] * dy; };
    const u = fade(fx), v = fade(fy);
    return lerp(lerp(g(x0, y0, fx, fy), g(x0 + 1, y0, fx - 1, fy), u), lerp(g(x0, y0 + 1, fx, fy - 1), g(x0 + 1, y0 + 1, fx - 1, fy - 1), u), v) * 1.4;
  }
  function fbm(fn, x, y, oct, s) {
    let sum = 0, amp = 1, freq = 1, norm = 0;
    for (let i = 0; i < oct; i++) { sum += amp * fn(x * freq, y * freq, s + i); norm += amp; amp *= 0.5; freq *= 2; }
    return sum / norm;
  }
  function draw() {
    const scale = Number(ui[0].value), oct = Number(ui[1].value), seed = Number(ui[2].value) | 0;
    const img = ctx.createImageData(c.width, c.height);
    for (let y = 0; y < c.height; y++) for (let x = 0; x < c.width; x++) {
      const left = x < c.width / 2;
      const n = fbm(left ? value : perlin, (x % 160) / 160 * scale, y / 160 * scale, oct, seed);
      const v = Math.max(0, Math.min(255, (n * 0.5 + 0.5) * 255)), i = (y * c.width + x) * 4;
      img.data[i] = img.data[i + 1] = img.data[i + 2] = v; img.data[i + 3] = 255;
    }
    ctx.putImageData(img, 0, 0);
    ctx.fillStyle = '#e53935'; ctx.fillRect(159, 0, 2, 160);
    document.getElementById('lbl').textContent = 'value | perlin';
  }
  ui.forEach((el) => el.addEventListener('input', draw));
  draw();
</script>

With one octave, value noise shows its grid (blobs line up horizontally and vertically) while Perlin looks organic. With five or six octaves both gain rocky detail.

Animating with noise

Feed time into one coordinate and noise becomes smooth random motion: shakeX = noise(time * 20, 0), shakeY = noise(time * 20, 100). Camera shake built this way looks far better than random jitter, and it is frame-rate independent because it depends on time, not on frames. Unity's Cinemachine "Perlin noise" channel and Unreal's camera shake "Perlin" pattern do exactly this.

Note: Perlin's original 1985 noise and Simplex noise were patented for a time; that patent (US 6867776, on simplex noise in 3D+) expired in 2022. Today the common choices are improved Perlin, OpenSimplex2, or the FastNoiseLite library, which offers all of them with the same API in C++, C#, GLSL, JavaScript and more.

Test yourself

Why is coherent noise better than plain random numbers for terrain?

  1. It is faster
  2. Nearby positions get similar values, so the result is smooth
  3. It never repeats
  4. It only produces positive values

What does Perlin noise store at each grid point?

  1. A random height
  2. A random gradient direction
  3. A color
  4. The distance to the nearest point

In fBm, what usually happens from one octave to the next?

  1. Frequency doubles and amplitude halves
  2. Frequency halves and amplitude doubles
  3. Both double
  4. The seed is reset