-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathnoise.js
More file actions
474 lines (451 loc) · 13.5 KB
/
noise.js
File metadata and controls
474 lines (451 loc) · 13.5 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//////////////////////////////////////////////////////////////
// http://mrl.nyu.edu/~perlin/noise/
// Adapting from PApplet.java
// which was adapted from toxi
// which was adapted from the german demo group farbrausch
// as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
// someday we might consider using "improved noise"
// http://mrl.nyu.edu/~perlin/paper445.pdf
// See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/
// blob/main/introduction/Noise1D/noise.js
/**
* @module Math
* @submodule Noise
* @for p5
*/
function noise(p5, fn){
const PERLIN_YWRAPB = 4;
const PERLIN_YWRAP = 1 << PERLIN_YWRAPB;
const PERLIN_ZWRAPB = 8;
const PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB;
const PERLIN_SIZE = 4095;
let perlin_octaves = 4; // default to medium smooth
let perlin_amp_falloff = 0.5; // 50% reduction/octave
const scaled_cosine = i => 0.5 * (1.0 - Math.cos(i * Math.PI));
let perlin; // will be initialized lazily by noise() or noiseSeed()
/**
* Returns random numbers that can be tuned to feel organic.
*
* Values returned by <a href="#/p5/random">random()</a> and
* <a href="#/p5/randomGaussian">randomGaussian()</a> can change by large
* amounts between function calls. By contrast, values returned by `noise()`
* can be made "smooth". Calls to `noise()` with similar inputs will produce
* similar outputs. `noise()` is used to create textures, motion, shapes,
* terrains, and so on. Ken Perlin invented `noise()` while animating the
* original <em>Tron</em> film in the 1980s.
*
* `noise()` always returns values between 0 and 1. It returns the same value
* for a given input while a sketch is running. `noise()` produces different
* results each time a sketch runs. The
* <a href="#/p5/noiseSeed">noiseSeed()</a> function can be used to generate
* the same sequence of Perlin noise values each time a sketch runs.
*
* The character of the noise can be adjusted in two ways. The first way is to
* scale the inputs. `noise()` interprets inputs as coordinates. The sequence
* of noise values will be smoother when the input coordinates are closer. The
* second way is to use the <a href="#/p5/noiseDetail">noiseDetail()</a>
* function.
*
* The version of `noise()` with one parameter computes noise values in one
* dimension. This dimension can be thought of as space, as in `noise(x)`, or
* time, as in `noise(t)`.
*
* The version of `noise()` with two parameters computes noise values in two
* dimensions. These dimensions can be thought of as space, as in
* `noise(x, y)`, or space and time, as in `noise(x, t)`.
*
* The version of `noise()` with three parameters computes noise values in
* three dimensions. These dimensions can be thought of as space, as in
* `noise(x, y, z)`, or space and time, as in `noise(x, y, t)`.
*
* @method noise
* @param {Number} x x-coordinate in noise space.
* @param {Number} [y] y-coordinate in noise space.
* @param {Number} [z] z-coordinate in noise space.
* @return {Number} Perlin noise value at specified coordinates.
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* describe('A black dot moves randomly on a gray square.');
* }
*
* function draw() {
* background(200);
*
* // Calculate the coordinates.
* let x = 100 * noise(0.005 * frameCount);
* let y = 100 * noise(0.005 * frameCount + 10000);
*
* // Draw the point.
* strokeWeight(5);
* point(x, y);
* }
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* describe('A black dot moves randomly on a gray square.');
* }
*
* function draw() {
* background(200);
*
* // Set the noise level and scale.
* let noiseLevel = 100;
* let noiseScale = 0.005;
*
* // Scale the input coordinate.
* let nt = noiseScale * frameCount;
*
* // Compute the noise values.
* let x = noiseLevel * noise(nt);
* let y = noiseLevel * noise(nt + 10000);
*
* // Draw the point.
* strokeWeight(5);
* point(x, y);
* }
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* describe('A hilly terrain drawn in gray against a black sky.');
* }
*
* function draw() {
* // Set the noise level and scale.
* let noiseLevel = 100;
* let noiseScale = 0.02;
*
* // Scale the input coordinate.
* let x = frameCount;
* let nx = noiseScale * x;
*
* // Compute the noise value.
* let y = noiseLevel * noise(nx);
*
* // Draw the line.
* line(x, 0, x, y);
* }
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* describe('A calm sea drawn in gray against a black sky.');
* }
*
* function draw() {
* background(200);
*
* // Set the noise level and scale.
* let noiseLevel = 100;
* let noiseScale = 0.002;
*
* // Iterate from left to right.
* for (let x = 0; x < 100; x += 1) {
* // Scale the input coordinates.
* let nx = noiseScale * x;
* let nt = noiseScale * frameCount;
*
* // Compute the noise value.
* let y = noiseLevel * noise(nx, nt);
*
* // Draw the line.
* line(x, 0, x, y);
* }
* }
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Set the noise level and scale.
* let noiseLevel = 255;
* let noiseScale = 0.01;
*
* // Iterate from top to bottom.
* for (let y = 0; y < 100; y += 1) {
* // Iterate from left to right.
* for (let x = 0; x < 100; x += 1) {
* // Scale the input coordinates.
* let nx = noiseScale * x;
* let ny = noiseScale * y;
*
* // Compute the noise value.
* let c = noiseLevel * noise(nx, ny);
*
* // Draw the point.
* stroke(c);
* point(x, y);
* }
* }
*
* describe('A gray cloudy pattern.');
* }
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* describe('A gray cloudy pattern that changes.');
* }
*
* function draw() {
* // Set the noise level and scale.
* let noiseLevel = 255;
* let noiseScale = 0.009;
*
* // Iterate from top to bottom.
* for (let y = 0; y < 100; y += 1) {
* // Iterate from left to right.
* for (let x = 0; x < width; x += 1) {
* // Scale the input coordinates.
* let nx = noiseScale * x;
* let ny = noiseScale * y;
* let nt = noiseScale * frameCount;
*
* // Compute the noise value.
* let c = noiseLevel * noise(nx, ny, nt);
*
* // Draw the point.
* stroke(c);
* point(x, y);
* }
* }
* }
*/
fn.noise = function(x, y = 0, z = 0) {
if (perlin == null) {
perlin = new Array(PERLIN_SIZE + 1);
for (let i = 0; i < PERLIN_SIZE + 1; i++) {
perlin[i] = Math.random();
}
}
if (x < 0) {
x = -x;
}
if (y < 0) {
y = -y;
}
if (z < 0) {
z = -z;
}
let xi = Math.floor(x),
yi = Math.floor(y),
zi = Math.floor(z);
let xf = x - xi;
let yf = y - yi;
let zf = z - zi;
let rxf, ryf;
let r = 0;
let ampl = 0.5;
let n1, n2, n3;
for (let o = 0; o < perlin_octaves; o++) {
let of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);
rxf = scaled_cosine(xf);
ryf = scaled_cosine(yf);
n1 = perlin[of & PERLIN_SIZE];
n1 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n1);
n2 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
n2 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);
n1 += ryf * (n2 - n1);
of += PERLIN_ZWRAP;
n2 = perlin[of & PERLIN_SIZE];
n2 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n2);
n3 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
n3 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);
n2 += ryf * (n3 - n2);
n1 += scaled_cosine(zf) * (n2 - n1);
r += n1 * ampl;
ampl *= perlin_amp_falloff;
xi <<= 1;
xf *= 2;
yi <<= 1;
yf *= 2;
zi <<= 1;
zf *= 2;
if (xf >= 1.0) {
xi++;
xf--;
}
if (yf >= 1.0) {
yi++;
yf--;
}
if (zf >= 1.0) {
zi++;
zf--;
}
}
return r;
};
/**
* Adjusts the character of the noise produced by the
* <a href="#/p5/noise">noise()</a> function.
*
* Perlin noise values are created by adding layers of noise together. The
* noise layers, called octaves, are similar to harmonics in music. Lower
* octaves contribute more to the output signal. They define the overall
* intensity of the noise. Higher octaves create finer-grained details.
*
* By default, noise values are created by combining four octaves. Each higher
* octave contributes half as much (50% less) compared to its predecessor.
* `noiseDetail()` changes the number of octaves and the falloff amount. For
* example, calling `noiseDetail(6, 0.25)` ensures that
* <a href="#/p5/noise">noise()</a> will use six octaves. Each higher octave
* will contribute 25% as much (75% less) compared to its predecessor. Falloff
* values between 0 and 1 are valid. However, falloff values greater than 0.5
* might result in noise values greater than 1.
*
* @method noiseDetail
* @param {Number} lod number of octaves to be used by the noise.
* @param {Number} [falloff=0.5] falloff factor for each octave.
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* // Set the noise level and scale.
* let noiseLevel = 255;
* let noiseScale = 0.02;
*
* // Iterate from top to bottom.
* for (let y = 0; y < 100; y += 1) {
* // Iterate from left to right.
* for (let x = 0; x < 50; x += 1) {
* // Scale the input coordinates.
* let nx = noiseScale * x;
* let ny = noiseScale * y;
*
* // Compute the noise value with six octaves
* // and a low falloff factor.
* noiseDetail(6, 0.25);
* let c = noiseLevel * noise(nx, ny);
*
* // Draw the left side.
* stroke(c);
* point(x, y);
*
* // Compute the noise value with four octaves
* // and a high falloff factor.
* noiseDetail(4, 0.5);
* c = noiseLevel * noise(nx, ny);
*
* // Draw the right side.
* stroke(c);
* point(x + 50, y);
* }
* }
*
* describe('Two gray cloudy patterns. The pattern on the right is cloudier than the pattern on the left.');
* }
*/
fn.noiseDetail = function(lod, falloff=0.5) {
if (lod > 0) {
perlin_octaves = lod;
}
if (falloff > 0) {
perlin_amp_falloff = falloff;
}
};
/**
* @private
* Returns the current number of octaves used by noise().
*/
fn._getNoiseOctaves = function() {
return perlin_octaves;
};
/**
* @private
* Returns the current falloff factor used by noise().
*/
fn._getNoiseAmpFalloff = function() {
return perlin_amp_falloff;
};
/**
* Sets the seed value for the <a href="#/p5/noise">noise()</a> function.
*
* By default, <a href="#/p5/noise">noise()</a> produces different results
* each time a sketch is run. Calling `noiseSeed()` with a constant argument,
* such as `noiseSeed(99)`, makes <a href="#/p5/noise">noise()</a> produce the
* same results each time a sketch is run.
*
* @method noiseSeed
* @param {Number} seed seed value.
*
* @example
* function setup() {
* createCanvas(100, 100);
*
* background(200);
*
* // Set the noise seed for consistent results.
* noiseSeed(99);
*
* describe('A black rectangle that grows randomly, first to the right and then to the left.');
* }
*
* function draw() {
* // Set the noise level and scale.
* let noiseLevel = 100;
* let noiseScale = 0.005;
*
* // Scale the input coordinate.
* let nt = noiseScale * frameCount;
*
* // Compute the noise value.
* let x = noiseLevel * noise(nt);
*
* // Draw the line.
* line(x, 0, x, height);
* }
*/
fn.noiseSeed = function(seed) {
// Linear Congruential Generator
// Variant of a Lehman Generator
const lcg = (() => {
// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
// m is basically chosen to be large (as it is the max period)
// and for its relationships to a and c
const m = 4294967296;
// a - 1 should be divisible by m's prime factors
const a = 1664525;
// c and m should be co-prime
const c = 1013904223;
let seed, z;
return {
setSeed(val) {
// pick a random seed if val is undefined or null
// the >>> 0 casts the seed to an unsigned 32-bit integer
z = seed = (val == null ? Math.random() * m : val) >>> 0;
},
getSeed() {
return seed;
},
rand() {
// define the recurrence relationship
z = (a * z + c) % m;
// return a float in [0, 1)
// if z = m then z / m = 0 therefore (z % m) / m < 1 always
return z / m;
}
};
})();
lcg.setSeed(seed);
perlin = new Array(PERLIN_SIZE + 1);
for (let i = 0; i < PERLIN_SIZE + 1; i++) {
perlin[i] = lcg.rand();
}
};
}
export default noise;
if(typeof p5 !== 'undefined'){
noise(p5, p5.prototype);
}