libnoise/core/sources/
perlin.rs

1use super::functional::{self, constants::PERMUTATION_TABLE_SIZE};
2use crate::core::{
3    generator::{Generator, Generator1D, Generator2D, Generator3D, Generator4D},
4    utils::ptable::{PermutationTable, Seed},
5};
6
7/// A generator which produces n-dimensional perlin noise.
8///
9/// For details, see the documentation of [`perlin()`]. Typically, this struct is not meant
10/// to be used directly. Instead, [`perlin()`] implemented by [`Source`], should be used to
11/// create a perlin noise generator.
12///
13/// # Direct usage of this struct
14///
15/// Direct instantiation of this struct:
16///
17/// ```
18/// # use libnoise::{Perlin, Generator};
19/// let generator = Perlin::new(42);
20/// let value = generator.sample([0.2, 0.5]);
21/// ```
22///
23/// [`perlin()`]: crate::Source::perlin
24/// [`Source`]: crate::Source
25#[derive(Clone, Debug)]
26pub struct Perlin<const D: usize> {
27    permutation_table: PermutationTable,
28}
29
30impl Generator1D for Perlin<1> {}
31impl Generator2D for Perlin<2> {}
32impl Generator3D for Perlin<3> {}
33impl Generator4D for Perlin<4> {}
34
35impl<const D: usize> Perlin<D> {
36    /// Create a new perlin noise generator.
37    #[inline]
38    pub fn new(seed: impl Seed) -> Self {
39        let permutation_table = PermutationTable::new(seed, PERMUTATION_TABLE_SIZE, true);
40        Self { permutation_table }
41    }
42}
43
44impl Generator<1> for Perlin<1> {
45    #[inline]
46    fn sample(&self, point: [f64; 1]) -> f64 {
47        functional::perlin::noise1d(&self.permutation_table, point)
48    }
49}
50
51impl Generator<2> for Perlin<2> {
52    #[inline]
53    fn sample(&self, point: [f64; 2]) -> f64 {
54        functional::perlin::noise2d(&self.permutation_table, point)
55    }
56}
57
58impl Generator<3> for Perlin<3> {
59    #[inline]
60    fn sample(&self, point: [f64; 3]) -> f64 {
61        functional::perlin::noise3d(&self.permutation_table, point)
62    }
63}
64
65impl Generator<4> for Perlin<4> {
66    #[inline]
67    fn sample(&self, point: [f64; 4]) -> f64 {
68        functional::perlin::noise4d(&self.permutation_table, point)
69    }
70}