Algorithm Search⌘K

Algorithmadvanced

Simplex noise

Also called Perlin simplex noise.

Gradient noise summed over the n + 1 corners of the simplex that holds the point, which costs O(n^2) instead of O(n 2^n) in n dimensions.

Time
Θ(q n^2) worst
Space
Θ(n) extra
Where
n = the dimension of the domain; q = the number of points at which the noise is evaluated
Properties
deterministicnot in placeonlineiterative
Origin
Ken Perlin, 2001

Simplex noise is a gradient noise on Rn\mathbb{R}^n, like Perlin noise, but it uses a different grid. Perlin noise blends the 2n2^n corners of a cube cell. Simplex noise splits space into simplices (triangles in 2D, tetrahedra in 3D) and adds one radial kernel for each of the n+1n + 1 corners of the simplex that holds the point. So it costs O(n2)O(n^2) per point in place of Θ(n2n)\Theta(n 2^n), it has less axis bias, and its gradient is continuous. Like Perlin noise it is a base noise for fractal noise. Worley noise is a different kind of base noise, made of distances to random points.

In plain words

Cover the plane with equal triangles. At each corner of each triangle, put a small tilted plane with a random slope, and fade it out in a round bump around the corner. The noise at a point is the sum of the bumps that reach it.

The trick is that the bumps are small enough that only the three corners of the triangle that holds the point can reach it. So you find that triangle, add three terms, and you are done. In 3D there are four corners, in 4D five. A square grid would need four, eight and sixteen corners.

To find the triangle quickly, the method stretches the plane along its diagonal, so that the triangles become halves of unit squares.

The problem

The input is a point x∈Rnx \in \mathbb{R}^n and a permutation PP of 0,…,2550, \dots, 255, stored twice as in Perlin noise. The output is a real number N(x)N(x). Let F=(n+1−1)/nF = (\sqrt{n+1} - 1)/n and G=(1−1/n+1)/nG = (1 - 1/\sqrt{n+1})/n, and let S(x)S(x) be the sum of the coordinates. The skew σ(x)=x+FS(x)1\sigma(x) = x + F S(x) \mathbf{1} maps the simplex grid onto the integer lattice Zn\mathbb{Z}^n, and the unskew τ(y)=y−GS(y)1\tau(y) = y - G S(y) \mathbf{1} is its inverse. In 2D, F=(3−1)/2F = (\sqrt3 - 1)/2 and G=(3−3)/6G = (3 - \sqrt3)/6.

Each lattice point kk has a gradient gkg_k, chosen by a nested hash of its coordinates through PP. Its kernel at xx is Tk(x)=max⁡(0,r2−∣d∣2)4 (gk⋅d)T_k(x) = \max(0, r^2 - |d|^2)^4 \, (g_k \cdot d) with d=x−τ(k)d = x - \tau(k) and r2=12r^2 = \tfrac12. The noise is N(x)=∑k∈ZnTk(x)N(x) = \sum_{k \in \mathbb{Z}^n} T_k(x). The task is to compute this sum without a search over the lattice.

The algorithm

  1. SIMPLEX-NOISE(x, P) ▷ x in R^n
  2. 1s ← F · (x_1 + ... + x_n) ▷ the skew
  3. 2k ← (⌊x_1 + s⌋, ..., ⌊x_n + s⌋) ▷ the cell in skewed space
  4. 3π ← the axes sorted by decreasing x_i + s - k_i
  5. 4c_0 ← k; c_m ← c_{m-1} + e_{π(m)} for m = 1..n
  6. 5for m ← 0 to n do
  7. 6d ← x - (c_m - G · (sum of c_m) · 1) ▷ the unskewed offset
  8. 7if r^2 - |d|^2 ≤ 0 then skip this corner
  9. 8total ← total + (r^2 - |d|^2)^4 · (g[HASH(c_m, P)] · d)
  10. 9return scale · total

The table gg in the code is the table of Gustavson's code in 2D and 3D: the 12 edge directions of a cube, with the hash modulo 12, and in 2D their first two components. In four or more dimensions it holds the vectors with entries in {−1,0,1}\{-1, 0, 1\} and exactly one zero. The scale is 70 in 2D, as in Gustavson's code, and 1 otherwise. It only sets the range.

