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
use super::{BoundaryBehaviour, Rule};
use crate::CellGrid;
use rand::seq::SliceRandom;
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use std::fmt::Display;

/// A Pattern Rule works by looping over the current state and replacing every occurence of one or more certain patterns with another, equally sized pattern of characters.
///
/// For more information about how [Pattern]s are processed, see [Pattern].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternRule {
    /// The replacment patterns of this rule.
    pub(crate) patterns: Vec<Pattern>,
    /// How the patterns in this rule will deal with the edges of the state space. Currently non-functional.
    pub(crate) boundaries: (BoundaryBehaviour, BoundaryBehaviour),
}

impl Display for PatternRule {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{};\n\n", self.boundaries.0)?;
        write!(f, "{};\n\n", self.boundaries.1)?;
        for pattern in self.patterns.iter() {
            writeln!(f, "{}", pattern)?;
        }
        write!(f, "")
    }
}

impl From<&str> for PatternRule {
    fn from(value: &str) -> Self {
        let mut vals = value.split(";\n\n");

        PatternRule {
            boundaries: (
                BoundaryBehaviour::from(vals.next().unwrap()),
                BoundaryBehaviour::from(vals.next().unwrap()),
            ),
            patterns: vals
                .filter(|val| !val.is_empty())
                .map(Pattern::from)
                .collect(),
        }
    }
}

/// A pattern consists both of a grid of cells to search for and a grid of cells to replace it with.
///
/// The ```before``` pattern may contain wildcards ```*``` to match any character.
/// The ```after``` pattern may contain wildcards ```*``` to not mutate that cell and simply keep its previous value.
///
/// Whenever a pattern matches, the attribute might randomly be discarded instead of being applied.
/// The ```chance``` attribute describes the likelihood of the pattern being applied without discard, i.e. any value over ```1.0``` means the pattern will always be applied when it matches.
///
/// If multiple patterns are applicable within a time step, the one with higher priority will always be applied first.
/// Only if no cell concerning the second pattern has been mutated, the second pattern will apply also.
/// ```
/// use cellumina::rule::Rule;
/// let rule = cellumina::rule::PatternRule::from_patterns(
///     &[
///         cellumina::rule::Pattern{
///             chance: 1.0,
///             priority: 1.0,
///             before: grid::grid![['X'][' ']],
///             after: grid::grid![[' ']['X']],
///         },
///         cellumina::rule::Pattern{
///             chance: 1.0,
///             priority: 0.5,
///             before: grid::grid![[' ', 'X']['X', ' ']],
///             after: grid::grid![['X', 'X'][' ', ' ']],
///         },
///     ],
///     cellumina::rule::BoundaryBehaviour::Symbol('_'),
///     cellumina::rule::BoundaryBehaviour::Symbol('_'),
/// );
///
/// let mut grid = grid::grid![[' ', 'X']['X', ' '][' ', ' ']];
/// rule.transform(&mut grid);
/// assert_eq!(grid, grid::grid![[' ', ' '][' ', 'X']['X', ' ']]);
/// rule.transform(&mut grid);
/// assert_eq!(grid, grid::grid![[' ', ' '][' ', ' ']['X', 'X']]);
///
/// let rule2 = cellumina::rule::PatternRule::from(rule.to_string().as_str());
///
/// grid = grid::grid![[' ', 'X']['X', ' '][' ', ' ']];
/// rule2.transform(&mut grid);
/// assert_eq!(grid, grid::grid![[' ', ' '][' ', 'X']['X', ' ']]);
/// rule2.transform(&mut grid);
/// assert_eq!(grid, grid::grid![[' ', ' '][' ', ' ']['X', 'X']]);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pattern {
    /// The chance for the pattern to apply on a match.
    pub chance: f32,
    /// The priority of this pattern over others.
    pub priority: f32,
    /// The cell pattern to search for.
    #[serde(with = "SerdeGrid")]
    pub before: CellGrid,
    /// The cell pattern it should be replaced with.
    #[serde(with = "SerdeGrid")]
    pub after: CellGrid,
}

