Skip to main content

brep_render/
scene.rs

1//! Renderer-independent display objects keyed by kernel feature names.
2//! Rendering, picking, and feature-reference display share this scene map.
3
4use crate::camera::Aabb;
5use std::cell::RefCell;
6use std::collections::HashMap;
7
8/// The kind of a display face (surface classification rides along when known —
9/// typed replacement for the previous app's untyped `faceKind` tag).
10#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
11pub enum FaceKind {
12    Unknown,
13    /// The cap a PMI section view draws over a cut (`pmi_section`): display
14    /// only, no kernel face — it carries the section colour and is picked as
15    /// its solid.
16    SectionCap,
17}
18
19/// One face of a solid: a contiguous triangle range of the solid mesh plus the
20/// kernel face identity.
21#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
22pub struct FaceDisplay {
23    /// Kernel face name (byte-exact pipeline name); empty when unnamed.
24    pub name: String,
25    /// Kernel topology face id.
26    pub topo_id: u64,
27    /// First triangle (not index) of this face in the mesh.
28    pub tri_start: u32,
29    /// Triangle count.
30    pub tri_count: u32,
31    pub kind: FaceKind,
32    /// Per-FACE base colour, resolved from this face's `color` metadata
33    /// attribute by [`RenderScene::apply_metadata_colors`]. Takes precedence
34    /// over the owning solid's colour (and over `faceColorMode`), but selection
35    /// / hover emphasis still wins over it. `None` = inherit the solid.
36    #[serde(default)]
37    pub color_override: Option<[f32; 3]>,
38    /// Per-FACE opacity (0 clear .. 1 opaque), resolved from this face's
39    /// `transparency` metadata attribute by
40    /// [`RenderScene::apply_metadata_opacity`]. `None` = inherit the solid.
41    #[serde(default)]
42    pub opacity: Option<f32>,
43    /// The DRAFT ANALYSIS tint (`crate::draft_analysis`), set while the
44    /// analysis is on. It wins over `color_override` and leaves it untouched,
45    /// so the user's face colours come back when the analysis is turned off.
46    #[serde(default)]
47    pub analysis_color: Option<[f32; 3]>,
48}
49
50/// One display edge: a world-space polyline plus the kernel edge identity and
51/// the typed flags the previous display layer kept per object.
52#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
53pub struct EdgeDisplay {
54    /// Kernel edge name (`faceA|faceB[n]` convention); empty when unnamed.
55    pub name: String,
56    /// Kernel topology edge id.
57    pub topo_id: u64,
58    /// World-space polyline (chord-tolerance sampled, ≥ 2 points).
59    pub polyline: Vec<[f32; 3]>,
60    /// Auxiliary display edge (not a real BREP boundary): drawn, but never
61    /// picked, listed or named — a board's copper outline is one.
62    pub aux: bool,
63    /// Centerline flag (hole/revolve axis display).
64    pub centerline: bool,
65    /// This edge's own colour (linear sRGB), from its `color` metadata
66    /// attribute; `None` draws it in the theme's edge colour.
67    #[serde(default)]
68    pub color_override: Option<[f32; 3]>,
69    /// This edge's own opacity (0 clear .. 1 opaque), from its `transparency`
70    /// metadata attribute; `None` draws it opaque.
71    #[serde(default)]
72    pub opacity: Option<f32>,
73}
74
75impl EdgeDisplay {
76    /// Whether this edge draws in a style of its own rather than the theme's.
77    pub fn is_styled(&self) -> bool {
78        self.color_override.is_some() || self.opacity.is_some_and(|o| o < 1.0)
79    }
80}
81
82/// One display vertex (kernel topology vertex).
83#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
84pub struct VertexDisplay {
85    pub topo_id: u64,
86    pub position: [f64; 3],
87}
88
89/// The triangle mesh of one solid, ready for GPU upload (f32; the kernel's f64
90/// buffers are narrowed exactly once, here).
91#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
92pub struct DisplayMesh {
93    /// Interleaved-ready parallel arrays: xyz per vertex.
94    pub positions: Vec<[f32; 3]>,
95    pub normals: Vec<[f32; 3]>,
96    /// Triangle indices (3 per triangle).
97    pub indices: Vec<u32>,
98    /// Per-TRIANGLE face index into `SolidDisplay::faces`.
99    pub face_ids: Vec<u32>,
100}
101
102/// A displayed solid: mesh + named faces/edges/vertices + visibility.
103#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
104pub struct SolidDisplay {
105    /// Kernel solid name — the scene key.
106    pub name: String,
107    /// The resident kernel handle this display was tessellated from (0 = none,
108    /// e.g. a synthesized sheet with no kernel solid). Handles are monotonic and
109    /// never recycled, so this is a stable identity for the geometry: the R10
110    /// display-reuse fast path keeps an existing display across a history rerun
111    /// ONLY when the name's resident handle still equals this — a name re-bound to
112    /// a DIFFERENT handle (a SUBTRACT result inherits its target's name; a
113    /// roll-back replays that name's ORIGINAL producer) must re-tessellate.
114    pub source_handle: u32,
115    pub visible: bool,
116    /// Optional per-solid base color override (R14 — user-set solid color),
117    /// else the name-hashed stable color is used.
118    pub color_override: Option<[f32; 3]>,
119    /// Display-only opacity (0 clear .. 1 opaque; `None` = opaque): a motion
120    /// study's transparency clip. A translucent solid draws after every opaque
121    /// one through the blended pass, with its base colour's alpha set to this.
122    pub opacity: Option<f32>,
123    /// The solid's own opacity (0 clear .. 1 opaque; `None` = opaque),
124    /// resolved from its `transparency` metadata attribute by
125    /// [`RenderScene::apply_metadata_opacity`]. Kept apart from
126    /// [`Self::opacity`] so a motion study's clip, which writes that field and
127    /// gives it back afterwards, never has to know about it; the clip wins
128    /// while it is set.
129    #[serde(default)]
130    pub model_opacity: Option<f32>,
131    /// Monotonic content revision (R10). Every freshly built display gets a
132    /// unique value, so the renderer's GPU-buffer cache re-uploads on any
133    /// rebuild — correct-by-default (equivalent to teardown-rebuild). The
134    /// reused-buffer fast path (keep a revision stable across a `reused`
135    /// pipeline result) is a follow-up optimization.
136    pub revision: u64,
137    /// Nonzero: this display is the solid of revision `shape_revision`, MOVED
138    /// rigidly (the same mesh topology, faces, edges, vertices and styles; only
139    /// positions and normals differ). The renderer may then rewrite those in the
140    /// buffers it already holds instead of rebuilding them. Every other change
141    /// resets it to 0, so a stale value can never skip a rebuild.
142    #[serde(default)]
143    pub shape_revision: u64,
144    /// The affine (column-major 4×4) that takes the geometry of shape
145    /// `shape_revision` to this display's positions, when that is all that
146    /// moved it (an explode pose): the renderer then draws the buffers it holds
147    /// for the shape through it, writing a matrix instead of every vertex.
148    /// `None` for an unposed display, and for one moved any other way; every
149    /// change that resets `shape_revision` resets this.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub pose: Option<[f32; 16]>,
152    pub mesh: DisplayMesh,
153    pub faces: Vec<FaceDisplay>,
154    pub edges: Vec<EdgeDisplay>,
155    pub vertices: Vec<VertexDisplay>,
156    /// Per-entity + group hide state (individual faces/edges/vertices, or a
157    /// whole group). Default = everything visible; see [`crate::visibility`].
158    /// Reused solids keep it across history reruns (this whole struct is cloned
159    /// forward); a re-tessellated solid resets to all-visible.
160    pub visibility: crate::visibility::EntityVisibility,
161    /// World bbox over mesh positions (edges lie on the mesh by construction).
162    pub bbox: Aabb,
163    /// This display is a SYNTHESIZED committed-sketch SHEET (planar face + named
164    /// boundary edges + corner vertices), not a kernel solid — it carries no
165    /// resident handle (`source_handle == 0`). The marker lets the UI treat a
166    /// sketch as a sketch: it is listed under "Sketches" (not among solids) yet is
167    /// pickable / selectable / measurable like any scene solid.
168    pub is_sketch: bool,
169    /// This body is SHEET METAL — its resident handle carried a `SheetTree` when
170    /// the display was built. Stamped by the pipeline from
171    /// [`brep_kernel::is_sheet_metal_handle`] on the RUNNER thread (where the
172    /// tree's thread-local is warm), so the UI thread can answer "is this a
173    /// sheet-metal body?" straight off the scene — the gate for the sheet-metal
174    /// edit features (SM Flange / Fillet / Chamfer). Immutable-correct: a tree is
175    /// attached at solid creation and dropped exactly when the handle is freed,
176    /// handles never recycle, and the display-reuse fast path clones this struct
177    /// forward only while the handle is unchanged.
178    pub is_sheet_metal: bool,
179    /// The colour this display's edges take when the metadata store names none
180    /// for them (`None`: the theme's edge colour). Set on a synthesized display
181    /// whose edges ARE the message — a refused Sew to Solid's open edges — so
182    /// [`RenderScene::apply_metadata_edge_looks`] keeps them highlighted.
183    #[serde(default)]
184    pub edge_color_base: Option<[f32; 3]>,
185}
186
187/// Source of monotonic [`SolidDisplay::revision`] values.
188pub(crate) fn next_revision() -> u64 {
189    use std::sync::atomic::{AtomicU64, Ordering};
190    static COUNTER: AtomicU64 = AtomicU64::new(1);
191    COUNTER.fetch_add(1, Ordering::Relaxed)
192}
193
194/// The scene: insertion-ordered solids + an exact name index (R8 — the
195/// `getObjectByName` heuristic-scoring lookup is replaced by this map).
196#[derive(Debug, Default)]
197pub struct RenderScene {
198    solids: Vec<SolidDisplay>,
199    index: HashMap<String, usize>,
200    /// Triangle BVHs for dense displays, built once on first pick. Scene
201    /// mutations invalidate these independently of camera and visibility.
202    pick_trees: RefCell<HashMap<String, brep_kernel::Bvh>>,
203    /// The B-rep of the kernel displays a drawing sheet has ASKED for, keyed by
204    /// solid name with the resident handle it came from: `name -> (handle,
205    /// fingerprint, solid)`. Only a sheet reads topology, and the runner sends
206    /// it only when asked (`EngineState::request_exact_solids`), so a document
207    /// with no sheet holds none. Beside the displays rather than inside them,
208    /// because a display is cloned (the PMI explode keeps originals) and
209    /// rebuilt on the UI thread (committed sketches), and neither wants a copy
210    /// of the topology. Read through [`Self::exact_solid`], which answers only
211    /// while the handle still matches the display's. The `u64` is the solid's
212    /// [`brep_fingerprint`], taken once here rather than per projection.
213    exact: HashMap<String, (u32, u64, brep_kernel::BrepSolid)>,
214    /// Bumped whenever [`Self::exact`] gains or loses a solid, so a projection
215    /// cached without a topology is redrawn when it arrives.
216    exact_revision: u64,
217    /// Bumped whenever [`Self::set_visible`] actually CHANGES a solid's
218    /// visibility — see [`Self::visibility_revision`].
219    visibility_revision: u64,
220    /// A Work part's CONTEXT scene only: the context faces drawn emphasised,
221    /// `(solid, face, selected)` (else hovered). Set by
222    /// `EngineState::sync_context_highlight`; the context render pass reads it.
223    pub highlight: Vec<(String, String, bool)>,
224    /// A Work part's CONTEXT scene only: its colour and opacity (`None`: the
225    /// default [`crate::render::WORK_PART_CONTEXT_RGBA`]). Set by
226    /// `EngineState::set_context_display`; the context render pass reads it.
227    pub tint: Option<[f32; 4]>,
228    /// Draw the scene as a Line art instructions step (set by the engine
229    /// while such a step is shown): a light grey ground, flat unlit fills,
230    /// the parts in `placed` white with grey lines, every other part flat
231    /// blue with black lines, and each part outlined.
232    pub line_art: Option<LineArtLook>,
233}
234
235/// What [`RenderScene::line_art`] needs: which solids earlier steps placed.
236#[derive(Debug, Clone, Default, PartialEq)]
237pub struct LineArtLook {
238    pub placed: std::collections::HashSet<String>,
239}
240
241impl SolidDisplay {
242    /// The opacity the solid's own faces draw at (0 clear .. 1 opaque): a
243    /// motion study's clip while one is set, else the `transparency`
244    /// attribute, else opaque.
245    pub fn base_opacity(&self) -> f32 {
246        self.opacity.or(self.model_opacity).unwrap_or(1.0).clamp(0.0, 1.0)
247    }
248
249    /// The opacity `face` draws at: a clip fades the whole solid, else the
250    /// face's own `transparency` attribute, else the solid's.
251    pub fn face_opacity(&self, face: &FaceDisplay) -> f32 {
252        match self.opacity {
253            Some(clip) => clip,
254            None => face.opacity.or(self.model_opacity).unwrap_or(1.0),
255        }
256        .clamp(0.0, 1.0)
257    }
258}
259
260impl RenderScene {
261    pub fn new() -> Self {
262        Self::default()
263    }
264
265    /// Insert or replace a solid by name (replacement keeps insertion order —
266    /// a boolean result reusing its target's name stays in place).
267    pub fn insert_solid(&mut self, solid: SolidDisplay) {
268        self.pick_trees.get_mut().remove(&solid.name);
269        match self.index.get(&solid.name) {
270            Some(&slot) => self.solids[slot] = solid,
271            None => {
272                self.index.insert(solid.name.clone(), self.solids.len());
273                self.solids.push(solid);
274            }
275        }
276    }
277
278    /// Drop every solid (the scene rebuild path clears then repopulates).
279    pub fn clear(&mut self) {
280        self.pick_trees.get_mut().clear();
281        self.solids.clear();
282        self.index.clear();
283        self.highlight.clear();
284    }
285
286    /// Empty the scene, RETURNING every solid by value (the name index is cleared
287    /// and the vec is `mem::take`-n out). The history-apply seam MOVES existing
288    /// displays out this way to reinsert the reused ones without cloning their
289    /// meshes — a scene-free [`crate::pipeline::SceneRunner`] delta is applied by
290    /// draining then reinserting in snapshot order.
291    pub fn drain(&mut self) -> Vec<SolidDisplay> {
292        self.pick_trees.get_mut().clear();
293        self.index.clear();
294        std::mem::take(&mut self.solids)
295    }
296
297    /// Set (or clear) a solid's metadata color override, bumping its revision
298    /// so the renderer re-derives the base style. Returns false if unknown.
299    pub fn set_color_override(&mut self, name: &str, color: Option<[f32; 3]>) -> bool {
300        let Some(slot) = self.index.get(name).copied() else {
301            return false;
302        };
303        let solid = &mut self.solids[slot];
304        if solid.color_override != color {
305            solid.color_override = color;
306            solid.revision = next_revision();
307            solid.shape_revision = 0;
308            solid.pose = None;
309        }
310        true
311    }
312
313    /// Set the per-FACE colour overrides of solid `name`, face `i` taking
314    /// `colors[i]` (faces past the slice are left alone), bumping the solid's
315    /// revision only when one changed. Returns false if the solid is unknown.
316    /// A display-only body (the mesh import's region view) colours its faces
317    /// through this.
318    pub fn set_face_colors(&mut self, name: &str, colors: &[Option<[f32; 3]>]) -> bool {
319        let Some(slot) = self.index.get(name).copied() else {
320            return false;
321        };
322        let solid = &mut self.solids[slot];
323        let mut changed = false;
324        for (face, &color) in solid.faces.iter_mut().zip(colors) {
325            if face.color_override != color {
326                face.color_override = color;
327                changed = true;
328            }
329        }
330        if changed {
331            solid.revision = next_revision();
332            solid.shape_revision = 0;
333            solid.pose = None;
334        }
335        true
336    }
337
338    /// Set the DRAFT ANALYSIS tint of solid `name`'s faces (face `i` takes
339    /// `colors[i]`; an empty slice clears every face), bumping the revision
340    /// only when one changed. The user's `color_override` is not touched.
341    /// Returns whether anything changed.
342    pub fn set_face_analysis_colors(&mut self, name: &str, colors: &[Option<[f32; 3]>]) -> bool {
343        let Some(slot) = self.index.get(name).copied() else {
344            return false;
345        };
346        let solid = &mut self.solids[slot];
347        let mut changed = false;
348        for (index, face) in solid.faces.iter_mut().enumerate() {
349            let color = colors.get(index).copied().flatten();
350            if face.analysis_color != color {
351                face.analysis_color = color;
352                changed = true;
353            }
354        }
355        if changed {
356            solid.revision = next_revision();
357            solid.shape_revision = 0;
358            solid.pose = None;
359        }
360        changed
361    }
362
363    /// Re-derive every solid's and face's opacity from the name-keyed
364    /// metadata store: the seam through which the durable `transparency`
365    /// attribute reaches the display, as [`Self::apply_metadata_colors`] is
366    /// for `color`.
367    ///
368    /// `lookup` maps an object NAME (a solid's or a face's) to its opacity
369    /// (0 clear .. 1 opaque), `None` for "nothing recorded". A solid that
370    /// resolves fully opaque stores `None`; a face keeps an explicit 1, which
371    /// is how one face of a see-through body is made opaque again. A section
372    /// cap inherits its solid.
373    ///
374    /// A changed solid's `revision` is bumped, and only then: the same no-op
375    /// guarantee the colour pass gives, for the same reason.
376    pub fn apply_metadata_opacity(&mut self, lookup: impl Fn(&str) -> Option<f32>) -> bool {
377        let mut any = false;
378        for solid in &mut self.solids {
379            let mut changed = false;
380            let want = lookup(&solid.name).map(|o| o.clamp(0.0, 1.0)).filter(|o| *o < 1.0);
381            if solid.model_opacity != want {
382                solid.model_opacity = want;
383                changed = true;
384            }
385            for face in &mut solid.faces {
386                let want = if face.name.is_empty() || face.kind == FaceKind::SectionCap {
387                    None
388                } else {
389                    lookup(&face.name).map(|o| o.clamp(0.0, 1.0))
390                };
391                if face.opacity != want {
392                    face.opacity = want;
393                    changed = true;
394                }
395            }
396            if changed {
397                solid.revision = next_revision();
398                solid.shape_revision = 0;
399                solid.pose = None;
400                any = true;
401            }
402        }
403        any
404    }
405
406    /// Re-derive every EDGE's own colour and opacity from the metadata store,
407    /// by the edge's own name. Its own lookups, not the solids' and faces':
408    /// an edge never inherits its solid's or its faces' look, and no derived
409    /// default (a board body's colour) may read an edge name as a face's.
410    /// Unnamed and display-only (aux) edges carry none. Returns whether
411    /// anything changed; bumps a changed solid's revision.
412    pub fn apply_metadata_edge_looks(
413        &mut self,
414        color: impl Fn(&str) -> Option<[f32; 3]>,
415        opacity: impl Fn(&str) -> Option<f32>,
416    ) -> bool {
417        let mut any = false;
418        for solid in &mut self.solids {
419            let mut changed = false;
420            let base = solid.edge_color_base;
421            for edge in &mut solid.edges {
422                let (want_color, want_opacity) = if edge.name.is_empty() || edge.aux {
423                    (base, None)
424                } else {
425                    (color(&edge.name).or(base), opacity(&edge.name).map(|o| o.clamp(0.0, 1.0)).filter(|o| *o < 1.0))
426                };
427                if edge.color_override != want_color || edge.opacity != want_opacity {
428                    edge.color_override = want_color;
429                    edge.opacity = want_opacity;
430                    changed = true;
431                }
432            }
433            if changed {
434                solid.revision = next_revision();
435                solid.shape_revision = 0;
436                solid.pose = None;
437                any = true;
438            }
439        }
440        any
441    }
442
443    /// Re-derive every solid's and face's base colour from the name-keyed
444    /// metadata store — the ONE seam through which the durable `color`
445    /// attribute reaches the display.
446    ///
447    /// `lookup` maps an object NAME (a solid's or a face's) to its resolved
448    /// colour. It returns `None` both for "no colour recorded" and for "the
449    /// display setting is overriding model colours", so this method needs to
450    /// know about neither.
451    ///
452    /// A SKETCH sheet's own `color_override` is the synthesized
453    /// `crate::engine_state::SKETCH_SHEET_COLOR`, not a metadata colour, and
454    /// re-deriving it from a store that has no record for the sheet would blank
455    /// it back to the global face colour — so it is left alone. The sketch's
456    /// `color` attribute (keyed by the sketch id, which is the sheet's name)
457    /// lands on the sheet's FACES instead: a face override wins over the
458    /// solid's colour, and clearing the attribute clears the face overrides,
459    /// which restores the synthesized sheet colour underneath.
460    ///
461    /// A changed solid's `revision` is bumped so the renderer re-uploads it —
462    /// and ONLY when something actually changed. That no-op guarantee is
463    /// load-bearing, not a nicety: this runs after EVERY history apply, and the
464    /// R10 GPU-buffer reuse fast path keys off a stable revision.
465    pub fn apply_metadata_colors(&mut self, lookup: impl Fn(&str) -> Option<[f32; 3]>) -> bool {
466        let mut any = false;
467        for solid in &mut self.solids {
468            let mut changed = false;
469            // A sketch sheet keeps its synthesized base colour; its metadata
470            // colour reaches the display through the faces below.
471            let sheet_color = if solid.is_sketch {
472                lookup(&solid.name)
473            } else {
474                let want = lookup(&solid.name);
475                if solid.color_override != want {
476                    solid.color_override = want;
477                    changed = true;
478                }
479                None
480            };
481            for face in &mut solid.faces {
482                // A section cap keeps the section colour its view gave it.
483                if face.kind == FaceKind::SectionCap {
484                    continue;
485                }
486                // An unnamed face can carry no metadata record, so it always
487                // inherits the solid rather than costing a store lookup.
488                let want = if face.name.is_empty() {
489                    None
490                } else {
491                    lookup(&face.name)
492                }
493                .or(sheet_color);
494                if face.color_override != want {
495                    face.color_override = want;
496                    changed = true;
497                }
498            }
499            if changed {
500                solid.revision = next_revision();
501                solid.shape_revision = 0;
502                solid.pose = None;
503                any = true;
504            }
505        }
506        any
507    }
508
509    /// Set a solid's visibility (R11). Returns false if unknown.
510    pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
511        let Some(solid) = self.solid_mut(name) else {
512            return false;
513        };
514        let changed = solid.visible != visible;
515        solid.visible = visible;
516        if changed {
517            self.visibility_revision = self.visibility_revision.wrapping_add(1);
518        }
519        true
520    }
521
522    /// Monotonic counter of VISIBILITY changes — the cache key for anything
523    /// derived from which bodies are shown.
524    ///
525    /// Hiding a body is SESSION state: it writes no history, runs nothing, and
526    /// lands no exact solid, so it moves none of the counters a derived
527    /// drawing would otherwise key on. A drawing sheet draws "the solids
528    /// visible in the scene" (`sheets::project::sheet_solid_names`), so its
529    /// cached projection depends on this and nothing else could tell it.
530    ///
531    /// Only a REAL change counts. `EngineState::apply_view_display` sets every
532    /// solid's visibility from the active PMI view's hidden set on every
533    /// activation, and almost all of those calls are no-ops; counting them
534    /// would re-project the open sheet for nothing.
535    pub fn visibility_revision(&self) -> u64 {
536        self.visibility_revision
537    }
538
539    /// Scene enumeration for the host scene-tree panel (R11): names, kind,
540    /// visibility, child face/edge/vertex counts — as JSON.
541    pub fn listing_json(&self) -> String {
542        let solids: Vec<serde_json::Value> = self
543            .solids
544            .iter()
545            .map(|solid| {
546                serde_json::json!({
547                    "name": solid.name,
548                    "kind": "SOLID",
549                    "visible": solid.visible,
550                    "faces": solid.faces.len(),
551                    "edges": solid.edges.iter().filter(|e| !e.aux).count(),
552                    "vertices": solid.vertices.len(),
553                })
554            })
555            .collect();
556        serde_json::Value::Array(solids).to_string()
557    }
558
559    /// Remove a solid by exact name.
560    pub fn remove_solid(&mut self, name: &str) -> bool {
561        let Some(slot) = self.index.remove(name) else {
562            return false;
563        };
564        self.solids.remove(slot);
565        self.pick_trees.get_mut().remove(name);
566        for value in self.index.values_mut() {
567            if *value > slot {
568                *value -= 1;
569            }
570        }
571        true
572    }
573
574    pub fn solid(&self, name: &str) -> Option<&SolidDisplay> {
575        self.index.get(name).map(|&slot| &self.solids[slot])
576    }
577
578    /// Drop every kept B-rep whose display is gone or now comes from a
579    /// different handle. Called after a run's displays are reconciled, so "the
580    /// display's handle" is that run's.
581    pub fn prune_exact_solids(&mut self) {
582        let (solids, index) = (&self.solids, &self.index);
583        let before = self.exact.len();
584        self.exact.retain(|name, (handle, _, _)| {
585            index.get(name).is_some_and(|&slot| solids[slot].source_handle == *handle)
586        });
587        if self.exact.len() != before {
588            self.exact_revision += 1;
589        }
590    }
591
592    /// Record the B-rep the runner sent for `name`, when `handle` is still the
593    /// one its display was tessellated from; `false` (and nothing kept) when
594    /// the display has moved on since the request went out.
595    pub fn set_exact_solid(&mut self, name: &str, handle: u32, solid: brep_kernel::BrepSolid) -> bool {
596        if handle == 0 || self.solid(name).map(|display| display.source_handle) != Some(handle) {
597            return false;
598        }
599        self.exact.insert(name.to_string(), (handle, brep_fingerprint(&solid), solid));
600        self.exact_revision += 1;
601        true
602    }
603
604    /// Forget the B-rep of `name`: its geometry changed under the SAME handle
605    /// (an assembly solve re-poses a resident solid in place), so the next
606    /// projection must ask again.
607    pub fn drop_exact_solid(&mut self, name: &str) {
608        if self.exact.remove(name).is_some() {
609            self.exact_revision += 1;
610        }
611    }
612
613    /// Forget every B-rep: the handles they were keyed by belong to a runner
614    /// that is gone (a cancel restarts its registry, which counts from one
615    /// again) or to a document that was replaced.
616    pub fn clear_exact_solids(&mut self) {
617        if !self.exact.is_empty() {
618            self.exact.clear();
619            self.exact_revision += 1;
620        }
621    }
622
623    /// See `Self::exact`'s revision counter.
624    pub fn exact_revision(&self) -> u64 {
625        self.exact_revision
626    }
627
628    /// The B-rep the displayed solid `name` was tessellated from, or `None`
629    /// when the scene holds none for its CURRENT handle — a synthesized sketch
630    /// sheet, or a solid whose topology did not reach this thread.
631    pub fn exact_solid(&self, name: &str) -> Option<&brep_kernel::BrepSolid> {
632        self.exact_solid_fingerprinted(name).map(|(solid, _)| solid)
633    }
634
635    /// [`Self::exact_solid`] with its content fingerprint.
636    pub fn exact_solid_fingerprinted(&self, name: &str) -> Option<(&brep_kernel::BrepSolid, u64)> {
637        let display = self.solid(name)?;
638        self.exact
639            .get(name)
640            .filter(|(handle, _, _)| *handle == display.source_handle && *handle != 0)
641            .map(|(_, fingerprint, solid)| (solid, *fingerprint))
642    }
643
644    pub fn solid_mut(&mut self, name: &str) -> Option<&mut SolidDisplay> {
645        let slot = *self.index.get(name)?;
646        // A caller can edit positions, indices or face ranges through this
647        // reference without changing the display revision.
648        self.pick_trees.get_mut().remove(name);
649        Some(&mut self.solids[slot])
650    }
651
652    pub(crate) fn pick_triangles(&self, solid: &SolidDisplay, ray: &crate::view::Ray, out: &mut Vec<usize>) {
653        let mut trees = self.pick_trees.borrow_mut();
654        let tree = trees.entry(solid.name.clone()).or_insert_with(|| {
655            let boxes: Vec<_> = solid.mesh.indices.chunks_exact(3).map(|indices| {
656                let mut bounds = brep_kernel::Aabb::empty();
657                for &index in indices {
658                    let p = solid.mesh.positions[index as usize];
659                    bounds.include_point(brep_kernel::Vec3::new(p[0] as f64, p[1] as f64, p[2] as f64));
660                }
661                bounds
662            }).collect();
663            brep_kernel::Bvh::build(&boxes)
664        });
665        let v = |p: [f64; 3]| brep_kernel::Vec3::new(p[0], p[1], p[2]);
666        tree.intersecting_ray(v(ray.origin), v(ray.dir), 1e-9, out);
667        // Preserve face/triangle traversal order, including tied hits.
668        out.sort_unstable();
669    }
670
671    /// Insertion-ordered iteration (deterministic — drives draw order).
672    pub fn solids(&self) -> &[SolidDisplay] {
673        &self.solids
674    }
675
676    /// The world-space polyline of the first display edge named `name` across all
677    /// solids (widened to `f64`), or `None` when no edge carries that exact name.
678    /// The engine-native sketch pickEdges tool (S6b-2) uses this to fetch a picked
679    /// scene edge's geometry for projection into the sketch plane. There is no name
680    /// index for edges (only solids), so this is a linear scan — fine for the
681    /// interactive per-click use.
682    pub fn edge_polyline_world(&self, name: &str) -> Option<Vec<[f64; 3]>> {
683        for solid in &self.solids {
684            for edge in &solid.edges {
685                if edge.name == name {
686                    return Some(
687                        edge.polyline
688                            .iter()
689                            .map(|p| [p[0] as f64, p[1] as f64, p[2] as f64])
690                            .collect(),
691                    );
692                }
693            }
694        }
695        None
696    }
697
698    /// The name of the solid owning the first display edge named `name`, or `None`
699    /// (the companion of [`edge_polyline_world`](Self::edge_polyline_world) — the
700    /// pickEdges tool stores it as external-ref metadata).
701    pub fn edge_solid_name(&self, name: &str) -> Option<&str> {
702        for solid in &self.solids {
703            if solid.edges.iter().any(|edge| edge.name == name) {
704                return Some(&solid.name);
705            }
706        }
707        None
708    }
709
710    /// The world plane of the first display face named `name` across all solids,
711    /// as `(centroid, unit outward normal)`: the area-weighted centroid of the
712    /// face's mesh triangles and the normalized sum of their cross products. The
713    /// watertight tessellation winds every face's triangles by `same_sense`, so
714    /// the cross-product sum IS the outward normal (the stored per-vertex normals
715    /// are shading normals and can be blended at shared boundary vertices). This
716    /// is what lets an extrude/revolve whose `profile` is a resident solid FACE
717    /// (not a sketch) anchor its dimension gizmo — the engine's dimension refs
718    /// fall back to it (`EngineState::lookup_profile_plane`). Hidden solids count
719    /// too: a hidden source solid still anchors the gizmo. `None` when no face
720    /// carries that exact name, it has no triangles, or the triangles are
721    /// degenerate (zero area). Linear scan like [`edge_polyline_world`](Self::edge_polyline_world).
722    pub fn face_plane_world(&self, name: &str) -> Option<([f64; 3], [f64; 3])> {
723        for solid in &self.solids {
724            let Some(face) = solid.faces.iter().find(|face| face.name == name) else {
725                continue;
726            };
727            let positions = &solid.mesh.positions;
728            let indices = &solid.mesh.indices;
729            let start = face.tri_start as usize;
730            let end = (start + face.tri_count as usize).min(indices.len() / 3);
731            let mut weighted = [0.0f64; 3];
732            let mut normal = [0.0f64; 3];
733            let mut total_area = 0.0f64;
734            for tri in start..end {
735                let a = f64_point(positions[indices[tri * 3] as usize]);
736                let b = f64_point(positions[indices[tri * 3 + 1] as usize]);
737                let c = f64_point(positions[indices[tri * 3 + 2] as usize]);
738                let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
739                let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
740                // Twice the signed-area vector; its length is 2·area.
741                let cross = [
742                    ab[1] * ac[2] - ab[2] * ac[1],
743                    ab[2] * ac[0] - ab[0] * ac[2],
744                    ab[0] * ac[1] - ab[1] * ac[0],
745                ];
746                let area =
747                    0.5 * (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt();
748                for k in 0..3 {
749                    weighted[k] += area * (a[k] + b[k] + c[k]) / 3.0;
750                    normal[k] += cross[k];
751                }
752                total_area += area;
753            }
754            let normal_len =
755                (normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]).sqrt();
756            if total_area <= 1e-18 || normal_len <= 1e-18 {
757                return None;
758            }
759            return Some((
760                [
761                    weighted[0] / total_area,
762                    weighted[1] / total_area,
763                    weighted[2] / total_area,
764                ],
765                [normal[0] / normal_len, normal[1] / normal_len, normal[2] / normal_len],
766            ));
767        }
768        None
769    }
770
771    /// Whether the display face named `name` is PLANAR: every one of its mesh
772    /// triangles' normals is parallel to the face's summed normal (within
773    /// `1e-4` in the sine). A cylinder, cone or freeform face fails this; a
774    /// face with no triangles is not planar either. Linear scan like
775    /// [`face_plane_world`](Self::face_plane_world) — the 3D sketch editor asks
776    /// this once per reference pick, never per frame.
777    pub fn face_is_planar(&self, name: &str) -> bool {
778        for solid in &self.solids {
779            let Some(face) = solid.faces.iter().find(|face| face.name == name) else {
780                continue;
781            };
782            let positions = &solid.mesh.positions;
783            let indices = &solid.mesh.indices;
784            let start = face.tri_start as usize;
785            let end = (start + face.tri_count as usize).min(indices.len() / 3);
786            if start >= end {
787                return false;
788            }
789            let cross_of = |tri: usize| -> [f64; 3] {
790                let a = f64_point(positions[indices[tri * 3] as usize]);
791                let b = f64_point(positions[indices[tri * 3 + 1] as usize]);
792                let c = f64_point(positions[indices[tri * 3 + 2] as usize]);
793                let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
794                let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
795                [
796                    ab[1] * ac[2] - ab[2] * ac[1],
797                    ab[2] * ac[0] - ab[0] * ac[2],
798                    ab[0] * ac[1] - ab[1] * ac[0],
799                ]
800            };
801            let mut sum = [0.0f64; 3];
802            for tri in start..end {
803                let n = cross_of(tri);
804                for k in 0..3 {
805                    sum[k] += n[k];
806                }
807            }
808            let sum_len = (sum[0] * sum[0] + sum[1] * sum[1] + sum[2] * sum[2]).sqrt();
809            if sum_len <= 1e-18 {
810                return false;
811            }
812            let unit = [sum[0] / sum_len, sum[1] / sum_len, sum[2] / sum_len];
813            for tri in start..end {
814                let n = cross_of(tri);
815                let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
816                if len <= 1e-18 {
817                    continue; // A sliver triangle says nothing about the plane.
818                }
819                let cross = [
820                    n[1] * unit[2] - n[2] * unit[1],
821                    n[2] * unit[0] - n[0] * unit[2],
822                    n[0] * unit[1] - n[1] * unit[0],
823                ];
824                let sine = (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() / len;
825                if sine > 1e-4 {
826                    return false;
827                }
828            }
829            return true;
830        }
831        false
832    }
833
834    pub fn is_empty(&self) -> bool {
835        self.solids.is_empty()
836    }
837
838    /// World bbox over every VISIBLE solid.
839    pub fn bbox(&self) -> Aabb {
840        let mut bbox = Aabb::empty();
841        for solid in &self.solids {
842            if solid.visible {
843                bbox.union(&solid.bbox);
844            }
845        }
846        bbox
847    }
848}
849
850/// A hash of everything in a B-rep the drawing sheet's hidden-line pass reads: every vertex,
851/// curve, carrier and pcurve number to the bit, and the topology that ties
852/// them together.
853pub fn brep_fingerprint(solid: &brep_kernel::BrepSolid) -> u64 {
854    use std::hash::{Hash, Hasher};
855    let mut hasher = std::collections::hash_map::DefaultHasher::new();
856    let mut numbers = |values: &mut dyn Iterator<Item = f64>| {
857        for value in values {
858            value.to_bits().hash(&mut hasher);
859        }
860    };
861    let curve = |curve: &brep_kernel::NurbsCurve| -> Vec<f64> {
862        let mut out = vec![curve.degree as f64];
863        out.extend(curve.knots.iter().copied());
864        out.extend(curve.control_points.iter().flat_map(|cp| [cp.x, cp.y, cp.z, cp.w]));
865        out
866    };
867    for vertex in &solid.vertices {
868        numbers(&mut [vertex.id as f64, vertex.point.x, vertex.point.y, vertex.point.z].into_iter());
869    }
870    for edge in &solid.edges {
871        numbers(&mut [edge.id as f64, edge.t0, edge.t1, edge.start_vertex_id as f64, edge.end_vertex_id as f64].into_iter());
872        numbers(&mut [edge.degenerate as u8 as f64].into_iter());
873        numbers(&mut curve(&edge.curve).into_iter());
874    }
875    for shell in &solid.shells {
876        for face in &shell.faces {
877            let surface = &face.surface;
878            numbers(&mut [face.same_sense as u8 as f64, surface.degree_u as f64, surface.degree_v as f64].into_iter());
879            numbers(&mut surface.knots_u.iter().chain(&surface.knots_v).copied());
880            numbers(&mut surface.control_points.iter().flatten().flat_map(|cp| [cp.x, cp.y, cp.z, cp.w]));
881            for lp in &face.loops {
882                numbers(&mut [f64::NAN].into_iter());
883                for coedge in &lp.coedges {
884                    numbers(&mut [coedge.edge_id as f64, coedge.forward as u8 as f64].into_iter());
885                    numbers(&mut curve(&coedge.pcurve).into_iter());
886                }
887            }
888        }
889    }
890    hasher.finish()
891}
892
893/// Widen a display-mesh vertex to `f64` (the mesh stores `f32`).
894fn f64_point(p: [f32; 3]) -> [f64; 3] {
895    [p[0] as f64, p[1] as f64, p[2] as f64]
896}
897
898/// Build a [`SolidDisplay`] from the kernel's native display payload.
899pub fn solid_display_from_payload(
900    name: &str,
901    payload: brep_kernel::DisplaySolidPayload,
902) -> SolidDisplay {
903    let mesh_in = payload.mesh;
904    let vertex_count = mesh_in.positions.len() / 3;
905    let mut positions = Vec::with_capacity(vertex_count);
906    let mut normals = Vec::with_capacity(vertex_count);
907    let mut bbox = Aabb::empty();
908    for i in 0..vertex_count {
909        let p = [
910            mesh_in.positions[i * 3],
911            mesh_in.positions[i * 3 + 1],
912            mesh_in.positions[i * 3 + 2],
913        ];
914        bbox.expand(p);
915        positions.push([p[0] as f32, p[1] as f32, p[2] as f32]);
916        normals.push([
917            mesh_in.normals[i * 3] as f32,
918            mesh_in.normals[i * 3 + 1] as f32,
919            mesh_in.normals[i * 3 + 2] as f32,
920        ]);
921    }
922
923    // Face ranges: the watertight mesh emits each face's triangles as one
924    // contiguous run of `face_ids`. Group runs; a face with no triangles gets
925    // an empty range.
926    let mut faces: Vec<FaceDisplay> = payload
927        .faces
928        .iter()
929        .map(|(topo_id, name)| FaceDisplay {
930            name: name.clone().unwrap_or_default(),
931            topo_id: *topo_id,
932            tri_start: 0,
933            tri_count: 0,
934            kind: FaceKind::Unknown,
935            color_override: None,
936            opacity: None,
937            analysis_color: None,
938        })
939        .collect();
940    let mut run_start = 0u32;
941    let mut run_face: Option<u32> = None;
942    for (tri, &face_id) in mesh_in.face_ids.iter().enumerate() {
943        if run_face != Some(face_id) {
944            run_face = Some(face_id);
945            run_start = tri as u32;
946        }
947        if let Some(face) = faces.get_mut(face_id as usize) {
948            if face.tri_count == 0 {
949                face.tri_start = run_start;
950            }
951            face.tri_count += 1;
952        }
953    }
954
955    // Edges and vertices expand the bbox too. For a real solid they lie ON the
956    // meshed boundary, so this changes nothing; for a synthesized OPEN-sketch
957    // display (edges + endpoints, no face) they are the ONLY extent there is, and
958    // an empty bbox would leave the sketch out of zoom-to-fit and out of every
959    // bbox-gated traversal.
960    for (_, _, points) in &payload.edges {
961        for point in points {
962            bbox.expand([point.x, point.y, point.z]);
963        }
964    }
965    for (_, point) in &payload.vertices {
966        bbox.expand([point.x, point.y, point.z]);
967    }
968
969    let edges = payload
970        .edges
971        .into_iter()
972        .map(|(topo_id, name, points)| EdgeDisplay {
973            name: name.unwrap_or_default(),
974            topo_id,
975            polyline: points
976                .iter()
977                .map(|p| [p.x as f32, p.y as f32, p.z as f32])
978                .collect(),
979            aux: false,
980            centerline: false,
981            color_override: None,
982            opacity: None,
983        })
984        .collect();
985
986    let vertices = payload
987        .vertices
988        .into_iter()
989        .map(|(topo_id, p)| VertexDisplay {
990            topo_id,
991            position: [p.x, p.y, p.z],
992        })
993        .collect();
994
995    SolidDisplay {
996        name: name.to_string(),
997        source_handle: 0, // set by the caller that knows the resident handle
998        visible: true,
999        color_override: None,
1000        opacity: None,
1001        model_opacity: None,
1002        revision: next_revision(),
1003        shape_revision: 0,
1004        pose: None,
1005        mesh: DisplayMesh {
1006            positions,
1007            normals,
1008            indices: mesh_in.indices,
1009            face_ids: mesh_in.face_ids,
1010        },
1011        faces,
1012        edges,
1013        vertices,
1014        visibility: crate::visibility::EntityVisibility::default(),
1015        bbox,
1016        is_sketch: false, // set by the sketch-sheet synthesizer for a committed sketch
1017        edge_color_base: None,
1018        is_sheet_metal: false, // stamped by the pipeline from the resident handle's SheetTree
1019    }
1020}