Algorithm Search⌘K

Techniquecore

Fractal Brownian motion noise

Also called fBm noise, turbulence function, fractal sum of noise.

Sum octaves of a noise function, each with doubled frequency and reduced amplitude, to get a self-similar texture for terrain, clouds and marble.

Fractal noise sums copies of a base noise at several scales. Each copy, an octave, has a higher frequency and a lower amplitude than the one before, so the sum has large hills with smaller bumps on them, and still smaller bumps on those. The base noise is any smooth noise with features of about one unit: Perlin noise, simplex noise or Worley noise. Those pages define a single scale. This page is the recipe that combines many scales. The result looks like terrain, clouds, smoke and rock, and it is the input of most bump mapping and displacement mapping of natural surfaces.

In plain words

One layer of noise looks like soft rolling hills, too smooth to be real. Real mountains have ridges on the hills, rocks on the ridges and pebbles on the rocks.

So make the same pattern several times. Make each copy twice as fine and half as tall as the one before, and add them all up. The big copies set the overall shape, and the small copies add the roughness. How fast the copies shrink sets how rough the result looks. Stop adding copies when they become smaller than a pixel, because the screen cannot show them and they would only flicker.

When it applies

  • The target is a natural texture with detail at many scales and no single feature size: terrain heights, clouds, fire, smoke, marble veins, rust and rough stone.
  • A base noise with a known feature size and a mean near zero is at hand.
  • The texture must be evaluated at any point, with no stored image, or at a resolution that is not known in advance.
  • It does not apply when the texture needs large, distinct structures such as rivers, roads or cliffs with a direction. A plain sum of noise has no such features.

The template

The inputs are a base noise NN, a point pp, the number of octaves KK, the lacunarity λ\lambda (the frequency ratio between octaves), the gain gg (the amplitude ratio, also called the persistence), and optional offsets oio_i.

  1. Set the total to 0, the amplitude to 1 and the frequency to 1.
  2. For each octave i=0,…,K−1i = 0, \dots, K - 1, add the amplitude times N(frequency⋅p+oi)N(\text{frequency} \cdot p + o_i) to the total.
  3. After each octave, multiply the amplitude by gg and the frequency by λ\lambda.
  4. Return the total. In one formula, fbm(p)=∑i=0K−1gi N(λip+oi)\mathrm{fbm}(p) = \sum_{i=0}^{K-1} g^i \, N(\lambda^i p + o_i).
  5. For turbulence, add gi ∣N(λip+oi)∣g^i \, |N(\lambda^i p + o_i)| in step 2 in place of the signed value.
  6. Choose KK so that the finest octave still has a period of at least two pixels: K−1≤log⁡λ(1/(2wf0))K - 1 \le \log_\lambda \big(1 / (2 w f_0)\big), where ww is the size of a pixel in the units of pp and f0f_0 is the base frequency.

The common choice λ=2\lambda = 2 and g=12g = \tfrac12 is tuning, not a law. Musgrave writes g=λ−Hg = \lambda^{-H}, where HH is a roughness exponent: the amplitude of octave ii is then (λi)−H(\lambda^i)^{-H}, a power of its frequency, as in the fractional Brownian motion of Mandelbrot and Van Ness. A smaller HH gives a rougher texture. The sum only imitates fractional Brownian motion: its spectrum follows a power law in the octave envelope, but the values are not Gaussian and the texture is self-similar only over the KK octaves.

If ∣N∣≤B|N| \le B, then ∣fbm∣≤B∑i<Kgi=B(1−gK)/(1−g)|\mathrm{fbm}| \le B \sum_{i<K} g^i = B (1 - g^K)/(1 - g), by the triangle inequality. This proved bound is loose. For the 2D gradient noise of the code, B=2B = 2, and with 8 octaves and g=12g = \tfrac12 the bound is 3.983.98. The largest value on 50000 random points with seed 0 is 1.1351.135, a measurement. The octaves often cancel, because their signs are not correlated.

The code in impl/python/ is deterministic for a fixed seed, and its test checks the sum against the base noise, octave by octave.

Classic examples

A trace. Take the 2D gradient noise of the code with seed 0, the point (0.3,0.7)(0.3, 0.7), K=4K = 4, λ=2\lambda = 2 and g=12g = \tfrac12.