impl Default for Pattern {
    fn default() -> Self {
        Self {
            chance: 1.,
            priority: 0.,
            before: grid::grid![['*']],
            after: grid::grid![['*']],
        }
    }
}

impl Display for Pattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{};", self.chance)?;
        write!(f, "{};", self.priority)?;
        for row in self.before.iter_rows() {
            writeln!(f)?;
            for b_cell in row {
                write!(f, "{}", b_cell)?;
            }
        }
        write!(f, ";")?;
        for row in self.after.iter_rows() {
            writeln!(f)?;
            for a_cell in row {
                write!(f, "{}", a_cell)?;
            }
        }
        writeln!(f, ";")
    }
}
/// ```
/// use cellumina::rule::Rule;
/// let pattern = cellumina::rule::Pattern{
///             chance: 1.0,
///             priority: 1.0,
///             before: grid::grid![[' ', ' ', 'X'][' ', 'X', 'X']],
///             after: grid::grid![['*', '*', ' ']['X', '*', '*']],
///         };
/// let pattern2 = cellumina::rule::Pattern::from(pattern.to_string().as_str());
/// assert_eq!(pattern.chance, pattern2.chance);
/// assert_eq!(pattern.priority, pattern2.priority);
/// assert_eq!(pattern.before.rows(), pattern2.before.rows());
/// assert_eq!(pattern.before.cols(), pattern2.before.cols());
/// assert_eq!(pattern.after.rows(), pattern2.after.rows());
/// assert_eq!(pattern.after.cols(), pattern2.after.cols());
/// for (c1, c2) in pattern.before.iter().zip(pattern2.before.iter()) {
///     assert_eq!(*c1, *c2);
/// }
/// for (c1, c2) in pattern.after.iter().zip(pattern2.after.iter()) {
///     assert_eq!(*c1, *c2);
/// }
/// ```
impl From<&str> for Pattern {
    fn from(value: &str) -> Self {
        let parts = value.split(";\n").collect::<Vec<&str>>();

        Pattern {
            chance: parts[0].parse().unwrap_or(1.),
            priority: parts[1].parse().unwrap_or(0.),
            before: {
                let lines = parts[2].split('\n').collect::<Vec<&str>>();
                grid::Grid::from_vec(
                    lines
                        .iter()
                        .flat_map(|line| line.chars())
                        .collect::<Vec<char>>(),
                    lines[0].len(),
                )
            },
            after: {
                let lines = parts[3].split('\n').collect::<Vec<&str>>();
                grid::Grid::from_vec(
                    lines
                        .iter()
                        .flat_map(|line| line.chars())
                        .collect::<Vec<char>>(),
                    lines[0].len(),
                )
            },
        }
    }
}

/// Custom struct to allow the implementaion of [serde::Serialize] and [serde::Deserialize] on foreign type grid.
/// As a grid can be constructed from ```data``` and ```columns``` alone, representing ```rows``` is not neccessary.
#[derive(Serialize, Deserialize)]
#[serde(remote = "grid::Grid")]
struct SerdeGrid<T> {
    /// Representer for the data in a grid
    #[serde(getter = "grid::Grid::flatten")]
    data: Vec<T>,
    /// Representer for the number of columns in a grid.
    #[serde(getter = "grid::Grid::cols")]
    cols: usize,
}

impl<T> From<SerdeGrid<T>> for grid::Grid<T> {
    fn from(value: SerdeGrid<T>) -> Self {
        grid::Grid::from_vec(value.data, value.cols)
    }
}

impl PatternRule {
    /// Create a new (empty) pattern rule.
    pub fn new_empty() -> Self {
        Self {
            patterns: Vec::new(),
            boundaries: (
                BoundaryBehaviour::Symbol('_'),
                BoundaryBehaviour::Symbol('_'),
            ),
        }
    }

