1use crate::model::{Add, Instructions, Step, Torque};
19use std::collections::{HashMap, HashSet};
20
21#[derive(Debug, Clone, Default, PartialEq)]
23pub struct Level {
24 pub path: String,
26 pub name: String,
28 pub components: Vec<Component>,
30 pub mates: Vec<(String, String)>,
33 pub exploded_order: Vec<String>,
36}
37
38#[derive(Debug, Clone, Default, PartialEq)]
39pub struct Component {
40 pub path: String,
42 pub part: String,
44 pub part_id: Option<String>,
47 pub signature: String,
49 pub find_number: String,
50 pub grounded: bool,
51 pub fastener: bool,
52 pub serial_tracked: bool,
53 pub torque: Option<String>,
55 pub children: Option<Box<Level>>,
57}
58
59pub fn propose(block: &mut Instructions, root: &Level) {
61 block.steps.clear();
62 block.steps = level_steps(block, root);
63}
64
65pub fn level_steps(block: &mut Instructions, level: &Level) -> Vec<Step> {
68 let mut steps = Vec::new();
69 for group in order(level) {
70 let mut step = step_for(block, &group);
71 if let Some(children) = &group[0].children {
72 step.steps = level_steps(block, children);
73 }
74 steps.push(step);
75 }
76 steps
77}
78
79pub fn order(level: &Level) -> Vec<Vec<&Component>> {
82 let parts: Vec<&Component> = level.components.iter().filter(|c| !c.fastener).collect();
83 let mut placed: Vec<&Component> = Vec::new();
84 let mut placed_set: HashSet<&str> = HashSet::new();
85 let neighbours = adjacency(level);
86 let seed: HashMap<&str, usize> =
87 level.exploded_order.iter().rev().enumerate().map(|(i, p)| (p.as_str(), i)).collect();
88
89 for c in parts.iter().filter(|c| c.grounded) {
91 placed.push(c);
92 placed_set.insert(c.path.as_str());
93 }
94 if placed.is_empty() && seed.is_empty() {
95 if let Some(first) = parts.first() {
96 placed.push(first);
97 placed_set.insert(first.path.as_str());
98 }
99 }
100 while placed.len() < parts.len() {
101 let remaining = parts.iter().filter(|c| !placed_set.contains(c.path.as_str()));
102 let next = if !seed.is_empty() {
103 remaining
106 .clone()
107 .filter(|c| seed.contains_key(c.path.as_str()))
108 .min_by_key(|c| seed[c.path.as_str()])
109 .copied()
110 .or_else(|| mated_first(remaining.clone(), &neighbours, &placed_set))
111 } else {
112 mated_first(remaining.clone(), &neighbours, &placed_set)
113 };
114 let next = next.or_else(|| remaining.clone().next().copied()).expect("a remaining part");
115 placed.push(next);
116 placed_set.insert(next.path.as_str());
117 }
118
119 let mut groups: Vec<Vec<&Component>> = placed.into_iter().map(|c| vec![c]).collect();
120
121 let position: HashMap<&str, usize> = groups.iter().enumerate().map(|(i, g)| (g[0].path.as_str(), i)).collect();
124 let mut fastener_groups: Vec<(usize, usize, Vec<&Component>)> = Vec::new();
125 for (index, c) in level.components.iter().enumerate().filter(|(_, c)| c.fastener) {
126 let after = neighbours
127 .get(c.path.as_str())
128 .into_iter()
129 .flatten()
130 .filter_map(|n| position.get(n).copied())
131 .max()
132 .unwrap_or(usize::MAX);
133 match fastener_groups.iter_mut().find(|(_, _, g)| g[0].part == c.part) {
134 Some((rank, _, group)) => {
135 *rank = (*rank).max(after);
136 group.push(c);
137 }
138 None => fastener_groups.push((after, index, vec![c])),
139 }
140 }
141 fastener_groups.sort_by_key(|(rank, index, _)| (*rank, *index));
142 groups.extend(fastener_groups.into_iter().map(|(_, _, g)| g));
143 groups
144}
145
146fn mated_first<'a, 'b>(
148 mut remaining: impl Iterator<Item = &'b &'a Component>,
149 neighbours: &HashMap<&str, Vec<&str>>,
150 placed: &HashSet<&str>,
151) -> Option<&'a Component>
152where
153 'a: 'b,
154{
155 remaining
156 .find(|c| neighbours.get(c.path.as_str()).is_some_and(|n| n.iter().any(|p| placed.contains(p))))
157 .copied()
158}
159
160fn adjacency(level: &Level) -> HashMap<&str, Vec<&str>> {
161 let mut map: HashMap<&str, Vec<&str>> = HashMap::new();
162 for (a, b) in &level.mates {
163 if a == b {
164 continue;
165 }
166 map.entry(a.as_str()).or_default().push(b.as_str());
167 map.entry(b.as_str()).or_default().push(a.as_str());
168 }
169 map
170}
171
172pub fn step_for(block: &mut Instructions, group: &[&Component]) -> Step {
174 let first = group[0];
175 let quantity = group.len();
176 let subassembly = first.children.is_some();
177 let title = match (subassembly, quantity) {
178 (true, _) => format!("Install sub-assembly {}", first.part),
179 (false, 1) => format!("Install {}", first.part),
180 (false, n) => format!("Install {n} × {}", first.part),
181 };
182 let torque = if first.fastener { first.torque.as_deref().and_then(Torque::from_attribute) } else { None };
183 Step {
184 id: block.next_id("MS"),
185 title,
186 adds: vec![Add {
187 find_number: first.find_number.clone(),
188 subassembly,
189 fastener: first.fastener,
190 serial_tracked: first.serial_tracked,
191 ..Add::named(group.iter().map(|c| c.path.clone()).collect(), first.part_key(), &first.part)
192 }],
193 torque,
194 ..Step::default()
195 }
196}
197
198impl Component {
199 pub fn part_key(&self) -> &str {
202 self.part_id.as_deref().unwrap_or(&self.part)
203 }
204}
205
206pub fn flatten(level: &Level) -> Vec<(&str, &Component)> {
209 let mut out = Vec::new();
210 fn walk<'a>(level: &'a Level, out: &mut Vec<(&'a str, &'a Component)>) {
211 for c in &level.components {
212 out.push((level.path.as_str(), c));
213 if let Some(children) = &c.children {
214 walk(children, out);
215 }
216 }
217 }
218 walk(level, &mut out);
219 out
220}
221
222pub fn find_level<'a>(root: &'a Level, path: &str) -> Option<&'a Level> {
224 if root.path == path {
225 return Some(root);
226 }
227 root.components.iter().filter_map(|c| c.children.as_deref()).find_map(|l| find_level(l, path))
228}
229