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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use math;
use math::{Point2, Point3, Point4};
use noise_fns::{NoiseFn, Seedable};
use permutationtable::PermutationTable;
use std;

/// Noise function that outputs Worley noise.
#[derive(Clone, Copy, Debug)]
pub struct Worley {
    /// Specifies the range function to use when calculating the boundaries of
    /// the cell.
    pub range_function: RangeFunction,

    /// Determines if the distance from the nearest seed point is applied to
    /// the output value.
    pub enable_range: bool,

    /// Frequency of the seed points.
    pub frequency: f64,

    /// Scale of the random displacement to apply to each cell.
    ///
    /// The noise function assigns each Worley cell a random constant value from
    /// a value noise function. The `displacement` _value_ controls the range
    /// random values to assign to each cell. The range of random values is +/-
    /// the displacement value.
    pub displacement: f64,

    seed: u32,
    perm_table: PermutationTable,
}

impl Worley {
    pub const DEFAULT_SEED: u32 = 0;
    pub const DEFAULT_RANGEFUNCTION: RangeFunction = RangeFunction::Euclidean;
    pub const DEFAULT_FREQUENCY: f64 = 1.0;
    pub const DEFAULT_DISPLACEMENT: f64 = 1.0;

    pub fn new() -> Self {
        Worley {
            perm_table: PermutationTable::new(Self::DEFAULT_SEED),
            seed: Self::DEFAULT_SEED,
            range_function: Self::DEFAULT_RANGEFUNCTION,
            enable_range: false,
            frequency: Self::DEFAULT_FREQUENCY,
            displacement: Self::DEFAULT_DISPLACEMENT,
        }
    }

    /// Sets the range function used by the Worley cells.
    pub fn set_range_function(self, range_function: RangeFunction) -> Self {
        Worley {
            range_function,
            ..self
        }
    }

    /// Enables or disables applying the distance from the nearest seed point
    /// to the output value.
    pub fn enable_range(self, enable_range: bool) -> Self {
        Worley {
            enable_range,
            ..self
        }
    }

    /// Sets the frequency of the seed points.
    pub fn set_frequency(self, frequency: f64) -> Self {
        Worley { frequency, ..self }
    }

    pub fn set_displacement(self, displacement: f64) -> Self {
        Worley {
            displacement,
            ..self
        }
    }
}

impl Default for Worley {
    fn default() -> Self {
        Self::new()
    }
}

impl Seedable for Worley {
    /// Sets the seed value used by the Worley cells.
    fn set_seed(self, seed: u32) -> Self {
        // If the new seed is the same as the current seed, just return self.
        if self.seed == seed {
            return self;
        }

        // Otherwise, regenerate the permutation table based on the new seed.
        Worley {
            perm_table: PermutationTable::new(seed),
            seed,
            ..self
        }
    }

    fn seed(&self) -> u32 {
        self.seed
    }
}

/// Set of distance functions that can be used in the Worley noise function.
#[derive(Clone, Copy, Debug)]
pub enum RangeFunction {
    /// The standard linear distance. Expensive to compute because it requires
    /// square root calculations.
    Euclidean,

    /// Same as Euclidean, but without the square root calculations. Distance
    /// results will be smaller, however, but hash patterns will be the same.
    EuclideanSquared,

    /// Measured by only moving in straight lines along the axes. Diagonal
    /// movement is not allowed, which leads to increased distances.
    Manhattan,

    /// Measured by taking the largest distance along any axis as the total
    /// distance. Since this eliminates all but one dimension, it results in
    /// significantly shorter distances and produces regions where the
    /// distances are uniform.
    Chebyshev,

    /// Experimental function where all values are multiplied together and then
    /// added up like a quadratic equation.
    Quadratic,
}

fn calculate_range(range_function: RangeFunction, p1: &[f64], p2: &[f64]) -> f64 {
    match range_function {
        RangeFunction::Euclidean => range_euclidean(p1, p2),
        RangeFunction::EuclideanSquared => range_euclidean_squared(p1, p2),
        RangeFunction::Manhattan => range_manhattan(p1, p2),
        RangeFunction::Chebyshev => range_chebyshev(p1, p2),
        RangeFunction::Quadratic => range_quadratic(p1, p2),
    }
}