octave ii frequency amplitude NN term running total
0 1 1 0.23250.2325 0.23250.2325 0.23250.2325
1 2 0.50.5 −0.3073-0.3073 −0.1536-0.1536 0.07880.0788
2 4 0.250.25 −0.3276-0.3276 −0.0819-0.0819 −0.0031-0.0031
3 8 0.1250.125 −0.0301-0.0301 −0.0038-0.0038 −0.0069-0.0069

The fBm value is −0.0069-0.0069: the first octave and the next three almost cancel. Turbulence adds the absolute values and gives 0.47180.4718.

Terrain. A height field h(x,y)=a⋅fbm(x/L,y/L)h(x, y) = a \cdot \mathrm{fbm}(x / L, y / L), with a feature size LL and a height aa, is the classic procedural landscape. The mesh is then displaced as in displacement mapping, or the derivative of hh perturbs the normal as in bump mapping.

Marble. Perlin's marble is sin⁡(x+a⋅turbulence(p))\sin(x + a \cdot \mathrm{turbulence}(p)): the turbulence bends straight stripes into veins. The creases of ∣N∣|N| at the zeros of each octave give the sharp, folded look.

Clouds. Map fBm through a threshold and a smooth ramp to a density or an opacity. Animate it with a fourth coordinate in time, which is where simplex noise costs less than Perlin noise.

Rock and craters. Summing octaves of F1F_1 of Worley noise gives pitted stone, with cells inside cells.

Variations

  • Turbulence. ∑gi∣N∣\sum g^i |N|, from Perlin's 1985 paper. It is positive, and it has creases at the zeros of each octave.
  • Ridged multifractal. Musgrave's form uses (c−∣N∣)2(c - |N|)^2 with an offset cc near 1, and makes the weight of each octave depend on the value of the octave before, which gives sharp ridges with smooth valleys.
  • Domain warping. Evaluate fbm(p+c⋅fbm(p))\mathrm{fbm}(p + c \cdot \mathrm{fbm}(p)), which gives swirls and flows.
  • Lacunarity near 2. A value such as 1.921.92 in place of exactly 2 keeps the lattices of the octaves from lining up. Per-octave offsets or rotations do the same.
  • Analytic derivatives. The gradient of the sum is the sum of giλi∇N(λip)g^i \lambda^i \nabla N(\lambda^i p), so a base noise with derivatives gives the normal for bump mapping at little extra cost.
  • Band limited octaves. Fade the last octave in or out with a fractional KK, so that the detail does not pop when the distance changes.

Pitfalls

  • Zeros at integer points. With a gradient noise as the base, λ=2\lambda = 2 and no offsets, every octave is zero at the integer points, so the sum is zero there. The code test checks this on 20×2020 \times 20 points, and checks that per-octave offsets remove it. Integer sample grids then show a regular pattern.
  • Aliasing. An octave with a period shorter than two pixels cannot be shown, and it aliases into flicker and moiré. Limit KK by the pixel footprint as in step 6. A mipmapped texture filters on its own, but procedural noise does not. See aliasing and the sampling theorem.
  • Too many octaves. Each octave costs one evaluation of the base noise, and octaves below the pixel size cost time and add only noise. The rule of step 6 also bounds the cost.
  • Assuming a range. The range grows with the amplitude sum, and the true values are much smaller than the proved bound. Normalize by a measured range, or by the bound if a clamp is not acceptable.
  • A biased base. The sum adds the mean of each octave. A base with a nonzero mean, such as F1F_1 of Worley noise, drifts with KK. Subtract the mean first.
  • Persistence and lacunarity are tuning. There are no correct values. Choose them by eye for each material.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fractal_noise.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fractal-noise/. The authors are listed in prov/KJNY6S.jsonl.

"""Fractal noise: a sum of octaves of a base noise.

fbm(x) = sum over i < K of g^i N(lambda^i x + o_i), where N is any base noise,
lambda is the lacunarity, g is the gain (the persistence) and o_i is an
optional offset per octave. Turbulence sums g^i |N| in place of g^i N.
Musgrave's form sets g = lambda^(-H) for a roughness exponent H.

The base noise here is a 2D gradient noise in the style of Perlin noise, so
that the module stands alone: a seeded permutation picks one of 8 gradients
at each integer point, and the quintic fade blends the 4 corners of the cell.
Any callable N(x, y) can take its place.
"""

import random
from math import floor, log

