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
//! World configuration. use crate::{ cells::State, rules::{Life, NtLife}, search::Search, world::World, }; use derivative::Derivative; use std::{ cmp::Ordering, error::Error, fmt::{self, Debug, Formatter}, str::FromStr, }; #[cfg(feature = "serialize")] use serde::{Deserialize, Serialize}; /// Transformations (rotations and reflections) after the last generation. /// /// After the last generation, the pattern will return to /// the first generation, applying this transformation first, /// and then the translation defined by `dx` and `dy`. /// /// 8 different values corresponds to 8 elements of the dihedral group /// _D_<sub>8</sub>. /// /// `Id` is the identity transformation. /// /// `R` means rotations around the center of the world. /// The number after it is the counterclockwise rotation angle in degrees. /// /// `F` means reflections (flips). /// The symbol after it is the axis of reflection. /// /// Some of the transformations are only valid when the world is square. #[derive(Clone, Copy, Derivative, PartialEq, Eq)] #[derivative(Default)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub enum Transform { /// `Id`. /// /// Identity transformation. #[derivative(Default)] Id, /// `R90`. /// /// 90° rotation counterclockwise. Rotate90, /// `R180`. /// /// 180° rotation counterclockwise. Rotate180, /// `R270`. /// /// 270° rotation counterclockwise. Rotate270, /// `F-`. /// /// Reflection across the middle row. FlipRow, /// `F|`. /// /// Reflection across the middle column. FlipCol, /// `F\`. /// /// Reflection across the diagonal. FlipDiag, /// `F/`. /// /// Reflection across the antidiagonal. FlipAntidiag, } impl FromStr for Transform { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "Id" => Ok(Transform::Id), "R90" => Ok(Transform::Rotate90), "R180" => Ok(Transform::Rotate180), "R270" => Ok(Transform::Rotate270), "F-" => Ok(Transform::FlipRow), "F|" => Ok(Transform::FlipCol), "F\\" => Ok(Transform::FlipDiag), "F/" => Ok(Transform::FlipAntidiag), _ => Err(String::from("invalid Transform")), } } } impl Debug for Transform { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let s = match self { Transform::Id => "Id", Transform::Rotate90 => "R90", Transform::Rotate180 => "R180", Transform::Rotate270 => "R270", Transform::FlipRow => "F-", Transform::FlipCol => "F|", Transform::FlipDiag => "F\\", Transform::FlipAntidiag => "F/", }; write!(f, "{}", s)?; Ok(()) } } impl Transform { /// Whether the transformation requires the world to be square. /// /// Returns `true` for `R90`, `R270`, `F\` and `F/`. pub fn square_world(self) -> bool { match self { Transform::Rotate90 | Transform::Rotate270 | Transform::FlipDiag | Transform::FlipAntidiag => true, _ => false, } } } /// Symmetries of the pattern. /// /// 10 different values corresponds to 10 subgroups of the dihedral group /// _D_<sub>8</sub>. /// /// The notation is stolen from Oscar Cunningham's /// [Logic Life Search](https://github.com/OscarCunningham/logic-life-search). /// /// Some of the symmetries are only valid when the world is square. #[derive(Clone, Copy, Derivative, PartialEq, Eq)] #[derivative(Default)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub enum Symmetry { /// `C1`. /// /// No symmetry at all. #[derivative(Default)] C1, /// `C2`. /// /// Symmetry under 180° rotation. C2, /// `C4`. /// /// Symmetry under 90° rotation. C4, /// `D2-`. /// /// Symmetry under reflection across the middle row. D2Row, /// `D2|`. /// /// Symmetry under reflection across the middle column. D2Col, /// `D2\`. /// /// Symmetry under reflection across the diagonal. D2Diag, /// `D2/`. /// /// Symmetry under reflection across the antidiagonal. D2Antidiag, /// `D4+`. /// /// Symmetry under reflections across the middle row /// and the middle column. D4Ortho, /// `D4X`. /// /// Symmetry under reflections across the diagonal /// and the antidiagonal. D4Diag, /// `D8`. /// /// Symmetry under all 8 transformations. D8, } impl FromStr for Symmetry { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "C1" => Ok(Symmetry::C1), "C2" => Ok(Symmetry::C2), "C4" => Ok(Symmetry::C4), "D2-" => Ok(Symmetry::D2Row), "D2|" => Ok(Symmetry::D2Col), "D2\\" => Ok(Symmetry::D2Diag), "D2/" => Ok(Symmetry::D2Antidiag), "D4+" => Ok(Symmetry::D4Ortho), "D4X" => Ok(Symmetry::D4Diag), "D8" => Ok(Symmetry::D8), _ => Err(String::from("invalid symmetry")), } } } impl Debug for Symmetry { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { let s = match self { Symmetry::C1 => "C1", Symmetry::C2 => "C2", Symmetry::C4 => "C4", Symmetry::D2Row => "D2-", Symmetry::D2Col => "D2|", Symmetry::D2Diag => "D2\\", Symmetry::D2Antidiag => "D2/", Symmetry::D4Ortho => "D4+", Symmetry::D4Diag => "D4X", Symmetry::D8 => "D8", }; write!(f, "{}", s)?; Ok(()) } } impl Symmetry { /// Whether the transformation requires the world to be square. /// /// Returns `true` for `C4`, `D2\`, `D2/`, `D4X` and `D8`. pub fn square_world(self) -> bool { match self { Symmetry::C4 | Symmetry::D2Diag | Symmetry::D2Antidiag | Symmetry::D4Diag | Symmetry::D8 => true, _ => false, } } } /// The order to find a new unknown cell. /// /// It will always search all generations of a cell first, /// and the go to another cell. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub enum SearchOrder { /// Searches all cells of a row first, /// and the go to the next row. /// /// ```plaintext /// 123 /// 456 /// 789 /// ``` RowFirst, /// Searches all cells of a column first, /// and the go to the next column. /// /// ```plaintext /// 147 /// 258 /// 369 /// ``` ColumnFirst, } /// How to choose a state for an unknown cell. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub enum NewState { /// Chooses the given state. /// /// For rules with `B0`, `Choose(Dead)` actually means /// choosing the background, i.e., `Dead` in even generations, /// `Alive` in odd generations. Choose(State), /// Random. The probability of either state is 1/2. Random, } impl Default for NewState { fn default() -> Self { NewState::Choose(State::Alive) } } /// World configuration. /// /// The world will be generated from this configuration. #[derive(Clone, Debug, Derivative, PartialEq, Eq)] #[derivative(Default)] #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))] pub struct Config { /// Width. #[derivative(Default(value = "16"))] pub width: isize, /// Height. #[derivative(Default(value = "16"))] pub height: isize, /// Period. #[derivative(Default(value = "1"))] pub period: isize, /// Horizontal translation. pub dx: isize, /// Vertical translation. pub dy: isize, /// Transformations (rotations and reflections) after the last generation. /// /// After the last generation, the pattern will return to /// the first generation, applying this transformation first, /// and then the translation defined by `dx` and `dy`. pub transform: Transform, /// Symmetries of the pattern. pub symmetry: Symmetry, /// The order to find a new unknown cell. /// /// It will always search all generations of a cell first, /// and then go to another cell. /// /// `None` means that it will automatically choose a search order /// according to the width and height of the world. pub search_order: Option<SearchOrder>, /// How to choose a state for an unknown cell. pub new_state: NewState, /// The number of minimum living cells in all generations must not /// exceed this number. /// /// `None` means that there is no limit for the cell count. pub max_cell_count: Option<usize>, /// Whether to force the first row/column to be nonempty. /// /// Here 'front' means the first row or column to search, /// according to the search order. #[derivative(Default(value = "true"))] pub non_empty_front: bool, /// Whether to automatically reduce the `max_cell_count` /// when a result is found. /// /// The `max_cell_count` will be set to the cell count of /// the current result minus one. pub reduce_max: bool, /// The rule string of the cellular automaton. #[derivative(Default(value = "String::from(\"B3/S23\")"))] pub rule_string: String, } impl Config { /// Sets up a new configuration with given size. pub fn new(width: isize, height: isize, period: isize) -> Self { Config { width, height, period, ..Config::default() } } /// Sets the translations `(dx, dy)`. pub fn set_translate(mut self, dx: isize, dy: isize) -> Self { self.dx = dx; self.dy = dy; self } /// Sets the transformation. pub fn set_transform(mut self, transform: Transform) -> Self { self.transform = transform; self } /// Sets the symmetry. pub fn set_symmetry(mut self, symmetry: Symmetry) -> Self { self.symmetry = symmetry; self } /// Sets the search order. pub fn set_search_order(mut self, search_order: Option<SearchOrder>) -> Self { self.search_order = search_order; self } /// Sets how to choose a state for an unknown cell. pub fn set_new_state(mut self, new_state: NewState) -> Self { self.new_state = new_state; self } /// Sets the maximal number of living cells. pub fn set_max_cell_count(mut self, max_cell_count: Option<usize>) -> Self { self.max_cell_count = max_cell_count; self } /// Sets whether to force the first row/column to be nonempty. pub fn set_non_empty_front(mut self, non_empty_front: bool) -> Self { self.non_empty_front = non_empty_front; self } /// Sets whether to automatically reduce the `max_cell_count` /// when a result is found. pub fn set_reduce_max(mut self, reduce_max: bool) -> Self { self.reduce_max = reduce_max; self } /// Sets the rule string. pub fn set_rule_string(mut self, rule_string: String) -> Self { self.rule_string = rule_string; self } /// Automatically determines the search order if `search_order` is `None`. pub(crate) fn auto_search_order(&self) -> SearchOrder { self.search_order.unwrap_or_else(|| { let (width, height) = match self.symmetry { Symmetry::D2Row => (self.width, (self.height + 1) / 2), Symmetry::D2Col => ((self.width + 1) / 2, self.height), _ => (self.width, self.height), }; match width.cmp(&height) { Ordering::Greater => SearchOrder::ColumnFirst, Ordering::Less => SearchOrder::RowFirst, Ordering::Equal => { if self.dx.abs() >= self.dy.abs() { SearchOrder::ColumnFirst } else { SearchOrder::RowFirst } } } }) } /// Creates a new world from the configuration. /// Returns an error if the rule string is invalid. /// /// In rules that contain `B0`, cells outside the search range are /// considered `Dead` in even generations, `Alive` in odd generations. /// In other rules, all cells outside the search range are `Dead`. /// /// After the last generation, the pattern will return to /// the first generation, applying the transformation first, /// and then the translation defined by `dx` and `dy`. pub fn world(&self) -> Result<Box<dyn Search>, Box<dyn Error>> { if let Ok(rule) = Life::parse_rule(&self.rule_string) { Ok(Box::new(World::new(&self, rule))) } else { let rule = NtLife::parse_rule(&self.rule_string)?; Ok(Box::new(World::new(&self, rule))) } } }