fn range_euclidean(p1: &[f64], p2: &[f64]) -> f64 {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a * a)
        .fold(0.0, |acc, x| acc + x)
        .sqrt()
}

fn range_euclidean_squared(p1: &[f64], p2: &[f64]) -> f64 {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a * a)
        .fold(0.0, |acc, x| acc + x)
}

fn range_manhattan(p1: &[f64], p2: &[f64]) -> f64 {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a.abs())
        .fold(0.0, |acc, x| acc + x)
}

fn range_chebyshev(p1: &[f64], p2: &[f64]) -> f64 {
    p1.iter()
        .zip(p2.iter())
        .map(|(a, b)| *a - *b)
        .map(|a| a.abs())
        .fold(std::f64::MIN, |a, b| a.max(b))
}

fn range_quadratic(p1: &[f64], p2: &[f64]) -> f64 {
    let temp: Vec<f64> = p1.iter().zip(p2.iter()).map(|(a, b)| *a - *b).collect();

    let mut result = 0.0;

    for i in &temp {
        for j in &temp {
            result += *i * *j;
        }
    }

    result
}

impl NoiseFn<Point2<f64>> for Worley {
    fn get(&self, point: Point2<f64>) -> f64 {
        #[inline(always)]
        fn get_point(perm_table: &PermutationTable, whole: Point2<isize>) -> Point2<f64> {
            math::add2(get_vec2(perm_table.get2(whole)), math::to_f642(whole))
        }

        let point = &math::mul2(point, self.frequency);

        let cell = math::map2(*point, f64::floor);
        let whole = math::to_isize2(cell);
        let frac = math::sub2(*point, cell);

        let x_half = frac[0] > 0.5;
        let y_half = frac[1] > 0.5;

        let near = [whole[0] + (x_half as isize), whole[1] + (y_half as isize)];
        let far = [whole[0] + (!x_half as isize), whole[1] + (!y_half as isize)];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (0.5 - frac[0]) * (0.5 - frac[0]); // x-distance squared to center line
        let y_range = (0.5 - frac[1]) * (0.5 - frac[1]); // y-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1]];
        }

        if y_range < range {
            test_point![near[0], far[1]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1]];
        }

        let value = if self.enable_range {
            range
        } else {
            self.displacement * self.perm_table.get2(seed_cell) as f64 / 255.0
        };

        value * 2.0 - 1.0
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec2(index: usize) -> Point2<f64> {
    let length = ((index & 0xF8) >> 3) as f64 * 0.5 / 31.0;
    let diag = length * std::f64::consts::FRAC_1_SQRT_2;
    match index & 0x07 {
        0 => [   diag,    diag],
        1 => [   diag,   -diag],
        2 => [  -diag,    diag],
        3 => [  -diag,   -diag],
        4 => [ length,     0.0],
        5 => [-length,     0.0],
        6 => [    0.0,  length],
        7 => [    0.0, -length],
        _ => unreachable!(),
    }
}

