Algorithmcore
Worley noise
Also called cellular noise, Voronoi noise.
A procedural texture basis whose value is the distance to the nearest, or the k-th nearest, of random feature points scattered in cells.
- Time
- O(q (1 + k/λ + (λ + k) k)) expected
- Space
- O(k) extra
- Where
- k = the order of the distance F_k; q = the number of queries; λ = the mean number of feature points per cell
- Model
- Real RAM
- Properties
- deterministicnot in placeonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Steven Worley, 1996
Worley noise is a procedural texture made from distances. Random feature points are scattered through space, a fixed set for each seed, and the value at a point is , the distance from to its -th nearest feature point. looks like a field of round cells, is zero on the edges of the Voronoi diagram of the points and draws a web of cracks, and other combinations give stone, scales, foam and leather. Perlin noise and simplex noise are the other base noises. They blend random gradients on a lattice, and their features have no sharp edges. Fractal noise sums octaves of any of these base noises.
In plain words
Throw a handful of seeds on the floor at random. For each spot on the floor, measure the distance to the nearest seed. Paint near spots dark and far spots light. You get round blobs around the seeds, and the blobs meet in straight lines halfway between neighbors.
You cannot store infinitely many seeds, so the floor is cut into square tiles, and each tile makes its own seeds from a random number generator started with the tile number. The same tile always gets the same seeds. To find the nearest seed, look at your own tile, then at the ring of tiles around it, and so on, until no tile further out could hold a nearer seed.
The problem
The input is a query point , an order , a seed, a mean density and a distance (Euclidean, Manhattan or Chebyshev). The plane is cut into unit cells. Cell holds a Poisson number of points with mean , placed uniformly in the cell, all taken from a generator seeded by a hash of the seed and . The output is the sorted list of the distances from to its nearest feature points. The answer must be exact, not an estimate, so that the texture has no holes or seams.
The algorithm
WORLEY(x, k, seed)- 1
c ← ⌊x⌋; m ← the distance from x to the nearest side of the cell c - 2
best ← an empty sorted list - 3
for r ← 0, 1, 2, ... do - 4
for each cell b at Chebyshev distance exactly r from c do - 5
for each feature point p of b do ▷ made from HASH(seed, b) - 6
insert δ(x, p) into best and keep the k smallest - 7
if best has k entries and best[k] ≤ r + m then - 8
return best
The cells at Chebyshev distance at most from form a square block. Every point outside the block is at a distance of at least from . So when the -th best distance is at most , no further ring can change the answer.
Example
Take , , seed 0 and in the code. Then and .
| ring | feature points | distances | best after the ring | stop test |
|---|---|---|---|---|
| 0 | , | , | is false | |
| 1 | 14 points in 8 cells | the smallest is | is true |
So , and . The first test fails by a small margin: a point in the next ring could still be at a distance just over , and the search must look. Ring 1 changes nothing here, but it must be searched.
Correctness
The proof file shows four facts. First, the ring function lists each cell of ring once, so after ring the search has seen every point of the block of cells within Chebyshev distance . Second, the list keeps the smallest distances seen. Third, a point outside the block differs from by at least in some coordinate, and all three distances are at least that difference. So when line L7 holds, no unseen point can be nearer than the -th entry, and the answer is exact. Fourth, the loop stops by ring , where is the ring of a -th nearest point. The code test compares the result with a brute force search over all points of a block of cells.
Proof: The ring search returns the exact k nearest feature distancesfull
We use the pseudocode and the notation of the page, in two dimensions. Arithmetic is exact (real-ram). The cells are the unit squares for integer . Each cell holds a finite set of feature points inside it, which depends only on the seed and the cell. The distance is the Euclidean, the Manhattan or the Chebyshev distance. All three satisfy for each axis .
Let be the cell of the query , and let . Line L1 sets . Let be the set of cells with . Ring is , with .
Lemma 1 (the rings). The code function ring(c, r) lists each cell of ring exactly once. So after the loop of lines L4 to L6 has run for , it has visited each cell of exactly once.
Proof. For it lists only. For it lists the two rows with from to , and the two columns with strictly between and . A cell has Chebyshev distance exactly from if and only if one of its coordinates differs by exactly and the other by at most , so these lists cover ring . The rows and the columns do not share a cell, so no cell repeats. There are cells, which the code test test_ring_enumerates_each_cell_once checks.
Lemma 2 (points outside the block are far). If a feature point lies in a cell outside , then .
Proof. The cells of cover the square , and the cells are disjoint, so . So for some axis , either or . In the first case . In the second case . So .
Invariant. After lines L4 to L6 have run for ring , the list best is the sorted list of the smallest distances from to the feature points in the cells of , counted with multiplicity, where is the number of those points.
Proof. By Lemma 1, line L5 sees each point of exactly once. Line L6 keeps a sorted list of at most values. A new distance enters when the list is short or is less than the largest kept value. Then the largest value drops off if the list grows past . This is the standard way to keep the smallest of a stream: a value that drops off has kept values at most as large as it, so it is not among the smallest of the stream so far, and it never returns.
Theorem 1 (exactness). If line L8 returns, its list is , the sorted distances from to its nearest feature points among all cells.
Proof. Line L7 holds, so best has entries and its largest is at most . By the invariant, best lists the smallest distances to points in . By Lemma 2, every other point has a distance of at least best. So no point outside can take a place among the smallest with a smaller value, and the sorted list of the smallest values over all points is best.
Theorem 2 (the loop stops). If at least feature points exist, line L8 returns. It returns no later than at ring , where is the ring of a -th nearest point.
Proof. After ring , the block holds the nearest points, so best has entries with the largest equal to . Since and , the test of line L7 holds.
The point of the margin is that the search can stop at ring in place of , which saves a full ring in many queries.
Theorem 3 (the 1-Lipschitz bound). For the Euclidean distance, for every .
Proof. Each point has by the triangle inequality. So the nearest points of are points within the distance of , and . The same holds with and swapped.
Expected cost. Assume the ideal model: the counts of the cells are independent Poisson variables with mean , and the points are uniform in their cells, so the points form a Poisson process of intensity . Then has the Gamma distribution with shape , and . A point at Euclidean distance lies in a ring at most , so by Theorem 2 the search visits at most cells, and the expected number of cells is at most . Whether ring is visited depends only on the rings before it, and the count of ring is independent of them, so by Wald's identity the expected number of points seen is times the expected number of cells, which is . Each point costs in line L6. The expected time per query is , which is for fixed and .
Complexity
In the ideal model, where the counts are independent Poisson variables and the points are uniform, the points form a Poisson process of intensity . Then , and the search visits cells and points on average. Each point costs to insert. So a query costs expected time, which is for fixed and . These are proved bounds in the model. The worst case has no bound, because any number of cells can be empty. The extra space is , plus the points of one cell. No table is stored.
Properties
- Exact. The ring search returns the true . This is proved.
- 1-Lipschitz. for the Euclidean distance. So is continuous, but its gradient jumps on the edges of the Voronoi cells, which gives the sharp creases of the texture.
- Zero at the feature points. at each feature point.
- Deterministic. Each cell makes the same points for the same seed, so the texture is fixed on the object.
- Not zero mean. Unlike gradient noise, is positive and grows with . Shift and scale it before you use it as a signed noise.
Variants and improvements
- One point per cell. A jittered grid with exactly one point per cell is a common GPU form. It usually searches a fixed block in 2D, or in 3D, for a fixed cost. This is still not exact in every case: for near a cell corner, the nine points of the block can all lie at a distance near , while a point two cells away lies at a distance just over 1. Its pattern is more regular than a Poisson pattern.
- Combinations. for cracks and cell edges, , products, and the index of the nearest point as a cell ID for a flat color per cell.
- Other distances. The Manhattan and the Chebyshev distances give diamond and square cells. The ring search is exact for both.
- Three and more dimensions. The same search works with cubes in place of squares. The cost per ring grows with the dimension.
- Fractal sums. Summing octaves of gives rough rock and craters, as in fractal noise.
When to use it
Use Worley noise for textures with cells or cracks: stone tiles, dry mud, scales, cells under a microscope, water caustics and foam. Use it as a source of cell IDs for a random color per cell. For smooth hills and clouds, use Perlin noise or simplex noise. When the points are given data, not a procedural texture, use a nearest neighbor search structure such as a k-d tree or a uniform grid.
Pitfalls
- The shortcut with a random count. With a Poisson count, the block can be empty, or a point outside it can be nearer. In the code, with , the shortcut gives a wrong for 3.5 percent of 20000 random queries, and with for 1 query in 20000. These are measurements. The errors show as small seams on the cell borders.
- Too few points for and higher. A block that is large enough for may not be large enough for or . The stop test of line L7 handles this, a fixed block does not.
- A poor cell hash. If the seeds of neighboring cells are correlated, the points line up. Use a well mixed hash of the cell index.
- Precision far from the origin. Far from the origin, loses bits in 32-bit floats, and the cells jitter.
- Aliasing on the creases. The gradient of jumps on the Voronoi edges, so at a small scale aliases. Filter it or fade it out with the distance. See aliasing.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worley-noise/. The authors are listed in prov/KRW8CM.jsonl.
"""Worley noise (cellular noise) in 2D, after Worley 1996.
Space is cut into unit cells. Each cell holds a Poisson number of feature
points, with the mean `density`, placed uniformly in the cell. The count and
the places come from a generator seeded by the seed and the cell index, so
the same cell always holds the same points and no table is stored.
F_k(x) is the distance from x to the k-th nearest feature point. The search
visits the cells in square rings around the cell of x and stops when no cell
outside the rings can hold a point nearer than the current k-th distance.
This makes the result exact. The common shortcut of a 3 x 3 block is exact
only when the cells are never empty and F_k is small, which a Poisson count
does not promise.
"""
import random
from bisect import insort
from math import exp, floor, inf, sqrt
METRICS = {
"euclidean": lambda dx, dy: sqrt(dx * dx + dy * dy),
"manhattan": lambda dx, dy: abs(dx) + abs(dy),
"chebyshev": lambda dx, dy: max(abs(dx), abs(dy)),
}
def poisson(rng, mean):
"""A Poisson sample by Knuth's product of uniforms (fine for a small mean)."""
limit, k, prod = exp(-mean), 0, rng.random()
while prod > limit:
k += 1
prod *= rng.random()
return k
def cell_points(seed, i, j, density):
"""The feature points of cell (i, j). A string seed is hashed the same way on every run."""
rng = random.Random(f"worley:{seed}:{i}:{j}")
count = poisson(rng, density)
return [(i + rng.random(), j + rng.random()) for _ in range(count)]
def ring(ci, cj, r):
"""The cells at Chebyshev distance exactly r from the cell (ci, cj)."""
if r == 0:
yield ci, cj
return
for a in range(-r, r + 1):
yield ci + a, cj - r
yield ci + a, cj + r
for b in range(-r + 1, r):
yield ci - r, cj + b
yield ci + r, cj + b
def worley(x, y, k=2, seed=0, density=2.0, metric="euclidean", max_rings=10000):
"""Return [F_1, ..., F_k] at (x, y): the sorted distances to the k nearest points."""
dist = METRICS[metric]
ci, cj = floor(x), floor(y)
fx, fy = x - ci, y - cj
margin = min(fx, 1 - fx, fy, 1 - fy) # @line L1
best = [] # @line L2
for r in range(max_rings): # @line L3
for (i, j) in ring(ci, cj, r): # @line L4
for (px, py) in cell_points(seed, i, j, density): # @line L5
d = dist(px - x, py - y)
if len(best) < k or d < best[-1]:
insort(best, d) # @line L6
del best[k:]
if len(best) == k and best[-1] <= r + margin: # @line L7
return best # @line L8
raise RuntimeError("no k feature points found within max_rings")
class WorleyNoise:
"""Seeded 2D Worley noise. Calling it returns (F1, F2, ..., Fk)."""
def __init__(self, seed=0, density=2.0, k=2, metric="euclidean"):
self.seed, self.density, self.k, self.metric = seed, density, k, metric
def __call__(self, x, y):
return worley(x, y, self.k, self.seed, self.density, self.metric)
def f2_minus_f1(self, x, y):
f = self(x, y)
return f[1] - f[0]
def points(self, i, j):
return cell_points(self.seed, i, j, self.density)
def nearest_brute_force(x, y, points, k, metric="euclidean"):
"""The k smallest distances from (x, y) to a list of points."""
dist = METRICS[metric]
return sorted(dist(px - x, py - y) for (px, py) in points)[:k]
def three_by_three(x, y, k=1, seed=0, density=2.0):
"""The common shortcut: search only the 3 x 3 block of cells. Not always exact."""
ci, cj = floor(x), floor(y)
pts = []
for i in range(ci - 1, ci + 2):
for j in range(cj - 1, cj + 2):
pts.extend(cell_points(seed, i, j, density))
out = nearest_brute_force(x, y, pts, k)
return out + [inf] * (k - len(out))
test_worley_noise.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/worley-noise/. The authors are listed in prov/KRW8CM.jsonl.
"""Tests of Worley noise.
The ring search is checked against a brute force search over every feature
point of a large block of cells. The tests also check the ring enumeration,
determinism for a seed, the 1-Lipschitz bound, the mean point count, and
that the 3 x 3 shortcut is not always exact.
"""
import random
from math import dist as euclid
from worley_noise import (
WorleyNoise,
cell_points,
nearest_brute_force,
ring,
three_by_three,
worley,
)
def block_points(seed, density, lo=-8, hi=8):
pts = []
for i in range(lo, hi):
for j in range(lo, hi):
pts.extend(cell_points(seed, i, j, density))
return pts
def test_ring_enumerates_each_cell_once():
for r in range(6):
cells = list(ring(3, -2, r))
assert len(cells) == len(set(cells)) == (1 if r == 0 else 8 * r)
assert all(max(abs(i - 3), abs(j + 2)) == r for i, j in cells)
def test_equals_brute_force():
rng = random.Random(1)
for seed, density in ((0, 2.0), (1, 0.7), (2, 4.0)):
pts = block_points(seed, density)
for metric in ("euclidean", "manhattan", "chebyshev"):
for _ in range(150):
x, y = rng.uniform(-2, 2), rng.uniform(-2, 2)
k = rng.randint(1, 4)
want = nearest_brute_force(x, y, pts, k, metric)
# Points within distance 6 of a query in [-2, 2]^2 lie in the block.
assert want[-1] < 6
assert worley(x, y, k, seed, density, metric) == want
def test_deterministic_for_seed():
a, b, c = WorleyNoise(seed=5), WorleyNoise(seed=5), WorleyNoise(seed=6)
rng = random.Random(2)
pts = [(rng.uniform(-50, 50), rng.uniform(-50, 50)) for _ in range(500)]
va = [a(*p) for p in pts]
assert va == [b(*p) for p in pts]
assert va != [c(*p) for p in pts]
def test_order_zero_at_points_and_lipschitz():
noise = WorleyNoise(seed=3, k=3)
for (px, py) in noise.points(0, 0) + noise.points(4, -1):
assert noise(px, py)[0] == 0.0
rng = random.Random(3)
for _ in range(500):
p = (rng.uniform(-20, 20), rng.uniform(-20, 20))
q = (p[0] + rng.uniform(-0.3, 0.3), p[1] + rng.uniform(-0.3, 0.3))
fp, fq = noise(*p), noise(*q)
assert fp == sorted(fp)
assert noise.f2_minus_f1(*p) >= 0
# Each F_k is 1-Lipschitz in the Euclidean metric.
for a, b in zip(fp, fq):
assert abs(a - b) <= euclid(p, q) + 1e-12
def test_mean_point_count():
for density in (0.5, 2.0, 5.0):
counts = [len(cell_points(9, i, j, density)) for i in range(60) for j in range(60)]
mean = sum(counts) / len(counts)
assert abs(mean - density) < 0.15 * density + 0.05
def test_three_by_three_shortcut_is_not_always_exact():
rng = random.Random(4)
wrong = 0
for _ in range(1500):
x, y = rng.uniform(-100, 100), rng.uniform(-100, 100)
exact = worley(x, y, 1, seed=7, density=0.5)
if three_by_three(x, y, 1, seed=7, density=0.5) != exact:
wrong += 1
# A measurement: with a mean of 0.5 points per cell a few percent of the
# queries get a wrong F1 from the shortcut.
assert wrong > 0
History
Steven Worley published the cellular texture basis function at SIGGRAPH 1996. He scattered feature points through space with a Poisson count per cube, defined as the distance to the -th nearest point, and showed textures made from linear combinations of to . The idea complements Perlin noise, whose features are smooth and have no edges. Later GPU code often used one jittered point per cell and a fixed block, which trades exactness and some randomness for a fixed cost.
References
- Steven Worley, A cellular texture basis function, SIGGRAPH 1996, pages 291 to 294, the whole paper (feature points with a Poisson count per cube, the functions F_n, and the search of the neighboring cubes)
- 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 chapter by Worley on cellular texturing (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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KRW8CM Edit this page History Report an error Markdown