Example

Take x=(14,12)x = (\tfrac14, \tfrac12) in 2D and the permutation of seed 0 in the code. Line L1 gives s=0.75F≈0.2745s = 0.75 F \approx 0.2745, so the skewed point is about (0.5245,0.7745)(0.5245, 0.7745) and k=(0,0)k = (0, 0). The yy part is larger, so line L4 steps along yy first, and the corners are (0,0)(0, 0), (0,1)(0, 1) and (1,1)(1, 1).

corner unskewed corner dd 12−∣d∣2\tfrac12 - \lvert d \rvert^2 gg g⋅dg \cdot d term
(0,0)(0, 0) (0,0)(0, 0) (0.2500,0.5000)(0.2500, 0.5000) 0.18750.1875 (1,0)(1, 0) 0.25000.2500 0.0003090.000309
(0,1)(0, 1) (−0.2113,0.7887)(-0.2113, 0.7887) (0.4613,−0.2887)(0.4613, -0.2887) 0.20380.2038 (0,−1)(0, -1) 0.28870.2887 0.0004980.000498
(1,1)(1, 1) (0.5774,0.5774)(0.5774, 0.5774) (−0.3274,−0.0774)(-0.3274, -0.0774) 0.38690.3869 (1,0)(1, 0) −0.3274-0.3274 −0.007332-0.007332

The sum is −0.006524-0.006524, and with the scale 70 the noise is N(x)≈−0.4567N(x) \approx -0.4567. The nearest corner, (1,1)(1, 1), has the largest weight, as expected.

Correctness

The proof file shows that the sum over the n+1n + 1 corners equals the sum over the whole lattice when r2≤12r^2 \le \tfrac12. The key step is a formula for the distance. If ee is an offset in skewed space, then ∣τ(e)∣2=∣e∣2−S(e)2/(n+1)|\tau(e)|^2 = |e|^2 - S(e)^2/(n+1), which is the spread of the n+1n + 1 numbers (e1,…,en,0)(e_1, \dots, e_n, 0) about their mean. For a lattice point that is not one of the chosen corners, two of these numbers differ by at least 1, so the squared distance is at least 12\tfrac12, and its kernel is zero.

Three facts follow. The value does not depend on how line L3 breaks ties, so the noise is continuous across the faces of the simplices. The noise is C3C^3, because max⁡(0,t)4\max(0, t)^4 is C3C^3. And the noise is zero at every lattice point. The bound 12\tfrac12 is reached, so a larger radius makes the corner sum drop terms that are not zero.

Proof: The sum over the corners of one simplex equals the sum over the whole latticefull

We use the pseudocode and the notation of the page. Arithmetic is exact (real-ram). Let n≥1n \ge 1, F=(n+1−1)/nF = (\sqrt{n+1} - 1)/n and G=(1−1/n+1)/nG = (1 - 1/\sqrt{n+1})/n. For x∈Rnx \in \mathbb{R}^n write S(x)=x1+⋯+xnS(x) = x_1 + \dots + x_n and 1=(1,…,1)\mathbf{1} = (1, \dots, 1). The skew is σ(x)=x+FS(x)1\sigma(x) = x + F S(x) \mathbf{1} and the unskew is τ(y)=y−GS(y)1\tau(y) = y - G S(y) \mathbf{1}. For each k∈Znk \in \mathbb{Z}^n let gkg_k be its hashed gradient, and let the kernel of kk at xx be

Tk(x)=max⁡(0, r2−∣x−τ(k)∣2)4  gk⋅(x−τ(k)).T_k(x) = \max(0,\, r^2 - |x - \tau(k)|^2)^4 \; g_k \cdot (x - \tau(k)).

The full noise is N(x)=∑k∈ZnTk(x)N(x) = \sum_{k \in \mathbb{Z}^n} T_k(x). Lines L5 to L8 sum TkT_k only over the n+1n + 1 corners that lines L1 to L4 select. We prove that for r2≤12r^2 \le \tfrac12 the two sums are equal.

Lemma 1 (the skew and the unskew are inverse). τ(σ(x))=x\tau(\sigma(x)) = x.