impl NoiseFn<Point3<f64>> for Worley {
    fn get(&self, point: Point3<f64>) -> f64 {
        #[inline(always)]
        fn get_point(perm_table: &PermutationTable, whole: Point3<isize>) -> Point3<f64> {
            math::add3(get_vec3(perm_table.get3(whole)), math::to_f643(whole))
        }

        let point = &math::mul3(point, self.frequency);

        let cell = math::map3(*point, f64::floor);
        let whole = math::to_isize3(cell);
        let frac = math::sub3(*point, cell);

        let x_half = frac[0] > 0.5;
        let y_half = frac[1] > 0.5;
        let z_half = frac[2] > 0.5;

        let near = [
            whole[0] + (x_half as isize),
            whole[1] + (y_half as isize),
            whole[2] + (z_half as isize),
        ];
        let far = [
            whole[0] + (!x_half as isize),
            whole[1] + (!y_half as isize),
            whole[2] + (!z_half as isize),
        ];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (0.5 - frac[0]) * (0.5 - frac[0]); // x-distance squared to center line
        let y_range = (0.5 - frac[1]) * (0.5 - frac[1]); // y-distance squared to center line
        let z_range = (0.5 - frac[2]) * (0.5 - frac[2]); // z-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr, $z:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y, $z]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y, $z];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1], near[2]];
        }
        if y_range < range {
            test_point![near[0], far[1], near[2]];
        }
        if z_range < range {
            test_point![near[0], near[1], far[2]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1], near[2]];
        }
        if x_range < range && z_range < range {
            test_point![far[0], near[1], far[2]];
        }
        if y_range < range && z_range < range {
            test_point![near[0], far[1], far[2]];
        }

        if x_range < range && y_range < range && z_range < range {
            test_point![far[0], far[1], far[2]];
        }

        let value = if self.enable_range {
            range
        } else {
            self.displacement * self.perm_table.get3(seed_cell) as f64 / 255.0
        };

        value * 2.0 - 1.0
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec3(index: usize) -> Point3<f64> {
    let length = ((index & 0xE0) >> 5) as f64 * 0.5 / 7.0;
    let diag = length * std::f64::consts::FRAC_1_SQRT_2;
    match index % 18 {
        0  => [   diag,    diag,     0.0],
        1  => [   diag,   -diag,     0.0],
        2  => [  -diag,    diag,     0.0],
        3  => [  -diag,   -diag,     0.0],
        4  => [   diag,     0.0,    diag],
        5  => [   diag,     0.0,   -diag],
        6  => [  -diag,     0.0,    diag],
        7  => [  -diag,     0.0,   -diag],
        8  => [    0.0,    diag,    diag],
        9  => [    0.0,    diag,   -diag],
        10 => [    0.0,   -diag,    diag],
        11 => [    0.0,   -diag,   -diag],
        12 => [ length,     0.0,     0.0],
        13 => [    0.0,  length,     0.0],
        14 => [    0.0,     0.0,  length],
        15 => [-length,     0.0,     0.0],
        16 => [    0.0, -length,     0.0],
        17 => [    0.0,     0.0, -length],
        _ => panic!("Attempt to access 3D gradient {} of 18", index % 18),
    }
}

impl NoiseFn<Point4<f64>> for Worley {
    fn get(&self, point: Point4<f64>) -> f64 {
        #[inline(always)]
        fn get_point(perm_table: &PermutationTable, whole: Point4<isize>) -> Point4<f64> {
            math::add4(get_vec4(perm_table.get4(whole)), math::to_f644(whole))
        }

        let point = &math::mul4(point, self.frequency);

        let cell = math::map4(*point, f64::floor);
        let whole = math::to_isize4(cell);
        let frac = math::sub4(*point, cell);

        let x_half = frac[0] > 0.5;
        let y_half = frac[1] > 0.5;
        let z_half = frac[2] > 0.5;
        let w_half = frac[3] > 0.5;

        let near = [
            whole[0] + (x_half as isize),
            whole[1] + (y_half as isize),
            whole[2] + (z_half as isize),
            whole[3] + (w_half as isize),
        ];
        let far = [
            whole[0] + (!x_half as isize),
            whole[1] + (!y_half as isize),
            whole[2] + (!z_half as isize),
            whole[3] + (!w_half as isize),
        ];

        let mut seed_cell = near;
        let seed_point = get_point(&self.perm_table, near);
        let mut range = calculate_range(self.range_function, point, &seed_point);

        let x_range = (0.5 - frac[0]) * (0.5 - frac[0]); // x-distance squared to center line
        let y_range = (0.5 - frac[1]) * (0.5 - frac[1]); // y-distance squared to center line
        let z_range = (0.5 - frac[2]) * (0.5 - frac[2]); // z-distance squared to center line
        let w_range = (0.5 - frac[3]) * (0.5 - frac[3]); // w-distance squared to center line

        macro_rules! test_point(
            [$x:expr, $y:expr, $z:expr, $w:expr] => {
                {
                    let cur_point = get_point(&self.perm_table, [$x, $y, $z, $w]);
                    let cur_range = calculate_range(self.range_function, point, &cur_point);
                    if cur_range < range {
                        range = cur_range;
                        seed_cell = [$x, $y, $z, $w];
                    }
                }
            }
        );

        if x_range < range {
            test_point![far[0], near[1], near[2], near[3]];
        }
        if y_range < range {
            test_point![near[0], far[1], near[2], near[3]];
        }
        if z_range < range {
            test_point![near[0], near[1], far[2], near[3]];
        }
        if w_range < range {
            test_point![near[0], near[1], near[2], far[3]];
        }

        if x_range < range && y_range < range {
            test_point![far[0], far[1], near[2], near[3]];
        }
        if x_range < range && z_range < range {
            test_point![far[0], near[1], far[2], near[3]];
        }
        if x_range < range && w_range < range {
            test_point![far[0], near[1], near[2], far[3]];
        }
        if y_range < range && z_range < range {
            test_point![near[0], far[1], far[2], near[3]];
        }
        if y_range < range && w_range < range {
            test_point![near[0], far[1], near[2], far[3]];
        }
        if z_range < range && w_range < range {
            test_point![near[0], near[1], far[2], far[3]];
        }

        if x_range < range && y_range < range && z_range < range {
            test_point![far[0], far[1], far[2], near[3]];
        }
        if x_range < range && y_range < range && w_range < range {
            test_point![far[0], far[1], near[2], far[3]];
        }
        if x_range < range && z_range < range && w_range < range {
            test_point![far[0], near[1], far[2], far[3]];
        }
        if y_range < range && z_range < range && w_range < range {
            test_point![near[0], far[1], far[2], far[3]];
        }

        if x_range < range && y_range < range && z_range < range && w_range < range {
            test_point![far[0], far[1], far[2], far[3]];
        }

        let value = if self.enable_range {
            range
        } else {
            self.displacement * self.perm_table.get4(seed_cell) as f64 / 255.0
        };

        value * 2.0 - 1.0
    }
}