GRADS = ((1, 1), (-1, 1), (1, -1), (-1, -1), (1, 0), (-1, 0), (0, 1), (0, -1))


def fade(t):
    return t * t * t * (t * (t * 6 - 15) + 10)


class GradientNoise2D:
    """A seeded 2D gradient noise. It is 0 at the integer points and |N| <= 2."""

    def __init__(self, seed=0):
        p = list(range(256))
        random.Random(seed).shuffle(p)
        self.perm = p + p

    def gradient(self, i, j):
        p = self.perm
        return GRADS[p[p[i & 255] + (j & 255)] & 7]

    def __call__(self, x, y):
        i, j = floor(x), floor(y)
        tx, ty = x - i, y - j
        u, v = fade(tx), fade(ty)
        total = 0.0
        for a in (0, 1):
            for b in (0, 1):
                gx, gy = self.gradient(i + a, j + b)
                w = (u if a else 1 - u) * (v if b else 1 - v)
                total += w * (gx * (tx - a) + gy * (ty - b))
        return total


def octave_offsets(count, seed=0):
    """Fixed pseudorandom offsets, one per octave, to break the alignment of the lattices."""
    rng = random.Random(seed)
    return [(rng.uniform(0, 256), rng.uniform(0, 256)) for _ in range(count)]


def fbm(noise, x, y, octaves=6, lacunarity=2.0, gain=0.5, offsets=None):
    """Fractal Brownian motion noise: sum of gain^i * noise(lacunarity^i * p + o_i)."""
    total, amp, freq = 0.0, 1.0, 1.0
    for i in range(octaves):
        ox, oy = offsets[i] if offsets else (0.0, 0.0)
        total += amp * noise(x * freq + ox, y * freq + oy)
        amp *= gain
        freq *= lacunarity
    return total


def turbulence(noise, x, y, octaves=6, lacunarity=2.0, gain=0.5, offsets=None):
    """Perlin's turbulence: the same sum with |noise| in place of noise."""
    total, amp, freq = 0.0, 1.0, 1.0
    for i in range(octaves):
        ox, oy = offsets[i] if offsets else (0.0, 0.0)
        total += amp * abs(noise(x * freq + ox, y * freq + oy))
        amp *= gain
        freq *= lacunarity
    return total


def musgrave_gain(H, lacunarity=2.0):
    """The gain g = lacunarity^(-H) that gives the amplitude a power law in the frequency."""
    return lacunarity ** (-H)


def amplitude_sum(octaves, gain):
    """The sum of gain^i for i < octaves, which bounds |fbm| / max|N|."""
    return sum(gain ** i for i in range(octaves))


def octave_limit(footprint, lacunarity=2.0, base_frequency=1.0):
    """The number of octaves whose period is at least two pixel footprints.

    Octave i has the frequency base_frequency * lacunarity^i. It is kept when
    base_frequency * lacunarity^i <= 1 / (2 * footprint).
    """
    top = 1.0 / (2.0 * footprint * base_frequency)
    if top < 1:
        return 0
    return floor(log(top) / log(lacunarity) + 1e-9) + 1
test_fractal_noise.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fractal-noise/. The authors are listed in prov/KJNY6S.jsonl.

"""Tests of fractal noise.

The sum is checked against a direct sum of the base noise, octave by octave.
The tests also check determinism for a fixed seed, the amplitude bound, the
sign of turbulence, the zeros at integer points when every octave has
lacunarity 2 and no offset, and the octave limit.
"""

import random

from fractal_noise import (
    GradientNoise2D,
    amplitude_sum,
    fbm,
    musgrave_gain,
    octave_limit,
    octave_offsets,
    turbulence,
)


def test_equals_sum_of_base_noise():
    noise = GradientNoise2D(seed=1)
    offs = octave_offsets(7, seed=2)
    rng = random.Random(1)
    for _ in range(500):
        x, y = rng.uniform(-30, 30), rng.uniform(-30, 30)
        K, lac, g = rng.randint(1, 7), rng.choice((2.0, 1.92, 2.5)), rng.uniform(0.3, 0.7)
        want, amp, freq = 0.0, 1.0, 1.0
        for i in range(K):
            want += amp * noise(x * freq + offs[i][0], y * freq + offs[i][1])
            amp, freq = amp * g, freq * lac
        assert abs(fbm(noise, x, y, K, lac, g, offs) - want) < 1e-12
        assert abs(fbm(noise, x, y, 1, lac, g) - noise(x, y)) < 1e-15