Proof. S(σ(x))=(1+nF)S(x)S(\sigma(x)) = (1 + nF) S(x), so τ(σ(x))=x+FS(x)1−G(1+nF)S(x)1\tau(\sigma(x)) = x + F S(x) \mathbf{1} - G (1 + nF) S(x) \mathbf{1}. Now 1+nF=n+11 + nF = \sqrt{n+1} and Gn+1=(n+1−1)/n=FG \sqrt{n+1} = (\sqrt{n+1} - 1)/n = F. So the two terms cancel. □\square

Lemma 2 (the distance in skewed coordinates). For e∈Rne \in \mathbb{R}^n, ∣τ(e)∣2=∣e∣2−S(e)2/(n+1)|\tau(e)|^2 = |e|^2 - S(e)^2/(n+1). Equivalently, if w=(e1,…,en,0)∈Rn+1w = (e_1, \dots, e_n, 0) \in \mathbb{R}^{n+1} and wˉ\bar w is the mean of its n+1n + 1 entries, then ∣τ(e)∣2=∑i=1n+1(wi−wˉ)2=min⁡c∈R∑i=1n+1(wi−c)2|\tau(e)|^2 = \sum_{i=1}^{n+1} (w_i - \bar w)^2 = \min_{c \in \mathbb{R}} \sum_{i=1}^{n+1} (w_i - c)^2.

Proof. ∣e−GS1∣2=∣e∣2−2GS2+nG2S2|e - G S \mathbf{1}|^2 = |e|^2 - 2 G S^2 + n G^2 S^2 with S=S(e)S = S(e). Put a=nG=1−1/n+1a = nG = 1 - 1/\sqrt{n+1}. Then 2G−nG2=(2a−a2)/n=(1−(1−a)2)/n=(1−1n+1)/n=1n+12G - nG^2 = (2a - a^2)/n = (1 - (1 - a)^2)/n = (1 - \tfrac{1}{n+1})/n = \tfrac{1}{n+1}. For the second form, wˉ=S/(n+1)\bar w = S/(n+1), and ∑(wi−wˉ)2=∑wi2−(n+1)wˉ2=∣e∣2−S2/(n+1)\sum (w_i - \bar w)^2 = \sum w_i^2 - (n+1) \bar w^2 = |e|^2 - S^2/(n+1). The mean minimizes the sum of squares. □\square

The second form does not change if the same constant is added to all n+1n + 1 entries of ww. We use this below.

Lemma 3 (the chosen corners). Let y=σ(x)y = \sigma(x), k=⌊y⌋k = \lfloor y \rfloor and f=y−k∈[0,1)nf = y - k \in [0, 1)^n, as in lines L1 and L2. Let π\pi be the order of line L3, so fπ(1)≥⋯≥fπ(n)f_{\pi(1)} \ge \dots \ge f_{\pi(n)}. The corners of line L4 are cm=k+∑j≤meπ(j)c_m = k + \sum_{j \le m} e_{\pi(j)} for m=0,…,nm = 0, \dots, n. Then yy is the convex combination ∑mλmcm\sum_m \lambda_m c_m with λ0=1−fπ(1)\lambda_0 = 1 - f_{\pi(1)}, λm=fπ(m)−fπ(m+1)\lambda_m = f_{\pi(m)} - f_{\pi(m+1)} for 0<m<n0 < m < n, and λn=fπ(n)\lambda_n = f_{\pi(n)}.

Proof. The weights are nonnegative by the order and sum to 1 by telescoping. Coordinate π(j)\pi(j) of ∑mλmcm\sum_m \lambda_m c_m is kπ(j)+∑m≥jλm=kπ(j)+fπ(j)k_{\pi(j)} + \sum_{m \ge j} \lambda_m = k_{\pi(j)} + f_{\pi(j)}, again by telescoping. □\square

So by Lemma 1, x=τ(y)x = \tau(y) lies in the simplex with the vertices τ(cm)\tau(c_m), and the code test test_point_lies_in_chosen_simplex checks the weights.

Lemma 4 (every other lattice point is far). Let q∈Znq \in \mathbb{Z}^n with q−k∉{c0−k,…,cn−k}q - k \notin \{c_0 - k, \dots, c_n - k\}. Then ∣x−τ(q)∣2≥12|x - \tau(q)|^2 \ge \tfrac12.

