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
use std::collections::HashMap;
use crate::arena::{Arena, ArenaId};
use crate::system::LSystem;
use crate::token::Token;
#[derive(Debug, Clone)]
struct TransformationRule {
predecessor: ArenaId,
successor: Vec<ArenaId>,
}
impl TransformationRule {
pub fn new(predecessor: ArenaId, successor: Vec<ArenaId>) -> Self {
Self {
predecessor,
successor,
}
}
}
#[derive(Default, Clone)]
pub struct LSystemBuilder {
arena: Arena<Token>,
axiom: Option<Vec<ArenaId>>,
rules: Vec<TransformationRule>,
}
impl LSystemBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn token<S: Into<String>>(&mut self, name: S) -> ArenaId {
self.arena.push(Token::new(name))
}
pub fn transformation_rule(&mut self, predecessor: ArenaId, successor: Vec<ArenaId>) {
if !self.arena.is_valid(predecessor) || !self.arena.is_valid_slice(&successor) {
panic!("Invalid token id provided to Lsystem::transformation_rule");
}
self.rules
.push(TransformationRule::new(predecessor, successor));
}
pub fn axiom(&mut self, axiom: Vec<ArenaId>) {
self.axiom = Some(axiom);
}
pub fn finish(self) -> LSystem {
let axiom = self.axiom.expect("finish called before axiom set");
let mut rules_map = HashMap::new();
for rule in self.rules.into_iter() {
rules_map.insert(rule.predecessor, rule.successor);
}
for (id, _token) in self.arena.enumerate() {
rules_map.entry(id).or_insert_with(|| vec![id]);
}
assert_eq!(self.arena.len(), rules_map.len());
LSystem::new(self.arena, axiom, rules_map)
}
}
fn build_rules_string(rules: &[TransformationRule], arena: &Arena<Token>) -> String {
let mut st = Vec::new();
for rule in rules {
st.push(format!(
"{} => {}",
arena.render(&[rule.predecessor]),
arena.render(&rule.successor)
));
}
st.join(",")
}
impl std::fmt::Debug for LSystemBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
f.debug_struct("LSystemBuilder")
.field("arena", &self.arena)
.field("axiom", &self.axiom)
.field("rules", &build_rules_string(&self.rules, &self.arena))
.finish()
}
}