#[inline(always)]
#[cfg_attr(rustfmt, rustfmt_skip)]
fn get_vec4(index: usize) -> Point4<f64> {
    let length = ((index & 0xE0) >> 5) as f64 * 0.5 / 7.0;
    let diag = length * 0.5773502691896258;
    match index % 32 {
        0  => [ diag,  diag,  diag,  0.0],
        1  => [ diag, -diag,  diag,  0.0],
        2  => [-diag,  diag,  diag,  0.0],
        3  => [-diag, -diag,  diag,  0.0],
        4  => [ diag,  diag, -diag,  0.0],
        5  => [ diag, -diag, -diag,  0.0],
        6  => [-diag,  diag, -diag,  0.0],
        7  => [-diag, -diag, -diag,  0.0],
        8  => [ diag,  diag,  0.0,  diag],
        9  => [ diag, -diag,  0.0,  diag],
        10 => [-diag,  diag,  0.0,  diag],
        11 => [-diag, -diag,  0.0,  diag],
        12 => [ diag,  diag,  0.0, -diag],
        13 => [ diag, -diag,  0.0, -diag],
        14 => [-diag,  diag,  0.0, -diag],
        15 => [-diag, -diag,  0.0, -diag],
        16 => [ diag,  0.0,  diag,  diag],
        17 => [ diag,  0.0, -diag,  diag],
        18 => [-diag,  0.0,  diag,  diag],
        19 => [-diag,  0.0, -diag,  diag],
        20 => [ diag,  0.0,  diag, -diag],
        21 => [ diag,  0.0, -diag, -diag],
        22 => [-diag,  0.0,  diag, -diag],
        23 => [-diag,  0.0, -diag, -diag],
        24 => [ 0.0,  diag,  diag,  diag],
        25 => [ 0.0,  diag, -diag,  diag],
        26 => [ 0.0, -diag,  diag,  diag],
        27 => [ 0.0, -diag, -diag,  diag],
        28 => [ 0.0,  diag,  diag, -diag],
        29 => [ 0.0,  diag, -diag, -diag],
        30 => [ 0.0, -diag,  diag, -diag],
        31 => [ 0.0, -diag, -diag, -diag],
        _ => panic!("Attempt to access 4D gradient {} of 32", index % 32),
    }
}