Skip to main content

brep_instructions/
retarget.rs

1//! Re-targeting to a new revision of the assembly.
2//!
3//! [`diff`] compares the two revisions' occurrence trees by path: an
4//! occurrence only in the new one is ADDED, only in the old one REMOVED, and
5//! one whose part or content signature changed is REPLACED. [`apply`] folds the
6//! diff into the steps, rerunning the wizard on the changed parts only, and
7//! records it as the block's pending `retarget`; [`approve`] makes the new
8//! revision the target. Until then release is refused.
9
10use crate::model::{for_each_step_mut, retain_steps, Add, Instructions, OccurrenceChange, Retarget, Step, Target};
11use crate::wizard::{self, Component, Level};
12use std::collections::{HashMap, HashSet};
13
14/// The changes between two revisions of the target assembly.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct Diff {
17    pub added: Vec<OccurrenceChange>,
18    pub removed: Vec<OccurrenceChange>,
19    pub replaced: Vec<OccurrenceChange>,
20}
21
22impl Diff {
23    pub fn is_empty(&self) -> bool {
24        self.added.is_empty() && self.removed.is_empty() && self.replaced.is_empty()
25    }
26}
27
28/// Compare `old` and `new` by occurrence path. An occurrence under a removed
29/// or replaced sub-assembly is reported only through that sub-assembly.
30pub fn diff(old: &Level, new: &Level) -> Diff {
31    let old_map: HashMap<&str, &Component> = wizard::flatten(old).into_iter().map(|(_, c)| (c.path.as_str(), c)).collect();
32    let new_map: HashMap<&str, &Component> = wizard::flatten(new).into_iter().map(|(_, c)| (c.path.as_str(), c)).collect();
33    let mut out = Diff::default();
34    let mut gone: Vec<&str> = Vec::new();
35    for (_, c) in wizard::flatten(old) {
36        if under_any(&c.path, &gone) {
37            continue;
38        }
39        match new_map.get(c.path.as_str()) {
40            None => {
41                out.removed.push(change(c, None));
42                gone.push(&c.path);
43            }
44            Some(n) if n.part != c.part || n.signature != c.signature || n.children.is_some() != c.children.is_some() => {
45                // A sub-assembly whose definition changed is compared inside
46                // instead, unless it stopped (or started) being one or became
47                // another part.
48                if n.part == c.part && n.children.is_some() && c.children.is_some() {
49                    continue;
50                }
51                out.replaced.push(change(n, Some(&c.part)));
52                gone.push(&c.path);
53            }
54            Some(_) => {}
55        }
56    }
57    let mut fresh: Vec<&str> = Vec::new();
58    for (_, c) in wizard::flatten(new) {
59        if under_any(&c.path, &gone) || under_any(&c.path, &fresh) {
60            continue;
61        }
62        if !old_map.contains_key(c.path.as_str()) {
63            out.added.push(change(c, None));
64            fresh.push(&c.path);
65        }
66    }
67    out
68}
69
70fn change(c: &Component, was: Option<&str>) -> OccurrenceChange {
71    OccurrenceChange { occurrence: c.path.clone(), part: c.part.clone(), was: was.map(str::to_string) }
72}
73
74/// Whether `path` lies strictly under one of `roots`.
75fn under_any(path: &str, roots: &[&str]) -> bool {
76    roots.iter().any(|r| path.len() > r.len() && path.starts_with(r) && path[r.len()..].starts_with(':'))
77}
78
79fn under_or_at(path: &str, root: &str) -> bool {
80    path == root || under_any(path, &[root])
81}
82
83/// Fold `diff` (from `old` to `new`) into `block` and record it as pending
84/// for `to`. Returns the recorded retarget. Refuses while one is pending.
85pub fn apply(block: &mut Instructions, new: &Level, diff: &Diff, to: Target) -> Result<Retarget, String> {
86    if block.retarget.is_some() {
87        return Err("a re-target is already waiting for approval".into());
88    }
89    let mut touched: Vec<String> = Vec::new();
90    let new_map: HashMap<&str, &Component> = wizard::flatten(new).into_iter().map(|(_, c)| (c.path.as_str(), c)).collect();
91
92    // Removed and replaced sub-assemblies lose the steps that built them (the
93    // children of the step placing them, descendants and all); a replaced one
94    // gets fresh children below.
95    let dropped: Vec<&str> = diff.removed.iter().chain(&diff.replaced).map(|c| c.occurrence.as_str()).collect();
96    for_each_step_mut(&mut block.steps, &mut |step| {
97        let places_dropped = step.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| dropped.iter().any(|d| under_or_at(o, d))));
98        if places_dropped {
99            step.steps.clear();
100        }
101    });
102
103    // Removed: strip the occurrence from its add.
104    for removed in &diff.removed {
105        for_each_step_mut(&mut block.steps, &mut |step| {
106            let before = step.adds.iter().map(Add::quantity).sum::<usize>();
107            for add in &mut step.adds {
108                add.occurrences.retain(|o| !under_or_at(o, &removed.occurrence));
109            }
110            step.adds.retain(|a| !a.occurrences.is_empty());
111            step.arrows.retain(|a| !under_or_at(&a.occurrence, &removed.occurrence));
112            if step.adds.iter().map(Add::quantity).sum::<usize>() != before {
113                touch(&step.id, &mut touched);
114            }
115        });
116    }
117
118    // Replaced: the occurrence's add takes the new part; an add shared with
119    // other occurrences of the old part splits it out; a replaced
120    // sub-assembly's step gets the steps that build the new one.
121    for replaced in &diff.replaced {
122        let Some(component) = new_map.get(replaced.occurrence.as_str()) else { continue };
123        let mut fresh_children = component.children.as_ref().map(|children| wizard::level_steps(block, children));
124        for_each_step_mut(&mut block.steps, &mut |step| {
125            let Some(index) = step.adds.iter().position(|a| a.occurrences.contains(&replaced.occurrence)) else { return };
126            let fresh = add_of(component);
127            if step.adds[index].occurrences.len() == 1 {
128                step.adds[index] = fresh;
129            } else {
130                step.adds[index].occurrences.retain(|o| o != &replaced.occurrence);
131                step.adds.insert(index + 1, fresh);
132            }
133            if let Some(children) = fresh_children.take() {
134                step.steps = children;
135            }
136            touch(&step.id, &mut touched);
137        });
138    }
139
140    // Added: the wizard's step for each, placed after the step that adds a
141    // mated neighbour; added fasteners of one part share a step.
142    let mut grouped: Vec<(String, Vec<&Component>)> = Vec::new();
143    for added in &diff.added {
144        let Some(component) = new_map.get(added.occurrence.as_str()) else { continue };
145        let level_path = parent_level_path(new, &component.path);
146        if component.fastener {
147            if let Some((_, group)) = grouped.iter_mut().find(|(l, g)| *l == level_path && g[0].part == component.part) {
148                group.push(component);
149                continue;
150            }
151        }
152        grouped.push((level_path, vec![component]));
153    }
154    for (level_path, group) in grouped {
155        let Some(level) = wizard::find_level(new, &level_path) else { continue };
156        if block.group_steps_mut(&level_path).is_none() {
157            continue;
158        }
159        let mut step = wizard::step_for(block, &group);
160        if let Some(children) = &group[0].children {
161            step.steps = wizard::level_steps(block, children);
162        }
163        let id = step.id.clone();
164        let Some(siblings) = block.group_steps_mut(&level_path) else { continue };
165        let at = insertion_index(siblings, level, &group);
166        siblings.insert(at, step);
167        touch(&id, &mut touched);
168    }
169
170    // Find numbers follow the new revision everywhere.
171    for_each_step_mut(&mut block.steps, &mut |step| {
172        for add in &mut step.adds {
173            if let Some(c) = add.occurrences.first().and_then(|o| new_map.get(o.as_str())) {
174                add.find_number = c.find_number.clone();
175            }
176        }
177    });
178
179    let retarget = Retarget {
180        from: block.target.clone(),
181        to,
182        added: diff.added.clone(),
183        removed: diff.removed.clone(),
184        replaced: diff.replaced.clone(),
185        touched_steps: touched,
186        empty_steps: crate::edit::empty_steps(block),
187    };
188    block.retarget = Some(retarget.clone());
189    Ok(retarget)
190}
191
192/// Approve the pending re-target: the new revision becomes the target and
193/// steps the re-target left empty are deleted.
194pub fn approve(block: &mut Instructions) -> Result<Target, String> {
195    let retarget = block.retarget.take().ok_or("no re-target is waiting for approval")?;
196    let empty: HashSet<&str> = retarget.empty_steps.iter().map(String::as_str).collect();
197    retain_steps(&mut block.steps, &|s| !(empty.contains(s.id.as_str()) && s.adds.is_empty() && s.steps.is_empty() && s.fields.is_empty()));
198    block.target = retarget.to.clone();
199    Ok(retarget.to)
200}
201
202fn touch(id: &str, touched: &mut Vec<String>) {
203    if !touched.iter().any(|t| t == id) {
204        touched.push(id.to_string());
205    }
206}
207
208fn add_of(c: &Component) -> Add {
209    Add {
210        find_number: c.find_number.clone(),
211        subassembly: c.children.is_some(),
212        fastener: c.fastener,
213        serial_tracked: c.serial_tracked,
214        ..Add::named(vec![c.path.clone()], c.part_key(), &c.part)
215    }
216}
217
218/// The path of the level that holds the component at `path`.
219fn parent_level_path(root: &Level, path: &str) -> String {
220    wizard::flatten(root).into_iter().find(|(_, c)| c.path == path).map(|(l, _)| l.to_string()).unwrap_or_default()
221}
222
223/// Where a new step for `group` goes among `steps` (the steps building its
224/// level): after the last step that adds a part mated to it; otherwise a part
225/// goes before the first fastener step and a fastener at the end.
226fn insertion_index(steps: &[Step], level: &Level, group: &[&Component]) -> usize {
227    let paths: HashSet<&str> = group.iter().map(|c| c.path.as_str()).collect();
228    let neighbours: HashSet<&str> = level
229        .mates
230        .iter()
231        .filter_map(|(a, b)| {
232            if paths.contains(a.as_str()) {
233                Some(b.as_str())
234            } else if paths.contains(b.as_str()) {
235                Some(a.as_str())
236            } else {
237                None
238            }
239        })
240        .collect();
241    let fastener = group[0].fastener;
242    let last_neighbour = steps.iter().rposition(|s| s.adds.iter().any(|a| a.occurrences.iter().any(|o| neighbours.contains(o.as_str()))));
243    match last_neighbour {
244        Some(i) if !fastener => {
245            // A part never goes after the fasteners.
246            let first_fastener = steps.iter().position(|s| s.adds.iter().any(|a| a.fastener)).unwrap_or(steps.len());
247            (i + 1).min(first_fastener)
248        }
249        Some(_) | None if fastener => steps.len(),
250        _ => steps.iter().position(|s| s.adds.iter().any(|a| a.fastener)).unwrap_or(steps.len()),
251    }
252}
253