Proof. Let z=q−k∈Znz = q - k \in \mathbb{Z}^n. By Lemma 1 and linearity, x−τ(q)=τ(y−q)=τ(f−z)x - \tau(q) = \tau(y - q) = \tau(f - z). Let w∈Rn+1w \in \mathbb{R}^{n+1} have wi=fi−ziw_i = f_i - z_i for i≤ni \le n and wn+1=0w_{n+1} = 0. Extend ff and zz by fn+1=0f_{n+1} = 0 and zn+1=0z_{n+1} = 0, so that w=f−zw = f - z in Rn+1\mathbb{R}^{n+1} with f∈[0,1)n+1f \in [0, 1)^{n+1}.

Suppose first that some pair has wi−wj≥1w_i - w_j \ge 1. By Lemma 2, ∣τ(f−z)∣2=min⁡c∑(wl−c)2≥min⁡c((wi−c)2+(wj−c)2)=(wi−wj)2/2≥12|\tau(f - z)|^2 = \min_c \sum (w_l - c)^2 \ge \min_c ((w_i - c)^2 + (w_j - c)^2) = (w_i - w_j)^2/2 \ge \tfrac12.

So it is enough to show: if ∣wi−wj∣<1|w_i - w_j| < 1 for all i,ji, j, then zz is one of the corners cm−kc_m - k. Assume this. For each ii, wi∈[−zi,1−zi)w_i \in [-z_i, 1 - z_i). If zj≥zi+2z_j \ge z_i + 2, then wi−wj>−zi−1+zj≥1w_i - w_j > -z_i - 1 + z_j \ge 1, which is false. So the values ziz_i take at most two consecutive integers, bb and b+1b + 1. If zi=b+1z_i = b + 1 and zj=bz_j = b, then wj−wi=fj−fi+1w_j - w_i = f_j - f_i + 1, so fj<fif_j < f_i by the assumption. So the set U={i:zi=b+1}U = \{i : z_i = b + 1\} is an upper set of ff: every ii in UU has a strictly larger fif_i than every jj not in UU. Since fn+1=0f_{n+1} = 0 is the smallest entry and zn+1=0z_{n+1} = 0, either n+1∉Un + 1 \notin U and b=0b = 0, or UU holds all indices and b+1=0b + 1 = 0, so z=0z = 0 in the first nn entries. In the second case z=c0−kz = c_0 - k. In the first case U⊆{1,…,n}U \subseteq \{1, \dots, n\} is a set of indices whose ff values are strictly larger than all others. An order π\pi that sorts ff in decreasing order, with any rule for ties, lists such a set first, because ties cannot cross the boundary of UU. So U={π(1),…,π(m)}U = \{\pi(1), \dots, \pi(m)\} with m=∣U∣m = |U|, and z=cm−kz = c_m - k. □\square

Theorem 1 (the corner sum is the noise). If r2≤12r^2 \le \tfrac12, then for every xx the sum of lines L5 to L8 equals N(x)=∑q∈ZnTq(x)N(x) = \sum_{q \in \mathbb{Z}^n} T_q(x).

Proof. The sum of lines L5 to L8 is ∑m=0nTcm(x)\sum_{m=0}^{n} T_{c_m}(x), and line L7 skips exactly the terms whose factor max⁡(0,⋅)\max(0, \cdot) is 0. For every other lattice point qq, Lemma 4 gives ∣x−τ(q)∣2≥12≥r2|x - \tau(q)|^2 \ge \tfrac12 \ge r^2, so Tq(x)=0T_q(x) = 0. □\square

The bound 12\tfrac12 is reached. In 2D, τ\tau maps the unit square to two equilateral triangles of side 2/3\sqrt{2/3}, whose height is 1/2\sqrt{1/2}. At the midpoint of the diagonal edge, the corner of the other triangle is at the distance 1/2\sqrt{1/2}. In any dimension, take f=(12,12,0,…,0)f = (\tfrac12, \tfrac12, 0, \dots, 0). Line L3 puts one of the first two axes first, and the unit step z=ejz = e_j along the other one is not a corner. Its ww is ±12\pm \tfrac12 in the first two entries and 0 elsewhere, so the squared distance is exactly 12\tfrac12. With a larger radius that point would add a term that the corner sum drops. The code test test_larger_radius_breaks_corner_sum measures such a difference with r2=0.6r^2 = 0.6 in 3D.

