Skip to main content

brep_app/panels/
exploded_views.rs

1//! The Exploded views section at the foot of the Assembly Constraints pane.
2//!
3//! An exploded view is a PMI view whose explode rows are its ordered steps
4//! (`brep_render::engine_state` `exploded_ops`), so this section is a front for
5//! the PMI view and annotation calls the PMI pane makes, plus the assembly
6//! ones: **New exploded view** (auto-explode, one step per top-level
7//! component), **Show** / **Hide** (activate the view in place, without the PMI
8//! workbench), **Explode** / **Collapse** (play the steps out or home) and a
9//! progress slider. A step row selects the step and arms the move gizmo on it
10//! (the same gizmo the PMI pane gives an open explode annotation); its trail
11//! box and delete and up / down buttons edit the PMI rows. **Hide selected**
12//! adds a HIDE step (a `hide` row: the selected components stay out of the
13//! view while it is shown), listed under the steps with its own delete.
14use crate::ui_kit;
15use crate::automation::hit_keys::HitKeyDoc;
16use brep_render::engine_state::EngineState;
17use eframe::egui;
18use std::collections::HashMap;
19
20/// Hit keys this section publishes, into the Constraints pane's `acon:` set.
21pub static HIT_KEYS: &[HitKeyDoc] = &[
22    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:header", meaning: "open or close the Exploded views section", command: None },
23    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:new", meaning: "make a new exploded view (auto-explode)", command: Some("assembly_auto_explode") },
24    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:deep", meaning: "a new exploded view opens the sub-assemblies too", command: Some("assembly_auto_explode") },
25    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:spread", meaning: "how far a new exploded view spreads the components", command: Some("assembly_auto_explode") },
26    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:show:", meaning: "show or hide an exploded view (explode:show:<view id>)", command: Some("pmi_activate_view") },
27    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:play", meaning: "play the shown view's steps out", command: Some("exploded_animate") },
28    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:collapse", meaning: "bring the shown view's steps home", command: Some("exploded_animate") },
29    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:progress", meaning: "the shown view's progress slider", command: Some("exploded_set_progress") },
30    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:add", meaning: "add a step that moves the selected components (a part inside a sub-assembly picked from the BOM is one)", command: Some("exploded_add_step") },
31    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:step:", meaning: "a step's row: select it and move it with the gizmo (explode:step:<id>)", command: None },
32    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:trace:", meaning: "a step's trail box", command: Some("pmi_update_annotation") },
33    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:up:", meaning: "move a step earlier", command: Some("pmi_move_annotation") },
34    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:del:", meaning: "delete a step", command: Some("pmi_remove_annotation") },
35    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:hide", meaning: "add a hide step that keeps the selected components (or solids) out of the shown view", command: Some("pmi_add_annotation") },
36    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:hidden:", meaning: "a hide step's row: select it (explode:hidden:<id>)", command: None },
37    HitKeyDoc { panel: "assemblyconstraints", prefix: "explode:unhide:", meaning: "delete a hide step (explode:unhide:<id>)", command: Some("pmi_remove_annotation") },
38];
39
40/// The section's own UI state.
41pub struct ExplodedSection {
42    /// A new view's spread (multiples of half the assembly diagonal).
43    spread: f64,
44    /// A new view opens the sub-assemblies too (their parts separate).
45    deep: bool,
46    /// The exploded views as last read, and the history revision they were
47    /// read at. Reading them parses the PMI block and names every step's
48    /// part: twice a frame, that was ~12 ms of every frame the pane showed a
49    /// 499-step view on l500.
50    views: Option<(u64, std::rc::Rc<Vec<brep_render::engine_state::ExplodedView>>)>,
51    /// The last refusal, shown under the buttons.
52    message: Option<String>,
53    /// The step row under the pointer: it lights the step's parts and shows
54    /// its chip (a deep view draws chips only for the selected or hovered step).
55    hovered: Option<String>,
56}
57
58impl Default for ExplodedSection {
59    fn default() -> Self {
60        Self { spread: 1.0, deep: false, views: None, message: None, hovered: None }
61    }
62}
63
64/// How deep "into sub-assemblies" opens.
65const DEEP: usize = 8;
66
67enum Action {
68    New,
69    Add,
70    HideSelected,
71    Show(String),
72    Hide,
73    Animate(bool),
74    Progress(f64),
75    Select(String),
76    Trace(String, bool),
77    Up(String),
78    Delete(String),
79}
80
81/// How fast Explode / Collapse play, in steps per second.
82const STEPS_PER_SECOND: f64 = 1.5;
83
84impl ExplodedSection {
85    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState, hits: &mut HashMap<String, egui::Rect>) {
86        let revision = state.history.revision();
87        let views = match &self.views {
88            Some((at, views)) if *at == revision => views.clone(),
89            _ => {
90                let views = std::rc::Rc::new(state.exploded_views());
91                self.views = Some((revision, views.clone()));
92                views
93            }
94        };
95        let active = state.pmi_active_view().map(str::to_string);
96        let locked = state.history.locked().is_some();
97        let mut action = None;
98        let mut hovered = None;
99        ui.add_space(6.0);
100        let header = egui::CollapsingHeader::new(format!("Exploded views ({})", views.len()))
101            .id_salt("explode:section")
102            .show(ui, |ui| {
103                ui.horizontal(|ui| {
104                    let new = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("New exploded view"));
105                    hits.insert("explode:new".into(), new.rect);
106                    if new.on_hover_text("One step per component, each moved straight away from the base component").clicked() {
107                        action = Some(Action::New);
108                    }
109                    let spread = ui.add(egui::DragValue::new(&mut self.spread).range(0.1..=10.0).speed(0.05).prefix("spread ×"));
110                    hits.insert("explode:spread".into(), spread.rect);
111                    let deep = ui_kit::checkbox(ui, &mut self.deep, "into sub-assemblies");
112                    hits.insert("explode:deep".into(), deep.rect);
113                    deep.on_hover_text("Also take each sub-assembly apart, after the assembly's own components");
114                });
115                if views.is_empty() {
116                    ui.weak("No exploded views yet. A PMI view with explode annotations is one too.");
117                }
118                for view in views.iter() {
119                    let shown = active.as_deref() == Some(view.id.as_str());
120                    ui.horizontal(|ui| {
121                        let toggle = ui.selectable_label(shown, if shown { "◉ Hide" } else { "○ Show" });
122                        hits.insert(format!("explode:show:{}", view.id), toggle.rect);
123                        if toggle.clicked() {
124                            action = Some(if shown { Action::Hide } else { Action::Show(view.id.clone()) });
125                        }
126                        ui.label(format!("{} · {} step{}", view.name, view.steps.len(), if view.steps.len() == 1 { "" } else { "s" }));
127                    });
128                    if !shown {
129                        continue;
130                    }
131                    ui.horizontal(|ui| {
132                        let play = ui.add(ui_kit::Button::new("▶ Explode"));
133                        hits.insert("explode:play".into(), play.rect);
134                        if play.clicked() {
135                            action = Some(Action::Animate(true));
136                        }
137                        let collapse = ui.add(ui_kit::Button::new("◀ Collapse"));
138                        hits.insert("explode:collapse".into(), collapse.rect);
139                        if collapse.clicked() {
140                            action = Some(Action::Animate(false));
141                        }
142                        let steps = state.exploded_step_count() as f64;
143                        let mut progress = state.exploded_progress();
144                        let slider = ui.add(egui::Slider::new(&mut progress, 0.0..=steps.max(1e-9)).show_value(false));
145                        hits.insert("explode:progress".into(), slider.rect);
146                        if slider.changed() {
147                            action = Some(Action::Progress(progress));
148                        }
149                    });
150                    let add = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("+ Add step from selection"));
151                    hits.insert("explode:add".into(), add.rect);
152                    if add
153                        .on_hover_text("Move the selected components as a new step, then drag its gizmo. A part inside a sub-assembly: pick its row in the BOM")
154                        .clicked()
155                    {
156                        action = Some(Action::Add);
157                    }
158                    let selected = state.pmi_open_annotation().map(str::to_string);
159                    for (n, step) in view.steps.iter().enumerate() {
160                        ui.horizontal(|ui| {
161                            let mut trace = step.trace;
162                            let trace_box = ui.add_enabled(!locked, egui::Checkbox::new(&mut trace, ""));
163                            hits.insert(format!("explode:trace:{}", step.id), trace_box.rect);
164                            if trace_box.on_hover_text("Draw this step's trail").changed() {
165                                action = Some(Action::Trace(step.id.clone(), trace));
166                            }
167                            let [x, y, z] = step.translate;
168                            let row = ui.selectable_label(
169                                selected.as_deref() == Some(step.id.as_str()),
170                                format!("{}. {}  ({x:.1}, {y:.1}, {z:.1})", n + 1, step.labels.join(", ")),
171                            );
172                            hits.insert(format!("explode:step:{}", step.id), row.rect);
173                            if row.hovered() {
174                                hovered = Some(step.id.clone());
175                            }
176                            if row.on_hover_text("Select, then drag the gizmo to move this step").clicked() {
177                                action = Some(Action::Select(step.id.clone()));
178                            }
179                            if n > 0 {
180                                let up = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("↑").size(ui_kit::Size::Sm));
181                                hits.insert(format!("explode:up:{}", step.id), up.rect);
182                                if up.on_hover_text("Earlier").clicked() {
183                                    action = Some(Action::Up(step.id.clone()));
184                                }
185                            }
186                            let del = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("✕").size(ui_kit::Size::Sm));
187                            hits.insert(format!("explode:del:{}", step.id), del.rect);
188                            if del.on_hover_text("Delete this step").clicked() {
189                                action = Some(Action::Delete(step.id.clone()));
190                            }
191                        });
192                    }
193                    // The view's hide steps: what it keeps out of sight, tracked
194                    // like its explode steps (added from the selection, listed,
195                    // deleted, undone), not steps of the playback.
196                    let hide = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("Hide selected"));
197                    hits.insert("explode:hide".into(), hide.rect);
198                    if hide
199                        .on_hover_text("Keep the selected components out of this view, as a hide step. A part inside a sub-assembly: pick its row in the BOM")
200                        .clicked()
201                    {
202                        action = Some(Action::HideSelected);
203                    }
204                    for step in view.hides.iter() {
205                        ui.horizontal(|ui| {
206                            let row = ui.selectable_label(
207                                selected.as_deref() == Some(step.id.as_str()),
208                                format!("{}hidden: {}", if step.enabled { "" } else { "(off) " }, step.labels.join(", ")),
209                            );
210                            hits.insert(format!("explode:hidden:{}", step.id), row.rect);
211                            if row.on_hover_text("Select this hide step; its form edits what it hides").clicked() {
212                                action = Some(Action::Select(step.id.clone()));
213                            }
214                            let del = ui_kit::button::add_enabled(ui, !locked, ui_kit::Button::new("✕").size(ui_kit::Size::Sm));
215                            hits.insert(format!("explode:unhide:{}", step.id), del.rect);
216                            if del.on_hover_text("Delete this hide step: its parts show again").clicked() {
217                                action = Some(Action::Delete(step.id.clone()));
218                            }
219                        });
220                    }
221                }
222                if let Some(message) = &self.message {
223                    ui.colored_label(ui.visuals().error_fg_color, message);
224                }
225            });
226        hits.insert("explode:header".into(), header.header_response.rect);
227        if hovered != self.hovered {
228            match &hovered {
229                Some(id) => state.pmi_hover(id),
230                None => state.pmi_hover_end(),
231            }
232            self.hovered = hovered;
233        }
234        // The gizmo follows the selected step, as it follows an open explode
235        // annotation in the PMI pane.
236        let open_step = state
237            .pmi_open_annotation()
238            .filter(|id| views.iter().any(|v| active.as_deref() == Some(v.id.as_str()) && v.steps.iter().any(|s| s.id == *id)))
239            .map(str::to_string);
240        if let Some(id) = open_step {
241            if !state.transform_armed_for(&id) {
242                state.arm_transform(&id);
243            }
244            state.sync_transform_gizmo();
245        }
246        let Some(action) = action else { return };
247        let result: Result<(), String> = match action {
248            Action::New => state.assembly_auto_explode_deep(None, self.spread, if self.deep { DEEP } else { 1 }).map(|_| ()),
249            Action::Add => state.exploded_add_step(&[]).map(|_| ()),
250            Action::HideSelected => state.pmi_hide_selected(None).map(|_| ()),
251            Action::Show(id) => state.pmi_activate_view(&id),
252            Action::Hide => {
253                state.pmi_deactivate_view();
254                Ok(())
255            }
256            // A deep view has many steps: the whole play stays about 4 s.
257            Action::Animate(explode) => {
258                let steps = state.exploded_step_count() as f64;
259                state.exploded_animate(explode, STEPS_PER_SECOND.max(steps / 4.0))
260            }
261            Action::Progress(progress) => {
262                state.exploded_set_progress(progress);
263                Ok(())
264            }
265            Action::Select(id) => {
266                state.pmi_set_annotation_open(Some(&id));
267                Ok(())
268            }
269            Action::Trace(id, trace) => match state.pmi_state().find_annotation(&id).map(|(_, a)| a.params.clone()) {
270                Some(mut params) => {
271                    params["showTraceLine"] = serde_json::json!(trace);
272                    state.pmi_update_annotation(&id, &params.to_string())
273                }
274                None => Err(format!("no step '{id}'")),
275            },
276            Action::Up(id) => {
277                // Just before the explode row ahead of it, in the view's own order.
278                let pmi = state.pmi_state();
279                let index = pmi.find_annotation(&id).and_then(|(view, _)| {
280                    let own = view.annotations.iter().position(|a| a.id() == id)?;
281                    view.annotations[..own].iter().rposition(|a| a.kind == "explode")
282                });
283                drop(pmi);
284                match index {
285                    Some(index) => state.pmi_move_annotation(&id, index),
286                    None => Ok(()),
287                }
288            }
289            Action::Delete(id) => state.pmi_remove_annotation(&id),
290        };
291        self.message = result.err();
292    }
293}