Skip to main content

brep_render/engine_state/
draft_analysis_ops.rs

1//! The DRAFT ANALYSIS view state on the engine (`crate::draft_analysis` holds
2//! the reading itself). Display only: opening, changing and closing it never
3//! touches the history, the document or undo. While it is open every shown
4//! solid's faces carry the analysis tint, re-read whenever the shown model
5//! changes (`Self::ensure_draft_analysis_current`, run with the per-frame
6//! overlay upkeep).
7
8use super::*;
9use crate::draft_analysis::{analyse_solid, face_normals, DraftClass, FaceDraft};
10
11/// The minimum draft a fresh analysis opens with, degrees.
12pub const DRAFT_ANALYSIS_DEFAULT_MIN_DEG: f64 = 1.0;
13
14/// What the analysis was asked for and what it read.
15#[derive(Debug, Clone, Default)]
16pub struct DraftAnalysisState {
17    /// The pull reference (a flat face, a datum plane or a straight edge), or
18    /// `None` for the default pull.
19    pub pull_ref: Option<String>,
20    pub flip: bool,
21    pub minimum_deg: f64,
22    /// The pull it read with (unit, flip applied) and where it came from.
23    pub pull: [f64; 3],
24    pub pull_source: String,
25    /// Why there is no reading (a pull reference that gives no direction).
26    pub error: Option<String>,
27    pub faces: Vec<FaceDraft>,
28    /// The shown solids `(name, revision)` the tint was last written for.
29    stamp: Vec<(String, u64)>,
30}
31
32impl EngineState {
33    pub fn draft_analysis_active(&self) -> bool {
34        self.draft_analysis.is_some()
35    }
36
37    /// Turn the analysis on (a no-op when it is on).
38    pub fn draft_analysis_open(&mut self) {
39        if self.draft_analysis.is_none() {
40            self.draft_analysis = Some(DraftAnalysisState { minimum_deg: DRAFT_ANALYSIS_DEFAULT_MIN_DEG, ..Default::default() });
41            self.recompute_draft_analysis();
42        }
43    }
44
45    /// Turn the analysis off: every tint goes and the faces draw in their own
46    /// colours again.
47    pub fn draft_analysis_close(&mut self) {
48        if self.draft_analysis.take().is_some() {
49            let names: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
50            for name in names {
51                self.scene.set_face_analysis_colors(&name, &[]);
52            }
53            self.dirty = true;
54        }
55    }
56
57    pub fn draft_analysis_toggle(&mut self) {
58        if self.draft_analysis_active() {
59            self.draft_analysis_close();
60        } else {
61            self.draft_analysis_open();
62        }
63    }
64
65    /// Start the window's pull pick (one name; the form's reference field).
66    pub fn begin_ref_select_for_draft_analysis(&mut self, path: Vec<String>, label: String, filter: Vec<String>, seed_names: Vec<String>) {
67        let restore_index = self.history.rollback();
68        self.selection_filter = SelectionFilter::from_ref_filter(&filter);
69        self.ref_select = Some(RefSelectState {
70            feature_id: "draftAnalysis".into(),
71            path,
72            label,
73            filter,
74            multiple: false,
75            names: seed_names,
76            restore_index,
77            target: RefSelectTarget::DraftAnalysis,
78            picks: 0,
79            claimed: false,
80            finish_requested: false,
81        });
82        self.sync_ref_select_emphasis();
83    }
84
85    /// Change what the analysis reads with; `None` leaves a setting as it is
86    /// (`Some(None)` clears the pull reference). Opens the analysis if it is
87    /// off. A minimum outside 0..90° is refused and nothing changes.
88    pub fn draft_analysis_set(
89        &mut self,
90        pull_ref: Option<Option<String>>,
91        flip: Option<bool>,
92        minimum_deg: Option<f64>,
93    ) -> Result<(), String> {
94        if let Some(m) = minimum_deg {
95            if !m.is_finite() || !(0.0..90.0).contains(&m) {
96                return Err(format!("the minimum draft must be at least 0° and under 90° (got {m})"));
97            }
98        }
99        self.draft_analysis_open();
100        let state = self.draft_analysis.as_mut().expect("opened above");
101        if let Some(pull_ref) = pull_ref {
102            state.pull_ref = pull_ref.filter(|name| !name.trim().is_empty());
103        }
104        if let Some(flip) = flip {
105            state.flip = flip;
106        }
107        if let Some(m) = minimum_deg {
108            state.minimum_deg = m;
109        }
110        self.recompute_draft_analysis();
111        Ok(())
112    }
113
114    /// The form's values: `{pullDirection, flipPull, minAngle}`.
115    pub fn draft_analysis_params(&self) -> serde_json::Value {
116        let state = self.draft_analysis.clone().unwrap_or(DraftAnalysisState {
117            minimum_deg: DRAFT_ANALYSIS_DEFAULT_MIN_DEG,
118            ..Default::default()
119        });
120        serde_json::json!({
121            "pullDirection": state.pull_ref,
122            "flipPull": state.flip,
123            "minAngle": state.minimum_deg,
124        })
125    }
126
127    /// The reading for a window, a test or a script.
128    pub fn draft_analysis_json(&self) -> serde_json::Value {
129        let Some(state) = self.draft_analysis.as_ref() else {
130            return serde_json::json!({ "open": false });
131        };
132        let mut counts = serde_json::Map::new();
133        for class in DraftClass::ALL {
134            counts.insert(class.key().into(), state.faces.iter().filter(|f| f.class == class).count().into());
135        }
136        serde_json::json!({
137            "open": true,
138            "pullDirection": state.pull_ref,
139            "flipPull": state.flip,
140            "minAngle": state.minimum_deg,
141            "pull": state.pull,
142            "pullSource": state.pull_source,
143            "error": state.error,
144            "counts": counts,
145            "faces": state.faces,
146        })
147    }
148
149    /// The open analysis' state, for the window.
150    pub fn draft_analysis_state(&self) -> Option<&DraftAnalysisState> {
151        self.draft_analysis.as_ref()
152    }
153
154    /// The reading of face `face`, when the analysis is open and read it.
155    pub fn draft_analysis_face(&self, face: &str) -> Option<&FaceDraft> {
156        self.draft_analysis.as_ref()?.faces.iter().find(|f| f.face == face)
157    }
158
159    /// The hovered face's reading as its hover line, while the analysis is open.
160    pub fn draft_analysis_hover_text(&self) -> Option<String> {
161        let state = self.draft_analysis.as_ref()?;
162        let mut hovered: Vec<&String> = self.emphasis.hovered_faces.iter().collect();
163        hovered.sort();
164        hovered.into_iter().find_map(|name| state.faces.iter().find(|f| &f.face == name)).map(FaceDraft::hover_text)
165    }
166
167    /// The faces of one class, for a legend row's click.
168    pub fn draft_analysis_faces_of(&self, class: DraftClass) -> Vec<String> {
169        self.draft_analysis
170            .as_ref()
171            .map(|state| state.faces.iter().filter(|f| f.class == class && !f.face.is_empty()).map(|f| f.face.clone()).collect())
172            .unwrap_or_default()
173    }
174
175    /// Per-frame upkeep: re-read when the shown solids changed since the tint
176    /// was written (a rebuild, a roll, a show/hide). A quiet frame compares a
177    /// short list and does nothing else.
178    pub(super) fn ensure_draft_analysis_current(&mut self) {
179        let Some(state) = self.draft_analysis.as_ref() else {
180            return;
181        };
182        if state.stamp != self.draft_analysis_stamp() {
183            self.recompute_draft_analysis();
184        }
185    }
186
187    fn draft_analysis_stamp(&self) -> Vec<(String, u64)> {
188        self.scene
189            .solids()
190            .iter()
191            .filter(|s| s.visible && !s.is_sketch)
192            .map(|s| (s.name.clone(), s.revision))
193            .collect()
194    }
195
196    /// The default pull: the last built Draft feature's (up to the rolled-to
197    /// step), else +Z.
198    fn draft_analysis_default_pull(&self) -> ([f64; 3], String) {
199        let rollback = self.history.rollback();
200        for index in (0..=rollback).rev() {
201            if self.history.feature_type(index).as_deref() != Some("DRAFT") {
202                continue;
203            }
204            if let (Some(pull), _) = self.draft_pull_and_neutral(index) {
205                let id = self.history.feature_id(index).unwrap_or_default();
206                return (pull, format!("the pull of {id}"));
207            }
208        }
209        ([0.0, 0.0, 1.0], "+Z (no Draft feature yet)".into())
210    }
211
212    /// The unit direction a pull reference names on the shown model: a datum
213    /// plane's normal, a flat face's OUTWARD normal (as Draft reads a face
214    /// pull) or a straight edge's direction.
215    fn draft_analysis_reference_direction(&self, name: &str) -> Result<[f64; 3], String> {
216        if let Some((_, frame)) = self.construction_frames.iter().find(|(n, _)| n == name) {
217            let z = frame.z_axis;
218            return unit3([z.x, z.y, z.z]).ok_or_else(|| format!("'{name}' has no normal"));
219        }
220        for solid in self.scene.solids() {
221            if let Some(index) = solid.faces.iter().position(|f| f.name == name) {
222                return match face_normals(solid, index) {
223                    Some((normals, false)) => Ok(normals[0]),
224                    Some((_, true)) => Err(format!("'{name}' is curved: pick a flat face, a datum plane or a straight edge")),
225                    None => Err(format!("'{name}' has no shown area")),
226                };
227            }
228            if let Some(edge) = solid.edges.iter().find(|e| e.name == name) {
229                let (Some(a), Some(b)) = (edge.polyline.first(), edge.polyline.last()) else {
230                    return Err(format!("'{name}' has no shown points"));
231                };
232                let d = [(b[0] - a[0]) as f64, (b[1] - a[1]) as f64, (b[2] - a[2]) as f64];
233                let dir = unit3(d).ok_or_else(|| format!("'{name}' is closed: pick a straight edge"))?;
234                let straight = edge.polyline.iter().all(|p| {
235                    let v = [(p[0] - a[0]) as f64, (p[1] - a[1]) as f64, (p[2] - a[2]) as f64];
236                    let along = v[0] * dir[0] + v[1] * dir[1] + v[2] * dir[2];
237                    let off = [v[0] - along * dir[0], v[1] - along * dir[1], v[2] - along * dir[2]];
238                    (off[0] * off[0] + off[1] * off[1] + off[2] * off[2]).sqrt() <= 1e-4 * (1.0 + norm3(d))
239                });
240                return if straight { Ok(dir) } else { Err(format!("'{name}' is curved: pick a straight edge")) };
241            }
242        }
243        Err(format!("'{name}' is not on the shown model"))
244    }
245
246    /// Read the shown model again and write the tints.
247    fn recompute_draft_analysis(&mut self) {
248        let Some(state) = self.draft_analysis.as_ref() else {
249            return;
250        };
251        let (pull_ref, flip, minimum) = (state.pull_ref.clone(), state.flip, state.minimum_deg);
252        let resolved = match &pull_ref {
253            Some(name) => self.draft_analysis_reference_direction(name).map(|d| (d, format!("from {name}"))),
254            None => Ok(self.draft_analysis_default_pull()),
255        };
256        let mut faces = Vec::new();
257        let mut tints: Vec<(String, Vec<Option<[f32; 3]>>)> = Vec::new();
258        let (pull, source, error) = match resolved {
259            Ok((d, source)) => {
260                let pull = if flip { [-d[0], -d[1], -d[2]] } else { d };
261                for solid in self.scene.solids().iter().filter(|s| s.visible && !s.is_sketch) {
262                    let read = analyse_solid(solid, pull, minimum);
263                    let colors = solid
264                        .faces
265                        .iter()
266                        .map(|face| read.iter().find(|r| r.face == face.name).map(|r| r.class.color()))
267                        .collect();
268                    tints.push((solid.name.clone(), colors));
269                    faces.extend(read);
270                }
271                (pull, source, None)
272            }
273            Err(error) => ([0.0; 3], String::new(), Some(error)),
274        };
275        let all: Vec<String> = self.scene.solids().iter().map(|s| s.name.clone()).collect();
276        for name in all {
277            let colors = tints.iter().find(|(n, _)| *n == name).map(|(_, c)| c.as_slice()).unwrap_or(&[]);
278            self.scene.set_face_analysis_colors(&name, colors);
279        }
280        let stamp = self.draft_analysis_stamp();
281        if let Some(state) = self.draft_analysis.as_mut() {
282            state.pull = pull;
283            state.pull_source = source;
284            state.error = error;
285            state.faces = faces;
286            state.stamp = stamp;
287        }
288        self.dirty = true;
289    }
290}
291
292fn norm3(v: [f64; 3]) -> f64 {
293    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
294}
295
296fn unit3(v: [f64; 3]) -> Option<[f64; 3]> {
297    let l = norm3(v);
298    (l > 1e-12).then(|| [v[0] / l, v[1] / l, v[2] / l])
299}
300