Theorem 2 (smoothness and zeros). For r2≤12r^2 \le \tfrac12, NN is C3C^3 on Rn\mathbb{R}^n, and N(τ(q))=0N(\tau(q)) = 0 for every q∈Znq \in \mathbb{Z}^n.

Proof. The map t↦max⁡(0,t)4t \mapsto \max(0, t)^4 is C3C^3: on t>0t > 0 its first three derivatives 4t34t^3, 12t212 t^2 and 24t24 t tend to 0 as t→0t \to 0, which match the zero function on t<0t < 0. The map x↦r2−∣x−τ(q)∣2x \mapsto r^2 - |x - \tau(q)|^2 is a polynomial, and gq⋅(x−τ(q))g_q \cdot (x - \tau(q)) is linear. So each TqT_q is C3C^3. On a bounded set only finitely many TqT_q are not zero, so NN is C3C^3. At x=τ(q)x = \tau(q), the term TqT_q has the factor gq⋅0=0g_q \cdot 0 = 0. Every other lattice point q′q' has q′−q≠0q' - q \ne 0, and with f=0f = 0 every entry of ff ties, so the only upper set of Lemma 4 that is allowed is the empty one, and z=q′−qz = q' - q is not a corner. So ∣τ(q)−τ(q′)∣2≥12≥r2|\tau(q) - \tau(q')|^2 \ge \tfrac12 \ge r^2 and Tq′=0T_{q'} = 0. □\square

By Theorem 1, the value of the code does not depend on how line L3 breaks ties, and it is the same function on both sides of a face of a simplex. So the corner sum is continuous, although the set of corners changes at the faces.

Cost. Lines L1 and L2 take O(n)O(n). The sort of line L3 takes O(nlog⁡n)O(n \log n) comparisons. Line L4 makes n+1n + 1 corners, and for each corner lines L6 to L8 take O(n)O(n): the unskew, the squared distance, the dot product, and nn table lookups for the hash. The total is O(n2)O(n^2) per point, against Θ(n2n)\Theta(n 2^n) for the 2n2^n corners of a cube cell.

Complexity

Lines L1 and L2 take O(n)O(n) time. The sort of line L3 takes O(nlog⁡n)O(n \log n). Each of the n+1n + 1 corners takes O(n)O(n) for the unskew, the distance, the dot product and the nn lookups of the hash. So one point costs Θ(n2)\Theta(n^2), and qq points cost Θ(qn2)\Theta(q n^2), in the real-RAM model. Perlin noise costs Θ(n2n)\Theta(n 2^n): in 3D that is 4 corners against 8, and in 4D 5 corners against 16. The extra space is Θ(n)\Theta(n) for the corner, plus the table of 512 entries.

Properties

  • Continuous with a continuous gradient. This is a proved property for r2≤12r^2 \le \tfrac12. The noise is C3C^3.
  • Zero at the lattice points. N(τ(k))=0N(\tau(k)) = 0 for every k∈Znk \in \mathbb{Z}^n. This is proved.
  • Less axis bias. The kernels are radial, so the pattern has fewer features along the axes than Perlin noise. This is an observation, not a theorem.
  • Range. With the scale 70 in 2D, the largest absolute value on 200000 random points with seed 0 is 0.9980.998. This is a measurement. Other dimensions need their own scale.
  • Period. The hash reduces each coordinate modulo 256, so the noise repeats every 256 units of the skewed lattice.

Variants and improvements

  • Gustavson's code. It unrolls the sort of line L3 into comparisons, two in 2D and a decision tree in 3D, and hard-codes the corner offsets.
  • Radius 0.6. Gustavson's 3D and 4D code first used r2=0.6r^2 = 0.6, which gives wider and smoother bumps. The PDF now marks it as an error: with 0.6 the noise jumps on the faces of the simplices. See the pitfall below.
  • Analytic derivatives. The kernel is a polynomial in dd, so its gradient costs little more than its value. This is useful for bump mapping and flow noise.
  • OpenSimplex and similar. Other lattices and kernels avoid some of the artifacts of the plain simplex grid. They follow the same plan of a few corners and a radial kernel.
  • Tiling. A tiling version needs a lattice whose period matches the simplex grid, which is harder than for Perlin noise.

When to use it

Use simplex noise in three or more dimensions, for example 3D noise animated in time as 4D noise, where the corner count of Perlin noise grows fast. Use it when the axis bias of Perlin noise shows, or when the shading needs a continuous gradient. In 2D at small scale the gain over Perlin noise is small, and Perlin noise tiles more easily. Use Worley noise for cell patterns, and fractal noise to sum several octaves of either base noise.

Pitfalls

  • A radius above 12\tfrac12. The sum then misses terms of lattice points outside the simplex. The noise jumps on the faces. In 3D the code test measures the jump with r2=0.6r^2 = 0.6.
  • A wrong unskew factor. FF and GG must satisfy (1+nF)(1−nG)=1(1 + nF)(1 - nG) = 1. A copy of the 2D constants in 3D, or a rounded constant, puts the point in the wrong simplex.
  • Truncation in place of floor. As for Perlin noise, a cast to an integer gives the wrong cell for negative coordinates.
  • Assuming a range. The scale depends on the dimension, the radius and the gradient set. Measure the range or bound it before you clamp.
  • Hash collisions in high dimensions. With a table of 256 entries, the nested hash repeats with the period 256, and in many dimensions this can show as repeats in the pattern.

Implementations

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.

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

"""Simplex noise in n dimensions (Perlin 2001), in the form of Gustavson 2005.

The skew x' = x + F (x_1 + ... + x_n) with F = (sqrt(n + 1) - 1) / n maps the
simplex grid to the integer lattice, where the simplices are the cells of the
unit cube cut by the order of the coordinates. The point lies in the simplex
whose n + 1 corners are reached from floor(x') by unit steps along the axes,
in decreasing order of the fractional parts. Each corner adds
max(0, r2 - |d|^2)^4 (g . d), where d is the offset from the corner after the
unskew with G = (1 - 1 / sqrt(n + 1)) / n, and g is a hashed gradient.

In 2D and 3D the gradients are those of Gustavson's code: the 12 edge
directions of a cube (in 2D their first two components), with the index hash
mod 12. In 2D the sum is scaled by 70, as in his code. For n >= 4 the
gradients are the vectors with entries in {-1, 0, 1} that have exactly one
zero, and the scale is 1. The radius r2 = 0.5 keeps the noise continuous in
every dimension (see the proof of the page). Gustavson's 3D and 4D code uses
0.6, which makes small jumps on the faces of the simplices.
"""

import random
from itertools import product
from math import floor, sqrt

GRAD3 = (
    (1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0),
    (1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
    (0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1),
)


def skew_constants(n):
    """Return (F, G) for dimension n."""
    return (sqrt(n + 1) - 1) / n, (1 - 1 / sqrt(n + 1)) / n


def gradient_set(n):
    """The gradient table for dimension n."""
    if n == 2:
        return tuple(g[:2] for g in GRAD3)
    if n == 3:
        return GRAD3
    out = []
    for zero in range(n):
        for signs in product((1, -1), repeat=n - 1):
            g = list(signs)
            g.insert(zero, 0)
            out.append(tuple(g))
    return tuple(out)


def make_permutation(rng):
    p = list(range(256))
    rng.shuffle(p)
    return p + p


def lattice_hash(k, perm):
    """Nested permutation hash of the integer point k (last axis innermost)."""
    h = 0
    for c in reversed(k):
        h = perm[(c & 255) + h]
    return h


def simplex_corners(x):
    """Return the skewed corner list of the simplex that holds the point x."""
    n = len(x)
    F, _ = skew_constants(n)
    s = sum(x) * F  # @line L1
    k = [floor(c + s) for c in x]  # @line L2
    f = [c + s - kc for c, kc in zip(x, k)]
    order = sorted(range(n), key=lambda a: -f[a])  # @line L3
    corners = [tuple(k)]
    cur = list(k)
    for a in order:  # @line L4
        cur[a] += 1
        corners.append(tuple(cur))
    return corners


def unskew(k):
    _, G = skew_constants(len(k))
    t = sum(k) * G
    return tuple(c - t for c in k)


def corner_term(x, k, perm, grads, r2):
    """The contribution of the lattice point k to the noise at x."""
    u = unskew(k)  # @line L6
    d = [a - b for a, b in zip(x, u)]
    t = r2 - sum(c * c for c in d)
    if t <= 0:  # @line L7
        return 0.0
    g = grads[lattice_hash(k, perm) % len(grads)]
    return t ** 4 * sum(a * b for a, b in zip(g, d))  # @line L8


class SimplexNoise:
    """Seeded simplex noise in n dimensions."""

    def __init__(self, n=2, seed=0, r2=0.5, scale=None):
        self.n = n
        self.perm = make_permutation(random.Random(seed))
        self.grads = gradient_set(n)
        self.r2 = r2
        self.scale = (70.0 if n == 2 else 1.0) if scale is None else scale

    def __call__(self, *x):
        if len(x) != self.n:
            raise ValueError("wrong number of coordinates")
        total = 0.0
        for k in simplex_corners(x):  # @line L5
            total += corner_term(x, k, self.perm, self.grads, self.r2)
        return self.scale * total  # @line L9
test_simplex_noise.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simplex-noise/. The authors are listed in prov/PWY9S0.jsonl.

"""Tests of simplex noise.

The 2D case is checked against a direct copy of the structure of Gustavson's
2D code. In 2, 3 and 4 dimensions the sum over the n + 1 corners is checked
against a brute force sum over every lattice point near the point, which is
the claim of the proof. The tests also check that the point lies in the
chosen simplex, the zeros at the lattice points, continuity, determinism for
a seed, and that a radius above 0.5 breaks the corner sum.
"""

import random
from itertools import product
from math import floor, sqrt

from simplex_noise import (
    GRAD3,
    SimplexNoise,
    corner_term,
    simplex_corners,
    skew_constants,
    unskew,
)


def gustavson_2d(xin, yin, perm):
    """The 2D noise written as in Gustavson's paper, with r^2 = 0.5 and scale 70."""
    F2 = 0.5 * (sqrt(3.0) - 1.0)
    G2 = (3.0 - sqrt(3.0)) / 6.0
    s = (xin + yin) * F2
    i, j = floor(xin + s), floor(yin + s)
    t = (i + j) * G2
    x0, y0 = xin - (i - t), yin - (j - t)
    i1, j1 = (1, 0) if x0 > y0 else (0, 1)
    x1, y1 = x0 - i1 + G2, y0 - j1 + G2
    x2, y2 = x0 - 1.0 + 2.0 * G2, y0 - 1.0 + 2.0 * G2
    ii, jj = i & 255, j & 255
    gi = (
        perm[ii + perm[jj]] % 12,
        perm[ii + i1 + perm[jj + j1]] % 12,
        perm[ii + 1 + perm[jj + 1]] % 12,
    )
    total = 0.0
    for g, (dx, dy) in zip(gi, ((x0, y0), (x1, y1), (x2, y2))):
        t = 0.5 - dx * dx - dy * dy
        if t > 0:
            t *= t
            total += t * t * (GRAD3[g][0] * dx + GRAD3[g][1] * dy)
    return 70.0 * total


def brute_force(noise, x, reach=2):
    """Sum the corner term of every lattice point whose skewed cell is near x."""
    n = len(x)
    F, _ = skew_constants(n)
    s = sum(x) * F
    base = [floor(c + s) for c in x]
    total = 0.0
    for off in product(range(-reach, reach + 1), repeat=n):
        k = tuple(b + o for b, o in zip(base, off))
        total += corner_term(x, k, noise.perm, noise.grads, noise.r2)
    return noise.scale * total


def test_matches_gustavson_2d():
    noise = SimplexNoise(n=2, seed=1)
    rng = random.Random(1)
    for _ in range(3000):
        x, y = rng.uniform(-300, 300), rng.uniform(-300, 300)
        assert abs(noise(x, y) - gustavson_2d(x, y, noise.perm)) < 1e-12


def test_skew_constants():
    F2, G2 = skew_constants(2)
    assert abs(F2 - (sqrt(3) - 1) / 2) < 1e-15
    assert abs(G2 - (3 - sqrt(3)) / 6) < 1e-15
    for n in range(1, 8):
        F, G = skew_constants(n)
        # The unskew undoes the skew: (1 + nF)(1 - nG) = 1.
        assert abs((1 + n * F) * (1 - n * G) - 1) < 1e-14


def test_point_lies_in_chosen_simplex():
    rng = random.Random(2)
    for n in (2, 3, 4, 5):
        F, _ = skew_constants(n)
        for _ in range(300):
            x = [rng.uniform(-50, 50) for _ in range(n)]
            y = [c + sum(x) * F for c in x]
            cs = simplex_corners(x)
            assert len(set(cs)) == n + 1
            # Barycentric weights in skewed space: differences of the sorted
            # fractional parts. They are nonnegative and rebuild the point.
            k = cs[0]
            f = sorted((a - b for a, b in zip(y, k)), reverse=True)
            lam = [1 - f[0]] + [f[m] - f[m + 1] for m in range(n - 1)] + [f[-1]]
            assert min(lam) >= -1e-12 and abs(sum(lam) - 1) < 1e-12
            rebuilt = [sum(lam[m] * cs[m][a] for m in range(n + 1)) for a in range(n)]
            assert max(abs(a - b) for a, b in zip(rebuilt, y)) < 1e-9


def test_corner_sum_equals_brute_force():
    rng = random.Random(3)
    for n, count in ((2, 400), (3, 200), (4, 40)):
        noise = SimplexNoise(n=n, seed=n)
        for _ in range(count):
            x = [rng.uniform(-40, 40) for _ in range(n)]
            assert abs(noise(*x) - brute_force(noise, x)) < 1e-12


def test_larger_radius_breaks_corner_sum():
    noise = SimplexNoise(n=3, seed=4, r2=0.6)
    rng = random.Random(4)
    worst = 0.0
    for _ in range(300):
        x = [rng.uniform(-20, 20) for _ in range(3)]
        worst = max(worst, abs(noise(*x) - brute_force(noise, x)))
    # With r2 = 0.5 the difference is below 1e-12 (the test above).
    assert worst > 1e-6


def test_zero_at_lattice_points():
    rng = random.Random(5)
    for n in (2, 3, 4):
        noise = SimplexNoise(n=n, seed=5)
        for _ in range(200):
            k = tuple(rng.randint(-300, 300) for _ in range(n))
            assert abs(noise(*unskew(k))) < 1e-9


def test_continuity():
    rng = random.Random(6)
    for n in (2, 3, 4):
        noise = SimplexNoise(n=n, seed=6)
        for _ in range(300):
            x = [rng.uniform(-20, 20) for _ in range(n)]
            e = [rng.uniform(-1e-7, 1e-7) for _ in range(n)]
            y = [a + b for a, b in zip(x, e)]
            assert abs(noise(*x) - noise(*y)) < 1e-4


def test_deterministic_for_seed():
    a, b, c = SimplexNoise(2, seed=9), SimplexNoise(2, seed=9), SimplexNoise(2, seed=10)
    rng = random.Random(7)
    pts = [(rng.uniform(-100, 100), rng.uniform(-100, 100)) for _ in range(2000)]
    va = [a(*p) for p in pts]
    assert va == [b(*p) for p in pts]
    assert va != [c(*p) for p in pts]
    assert max(abs(v) for v in va) <= 1.0

History

Ken Perlin presented simplex noise in his SIGGRAPH course notes of 2001 and 2002, with a compact reference code in Java. His aims were a lower cost in high dimensions, a design that suits hardware, and the removal of the axis artifacts of his 1985 noise. Few people used it at first, because the reference code was hard to read. In 2005 Stefan Gustavson wrote Simplex noise demystified, which explains the skew and the choice of the simplex and gives readable code for two, three and four dimensions. Most later implementations follow his code.

References

  1. Ken Perlin, Noise hardware, SIGGRAPH 2001 course notes, the simplex grid, the skew of the input, and the radial kernel per corner (general locator)
  2. Stefan Gustavson, Simplex noise demystified, Linköping University, 2005, the 2D code (skew factor F2, unskew factor G2, the radius 0.5 and the scale 70) and the 3D code, with the note that its radius 0.6 should be 0.5 for continuity
  3. Ken Perlin, An image synthesizer, Computer Graphics 19(3), SIGGRAPH 1985, pages 287 to 296, the lattice gradient noise that simplex noise replaces (general locator)

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example