brep_render/engine_state/scene_query.rs
1use super::*;
2
3impl EngineState {
4 /// Ranked candidate list under CSS-pixel `(x, y)`, kernel names, priority
5 /// VERTEX > EDGE > FACE > … > SOLID.
6 ///
7 /// SCENE ONLY, deliberately: this R3-boundary accessor (and its
8 /// [`hover_json`](Self::hover_json) sibling) reports kernel-named GEOMETRY, and
9 /// its in-tree consumer is the sketch's external-edge picker, which wants
10 /// edges. The construction PLANE cards join the pick list one level up, in
11 /// [`pick_candidates_at`](Self::pick_candidates_at) — that is what the
12 /// selection paths and the app's pick-list popup consume.
13 pub fn pick_json(&self, x: f64, y: f64) -> String {
14 let candidates = pick::pick_unoccluded(&self.scene, &self.context_scene, &self.camera, x, y, &self.pick_options());
15 pick::candidates_to_json(&candidates)
16 }
17
18 /// The single best candidate under `(x, y)` (hover), or `null`.
19 pub fn hover_json(&self, x: f64, y: f64) -> String {
20 let candidates = pick::pick_unoccluded(&self.scene, &self.context_scene, &self.camera, x, y, &self.pick_options());
21 match candidates.first() {
22 Some(best) => pick::candidates_to_json(std::slice::from_ref(best))
23 .strip_prefix('[')
24 .and_then(|s| s.strip_suffix(']'))
25 .map(str::to_string)
26 .unwrap_or_else(|| "null".to_string()),
27 None => "null".to_string(),
28 }
29 }
30
31 // --- Settings / emphasis / visibility (R11/R14/R17) -------------------
32
33 pub fn apply_settings_json(&mut self, json: &str) -> Result<(), String> {
34 let prev_lod = self.settings.lod_factor;
35 let prev_override_model_colors = self.settings.override_model_colors;
36 let prev_wireframe = self.settings.wireframe;
37 self.settings.apply_json(json)?;
38 self.settings_generation = self.settings_generation.wrapping_add(1);
39 self.dirty = true;
40 // While a PMI view is active the wireframe on screen is that view's:
41 // toggling it is an edit of the view (one undo step), so leaving and
42 // re-entering the view keeps it, and the modeling setting comes back
43 // on exit.
44 if self.settings.wireframe != prev_wireframe {
45 if let Some(view) = self.pmi_active_view.clone() {
46 let patch = super::PmiViewPatch { wireframe: Some(self.settings.wireframe), ..Default::default() };
47 let _ = self.pmi_set_view_display(&view, &patch);
48 }
49 }
50 // "Override model colors" is resolved when colours are derived, not when
51 // they are drawn, so flipping it has to re-derive. Guarded on an actual
52 // change: this apply path also runs on every unrelated settings edit.
53 if self.settings.override_model_colors != prev_override_model_colors {
54 self.sync_colors_from_metadata();
55 }
56 // Push the (possibly changed) ViewCube size into the widget so the rendered
57 // cube AND its hit-test rect track the setting. Always re-pushed (idempotent
58 // for an unchanged value) so this ONE choke point covers panel edits, boot
59 // restore, and Reset-to-defaults alike.
60 self.widgets.set_viewcube_size(self.settings.viewcube_size_px);
61 // Projection rides in the settings JSON as `orthographic` (see `settings_json`)
62 // so the toolbar toggle AND a reload both go through this ONE apply path — the
63 // same way wireframe does. It is NOT a `RenderSettings` field: read it straight
64 // off the JSON and drive the camera. A PARTIAL apply (the wireframe toggle's
65 // `{"wireframe":true}`) omits the key and leaves the projection untouched, and
66 // the panel's full-buffer apply carries the live value (so it's a no-op).
67 if let Some(want_ortho) = serde_json::from_str::<serde_json::Value>(json)
68 .ok()
69 .and_then(|v| v.get("orthographic").and_then(|o| o.as_bool()))
70 {
71 let is_ortho = matches!(
72 self.camera.projection,
73 crate::view::Projection::Orthographic { .. }
74 );
75 if want_ortho != is_ortho {
76 self.set_projection(if want_ortho { "orthographic" } else { "perspective" });
77 }
78 }
79 // The LOD factor scales DISPLAY tessellation, so a change must re-run so the
80 // resident meshes re-tessellate at the new chord tolerance (the runner drops
81 // its reuse baseline when the lod differs). Every OTHER setting is pure
82 // render state and needs no re-run. Skip the re-run when there are no
83 // features (e.g. boot restores a saved `lodFactor` before any document is
84 // loaded): the run would be empty, and the real doc load re-runs with the
85 // lod already injected.
86 if self.settings.lod_factor != prev_lod && !self.history.is_empty() {
87 self.rerun_history();
88 }
89 // Sketch colors live in the settings too: when a sketch is being edited, push
90 // the (possibly) new palette into the live session and re-push the overlay so
91 // an edited color takes effect immediately (mirrors how a wireframe/lod change
92 // refreshes the view). Compute the palette first to avoid a split borrow.
93 if self.sketch_edit.is_some() {
94 let colors = self.settings.sketch_colors();
95 if let Some(edit) = self.sketch_edit.as_mut() {
96 edit.session.colors = colors;
97 }
98 self.refresh_sketch_overlay();
99 }
100 Ok(())
101 }
102
103 /// The FULL current settings as JSON (the round-trip counterpart of
104 /// [`apply_settings_json`](Self::apply_settings_json)): the schema-driven form seeds its widgets from
105 /// this and the storage seam persists it.
106 pub fn settings_json(&self) -> String {
107 self.settings_value().to_string()
108 }
109
110 /// [`Self::settings_json`] as a JSON value.
111 pub fn settings_value(&self) -> serde_json::Value {
112 // Projection is live CAMERA state surfaced to the settings layer as a boolean
113 // (`orthographic`) so the toolbar toggle persists and the settings panel can
114 // round-trip it without clobbering. DERIVE it from the camera here — it is
115 // never a stored `RenderSettings` field — so it can NEVER drift from the
116 // actual projection no matter which code path last changed it.
117 let mut value: serde_json::Value =
118 serde_json::from_str(&self.settings.to_json()).unwrap_or(serde_json::Value::Null);
119 if let Some(obj) = value.as_object_mut() {
120 obj.insert(
121 "orthographic".into(),
122 serde_json::Value::Bool(matches!(
123 self.camera.projection,
124 crate::view::Projection::Orthographic { .. }
125 )),
126 );
127 }
128 value
129 }
130
131 /// The current per-solid metadata color overrides as JSON —
132 /// `[{"name": "...", "override": "#rrggbb" | null, "opacity": 0..1 | null,
133 /// "edges": [{"name", "override", "opacity"}, …]}, …]`. Lets a UI list the
134 /// scene's solids with their current override so the picker reflects state.
135 pub fn solid_color_overrides_json(&self) -> String {
136 let solids: Vec<serde_json::Value> = self
137 .scene
138 .solids()
139 .iter()
140 .map(|solid| {
141 let hex = |rgb: [f32; 3]| {
142 let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
143 format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
144 };
145 let over = solid.color_override.map(hex);
146 // `opacity`: the solid's own `transparency` attribute as drawn
147 // (1 − transparency); null when the solid is opaque.
148 // `edges`: only the edges drawn in a look of their own (their
149 // `color` / `transparency` attributes), by name.
150 let edges: Vec<serde_json::Value> = solid
151 .edges
152 .iter()
153 .filter(|edge| edge.is_styled())
154 .map(|edge| serde_json::json!({ "name": edge.name, "override": edge.color_override.map(hex), "opacity": edge.opacity }))
155 .collect();
156 serde_json::json!({ "name": solid.name, "override": over, "opacity": solid.model_opacity, "edges": edges })
157 })
158 .collect();
159 serde_json::Value::Array(solids).to_string()
160 }
161
162 pub fn apply_emphasis_json(&mut self, json: &str) -> Result<(), String> {
163 self.emphasis.apply_json(json)?;
164 self.dirty = true;
165 Ok(())
166 }
167
168 /// Show or hide the scene object `name`. A committed SKETCH has one
169 /// visibility, `hidden_sketches` (the Scene checkbox's): its sheet solid's
170 /// own flag is rebuilt away by every refresh, so a sketch name goes through
171 /// [`Self::set_sketch_visible`] whichever path asked (context-bar Hide,
172 /// MCP `set_visible`, a Scene "all" toggle). False for an unknown name.
173 ///
174 /// While a PMI view is active, hiding or showing a solid is an edit of
175 /// that view's hide steps (`Self::pmi_record_visibility`), never a
176 /// live-only change the next exit or re-entry would lose.
177 pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
178 self.set_visible_many(&[name.to_string()], visible) > 0
179 }
180
181 /// [`Self::set_visible`] for several names at once — a BOM row or a
182 /// component standing for many solids — so an active view records ONE
183 /// hide step (one undo) for them all. How many names were known.
184 pub fn set_visible_many(&mut self, names: &[String], visible: bool) -> usize {
185 let mut known = 0usize;
186 let mut solids: Vec<String> = Vec::new();
187 for name in names {
188 if self.is_committed_sketch_name(name) {
189 if self.sketch_visible(name) != visible {
190 self.set_sketch_visible(name, visible);
191 }
192 known += 1;
193 } else if self.scene.solid(name).is_some() {
194 known += 1;
195 solids.push(name.clone());
196 }
197 }
198 if solids.is_empty() {
199 return known;
200 }
201 if let Some(view) = self.pmi_active_view.clone() {
202 self.pmi_record_visibility(&view, &solids, visible);
203 return known;
204 }
205 for name in &solids {
206 self.set_solid_visible_live(name, visible);
207 }
208 known
209 }
210
211 /// The modeling (no active view) half of [`Self::set_visible_many`].
212 fn set_solid_visible_live(&mut self, name: &str, visible: bool) -> bool {
213 let ok = self.scene.set_visible(name, visible);
214 if ok {
215 // A derived BOARD body is dropped by every run's scene reconcile
216 // and re-seated from the KEPT display, so the hide has to reach
217 // that copy or it lasts only until the next feature edit.
218 self.remember_board_visibility(name, visible);
219 // The user's hide or show outlasts the active view's poses and
220 // section: the un-posed original carries it (sheets read it, the
221 // restore writes it back), and the section no longer owns it.
222 if let Some(original) = self.pmi_explode_originals.get_mut(name).filter(|original| original.visible != visible) {
223 original.visible = visible;
224 self.pmi_unposed_visibility += 1;
225 }
226 self.pmi_section_hidden.retain(|hidden| hidden != name);
227 self.dirty = true;
228 // A balloon on this body loses or regains its leader at once.
229 if self.pmi_active_view.is_some() {
230 self.refresh_pmi_overlay();
231 }
232 }
233 ok
234 }
235
236 pub fn scene_listing_json(&self) -> String {
237 self.scene.listing_json()
238 }
239
240 // --- Overlay widgets --------------------------------------------------
241
242 /// The BASE bbox the camera depth-range fit starts from: the visible SOLIDS
243 /// unioned with the pushed OVERLAY groups (sketch curves/points, dimension
244 /// leaders, constraint glyphs — the `set_overlay` channel). Folding in the
245 /// groups stops orbiting an editing sketch from clipping it against the
246 /// solids-only bounds (the reported clipping when "Lock to sketch" is off).
247 /// The render path ([`Self::fit_camera_and_overlay`]) unions the FULL widget
248 /// overlay's world bounds (datum planes, world axes, frames, transform
249 /// gizmo — NOT in this bbox's channels) and the world origin on top of this
250 /// before fitting, so construction geometry never clips. Callers must bind
251 /// this to a local before `camera.fit_depth_range` (which needs
252 /// `&mut self.camera`).
253 pub fn depth_range_bbox(&self) -> crate::camera::Aabb {
254 let mut bbox = self.scene.bbox();
255 bbox.union(&self.context_scene.bbox());
256 bbox.union(&self.widgets.overlay_groups_bbox());
257 bbox
258 }
259
260}
261
262impl EngineState {
263 /// A RICHER scene listing than [`scene_listing_json`](Self::scene_listing_json)
264 /// (which is counts only): per solid the individual face + edge kernel NAMES
265 /// and vertex refs (topo id + world position), plus visibility — the shape the
266 /// engine-native Scene tree lists entities from and the headed verifier asserts
267 /// against. Vertices carry no kernel name, so they are keyed by topo id + world
268 /// position (the same shape the emphasis vertex-ref selection uses).
269 pub fn scene_entities_json(&self) -> String {
270 let solids: Vec<serde_json::Value> = self
271 .scene
272 .solids()
273 .iter()
274 // Committed-sketch SHEETS are scene solids (pickable/measurable) but list
275 // under "Sketches" (`committed_sketches`), not among the real solids.
276 .filter(|solid| !solid.is_sketch)
277 .map(|solid| {
278 let faces: Vec<&str> = solid.faces.iter().map(|f| f.name.as_str()).collect();
279 // Display-only (aux) edges are not entities: a board's copper
280 // outline would list thousands of unnamed ones.
281 let edges: Vec<&str> = solid.edges.iter().filter(|e| !e.aux).map(|e| e.name.as_str()).collect();
282 let vertices: Vec<serde_json::Value> = solid
283 .vertices
284 .iter()
285 .map(|v| serde_json::json!({ "topoId": v.topo_id, "position": v.position }))
286 .collect();
287 serde_json::json!({
288 "name": solid.name,
289 "visible": solid.visible,
290 "faces": faces,
291 "edges": edges,
292 "vertices": vertices,
293 })
294 })
295 .collect();
296 serde_json::Value::Array(solids).to_string()
297 }
298
299 /// Drive the engine SELECTION by kernel NAME from a UI tree (the name-based
300 /// analogue of [`select_top_at`](Self::select_top_at), which picks under the
301 /// cursor). Replaces the current selection with the single named `solid` /
302 /// `face` / `edge` so clicking a Scene-tree row highlights that entity in the
303 /// viewport (the render pass reads `emphasis`). Vertices have no kernel name —
304 /// use [`select_vertex_by_position`](Self::select_vertex_by_position). Returns
305 /// false for an unknown `kind` or an empty `name`.
306 pub fn select_by_name(&mut self, kind: &str, name: &str) -> bool {
307 // A construction datum/plane routes to its own name-keyed selection.
308 if kind == "datum" {
309 return self.select_datum(name);
310 }
311 if name.is_empty() || !matches!(kind, "solid" | "face" | "edge") {
312 return false;
313 }
314 let had_datum = !self.emphasis.selected_datums.is_empty();
315 self.emphasis.selected_solids.clear();
316 self.emphasis.selected_faces.clear();
317 self.emphasis.selected_edges.clear();
318 self.emphasis.selected_vertices.clear();
319 self.emphasis.selected_datums.clear();
320 match kind {
321 "solid" => {
322 self.emphasis.selected_solids.insert(name.to_string());
323 }
324 "face" => {
325 self.emphasis.selected_faces.insert(name.to_string());
326 }
327 "edge" => {
328 self.emphasis.selected_edges.insert(name.to_string());
329 }
330 _ => unreachable!(),
331 }
332 self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
333 self.dirty = true;
334 if had_datum {
335 self.refresh_construction_datums();
336 }
337 true
338 }
339
340 /// Select a single vertex by its owning solid + world position — vertices have
341 /// no kernel name, so emphasis keys them by solid + position (matched with a
342 /// tolerance in the render pass). Replaces the current selection. Returns false
343 /// for an empty solid name.
344 pub fn select_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
345 if solid.is_empty() {
346 return false;
347 }
348 let had_datum = !self.emphasis.selected_datums.is_empty();
349 self.emphasis.selected_solids.clear();
350 self.emphasis.selected_faces.clear();
351 self.emphasis.selected_edges.clear();
352 self.emphasis.selected_vertices.clear();
353 self.emphasis.selected_datums.clear();
354 self.emphasis.selected_vertices.push(crate::style::VertexRef {
355 solid: solid.to_string(),
356 position,
357 });
358 self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
359 self.dirty = true;
360 if had_datum {
361 self.refresh_construction_datums();
362 }
363 true
364 }
365
366 // -----------------------------------------------------------------------
367 // Scene-tree row HOVER → the viewport hover highlight
368 //
369 // The hover twin of the name-based selection above: mousing over a Scene-tree
370 // row lights the entity EXACTLY as mousing over it in the 3D view does,
371 // because it feeds the SAME `emphasis` hover buckets through the SAME
372 // `hover_candidate` bucketing the viewport's `hover_at` uses (so a hovered
373 // datum plane gets its accent re-feed, a solid lights whole, and the render
374 // pass needs no new concept). The pointer is off the viewport while it is over
375 // a row, so the viewport's pointer-left-the-viewport `clear_hover` would
376 // otherwise wipe it every frame — hence the one-frame yield flag, the twin of
377 // `take_sketch_list_hover` / `take_constraint_label_hover`.
378 // -----------------------------------------------------------------------
379
380 /// Hover-highlight by kernel NAME from a UI tree — the hover twin of
381 /// [`select_by_name`](Self::select_by_name) (`kind` is `"solid"` / `"face"` /
382 /// `"edge"` / `"datum"`; vertices carry no kernel name, so they use
383 /// [`hover_vertex_by_position`](Self::hover_vertex_by_position)).
384 ///
385 /// Deliberately does NOT consult the selection filter, matching the row's
386 /// CLICK: a row selects whatever kind it is, so its hover previews the same
387 /// entity. An unknown `kind`, an empty `name` or an unresolved datum frame is
388 /// refused without touching the current hover.
389 ///
390 /// Call it EVERY frame the row is hovered: it re-arms the one-frame
391 /// [`take_scene_tree_hover`](Self::take_scene_tree_hover) yield flag and
392 /// re-lights nothing when the hover is already this entity. Returns whether
393 /// the hover CHANGED (the [`hover_at`](Self::hover_at) convention) so the
394 /// caller can request a repaint.
395 pub fn hover_by_name(&mut self, kind: &str, name: &str) -> bool {
396 if name.is_empty() {
397 return false;
398 }
399 let pick_kind = match kind {
400 "solid" => pick::PickKind::Solid,
401 "face" => pick::PickKind::Face,
402 "edge" => pick::PickKind::Edge,
403 // A construction datum/plane hovers by FRAME name — the bucket
404 // `select_datum` and the viewport's plane picks fill.
405 "datum" => pick::PickKind::Plane,
406 _ => return false,
407 };
408 let candidate = pick::PickCandidate {
409 kind: pick_kind,
410 name: name.to_string(),
411 // A SOLID candidate resolves through `candidate_solid_name`, which
412 // prefers `solid` — and this row IS the solid.
413 solid: match pick_kind {
414 pick::PickKind::Solid => name.to_string(),
415 _ => String::new(),
416 },
417 depth: 0.0,
418 screen_dist: 0.0,
419 position: [0.0; 3],
420 };
421 self.set_scene_tree_hover(candidate)
422 }
423
424 /// Hover a single vertex by its owning solid + world position — the hover twin
425 /// of [`select_vertex_by_position`](Self::select_vertex_by_position) (vertices
426 /// have no kernel name, so emphasis keys them by solid + position). Same
427 /// per-frame contract and return as [`hover_by_name`](Self::hover_by_name).
428 pub fn hover_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
429 if solid.is_empty() {
430 return false;
431 }
432 self.set_scene_tree_hover(pick::PickCandidate {
433 kind: pick::PickKind::Vertex,
434 // Vertices are unnamed: `solid` + `position` is the identity.
435 name: String::new(),
436 solid: solid.to_string(),
437 depth: 0.0,
438 screen_dist: 0.0,
439 position,
440 })
441 }
442
443 /// The pointer left the Scene tree's rows: drop the row-driven highlight.
444 /// Clears ONLY a hover the tree itself lit and that is STILL lit — if the
445 /// viewport has since hovered something else (it may draw before the panel in
446 /// the dock), that hover is left alone. Safe to call every frame no row is
447 /// hovered: the target is taken, so it is a no-op from the second call on.
448 /// Returns whether the hover changed.
449 pub fn scene_tree_hover_end(&mut self) -> bool {
450 match self.scene_tree_hovered.take() {
451 Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
452 _ => false,
453 }
454 }
455
456 /// Consume the one-frame "a Scene-tree row is hovering an entity" flag — the
457 /// viewport's modeling hover branch skips its pointer-off-viewport
458 /// `clear_hover` while it is set (mirrors
459 /// [`take_sketch_list_hover`](Self::take_sketch_list_hover)) so the row-driven
460 /// highlight survives the frame instead of being cleared and re-applied.
461 pub fn take_scene_tree_hover(&mut self) -> bool {
462 std::mem::take(&mut self.scene_tree_hover_active)
463 }
464
465 /// Light one Scene-tree row's candidate: arm the yield flag (every frame — the
466 /// viewport consumes it every frame), record the target so
467 /// [`scene_tree_hover_end`](Self::scene_tree_hover_end) knows what the tree
468 /// lit, and re-emphasize only when the hover actually changed (a held row must
469 /// not re-bump the emphasis generation / re-feed the datums every frame).
470 fn set_scene_tree_hover(&mut self, candidate: pick::PickCandidate) -> bool {
471 self.scene_tree_hover_active = true;
472 match self.apply_ui_hover(&candidate) {
473 // Refused (an unresolved datum frame): nothing lit, so the tree records
474 // no target and has nothing to end.
475 None => false,
476 Some(changed) => {
477 // Recorded even when unchanged: the viewport may have lit the
478 // identical entity, and the tree still owns ending it.
479 self.scene_tree_hovered = Some(candidate);
480 changed
481 }
482 }
483 }
484
485 /// Apply ONE UI-driven hover candidate to the emphasis — the shared body
486 /// behind every list→viewport highlight (the Scene tree's rows, the dialog
487 /// rows below). `None` = REFUSED, `Some(changed)` = applied, and `changed`
488 /// says whether the hover actually moved (a held row must not re-bump the
489 /// emphasis generation / re-feed the datums every frame).
490 ///
491 /// Each caller records its OWN target: that is what keeps two panes' `_end`
492 /// calls from ending each other's highlight.
493 fn apply_ui_hover(&mut self, candidate: &pick::PickCandidate) -> Option<bool> {
494 if self.hover_is(candidate) {
495 return Some(false);
496 }
497 // Only a RESOLVED datum frame hovers (the `select_datum` guard); an
498 // unresolved name would light nothing and churn the datum feed. Checked on
499 // the change path only — the dedupe above carries the held frames.
500 if candidate.kind == pick::PickKind::Plane
501 && !self.construction_frames.iter().any(|(n, _)| *n == candidate.name)
502 {
503 return None;
504 }
505 self.hover_candidate(candidate);
506 Some(true)
507 }
508}
509
510// ---------------------------------------------------------------------------
511// DIALOG row HOVER → the viewport hover highlight
512//
513// The Scene tree knows the KIND of every row it draws; a dialog does not. A
514// feature form's reference line, its read-only `Outputs` line and the picker
515// card's picked-name line all carry a bare kernel NAME, so this lane resolves the
516// kind from the scene itself and then feeds the SAME hover buckets the tree and
517// the viewport's `hover_at` fill.
518// ---------------------------------------------------------------------------
519impl EngineState {
520 /// Hover-highlight the entity a DIALOG row names — the kind-less twin of
521 /// [`hover_by_name`](Self::hover_by_name), for the lists that show a bare
522 /// kernel name (a reference line, an `Outputs` line, the picker card).
523 ///
524 /// `owner` is the pane that is hovering (`"history"`, `"constraints"`,
525 /// `"pmi"`, `"refsel"`): [`dialog_hover_end`](Self::dialog_hover_end) acts
526 /// only for the owner that set the hover, so panes that are on screen together
527 /// in a split dock cannot end each other's highlight.
528 ///
529 /// The name is resolved by `resolve_entity_name`,
530 /// which also covers the row whose entity the feature CONSUMED — an open
531 /// fillet form is rolled to the fillet, so its `Edges` rows name edges that no
532 /// longer exist and the blend faces the kernel built from them are lit
533 /// instead. Call it EVERY frame the row is hovered: the resolution is memoized
534 /// on the row text and the emphasis re-feed is deduped, so a held hover costs
535 /// nothing. Returns whether the hover CHANGED (the
536 /// [`hover_at`](Self::hover_at) convention), so the caller can repaint.
537 pub fn hover_entity_by_name(&mut self, owner: &'static str, name: &str) -> bool {
538 if name.is_empty() {
539 return false;
540 }
541 // Armed even for a row that resolves to nothing: the pointer is over the
542 // dialog, so the viewport's pointer-left-the-viewport `clear_hover` must
543 // still yield — otherwise moving along a list of rows would strobe the
544 // highlight off on every unresolvable one.
545 self.dialog_hover_active = true;
546 let memo = match &self.dialog_hovered {
547 Some(held) if held.owner == owner && held.row == name => Some(held.candidate.clone()),
548 _ => None,
549 };
550 let candidate = match memo {
551 Some(cached) => cached,
552 None => self.resolve_entity_name(name),
553 };
554 let applied = match &candidate {
555 Some(c) => self.apply_ui_hover(c),
556 None => None,
557 };
558 let changed = match applied {
559 Some(changed) => changed,
560 // Nothing to light (the scene carries no such name, or the candidate
561 // was refused): end whatever the slot holds — WHOEVER set it. Leaving
562 // the previous row's entity standing while the pointer sits on a
563 // different row reads as "this row is that entity", and the previous
564 // row is not always this owner's: moving from a History line straight
565 // onto an unresolvable Constraints one (a component-local vertex ref)
566 // would otherwise strand the History highlight with nobody left
567 // holding the record that could end it.
568 None => self.take_dialog_hover_slot(),
569 };
570 self.dialog_hovered = Some(super::DialogHover {
571 owner,
572 row: name.to_string(),
573 candidate,
574 });
575 changed
576 }
577
578 /// The pointer left `owner`'s dialog rows: drop the row-driven highlight.
579 /// Clears ONLY a hover THIS owner lit and that is STILL lit — a pane that
580 /// never hovered a row (or whose hover the viewport has since replaced) is a
581 /// no-op, which is what lets every consumer call it unconditionally every
582 /// frame. Returns whether the hover changed.
583 pub fn dialog_hover_end(&mut self, owner: &'static str) -> bool {
584 let mine = matches!(&self.dialog_hovered, Some(held) if held.owner == owner);
585 if mine {
586 self.take_dialog_hover_slot()
587 } else {
588 false
589 }
590 }
591
592 /// Take the dialog-hover slot and drop the highlight it recorded, when that
593 /// highlight is still the live one (the viewport may have replaced it since).
594 /// Owner-AGNOSTIC: [`dialog_hover_end`](Self::dialog_hover_end) checks the
595 /// owner before calling this, while a row that lights nothing calls it
596 /// directly — the pointer is on THAT row now, so whatever the slot still
597 /// records is stale whoever set it.
598 fn take_dialog_hover_slot(&mut self) -> bool {
599 match self.dialog_hovered.take() {
600 Some(held) => match held.candidate {
601 Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
602 _ => false,
603 },
604 None => false,
605 }
606 }
607
608 /// Consume the one-frame "a dialog row is hovering an entity" flag — the
609 /// viewport's modeling hover branch skips its pointer-off-viewport
610 /// `clear_hover` while it is set (the twin of
611 /// [`take_scene_tree_hover`](Self::take_scene_tree_hover)).
612 pub fn take_dialog_hover(&mut self) -> bool {
613 std::mem::take(&mut self.dialog_hover_active)
614 }
615
616 /// Resolve one bare kernel NAME to the entity it addresses, or `None` when the
617 /// scene carries nothing by that name.
618 ///
619 /// Order — most specific identity first: a SOLID (a shown committed sketch is
620 /// a scene solid keyed by its sketch id — `refresh_committed_sketches` inserts
621 /// the sheet under the feature id an extrude's `profile` stores — so a
622 /// `SKETCH` reference lands here whenever that sheet is shown), a
623 /// construction datum FRAME, a FACE, an EDGE, then a `{solid}@x,y,z` VERTEX
624 /// ref (the position-keyed form assembly constraints and PMI store, accepted
625 /// only when it really is a vertex of that solid — a component-LOCAL ref lights
626 /// nothing rather than lighting the wrong vertex).
627 ///
628 /// # The consumed row
629 ///
630 /// A feature's form is drawn with the model rolled TO that feature, so the
631 /// feature has RUN and the entities its references name are gone: a fillet's
632 /// `Edges` rows name edges the blend replaced. The kernel names what it builds
633 /// after what it consumed — `{featureId}:BLEND:{originatingEdgeName}`, asserted
634 /// by the kernel's own `fillet_by_face_ref_rounds_the_top_ring` /
635 /// `chamfer` naming tests — so a row that resolves to nothing falls back to the
636 /// FACE whose name ends with `:{row}`: the thing the feature made from it.
637 /// Only when EXACTLY ONE face matches, so an ambiguous mapping lights nothing
638 /// rather than an arbitrary half of it. Ends-with, never `contains`: the edges
639 /// bounding that blend are named `BOX_NZ|F1:BLEND:BOX_NX|BOX_NZ[0][0]`, which
640 /// CONTAINS the row but is not what it became.
641 fn resolve_entity_name(&self, name: &str) -> Option<pick::PickCandidate> {
642 let at = |kind: pick::PickKind, entity: &str, solid: &str| pick::PickCandidate {
643 kind,
644 name: entity.to_string(),
645 solid: solid.to_string(),
646 depth: 0.0,
647 screen_dist: 0.0,
648 position: [0.0; 3],
649 };
650 let solids = self.scene.solids();
651 if solids.iter().any(|s| s.name == name) {
652 // A SOLID candidate resolves through `candidate_solid_name`, which
653 // prefers `solid` — and this row IS the solid.
654 return Some(at(pick::PickKind::Solid, name, name));
655 }
656 if self.construction_frames.iter().any(|(n, _)| n.as_str() == name) {
657 return Some(at(pick::PickKind::Plane, name, ""));
658 }
659 for solid in solids {
660 if solid.faces.iter().any(|f| f.name == name) {
661 return Some(at(pick::PickKind::Face, name, &solid.name));
662 }
663 }
664 for solid in solids {
665 if solid.edges.iter().any(|e| e.name == name) {
666 return Some(at(pick::PickKind::Edge, name, &solid.name));
667 }
668 }
669 if let Some(candidate) = self.resolve_vertex_ref(name) {
670 return Some(candidate);
671 }
672 let suffix = format!(":{name}");
673 let mut derived = solids
674 .iter()
675 .flat_map(|solid| solid.faces.iter().map(move |face| (solid, face)))
676 .filter(|(_, face)| face.name.ends_with(&suffix));
677 match (derived.next(), derived.next()) {
678 (Some((solid, face)), None) => {
679 Some(at(pick::PickKind::Face, &face.name, &solid.name))
680 }
681 _ => None,
682 }
683 }
684
685 /// A `{solid}@x,y,z` VERTEX reference → its candidate, when the position
686 /// really is a vertex of that solid within the emphasis match tolerance.
687 /// Vertices carry no kernel name, so this is the only form a dialog can list
688 /// one under; PMI stores WORLD coordinates (which resolve here), assembly
689 /// constraints store component-LOCAL ones (which do not, and so light nothing
690 /// rather than the wrong vertex).
691 fn resolve_vertex_ref(&self, name: &str) -> Option<pick::PickCandidate> {
692 /// The tolerance the render pass matches an emphasis vertex ref at.
693 const TOL: f64 = 1e-4;
694 let (solid_name, coords) = name.rsplit_once('@')?;
695 let mut parts = coords.split(',').map(|p| p.trim().parse::<f64>().ok());
696 let position = [parts.next()??, parts.next()??, parts.next()??];
697 if parts.next().is_some() {
698 return None;
699 }
700 let solid = self.scene.solids().iter().find(|s| s.name == solid_name)?;
701 solid.vertices.iter().find(|v| {
702 (v.position[0] - position[0]).abs() <= TOL
703 && (v.position[1] - position[1]).abs() <= TOL
704 && (v.position[2] - position[2]).abs() <= TOL
705 })?;
706 Some(pick::PickCandidate {
707 kind: pick::PickKind::Vertex,
708 name: String::new(),
709 solid: solid_name.to_string(),
710 depth: 0.0,
711 screen_dist: 0.0,
712 position,
713 })
714 }
715}
716
717
718impl EngineState {
719 /// The resident kernel handle of every solid currently displayed, keyed by
720 /// name. Obtained by replaying the CURRENT rolled-to history prefix through
721 /// [`brep_kernel::execute_history`]: after a build the incremental cache
722 /// holds exactly this prefix, so the replay is a clean cache hit — it
723 /// re-tessellates nothing and hands back the SAME handles the scene was built
724 /// from (mirrors the pipeline's `fold_history`: removals then additions).
725 /// `pub(super)`: the interference check (`engine_state::interference`) reads
726 /// the same warm main-side handle map for its non-destructive booleans.
727 pub(super) fn resident_solid_handles(&self) -> HashMap<String, u32> {
728 let request: HistoryRequest = match serde_json::from_value(self.run_request_value()) {
729 Ok(request) => request,
730 Err(_) => return HashMap::new(),
731 };
732 let _trace = crate::run_trace::span("resident_solid_handles");
733 let result = self.execute_plugin_history(&request);
734 let mut handles: HashMap<String, u32> = HashMap::new();
735 for feature in &result.results {
736 for removed in &feature.removed {
737 handles.remove(removed);
738 }
739 for added in &feature.added {
740 handles.insert(added.name.clone(), added.handle);
741 }
742 }
743 handles
744 }
745
746 /// Mass properties for the Inspector panel, from the kernel's exact
747 /// (divergence-theorem) integrator. `name = Some(solid)` reports that resident
748 /// solid; `None` reports the whole model. `density` (mass units per mm³; the
749 /// kernel length convention is millimetres) scales `mass` and the inertia
750 /// tensor — the centroid and principal axes are density-independent.
751 ///
752 /// Returns JSON:
753 /// ```json
754 /// { "ok": true, "target": "Box", "solidCount": 1, "density": 1.0,
755 /// "volume": 5738.05, "surfaceArea": 2927.79, "mass": 5738.05,
756 /// "centroid": [10.0, 10.0, 10.0],
757 /// "inertia": [[..],[..],[..]] | null,
758 /// "principalMoments": [a,b,c] | null,
759 /// "principalAxes": [[..],[..],[..]] | null }
760 /// ```
761 /// A single resolved solid carries the full centroidal inertia tensor +
762 /// principal axes/moments; a multi-solid aggregate reports summed volume /
763 /// area / mass and the volume-weighted centroid, with the tensor fields
764 /// `null` (select one solid for its inertia). `ok:false` with a `message` on
765 /// no solids / an unknown name / an integrator failure.
766 /// The model summary an agent checks a build against: every scene solid
767 /// with resident geometry, each with its kernel validation (topology
768 /// incidence checks; an `error` issue makes it invalid), its exact volume
769 /// and its display bounds (the mesh's world box, which edges lie on).
770 /// `valid` is true only when every solid validated and measured; an empty
771 /// model is valid with no solids, `bounds` and `volume` null. Numbers the
772 /// kernel could not give are null with a warning naming the solid.
773 ///
774 /// The checks run on the RUNNER, against its warm registry, as
775 /// measurement queries ([`crate::runner::MeasureKind::Inspect`]): `None`
776 /// while any is still in flight (call again on a later frame). A
777 /// main-thread re-execution of the history — what a resident-handle
778 /// collection here would cost — replayed a 27 MB STEP import on the frame
779 /// thread for 157 s (2026-10-28).
780 pub fn model_inspect_poll(&mut self) -> Option<serde_json::Value> {
781 let names: Vec<String> = self.scene.solids().iter().filter(|s| !s.is_sketch).map(|s| s.name.clone()).collect();
782 let key = |name: &str| format!("\u{1}inspect:{name}");
783 for name in &names {
784 let k = key(name);
785 if !self.info_cache.contains_key(&k) && !self.pending_query.values().any(|p| *p == k) {
786 self.next_query_id += 1;
787 let id = self.next_query_id;
788 self.pending_query.insert(id, k);
789 self.runner.submit_query(crate::runner::MeasureQuery {
790 id,
791 kind: crate::runner::MeasureKind::Inspect,
792 owner: name.clone(),
793 entity: name.clone(),
794 density: 1.0,
795 });
796 }
797 }
798 self.pump_queries();
799 if names.iter().any(|n| !self.info_cache.contains_key(&key(n))) {
800 return None;
801 }
802 let mut solids = Vec::new();
803 let mut warnings = Vec::new();
804 let mut valid = true;
805 let mut total_volume = Some(0.0f64);
806 let mut bounds: Option<([f64; 3], [f64; 3])> = None;
807 for solid in self.scene.solids().iter().filter(|s| !s.is_sketch) {
808 let reply: serde_json::Value = serde_json::from_str(&self.info_cache[&key(&solid.name)]).unwrap_or_default();
809 if reply["ok"] != true {
810 // No resident geometry: not a solid of the model the kernel holds.
811 continue;
812 }
813 let issues = reply["issues"].as_array().cloned().unwrap_or_default();
814 let solid_valid = !issues.iter().any(|i| i["severity"].as_str().is_some_and(|s| s.eq_ignore_ascii_case("error")));
815 let volume = reply["volume"].as_f64();
816 if let Some(error) = reply["volumeError"].as_str() {
817 warnings.push(format!("{}: volume unavailable: {error}", solid.name));
818 }
819 valid &= solid_valid && volume.is_some();
820 total_volume = total_volume.zip(volume).map(|(a, b)| a + b);
821 let (min, max) = (solid.bbox.min, solid.bbox.max);
822 bounds = Some(match bounds {
823 None => (min, max),
824 Some((lo, hi)) => (std::array::from_fn(|i| lo[i].min(min[i])), std::array::from_fn(|i| hi[i].max(max[i]))),
825 });
826 solids.push(serde_json::json!({
827 "name": solid.name,
828 "valid": solid_valid,
829 "issues": issues,
830 "volumeMm3": volume,
831 "boundsMm": { "min": min, "max": max },
832 }));
833 }
834 let vec3 = |v: [f64; 3]| serde_json::json!({ "x": v[0], "y": v[1], "z": v[2] });
835 Some(serde_json::json!({
836 "solidCount": solids.len(),
837 "valid": valid,
838 "boundsMm": bounds.map(|(lo, hi)| serde_json::json!({ "min": vec3(lo), "max": vec3(hi) })),
839 "volumeMm3": if solids.is_empty() { None } else { total_volume },
840 "warnings": warnings,
841 "solids": solids,
842 }))
843 }
844
845 /// The weld list: every weld feature in the history with its kind, its
846 /// size and run texts (as its weld symbol states them), its seam's length,
847 /// and its weld metal: how many bodies, their volume and their mass (each
848 /// bead's own density, the default where it has none). For BOM and
849 /// instructions, and the `weld_list` command. Only the weld's own bead
850 /// bodies count (`{id}`, `{id}:Bead{n}`): a prepared groove's cut parts
851 /// are the parts', not weld metal.
852 pub fn weld_list_json(&self) -> String {
853 let handles = self.resident_solid_handles();
854 let mut rows = Vec::new();
855 let (mut total_volume, mut total_mass) = (0.0_f64, 0.0_f64);
856 let env = brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator()).ok();
857 for index in 0..self.history_len() {
858 let Some(kind) = self.feature_type_at(index) else { continue };
859 if !brep_kernel::is_weld_type(&kind) { continue; }
860 let Some(id) = self.feature_id_at(index) else { continue };
861 let params: serde_json::Value = serde_json::from_str(&self.feature_params_json(index)).unwrap_or_default();
862 use brep_kernel::feature_pipeline::pmi::weld_symbol as symbols;
863 // The seam's length: its published path, measured along the curves.
864 let seam = format!("{id}:Seam");
865 let length: f64 = self.sketch_paths.iter().filter(|(name, _)| *name == seam).map(|(_, curves)| symbols::path_length(curves)).sum();
866 // Expressions read as the history reads them.
867 let evaluate = |source: &str| env.as_ref().and_then(|env| env.eval(source).ok());
868 let segments = symbols::segments(&kind, ¶ms, length, &evaluate);
869 let symbol = symbols::WeldSymbol::from_params(&serde_json::json!({}), &kind, ¶ms, &evaluate, segments).ok().flatten();
870 let number = |key: &str| params.get(key).and_then(serde_json::Value::as_f64);
871 let size = match &symbol {
872 Some(symbol) => symbol.size.clone(),
873 None => number(if kind == "WELD.EDGE" { "reinforcement" } else { "size" }).map(|v| v.to_string()).unwrap_or_default(),
874 };
875 let mut bodies: Vec<&String> = handles.keys()
876 .filter(|name| **name == id || name.strip_prefix(id.as_str()).is_some_and(|rest| rest.starts_with(":Bead")))
877 .collect();
878 bodies.sort();
879 let (mut volume, mut mass) = (0.0, 0.0);
880 for body in &bodies {
881 let density = self.metadata.density(body);
882 if let Ok(properties) = brep_kernel::mass_properties_handle_native(handles[*body], density) {
883 volume += properties.volume.abs();
884 mass += properties.mass.abs();
885 }
886 }
887 total_volume += volume;
888 total_mass += mass;
889 rows.push(serde_json::json!({
890 "id": id,
891 "type": kind,
892 "name": crate::features::feature_plain_name(&kind),
893 "size": size,
894 "run": symbol.as_ref().map(|symbol| symbol.length.clone()).unwrap_or_default(),
895 "seamLength": length,
896 "bodies": bodies.len(),
897 "volume": volume,
898 "mass": mass,
899 }));
900 }
901 serde_json::json!({ "welds": rows, "volume": total_volume, "mass": total_mass }).to_string()
902 }
903
904 /// The solids a mass read measures, with their resident handles: a named solid (must be resident) or, for
905 /// the whole model, every scene solid that has resident geometry (draw order). `Err` is the reply's message.
906 fn mass_targets(&self, name: Option<&str>) -> Result<(HashMap<String, u32>, Vec<String>), String> {
907 let handles = self.resident_solid_handles();
908 let targets: Vec<String> = match name {
909 Some(name) if handles.contains_key(name) => vec![name.to_string()],
910 Some(name) => return Err(format!("solid '{name}' has no resident geometry")),
911 None => self
912 .scene
913 .solids()
914 .iter()
915 .map(|solid| solid.name.clone())
916 .filter(|name| handles.contains_key(name))
917 .collect(),
918 };
919 if targets.is_empty() {
920 return Err("no solids".to_string());
921 }
922 Ok((handles, targets))
923 }
924
925 /// Volume and surface area only, of one solid or (summed) of all: the first sweep of
926 /// [`Self::mass_properties_json`] without the second-moment sweep, which costs as much again. Both
927 /// numbers are bit-identical to that reply's `volume` and `surfaceArea`.
928 pub fn volume_json(&self, name: Option<&str>) -> String {
929 let (handles, targets) = match self.mass_targets(name) {
930 Ok(found) => found,
931 Err(message) => return serde_json::json!({ "ok": false, "message": message }).to_string(),
932 };
933 let (mut volume, mut surface_area) = (0.0, 0.0);
934 for target in &targets {
935 match brep_kernel::mass_measures_handle_native(handles[target]) {
936 Ok(properties) => {
937 volume += properties.volume;
938 surface_area += properties.surface_area;
939 }
940 Err(error) => {
941 return serde_json::json!({ "ok": false, "message": format!("{target}: {error}") }).to_string();
942 }
943 }
944 }
945 let target = if targets.len() == 1 { targets[0].clone() } else { "(whole model)".to_string() };
946 serde_json::json!({
947 "ok": true,
948 "target": target,
949 "solidCount": targets.len(),
950 "volume": volume,
951 "surfaceArea": surface_area,
952 })
953 .to_string()
954 }
955
956 pub fn mass_properties_json(&self, name: Option<&str>, density: f64) -> String {
957 let (handles, targets) = match self.mass_targets(name) {
958 Ok(found) => found,
959 Err(message) => return serde_json::json!({ "ok": false, "message": message }).to_string(),
960 };
961
962 // Per-solid density mass properties straight from the kernel.
963 let mut props = Vec::with_capacity(targets.len());
964 for target in &targets {
965 match brep_kernel::mass_properties_handle_native(handles[target], density) {
966 Ok(properties) => props.push(properties),
967 Err(error) => {
968 return serde_json::json!({
969 "ok": false,
970 "message": format!("{target}: {error}"),
971 })
972 .to_string();
973 }
974 }
975 }
976
977 let target_label = if targets.len() == 1 {
978 targets[0].clone()
979 } else {
980 "(whole model)".to_string()
981 };
982
983 if props.len() == 1 {
984 // Single solid: the full tensor + principal frame are meaningful.
985 let p = &props[0];
986 serde_json::json!({
987 "ok": true,
988 "target": target_label,
989 "solidCount": 1,
990 "density": p.density,
991 "volume": p.volume,
992 "surfaceArea": p.surface_area,
993 "mass": p.mass,
994 "centroid": [p.centroid.x, p.centroid.y, p.centroid.z],
995 "inertia": p.inertia,
996 "principalMoments": p.principal_moments,
997 "principalAxes": p.principal_axes,
998 })
999 .to_string()
1000 } else {
1001 // Aggregate: additive scalars + volume-weighted centroid. Combining
1002 // the tensors needs a parallel-axis shift per solid; left to the
1003 // single-solid view rather than approximated here.
1004 let volume: f64 = props.iter().map(|p| p.volume).sum();
1005 let surface_area: f64 = props.iter().map(|p| p.surface_area).sum();
1006 let mass: f64 = props.iter().map(|p| p.mass).sum();
1007 let centroid = if volume.abs() > f64::EPSILON {
1008 let mut acc = [0.0f64; 3];
1009 for p in &props {
1010 acc[0] += p.volume * p.centroid.x;
1011 acc[1] += p.volume * p.centroid.y;
1012 acc[2] += p.volume * p.centroid.z;
1013 }
1014 [acc[0] / volume, acc[1] / volume, acc[2] / volume]
1015 } else {
1016 [0.0, 0.0, 0.0]
1017 };
1018 serde_json::json!({
1019 "ok": true,
1020 "target": target_label,
1021 "solidCount": props.len(),
1022 "density": density,
1023 "volume": volume,
1024 "surfaceArea": surface_area,
1025 "mass": mass,
1026 "centroid": centroid,
1027 "inertia": serde_json::Value::Null,
1028 "principalMoments": serde_json::Value::Null,
1029 "principalAxes": serde_json::Value::Null,
1030 })
1031 .to_string()
1032 }
1033 }
1034}
1035
1036