def test_deterministic_for_seed():
    a, b, c = GradientNoise2D(4), GradientNoise2D(4), GradientNoise2D(5)
    rng = random.Random(2)
    pts = [(rng.uniform(-50, 50), rng.uniform(-50, 50)) for _ in range(400)]
    va = [fbm(a, x, y) for x, y in pts]
    assert va == [fbm(b, x, y) for x, y in pts]
    assert va != [fbm(c, x, y) for x, y in pts]


def test_amplitude_bound_and_turbulence_sign():
    noise = GradientNoise2D(seed=3)
    rng = random.Random(3)
    bound = 2 * amplitude_sum(8, 0.5)
    for _ in range(1000):
        x, y = rng.uniform(-20, 20), rng.uniform(-20, 20)
        assert abs(fbm(noise, x, y, 8)) <= bound
        t = turbulence(noise, x, y, 8)
        assert 0 <= t <= bound
        assert t >= abs(fbm(noise, x, y, 8)) - 1e-12


def test_zero_at_integers_without_offsets():
    noise = GradientNoise2D(seed=6)
    offs = octave_offsets(6, seed=6)
    nonzero = 0
    for i in range(-10, 10):
        for j in range(-10, 10):
            # With lacunarity 2, every octave samples its own lattice points.
            assert fbm(noise, i, j, 6, 2.0, 0.5) == 0.0
            if fbm(noise, i, j, 6, 2.0, 0.5, offs) != 0.0:
                nonzero += 1
    assert nonzero == 400


def test_musgrave_gain_and_octave_limit():
    assert musgrave_gain(0.5) == 2 ** -0.5
    assert musgrave_gain(1.0) == 0.5
    # A pixel covers 1/256 of a unit: periods 1, 1/2, ..., 1/128 are >= 2 pixels.
    assert octave_limit(1 / 256) == 8
    assert octave_limit(1 / 256, base_frequency=4.0) == 6
    assert octave_limit(1.0) == 0
    for fp in (0.001, 0.003, 0.02, 0.1):
        k = octave_limit(fp)
        assert 2.0 ** (k - 1) <= 1 / (2 * fp) < 2.0 ** k

Exercises

  1. Show that ∑i<Kgi=(1−gK)/(1−g)\sum_{i<K} g^i = (1 - g^K)/(1 - g), and find KK so that the octaves after KK add at most 1 percent of the total amplitude for g=12g = \tfrac12.
  2. A terrain spans 1000 m on a screen of 2000 pixels, and the base noise has a period of 100 m. With λ=2\lambda = 2, how many octaves have a period of at least two pixels?
  3. Show that fbm(q)=0\mathrm{fbm}(q) = 0 for every integer point qq when the base noise is zero at integer points, λ\lambda is an integer and there are no offsets.
  4. With g=λ−Hg = \lambda^{-H}, show that the amplitude of an octave is f−Hf^{-H} in terms of its frequency ff, and compute the gain for H=0.8H = 0.8 and λ=2\lambda = 2.
  5. Compute the gradient of fbm\mathrm{fbm} from the gradient of NN, and explain why the fine octaves dominate the normal of a bump map even when they are small in height.

References

  1. Ken Perlin, An image synthesizer, Computer Graphics 19(3), SIGGRAPH 1985, pages 287 to 296, turbulence, a sum of the absolute value of noise over octaves, and its use for marble and fire (general locator)
  2. Benoit B. Mandelbrot and John W. Van Ness, Fractional Brownian motions, fractional noises and applications, SIAM Review 10(4), 1968, pages 422 to 437, the definition of fractional Brownian motion with the exponent H (general locator)
  3. David S. Ebert, F. Kenton Musgrave, Darwyn Peachey, Ken Perlin and Steven Worley, Texturing and Modeling, A Procedural Approach, third edition, Morgan Kaufmann, 2003, the chapters by Musgrave on fractal terrain (the fBm sum with lacunarity, H and octaves, and multifractals) and by Peachey on spectral synthesis (general locator)
  4. Matt Pharr, Wenzel Jakob and Greg Humphreys, Physically Based Rendering, From Theory to Implementation, third edition, Morgan Kaufmann, 2016, Section 10.6.3, Noise Idioms and Spectral Synthesis

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples