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
pub mod ruleset;

use ruleset::RuleSet;
use std::{cmp::Ordering, iter, mem};

use wasm_bindgen::prelude::wasm_bindgen;

/// A two-dimensional cellular automaton with a finite grid of cells.
#[wasm_bindgen(inspectable)]
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Automaton {
    rows: usize,
    cols: usize,
    cells: Vec<u8>,
    cells_step: Vec<u8>,
    rules: RuleSet,
    neighbor_deltas: [[usize; 2]; 8],
}

#[wasm_bindgen]
impl Automaton {
    /// Constructs a new automaton with all cell states set to 0.
    ///
    /// # Examples
    ///
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(constructor)]
    #[must_use]
    pub fn new(rows: usize, cols: usize) -> Self {
        #[cfg(feature = "console_error_panic_hook")]
        console_error_panic_hook::set_once();

        let neighbor_deltas = [
            [rows - 1, cols - 1],
            [rows - 1, 0],
            [rows - 1, 1],
            [0, cols - 1],
            [0, 1],
            [1, cols - 1],
            [1, 0],
            [1, 1],
        ];

        Self {
            rows,
            cols,
            cells: vec![0; cols * rows],
            cells_step: vec![0; cols * rows],
            rules: RuleSet::default(),
            neighbor_deltas,
        }
    }

    /// Resizes the automaton so that `cols` is equal to `width`.
    ///
    /// If `width` is greater than `cols`, the automaton's rows are extended by the
    /// difference, with each additional column filled with 0. If `width` is less
    /// than `cols`, the automaton's rows are simply truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(setter = cols, js_name = resizeWidth)]
    pub fn resize_width(&mut self, width: usize) {
        match width.cmp(&self.cols) {
            Ordering::Greater => {
                let width_diff = width - self.cols;
                let cols = self.cols;
                self.cells.reserve_exact(width_diff * self.rows);
                for i in (0..self.rows).rev().map(|n| n * cols + cols) {
                    self.cells.splice(i..i, iter::repeat(0).take(width_diff));
                }
                // TODO: benchmark against the following alternative
                // let width_diff = width - self.width;
                // for _ in 0..self.height {
                //     self.cells.extend(iter::repeat(0).take(width_diff));
                //     self.cells.rotate_right(width);
                // }
            }
            Ordering::Less => {
                let width_diff = self.cols - width;
                let cols = self.cols;
                for (start, end) in (1..=self.rows)
                    .rev()
                    .map(|n| (n * cols - width_diff, n * cols))
                {
                    self.cells.splice(start..end, iter::empty());
                }
                // TODO: benchmark against the following alternative
                // let width_diff = self.width - width;
                // for _ in 0..self.height {
                //     self.cells.truncate(self.cells.len() - width_diff);
                //     self.cells.rotate_right(width);
                // }
            }
            Ordering::Equal => (),
        }
        self.cells_step
            .resize_with(width * self.rows, Default::default);
        self.cells_step.shrink_to_fit();
        self.cols = width;
        self.set_neighbor_deltas(width, self.rows);
    }

    /// Resizes the automaton so that `rows` is equal to `height`.
    ///
    /// If `height` is greater than `rows`, the automaton's columns are extended by
    /// the difference, with each additional row filled with 0. If `height` is less
    /// than `rows`, the automaton's columns are simply truncated.
    ///
    /// # Examples
    ///
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(setter = rows, js_name = resizeHeight)]
    pub fn resize_height(&mut self, height: usize) {
        self.cells.resize_with(self.cols * height, Default::default);
        self.cells.shrink_to_fit();
        self.cells_step
            .resize_with(self.cols * height, Default::default);
        self.cells_step.shrink_to_fit();
        self.rows = height;
        self.set_neighbor_deltas(self.cols, height);
    }

    /// Returns a raw pointer to the automaton cells' buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(getter = cellsPtr, js_name = getCellsPtr)]
    #[must_use]
    pub fn cells_ptr(&self) -> *const u8 {
        self.cells.as_ptr()
    }

    /// Toggles the state of a cell. If the cell state is 0, it is set to 1. If the
    /// cell is any other state, it is set to 0.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(js_name = toggleCell)]
    pub fn toggle_cell(&mut self, row: usize, col: usize) {
        let idx = self.index(row, col);
        if let Some(cell) = self.cells.get_mut(idx) {
            *cell = match cell {
                0 => 1,
                _ => 0,
            }
        }
    }

    /// Sets the state of cells in `locations` to 1.
    ///
    /// `locations` is a list of alternating row and column coordinates. This
    /// function is implemented with an array as the parameter because
    /// `wasm_bindgen` does not support nested arrays.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(js_name = setCellsOn)]
    pub fn set_cells_on(&mut self, locations: &[usize]) {
        for (&row, &col) in locations
            .iter()
            .step_by(2)
            .zip(locations.iter().skip(1).step_by(2))
        {
            let idx = self.index(row, col);
            if let Some(cell) = self.cells.get_mut(idx) {
                *cell = 1;
            }
        }
    }

    /// Sets the cell state of all the automaton's cells to `n`.
    ///
    /// Only changes the automaton if `n` is less than or equal to the generation
    /// rule.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(js_name = setAllCells)]
    pub fn set_all_cells(&mut self, n: u8) {
        if n <= self.rules.generation {
            self.cells.fill(n);
        }
    }

    /// Randomizes the cell state of all the automaton's cells.
    ///
    /// Loops through the automaton's cells and if `rand::random()` is less than the
    /// percentage `n`, the cell state is set to 1.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(js_name = randomizeCells)]
    pub fn randomize_cells(&mut self, n: f64) {
        for cell in &mut self.cells {
            *cell = if rand::random::<f64>() < n / 100.0 {
                1
            } else {
                0
            };
        }
    }

    /// Sets all three cell state rules to different values.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(js_name = setRules)]
    pub fn set_rules(&mut self, s: &[u8], b: &[u8], c: u8) {
        self.rules.survival = s.to_vec();
        self.rules.birth = b.to_vec();
        self.rules.generation = c;
    }

    /// Sets the cell survival rule to a different value.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(setter = survivalRule, js_name = setSurvivalRule)]
    pub fn set_survival_rule(&mut self, s: &[u8]) {
        self.rules.survival = s.to_vec();
    }

    /// Sets the cell birth rule to a different value.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(setter = birthRule, js_name = setBirthRule)]
    pub fn set_birth_rule(&mut self, b: &[u8]) {
        self.rules.birth = b.to_vec();
    }

    /// Sets the cell generation rule to a different value.
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    #[wasm_bindgen(setter = generationRule, js_name = setGenerationRule)]
    pub fn set_generation_rule(&mut self, c: u8) {
        self.rules.generation = c - 1;
    }

    /// Calculates and the state of all cells in the automaton after `n` generations
    ///
    /// # Examples
    /// ```
    /// todo!();
    /// ```
    pub fn step(&mut self, n: usize) {
        for _ in 0..n {
            for row in 0..self.rows {
                for col in 0..self.cols {
                    let idx = self.index(row, col);

                    self.cells_step[idx] = match (self.cells[idx], self.neighbors(row, col)) {
                        (0, n) => self.rules.birth.contains(&n).into(),
                        (1, n) if self.rules.survival.contains(&n) => 1,
                        (s, _) if s < self.rules.generation => s + 1,
                        _ => 0,
                    }
                }
            }

            mem::swap(&mut self.cells, &mut self.cells_step);
        }
    }

    // Returns the index of a cell in the automaton.
    const fn index(&self, row: usize, col: usize) -> usize {
        row * self.cols + col
    }

    // Returns the count of a cell's live, first-generation neighbors.
    fn neighbors(&self, row: usize, col: usize) -> u8 {
        self.neighbor_deltas
            .iter()
            .fold(0, |count, &[row_delta, col_delta]| {
                match self
                    .cells
                    .get(self.index((row + row_delta) % self.rows, (col + col_delta) % self.cols))
                    .unwrap()
                {
                    1 => count + 1,
                    _ => count,
                }
            })
    }

    // Returns the offsets of neighboring cell locations; these deltas are required
    // for the automaton's `neighbors` method.
    fn set_neighbor_deltas(&mut self, rows: usize, cols: usize) {
        self.neighbor_deltas = [
            [rows - 1, cols - 1],
            [rows - 1, 0],
            [rows - 1, 1],
            [0, cols - 1],
            [0, 1],
            [1, cols - 1],
            [1, 0],
            [1, 1],
        ];
    }
}