    /// Create a new pattern rule from a set of patterns.
    pub fn from_patterns(
        rules: &[Pattern],
        row_boundary: BoundaryBehaviour,
        column_boundary: BoundaryBehaviour,
    ) -> Self {
        Self {
            patterns: rules.to_vec(),
            boundaries: (row_boundary, column_boundary),
        }
    }
}

/// A collection of replacement actions, containing a priority, a position (row/column) and a placement character.
/// A pattern will always produce such a collection of replacements belonging together.
type ReplacementCollection = Vec<Vec<(f32, usize, usize, char)>>;

impl Rule for PatternRule {
    fn transform(&self, grid: &mut CellGrid) {
        let (rows, cols) = grid.size();

        let mut replacements: ReplacementCollection = self
            .patterns
            .par_iter()
            .filter_map(|pattern| {
                let mut partial_res = Vec::new();

                let row_stop = match self.boundaries.0 {
                    BoundaryBehaviour::Periodic => rows,
                    BoundaryBehaviour::Symbol(_)=> 
                        rows - pattern.before.rows() + 1
                    ,
                };

                let col_stop = match self.boundaries.1 {
                    BoundaryBehaviour::Periodic => cols,
                    BoundaryBehaviour::Symbol(_)=> 
                        cols - pattern.before.cols() + 1,
                };

                for row in 0..row_stop {
                    'inner_loop: for col in 0..col_stop {
                        let (p_rows, p_cols) = pattern.after.size();

                        // possibly immediately randomly stop to adhere to pattern chance
                        if rand::random::<f32>() > pattern.chance {
                            continue 'inner_loop;
                        }

                        // check if pattern is applicable
                        for row_del in 0..p_rows {
                            for col_del in 0..p_cols {
                                if pattern.before[row_del][col_del] != '*'
                                // do modulo in case we are wrapping - if edge behaviour is set to stop, this will never change anything
                                    && grid
                                        .get(row + row_del, col + col_del)
                                        .copied()
                                        .unwrap_or_else(|| grid[(row + row_del)%rows][(col + col_del) % cols])
                                    != pattern.before[row_del][col_del]
                                {
                                    continue 'inner_loop;
                                }
                            }
                        }

                        // if we arrive here, the pattern fits
                        let mut rep_group = Vec::new();
                        // push replacements as dictated by the pattern
                        for row_del in 0..p_rows {
                            for col_del in 0..p_cols {
                                let rep = pattern.after[row_del][col_del];
                                // make sure to not replace wild cards, and check edge behaviour
                                if rep != '*' {
                                    // apply modulus to replacement coordinates to be sure
                                    rep_group.push((
                                        pattern.priority,
                                        (row + row_del) % rows,
                                        (col + col_del) % cols,
                                        rep,
                                    ));
                                }
                            }
                        }
                        partial_res.push(rep_group);
                    }
                }
                // only return partial result if it contains any elements
                if partial_res.is_empty() {
                    None
                } else {
                    Some(partial_res)
                }
            })
            .flatten()
            .collect();

        // shuffle the replacements
        replacements.shuffle(&mut rand::thread_rng());
        // then re-sort them by priority
        replacements.sort_by(|rule1, rule2| {
            if let Some(rep1) = rule1.first() {
                if let Some(rep2) = rule2.first() {
                    rep2.0
                        .partial_cmp(&rep1.0)
                        .unwrap_or(std::cmp::Ordering::Equal)
                } else {
                    std::cmp::Ordering::Equal
                }
            } else {
                std::cmp::Ordering::Equal
            }
        });

        let mut mutated = grid::Grid::new(rows, cols);
        mutated.fill(false);

        for rep_group in replacements.iter() {
            if rep_group
                .iter()
                .all(|(_, row, col, _)| !mutated[*row][*col])
            {
                for (_, row, col, rep) in rep_group.iter().copied() {
                    grid[row][col] = rep;
                    mutated[row][col] = true;
                }
            }
        }
    }
}