Skip to main content

brep_render/engine_state/
pmi_overlay.rs

1//! The active PMI view's annotation graphics: dimension lines, extension
2//! lines, arcs, leaders and arrowheads baked into the `pmi-overlay` group
3//! from the kernel's presentation layout (the SAME layout the STEP file
4//! writes), sized in pixels at bake time and re-baked when the zoom or the
5//! viewing direction moves materially; plus the label feed the app's chip
6//! pass draws.
7
8use super::*;
9use brep_kernel::{pmi_present, pmi_type, PmiLayoutStyle, PmiStatus};
10
11const PMI_OVERLAY_GROUP: &str = "pmi-overlay";
12/// Arrowhead length, in pixels.
13pub(crate) const ARROW_PX: f64 = 12.0;
14/// The reference text cap height at 12 pt, in pixels (frames scale with the
15/// view's text size).
16pub(crate) const TEXT_PX_AT_12PT: f64 = 11.0;
17/// PMI line / arrow colour (amber, distinct from the dimension gizmo's rods
18/// and the constraint status colours).
19const PMI_RGB: [f32; 3] = [0.98, 0.78, 0.22];
20/// An exploded view's trace arrows and the instructions' insertion arrows:
21/// black on a light ground, near-white on the dark viewport.
22const EXPLODE_ARROW_RGB: [f32; 3] = [0.0, 0.0, 0.0];
23const EXPLODE_ARROW_ON_DARK_RGB: [f32; 3] = [0.92, 0.94, 0.96];
24/// Their filled head's length on screen, px (the reference frames' ~20 px;
25/// its width is 0.7 of it).
26const INSERTION_HEAD_PX: f64 = 20.0;
27/// An error annotation's chip colour.
28const ERROR_RGB: [f32; 3] = [0.97, 0.32, 0.29];
29/// A disabled annotation's chip colour.
30const DISABLED_RGB: [f32; 3] = [0.55, 0.55, 0.55];
31/// The error a balloon shows while its target is hidden in the viewport and
32/// the view's hidden list has not caught up (no run has happened).
33pub(crate) const LIVE_HIDDEN_MESSAGE: &str = "target hidden in the viewport: show it, or update the view's visibility";
34
35/// One chip of [`EngineState::pmi_labels`]; serialised, the
36/// `__brepPmiLabels` row.
37#[derive(Debug, Clone, PartialEq, serde::Serialize)]
38#[serde(rename_all = "camelCase")]
39pub struct PmiLabel {
40    pub id: String,
41    #[serde(rename = "type")]
42    pub kind: String,
43    pub icon: &'static str,
44    /// What the chip reads: the resolved text, or the type's glyph and the
45    /// id for an error or an empty one.
46    pub text: String,
47    /// `ok` or `error`.
48    pub status: &'static str,
49    pub message: String,
50    pub color: [f32; 3],
51    /// The label anchor, world coordinates.
52    pub world: [f64; 3],
53    pub enabled: bool,
54    /// Its form is open.
55    pub open: bool,
56    /// Selected in the PMI tree.
57    pub selected: bool,
58    pub text_size_pt: f64,
59}
60
61impl EngineState {
62    /// Re-bake the overlay from the cached report (empty without an active
63    /// view or while a sketch edit is live).
64    pub fn refresh_pmi_overlay(&mut self) {
65        let Some(active) = self.pmi_active_view.clone() else {
66            self.clear_pmi_overlay();
67            return;
68        };
69        if self.any_sketch_mode() {
70            self.clear_pmi_overlay();
71            return;
72        }
73        // Camera movement changes an automatic leader's closest screen point.
74        // Fetch missing topology in one batch; the topology callback retries
75        // this bake once the last pending balloon can be projected.
76        let camera = self.snapshot_camera();
77        let ids: Vec<String> = self.pmi_report.as_ref().and_then(|r| r.view(&active))
78            .map(|v| v.annotations.iter().filter(|row| matches!(&row.geometry,
79                brep_kernel::PmiGeometry::Leader { anchor: Some(a), balloon: true, .. }
80                if matches!(a.mode, brep_kernel::BalloonAnchorMode::Surface) && a.camera.as_ref() != Some(&camera)))
81                .map(|row| row.id.clone()).collect()).unwrap_or_default();
82        let mut missing = Vec::new();
83        for id in &ids {
84            if let Some(names) = self.pmi_balloon_head_now(id) {
85                missing.extend(names);
86                self.pmi_balloon_stale = Some(id.clone());
87            }
88        }
89        if !missing.is_empty() {
90            missing.sort();
91            missing.dedup();
92            self.request_exact_solids(missing.iter().map(String::as_str));
93            for id in &ids { let _ = self.pmi_balloon_head_now(id); }
94        }
95        // Borrowed, not cloned: a 500-step view's rows are ~4 ms to copy, every
96        // animation frame. Nothing below writes `self` until the bake is done.
97        let Some(view) = self.pmi_report.as_ref().and_then(|report| report.view(&active)) else {
98            self.clear_pmi_overlay();
99            return;
100        };
101        let text_size = self
102            .pmi_state_shared()
103            .find_view(&active)
104            .map(|view| view.display.text_size_pt)
105            .unwrap_or(12.0);
106        let wpp = self.camera.world_per_pixel();
107        let (_, up, view_dir) = self.camera.basis();
108        let style = PmiLayoutStyle {
109            arrow: ARROW_PX * wpp,
110            text_height: TEXT_PX_AT_12PT * wpp * (text_size / 12.0),
111            view_dir,
112            view_up: up,
113            plane: None,
114        };
115        let mut lines: Vec<f32> = Vec::new();
116        let mut line_colors: Vec<f32> = Vec::new();
117        let mut tris: Vec<f32> = Vec::new();
118        let mut tri_colors: Vec<f32> = Vec::new();
119        let mut explode_step = 0;
120        let mut arrows: Vec<([f64; 3], [f64; 3])> = Vec::new();
121        let mut center_marks: Vec<(String, Vec<[[f64; 3]; 2]>)> = Vec::new();
122        // Part-way through playback, a balloon rides its moving target.
123        let playback = self.explode_playback_poses();
124        for row in &view.annotations {
125            if !row.enabled || row.status != PmiStatus::Ok || self.balloon_target_hidden_live(row) {
126                continue;
127            }
128            // An explode trail follows its step's playback fraction, like its bodies.
129            let geometry = if matches!(row.geometry, brep_kernel::PmiGeometry::Explode { .. }) {
130                explode_step += 1;
131                super::exploded_ops::explode_at(&row.geometry, self.explode_fraction(explode_step - 1))
132            } else {
133                playback.as_ref().and_then(|poses| poses.shown_geometry(row)).unwrap_or_else(|| row.geometry.clone())
134            };
135            let label = playback.as_ref().map_or(row.label_world, |poses| poses.shown(row, row.label_world));
136            // A picked annotation plane lays the row out in that plane.
137            let row_style = PmiLayoutStyle {
138                plane: row.plane,
139                ..style
140            };
141            // An explode trace is an insertion arrow (`arrows` below), drawn
142            // from the parts where they stand to their seat.
143            if let brep_kernel::PmiGeometry::Explode { solids, translate, trace, .. } = &geometry {
144                if *trace {
145                    let mut now = crate::camera::Aabb::empty();
146                    for solid in self.scene.solids() {
147                        if solids.iter().any(|s| solid.name == *s || solid.name.strip_prefix(s.as_str()).is_some_and(|rest| rest.starts_with(':'))) {
148                            now.union(&solid.bbox);
149                        }
150                    }
151                    if !now.is_empty() {
152                        let home = crate::camera::Aabb {
153                            min: std::array::from_fn(|k| now.min[k] - translate[k]),
154                            max: std::array::from_fn(|k| now.max[k] - translate[k]),
155                        };
156                        arrows.extend(self.outline_arrow(&home, *translate));
157                    }
158                }
159                continue;
160            }
161            // A weld callout in symbol style is drawn as its weld symbol from the
162            // kernel leader's seam point and the label (the elbow).
163            let drawn = match self.weld_symbol_layout(row, &geometry, label) {
164                Some((symbol, anchor, elbow, frame)) => {
165                    let mut drawn = crate::pmi_weld_symbol::present(&symbol, anchor, elbow, &frame);
166                    let strokes: Vec<Vec<[f64; 3]>> = drawn.texts.iter().flat_map(|run| run.strokes()).collect();
167                    drawn.polylines.extend(strokes);
168                    drawn
169                }
170                None => pmi_present(&geometry, label, &row.text, &row_style),
171            };
172            if let brep_kernel::PmiGeometry::CenterMark { marks, .. } = &geometry {
173                // Each mark is drawn as six polylines, its two short cross
174                // arms first.
175                let arm = |line: &Vec<[f64; 3]>| -> [f64; 3] {
176                    let d: [f64; 3] = std::array::from_fn(|k| line[1][k] - line[0][k]);
177                    let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
178                    if length > 0.0 { d.map(|c| c / length) } else { [0.0; 3] }
179                };
180                let arms = (0..marks.len())
181                    .filter_map(|k| Some([arm(drawn.polylines.get(6 * k)?), arm(drawn.polylines.get(6 * k + 1)?)]))
182                    .collect();
183                center_marks.push((row.id.clone(), arms));
184            }
185            let rgb = PMI_RGB;
186            for polyline in &drawn.polylines {
187                for pair in polyline.windows(2) {
188                    for point in pair {
189                        lines.extend(point.iter().map(|c| *c as f32));
190                        line_colors.extend_from_slice(&rgb);
191                    }
192                }
193            }
194            for arrow in &drawn.arrows {
195                for point in arrow {
196                    tris.extend(point.iter().map(|c| *c as f32));
197                    tri_colors.extend_from_slice(&rgb);
198                }
199                // Both windings, so the arrowhead reads from either side.
200                for point in [arrow[0], arrow[2], arrow[1]] {
201                    tris.extend(point.iter().map(|c| *c as f32));
202                    tri_colors.extend_from_slice(&rgb);
203                }
204            }
205        }
206        // The exploded view's traces and the instructions player's insertion
207        // arrows: a thin solid line from each moving part to its seat and a
208        // filled head there (owner 2026-11-07), in ink that reads on the
209        // ground: black on a light one (a Line art step's), near-white on
210        // the dark viewport.
211        arrows.extend(self.instructions_insertion_arrows());
212        let ground = if self.scene.line_art.is_some() { crate::thumbnail::line_art::BACKGROUND } else { self.settings.background };
213        let light = 0.2126 * ground[0] + 0.7152 * ground[1] + 0.0722 * ground[2] > 0.5;
214        let ink = if light { EXPLODE_ARROW_RGB } else { EXPLODE_ARROW_ON_DARK_RGB };
215        for (tail, tip) in arrows {
216            let d = [tip[0] - tail[0], tip[1] - tail[1], tip[2] - tail[2]];
217            let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
218            if !(length > 1e-9) {
219                continue;
220            }
221            let d = d.map(|v| v / length);
222            let head = (INSERTION_HEAD_PX * wpp).min(length * 0.6);
223            let w = crate::geometry3d::cross3(view_dir, d);
224            let wl = (w[0] * w[0] + w[1] * w[1] + w[2] * w[2]).sqrt();
225            let w = if wl > 1e-9 { w.map(|v| v / wl) } else { up };
226            let base: [f64; 3] = std::array::from_fn(|k| tip[k] - d[k] * head);
227            for point in [tail, base] {
228                lines.extend(point.iter().map(|c| *c as f32));
229                line_colors.extend_from_slice(&ink);
230            }
231            let half = head * 0.35;
232            let corners = [tip, std::array::from_fn(|k| base[k] + w[k] * half), std::array::from_fn(|k| base[k] - w[k] * half)];
233            for point in [corners[0], corners[1], corners[2], corners[0], corners[2], corners[1]] {
234                tris.extend(point.iter().map(|c| *c as f32));
235                tri_colors.extend_from_slice(&ink);
236            }
237        }
238        let group = if lines.is_empty() && tris.is_empty() {
239            serde_json::json!({ "name": PMI_OVERLAY_GROUP })
240        } else {
241            serde_json::json!({
242                "name": PMI_OVERLAY_GROUP,
243                "renderOrder": 10001,
244                "lines": { "positions": lines, "colors": line_colors },
245                "tris": { "positions": tris, "colors": tri_colors },
246            })
247        };
248        let _ = self.set_overlay_json(&serde_json::json!({ "groups": [group] }).to_string());
249        self.pmi_overlay_key = Some((if wpp > 0.0 { wpp } else { f64::MIN_POSITIVE }, view_dir));
250        self.pmi_center_marks_drawn = (center_marks, view_dir);
251        self.dirty = true;
252    }
253
254    /// The center marks the PMI overlay last drew, for automation:
255    /// `{viewDir, marks: [{id, arms: [[u, v], …]}]}` — per mark the cross's
256    /// two arms as unit world directions (f64, before the overlay's f32
257    /// buffers) and the view direction of that bake, so a check can see the
258    /// overlay re-baked while the arms held still.
259    pub fn pmi_center_marks_json(&self) -> String {
260        let (marks, view_dir) = &self.pmi_center_marks_drawn;
261        serde_json::json!({
262            "viewDir": view_dir,
263            "marks": marks.iter().map(|(id, arms)| serde_json::json!({ "id": id, "arms": arms })).collect::<Vec<_>>(),
264        })
265        .to_string()
266    }
267
268    /// Whether a balloon row's target is hidden in the LIVE scene: every
269    /// solid its recipe projects onto is invisible now. The kernel resolves
270    /// against the view's stored hidden list; a hide made in the viewport
271    /// after the run is only known here, so the leader is withheld and the
272    /// chip reads as an error until the view's visibility is updated.
273    pub(crate) fn balloon_target_hidden_live(&self, row: &brep_kernel::PmiAnnotationReport) -> bool {
274        match &row.geometry {
275            brep_kernel::PmiGeometry::Leader { balloon: true, anchor: Some(anchor), .. } => {
276                !anchor.solids.is_empty()
277                    && anchor
278                        .solids
279                        .iter()
280                        .all(|name| self.scene.solid(name).is_none_or(|solid| !solid.visible))
281            }
282            _ => false,
283        }
284    }
285
286    fn clear_pmi_overlay(&mut self) {
287        self.pmi_center_marks_drawn.0.clear();
288        if self.pmi_overlay_key.take().is_some() {
289            let _ = self.set_overlay_json(
290                &serde_json::json!({ "groups": [ { "name": PMI_OVERLAY_GROUP } ] }).to_string(),
291            );
292            self.dirty = true;
293        }
294    }
295
296    /// Per-frame upkeep: re-bake when the zoom (>0.5 %) or the viewing
297    /// direction (>0.5°) moved, so arrowheads stay pixel-sized and face the
298    /// camera.
299    pub fn ensure_pmi_overlay_current(&mut self) {
300        let Some((baked_wpp, baked_dir)) = self.pmi_overlay_key else {
301            if self.pmi_active_view.is_some() {
302                self.refresh_pmi_overlay();
303            }
304            return;
305        };
306        if self.any_sketch_mode() {
307            self.clear_pmi_overlay();
308            return;
309        }
310        let wpp = self.camera.world_per_pixel();
311        let (_, _, view_dir) = self.camera.basis();
312        let dot = baked_dir[0] * view_dir[0] + baked_dir[1] * view_dir[1] + baked_dir[2] * view_dir[2];
313        let camera = self.snapshot_camera();
314        let balloon_camera_changed = self.pmi_report.as_ref()
315            .and_then(|r| self.pmi_active_view.as_ref().and_then(|id| r.view(id)))
316            .is_some_and(|v| v.annotations.iter().any(|row| matches!(&row.geometry,
317                brep_kernel::PmiGeometry::Leader { anchor: Some(a), balloon: true, .. }
318                if matches!(a.mode, brep_kernel::BalloonAnchorMode::Surface) && a.camera.as_ref() != Some(&camera))));
319        if balloon_camera_changed || super::overlay_wpp_stale(baked_wpp, wpp) || dot < (0.5f64).to_radians().cos() {
320            self.refresh_pmi_overlay();
321        }
322    }
323
324    /// The label feed for the app's chip pass — the active view's
325    /// annotations: `[{id, type, icon, text, status, message, color:[r,g,b],
326    /// world:[x,y,z], enabled, open, selected, textSizePt}]`. Empty without an
327    /// active view. The automation registry's copy of [`Self::pmi_labels`].
328    /// The weld symbol a row draws, when it draws one: the kernel builds it
329    /// on the report row (`weldSymbol`) for every consumer alike.
330    pub(crate) fn weld_symbol(&self, row: &brep_kernel::PmiAnnotationReport) -> Option<crate::pmi_weld_symbol::WeldSymbol> {
331        row.weld_symbol.clone()
332    }
333
334    /// Everything a weld symbol row is drawn from: the symbol, the seam point
335    /// (the kernel leader's target), the elbow (the dragged label, else a
336    /// screen-space default beside the seam) and the view frame.
337    pub(crate) fn weld_symbol_layout(
338        &self,
339        row: &brep_kernel::PmiAnnotationReport,
340        geometry: &brep_kernel::PmiGeometry,
341        label: [f64; 3],
342    ) -> Option<(crate::pmi_weld_symbol::WeldSymbol, [f64; 3], [f64; 3], crate::pmi_weld_symbol::Frame)> {
343        let brep_kernel::PmiGeometry::Leader { targets, .. } = geometry else { return None };
344        let anchor = *targets.first()?;
345        let symbol = self.weld_symbol(row)?;
346        let active = self.pmi_active_view.as_deref()?;
347        let state = self.pmi_state_shared();
348        let text_size = state.find_view(active).map(|view| view.display.text_size_pt).unwrap_or(12.0);
349        let wpp = self.camera.world_per_pixel();
350        let (_, up, forward) = self.camera.basis();
351        let (height, arrow) = (TEXT_PX_AT_12PT * wpp * (text_size / 12.0), ARROW_PX * wpp);
352        // A picked annotation plane holds the symbol, as it holds every planar PMI row.
353        let frame = match row.plane {
354            Some(plane) => crate::pmi_weld_symbol::Frame::from_plane(plane.normal, plane.x_axis, height, arrow),
355            None => crate::pmi_weld_symbol::Frame::from_view(forward, up, height, arrow),
356        };
357        let dragged = state.find_annotation(&row.id).is_some_and(|(_, annotation)| annotation.label_world.is_some());
358        let elbow = if dragged { label } else { crate::pmi_weld_symbol::default_elbow(anchor, &frame) };
359        // In a picked annotation plane the elbow (and so the whole symbol) lies
360        // in the plane, as the kernel projects a dragged label.
361        let elbow = row.plane.map_or(elbow, |plane| plane.project(elbow));
362        Some((symbol, anchor, elbow, frame))
363    }
364
365    pub fn pmi_labels_json(&self) -> String {
366        serde_json::to_string(&self.pmi_labels()).unwrap_or_else(|_| "[]".into())
367    }
368
369    /// The label feed, typed: what the viewport's chip pass reads every
370    /// frame. It reads the shared parse of the PMI block, so a frame with
371    /// nothing changed builds the rows and nothing else.
372    pub fn pmi_labels(&self) -> Vec<PmiLabel> {
373        let Some(active) = self.pmi_active_view.as_deref() else {
374            return Vec::new();
375        };
376        let Some(view) = self.pmi_report.as_ref().and_then(|report| report.view(active)) else {
377            return Vec::new();
378        };
379        // An explode step's chip is an editing handle of the PMI workbench; an
380        // exploded view shown from the Assembly workbench draws its bodies and
381        // trails without them (`exploded_ops`).
382        let explode_chips = matches!(self.settings.workbench.as_str(), "pmi" | "all");
383        if !explode_chips && view.annotations.iter().all(|row| matches!(row.kind.as_str(), "explode" | "hide")) {
384            return Vec::new();
385        }
386        let text_size = self
387            .pmi_state_shared()
388            .find_view(active)
389            .map(|view| view.display.text_size_pt)
390            .unwrap_or(12.0);
391        // Part-way through playback a balloon rides its body.
392        let playback = self.explode_playback_poses();
393        // An explode step draws NO label in the 3D view (owner 2026-10-26:
394        // "I don't want to see the exploded labels at all"): its name lives
395        // in the PMI tree and the Assembly workbench's step list, and while
396        // its form is open the transform gizmo stands on its parts. A hide
397        // step draws nothing either: its bodies are not there to label. A
398        // center mark or centerline carries no text and draws no chip:
399        // its name lives in the PMI tree; only an
400        // unresolved one keeps its red chip, the one place its error shows
401        // in the view.
402        view.annotations
403            .iter()
404            .filter(|row| !matches!(row.kind.as_str(), "explode" | "hide"))
405            .filter(|row| !(row.kind == "centerline" && row.status == PmiStatus::Ok))
406            .map(|row| {
407                // A balloon whose target was hidden in the viewport AFTER
408                // the run (the view's hidden list not yet updated) is an
409                // error chip with no leader: the kernel's head is on a body
410                // nobody sees.
411                let (status, message) = if row.status == PmiStatus::Ok && self.balloon_target_hidden_live(row) {
412                    (PmiStatus::Error, LIVE_HIDDEN_MESSAGE.to_string())
413                } else {
414                    (row.status, row.message.clone())
415                };
416                let color = if status == PmiStatus::Error {
417                    ERROR_RGB
418                } else if !row.enabled {
419                    DISABLED_RGB
420                } else {
421                    PMI_RGB
422                };
423                let icon = pmi_type(&row.kind).map(|def| def.icon).unwrap_or("");
424                let text = if status == PmiStatus::Error || row.text.is_empty() {
425                    format!("{} {}", icon, row.id)
426                } else if self.weld_symbol(row).is_some() {
427                    // The symbol carries the weld's texts; its chip is just the
428                    // handle (the type icon), so it does not cover the symbol.
429                    icon.to_string()
430                } else {
431                    row.text.clone()
432                };
433                PmiLabel {
434                    id: row.id.clone(),
435                    kind: row.kind.clone(),
436                    icon,
437                    text,
438                    status: match status { PmiStatus::Ok => "ok", PmiStatus::Error => "error" },
439                    message,
440                    color,
441                    world: match self.weld_symbol_layout(row, &row.geometry, row.label_world) {
442                        Some((_, _, elbow, _)) => elbow,
443                        None => playback.as_ref().map_or(row.label_world, |poses| poses.shown(row, row.label_world)),
444                    },
445                    enabled: row.enabled,
446                    open: self.pmi_open_annotation.as_deref() == Some(row.id.as_str()),
447                    selected: self.pmi_selected_annotation.as_deref() == Some(row.id.as_str()),
448                    text_size_pt: text_size,
449                }
450            })
451            .collect()
452    }
453}