#[cfg(test)]
// flatten a slice of tuples that contain (x, y) locations of cells
fn flatten_locations(locations: &[(usize, usize)]) -> Vec<usize> {
    locations
        .iter()
        .flat_map(|&(x, y)| iter::once(x).chain(iter::once(y)))
        .collect()
}

#[cfg(test)]
// build an automaton with width, height, and locations of live cells
fn build_automaton(width: usize, height: usize, locations: &[(usize, usize)]) -> Automaton {
    let mut a = Automaton::new(width, height);
    a.set_cells_on(&flatten_locations(locations));
    a
}

#[cfg(test)]
pub mod tests {
    use super::{build_automaton, flatten_locations, Automaton};
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test]
    fn automaton_new() {
        let a = Automaton::new(64, 64);
        assert_eq!(a.cells, vec![0; 64 * 64]);
    }

    #[wasm_bindgen_test]
    fn automaton_set_cells_on() {
        let mut a = Automaton::new(3, 3);
        a.set_cells_on(&flatten_locations(&[
            (0, 0),
            (0, 1),
            (0, 2),
            (1, 0),
            (1, 1),
            (1, 2),
            (2, 0),
            (2, 1),
            (2, 2),
        ]));
        assert_eq!(a.cells, vec![1, 1, 1, 1, 1, 1, 1, 1, 1]);
    }

    #[wasm_bindgen_test]
    fn automaton_new_rect() {
        let mut a = Automaton::new(2, 3);
        a.set_cells_on(&flatten_locations(&[(1, 1)]));
        assert_eq!(a.cells, vec![0, 0, 0, 0, 1, 0]);
    }

    #[wasm_bindgen_test]
    fn automaton_set_all_cells() {
        let mut a = Automaton::new(3, 3);
        a.set_all_cells(1);
        assert_eq!(a.cells, vec![1, 1, 1, 1, 1, 1, 1, 1, 1]);
        a.set_all_cells(0);
        assert_eq!(a.cells, vec![0, 0, 0, 0, 0, 0, 0, 0, 0]);
    }

    #[wasm_bindgen_test]
    fn automaton_resize_width_larger() {
        let mut a = Automaton::new(3, 3);
        a.set_all_cells(1);
        a.resize_width(5);
        assert_eq!(a.cells, vec![1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0]);
    }

    #[wasm_bindgen_test]
    fn automaton_resize_width_smaller() {
        let mut a = Automaton::new(3, 3);
        a.set_all_cells(1);
        a.resize_width(2);
        assert_eq!(a.cells, vec![1, 1, 1, 1, 1, 1]);
    }

    #[wasm_bindgen_test]
    fn automaton_resize_height_larger() {
        let mut a = Automaton::new(3, 3);
        a.set_all_cells(1);
        a.resize_height(5);
        assert_eq!(a.cells, vec![1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]);
    }

    #[wasm_bindgen_test]
    fn automaton_resize_height_smaller() {
        let mut a = Automaton::new(3, 3);
        a.set_all_cells(1);
        a.resize_height(2);
        assert_eq!(a.cells, vec![1, 1, 1, 1, 1, 1]);
    }

    #[wasm_bindgen_test]
    fn automaton_wrapping() {
        let mut a = build_automaton(2, 2, &[(0, 0), (0, 1)]);
        let a_1 = build_automaton(2, 2, &[(0, 0), (0, 1)]);

        a.step(1);
        assert_eq!(a.cells, a_1.cells);
    }

    #[wasm_bindgen_test]
    fn automaton_step() {
        let mut a = build_automaton(6, 6, &[(1, 2), (2, 3), (3, 1), (3, 2), (3, 3)]);
        let a_1 = build_automaton(6, 6, &[(2, 1), (2, 3), (3, 2), (3, 3), (4, 2)]);

        a.step(1);
        assert_eq!(a.cells, a_1.cells);
    }
}