1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
|
//! Noise, without a table: see `noise`.
const std = @import("std");
/// Smooth noise in 0..1, like Processing's and p5's `noise()`: four octaves
/// of gradient noise, each at twice the frequency and half the weight of the
/// one before, around 0.5. Neighbouring inputs give neighbouring values; one
/// unit is roughly one bump. Pass 0 for unused axes (`noise(seed, t, 0, 0)`
/// is 1D noise).
///
/// Its spread is Processing's: standard deviation about 0.11 (0.12 in 1D),
/// almost all of it within 0.1..0.9, so `noise → angle` turns all the way
/// round as in the book. Each octave is shifted by an irrational offset,
/// so integer inputs are not special (plain Perlin noise is 0 at every
/// lattice point). The mean is 0.5 (Processing's is about 0.47).
///
/// No table and no state: the lattice gradients come from hashing the
/// integer coordinates with `seed`, so the seed can be a State field and
/// changing it is free. Only f32 arithmetic and integer hashing, no
/// library calls, so the bits are the same on every target (native and
/// wasm32, Debug and release; tested). Coordinates are clamped to ±1e9.
pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32 {
var sum: f32 = 0;
var weight: f32 = 0.5;
var frequency: f32 = 1;
for (octave_offsets, 0..) |o, octave| {
const s = seed +% @as(u32, @intCast(octave)) *% 0x9e3779b9;
sum += weight * gradient(s, x * frequency + o[0], y * frequency + o[1], z * frequency + o[2]);
weight *= 0.5;
frequency *= 2;
}
// One octave of 3D gradient noise has a deviation of about 0.2; the
// octaves together about 0.16, scaled here to Processing's 0.11.
return std.math.clamp(0.5 + 0.7 * sum, 0, 1);
}
/// Fractions of multiples of the golden ratio (and of the plastic number,
/// for z): far from every lattice point and from each other.
const octave_offsets = [4][3]f32{
.{ 0.6180340, 0.3819660, 0.7548777 },
.{ 0.2360680, 0.7639320, 0.5097553 },
.{ 0.8541020, 0.1458980, 0.2646330 },
.{ 0.4721360, 0.5278640, 0.0195106 },
};
/// Ken Perlin's improved noise at one octave, about -1..1, with the
/// permutation table replaced by a hash.
fn gradient(seed: u32, x: f32, y: f32, z: f32) f32 {
const fx = @floor(std.math.clamp(x, -1e9, 1e9));
const fy = @floor(std.math.clamp(y, -1e9, 1e9));
const fz = @floor(std.math.clamp(z, -1e9, 1e9));
const ix: u32 = @bitCast(@as(i32, @intFromFloat(fx)));
const iy: u32 = @bitCast(@as(i32, @intFromFloat(fy)));
const iz: u32 = @bitCast(@as(i32, @intFromFloat(fz)));
const dx = clampUnit(x - fx);
const dy = clampUnit(y - fy);
const dz = clampUnit(z - fz);
const u = fade(dx);
const v = fade(dy);
const w = fade(dz);
const x0 = lerp(grad(lattice(seed, ix, iy, iz), dx, dy, dz), grad(lattice(seed, ix +% 1, iy, iz), dx - 1, dy, dz), u);
const x1 = lerp(grad(lattice(seed, ix, iy +% 1, iz), dx, dy - 1, dz), grad(lattice(seed, ix +% 1, iy +% 1, iz), dx - 1, dy - 1, dz), u);
const x2 = lerp(grad(lattice(seed, ix, iy, iz +% 1), dx, dy, dz - 1), grad(lattice(seed, ix +% 1, iy, iz +% 1), dx - 1, dy, dz - 1), u);
const x3 = lerp(grad(lattice(seed, ix, iy +% 1, iz +% 1), dx, dy - 1, dz - 1), grad(lattice(seed, ix +% 1, iy +% 1, iz +% 1), dx - 1, dy - 1, dz - 1), u);
return lerp(lerp(x0, x1, v), lerp(x2, x3, v), w);
}
/// Past ±2^24 a float has no fraction left, and rounding may give 1.
fn clampUnit(t: f32) f32 {
return @min(@max(t, 0), 1);
}
fn fade(t: f32) f32 {
return t * t * t * (t * (t * 6 - 15) + 10);
}
fn lerp(a: f32, b: f32, t: f32) f32 {
return a + t * (b - a);
}
/// A well-mixed 32-bit hash of a lattice point (lowbias32's finalizer).
fn lattice(seed: u32, x: u32, y: u32, z: u32) u32 {
var h = seed ^ (x *% 0x8da6b343) ^ (y *% 0xd8163841) ^ (z *% 0xcb1ab31f);
h ^= h >> 16;
h *%= 0x7feb352d;
h ^= h >> 15;
h *%= 0x846ca68b;
h ^= h >> 16;
return h;
}
/// One of Perlin's 12 edge gradients (4 of them twice), dotted with the
/// offset.
fn grad(hash: u32, x: f32, y: f32, z: f32) f32 {
const h = hash >> 28;
const u = if (h < 8) x else y;
const v = if (h < 4) y else if (h == 12 or h == 14) x else z;
return (if (h & 1 == 0) u else -u) + (if (h & 2 == 0) v else -v);
}
/// Golden values, as bits: the test runs on native targets and, through
/// `zig build test`, on wasm32-wasi too, so a change in either shows.
const noise_goldens = [_]struct { seed: u32, p: [3]f32, bits: u32 }{
.{ .seed = 0, .p = .{ 0, 0, 0 }, .bits = 0x3f14f2bf },
.{ .seed = 0, .p = .{ 0.5, 0, 0 }, .bits = 0x3ef55b7e },
.{ .seed = 1, .p = .{ 0.3, 0.7, 0 }, .bits = 0x3f01da7c },
.{ .seed = 7, .p = .{ 12.25, -3.5, 0.125 }, .bits = 0x3efb37d9 },
.{ .seed = 42, .p = .{ 1000.1, 2000.2, 3.3 }, .bits = 0x3f142994 },
.{ .seed = 0xdeadbeef, .p = .{ -0.01, 5.5, 99.9 }, .bits = 0x3edcff5c },
};
test "noise is smooth, in 0..1, and the same bits everywhere" {
var lo: f32 = 1;
var hi: f32 = 0;
var previous = noise(3, 0, 0, 1.5);
for (1..4000) |i| {
const t = @as(f32, @floatFromInt(i)) * 0.01;
const n = noise(3, t, t * 0.5, 1.5);
try std.testing.expect(n >= 0 and n <= 1);
try std.testing.expect(@abs(n - previous) < 0.1);
lo = @min(lo, n);
hi = @max(hi, n);
previous = n;
}
try std.testing.expect(hi - lo > 0.5);
try std.testing.expect(noise(1, 0.3, 0.7, 0) != noise(2, 0.3, 0.7, 0));
for (noise_goldens) |g| {
const n = noise(g.seed, g.p[0], g.p[1], g.p[2]);
std.testing.expectEqual(g.bits, @as(u32, @bitCast(n))) catch |err| {
std.debug.print("noise({d}, {d}, {d}, {d}) = {d} (0x{x})\n", .{ g.seed, g.p[0], g.p[1], g.p[2], n, @as(u32, @bitCast(n)) });
return err;
};
}
}
test "noise has Processing's spread, and lattice points are not special" {
// Processing's noise() on this grid (flow_field's, 0.1 apart, z = 0):
// deviation 0.111, range 0.08..0.81, over 50 seeds.
var sum: f64 = 0;
var squares: f64 = 0;
var count: f64 = 0;
for (0..50) |seed| for (0..32) |i| for (0..18) |j| {
const v: f64 = noise(@intCast(seed), @as(f32, @floatFromInt(i)) * 0.1, @as(f32, @floatFromInt(j)) * 0.1, 0);
sum += v;
squares += v * v;
count += 1;
};
const mean = sum / count;
const deviation = @sqrt(squares / count - mean * mean);
try std.testing.expect(@abs(mean - 0.5) < 0.02);
try std.testing.expect(deviation > 0.095 and deviation < 0.13);
var at_half: u32 = 0;
for (0..100) |i| {
const v = noise(9, @floatFromInt(i), @floatFromInt(i * 7 % 13), 0);
if (v == 0.5) at_half += 1;
}
try std.testing.expectEqual(@as(u32, 0), at_half);
}
|