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
use rand;

use rand::Rng;

pub struct CellularMap {
    width: u32,
    height: u32,
    map: Vec<u8>,
}

pub enum EvolveStrategy {
    Default, // The standard evolution rules.
    Cleaning, // Aggressive cleaning. Remove a lot of "single" occupied tiles.
}

impl CellularMap {
    /// Create a new `CellularMap` instance.
    ///
    /// # Arguments
    ///
    /// * `w` - The desired map width.
    /// * `h` - The desired map height.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cellular_maps::CellularMap;
    ///
    /// // Create a 30x30 celular map.
    /// let mut cm = CellularMap::new(30,30);
    /// ```
    ///
    pub fn new(w: u32, h: u32) -> CellularMap {
        let mut arraymap: Vec<u8> = Vec::with_capacity((w * h) as usize);
        for _ in 0..w * h {
            arraymap.push(0);
        }
        CellularMap {
            width: w,
            height: h,
            map: arraymap,
        }
    }

    /// Get the map width.
    pub fn get_width(self: &CellularMap) -> u32 {
        self.width
    }

    /// Get the map height.
    pub fn get_height(self: &CellularMap) -> u32 {
        self.height
    }

    /// Get the element in position `<r,c>`.
    pub fn get_element(self: &CellularMap, r: u32, c: u32) -> u8 {
        return self.map[self.get_index(r, c)];
    }

    /// Initialize a random `CellularMap`.
    pub fn random_fill(self: &mut CellularMap, wall_prob: u32) {
        for index in 0..self.width * self.height {
            let (c, r) = (index % self.width, index / self.width);
            self.map[index as usize] = if self.is_on_border(r, c) {
                1
            } else {
                let map_middle = self.height / 2;
                if r == map_middle {
                    0
                } else {
                    let value = rand::thread_rng().gen_range(0, 100);
                    if value < wall_prob {
                        1
                    } else {
                        0
                    }
                }
            };
        }
    }

    pub fn evolve_default(self: &mut CellularMap) {
        self.evolve(EvolveStrategy::Default)
    }

    /// Evolve the `CellularMap` according the automata rules.
    pub fn evolve(self: &mut CellularMap, _strategy: EvolveStrategy) {
        for r in 0..self.height {
            for c in 0..self.width {
                let value = self.place_logic(r, c);
                let index = self.get_index(r, c);
                self.map[index] = value;
            }
        }
    }

    /// Implements the wall evolution automata rules for a given position `<r,c>`.
    fn place_logic(self: &mut CellularMap, r: u32, c: u32) -> u8 {
        let num_wall1 = self.count_adjacent_wall(r, c, 1, 1);
        let num_wall2 = self.count_adjacent_wall(r, c, 2, 2);

        let index = self.get_index(r, c);
        if self.map[index] == 1u8 {
            if num_wall1 >= 3 {
                1
            } else {
                0
            }
        } else {
            if num_wall1 >= 5 || num_wall2 <= 2 {
                1
            } else {
                0
            }
        }
    }

    /// Count the number of walls adjacent to `<r,c>` in a given radius `scopex` - `scopey`.
    fn count_adjacent_wall(self: &mut CellularMap,
                           r: u32,
                           c: u32,
                           scopex: u32,
                           scopey: u32)
                           -> u32 {
        let endx = c + scopex + 1;
        let endy = r + scopey + 1;

        let startx = if scopex > c {
            0
        } else {
            c - scopex
        };
        let underx = if scopex > c {
            scopex - c
        } else {
            0
        };

        let starty = if scopey > r {
            0
        } else {
            r - scopey
        };
        let undery = if scopey > r {
            scopey - r
        } else {
            0
        };

        let mut wallcounter = underx * (2 * scopex + 1) + undery * (2 * scopey + 1) -
                              undery * underx;

        for iy in starty..endy {
            for ix in startx..endx {
                if (ix != c || iy != r) && self.is_wall(iy, ix) {
                    wallcounter += 1;
                }
            }
        }
        return wallcounter;
    }

    /// Check if a given position `<r,c>` is a wall.
    fn is_wall(self: &CellularMap, r: u32, c: u32) -> bool {
        let index = self.get_index(r, c);
        self.is_out_of_bound(r, c) || self.map[index] == 1
    }

    /// Check if a given position `<r,c>` is out of bound.
    fn is_out_of_bound(self: &CellularMap, r: u32, c: u32) -> bool {
        c > self.width - 1 || r > self.height - 1
    }

    /// Check if a given position `<r,c>` is on the map border.
    fn is_on_border(self: &CellularMap, r: u32, c: u32) -> bool {
        c == 0 || r == 0 || c == self.width - 1 || r == self.height - 1
    }

    /// Get the row-major index for the given position.
    fn get_index(self: &CellularMap, r: u32, c: u32) -> usize {
        (c + r * self.width) as usize
    }
}

// Commented due to Rust Stable unstable ban madness.
//

#[test]
fn constructor_test() {
    let cm = CellularMap::new(12, 12);

    assert!(12 == cm.width);
    assert!(12 == cm.height);
}

#[test]
fn get_element_test() {
    let mut cm = CellularMap::new(12, 12);
    cm.map[4] = 2u8;
    assert_eq!(2u8, cm.get_element(0, 4));
}

// #[bench]
// fn evolve_bench(b:&mut Bencher) {
//     let mut cm = CellularMap::new(30,30);
//     cm.random_fill(40);
//     b.iter(|| {
//         cm.evolve_default();
//     });
// }