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