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(&self.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(&self.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`]): the schema-driven form seeds its widgets from
94 /// this and the storage seam persists it.
95 pub fn settings_json(&self) -> String {
96 // Projection is live CAMERA state surfaced to the settings layer as a boolean
97 // (`orthographic`) so the toolbar toggle persists and the settings panel can
98 // round-trip it without clobbering. DERIVE it from the camera here — it is
99 // never a stored `RenderSettings` field — so it can NEVER drift from the
100 // actual projection no matter which code path last changed it.
101 let mut value: serde_json::Value =
102 serde_json::from_str(&self.settings.to_json()).unwrap_or(serde_json::Value::Null);
103 if let Some(obj) = value.as_object_mut() {
104 obj.insert(
105 "orthographic".into(),
106 serde_json::Value::Bool(matches!(
107 self.camera.projection,
108 crate::view::Projection::Orthographic { .. }
109 )),
110 );
111 }
112 value.to_string()
113 }
114
115 /// The current per-solid metadata color overrides as JSON —
116 /// `[{"name": "...", "override": "#rrggbb" | null}, …]`. Lets a UI list the
117 /// scene's solids with their current override so the picker reflects state.
118 pub fn solid_color_overrides_json(&self) -> String {
119 let solids: Vec<serde_json::Value> = self
120 .scene
121 .solids()
122 .iter()
123 .map(|solid| {
124 let over = solid.color_override.map(|rgb| {
125 let q = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u32;
126 format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
127 });
128 serde_json::json!({ "name": solid.name, "override": over })
129 })
130 .collect();
131 serde_json::Value::Array(solids).to_string()
132 }
133
134 pub fn apply_emphasis_json(&mut self, json: &str) -> Result<(), String> {
135 self.emphasis.apply_json(json)?;
136 self.dirty = true;
137 Ok(())
138 }
139
140 pub fn set_visible(&mut self, name: &str, visible: bool) -> bool {
141 let ok = self.scene.set_visible(name, visible);
142 if ok {
143 self.dirty = true;
144 }
145 ok
146 }
147
148 pub fn scene_listing_json(&self) -> String {
149 self.scene.listing_json()
150 }
151
152 // --- Overlay widgets --------------------------------------------------
153
154 /// The BASE bbox the camera depth-range fit starts from: the visible SOLIDS
155 /// unioned with the pushed OVERLAY groups (sketch curves/points, dimension
156 /// leaders, constraint glyphs — the `set_overlay` channel). Folding in the
157 /// groups stops orbiting an editing sketch from clipping it against the
158 /// solids-only bounds (the reported clipping when "Lock to sketch" is off).
159 /// The render path ([`Self::fit_camera_and_overlay`]) unions the FULL widget
160 /// overlay's world bounds (datum planes, world axes, frames, transform
161 /// gizmo — NOT in this bbox's channels) and the world origin on top of this
162 /// before fitting, so construction geometry never clips. Callers must bind
163 /// this to a local before `camera.fit_depth_range` (which needs
164 /// `&mut self.camera`).
165 pub fn depth_range_bbox(&self) -> crate::camera::Aabb {
166 let mut bbox = self.scene.bbox();
167 bbox.union(&self.widgets.overlay_groups_bbox());
168 bbox
169 }
170
171}
172
173impl EngineState {
174 /// A RICHER scene listing than [`scene_listing_json`](Self::scene_listing_json)
175 /// (which is counts only): per solid the individual face + edge kernel NAMES
176 /// and vertex refs (topo id + world position), plus visibility — the shape the
177 /// engine-native Scene tree lists entities from and the headed verifier asserts
178 /// against. Vertices carry no kernel name, so they are keyed by topo id + world
179 /// position (the same shape the emphasis vertex-ref selection uses).
180 pub fn scene_entities_json(&self) -> String {
181 let solids: Vec<serde_json::Value> = self
182 .scene
183 .solids()
184 .iter()
185 // Committed-sketch SHEETS are scene solids (pickable/measurable) but list
186 // under "Sketches" (`committed_sketches`), not among the real solids.
187 .filter(|solid| !solid.is_sketch)
188 .map(|solid| {
189 let faces: Vec<&str> = solid.faces.iter().map(|f| f.name.as_str()).collect();
190 let edges: Vec<&str> = solid.edges.iter().map(|e| e.name.as_str()).collect();
191 let vertices: Vec<serde_json::Value> = solid
192 .vertices
193 .iter()
194 .map(|v| serde_json::json!({ "topoId": v.topo_id, "position": v.position }))
195 .collect();
196 serde_json::json!({
197 "name": solid.name,
198 "visible": solid.visible,
199 "faces": faces,
200 "edges": edges,
201 "vertices": vertices,
202 })
203 })
204 .collect();
205 serde_json::Value::Array(solids).to_string()
206 }
207
208 /// Drive the engine SELECTION by kernel NAME from a UI tree (the name-based
209 /// analogue of [`select_top_at`](Self::select_top_at), which picks under the
210 /// cursor). Replaces the current selection with the single named `solid` /
211 /// `face` / `edge` so clicking a Scene-tree row highlights that entity in the
212 /// viewport (the render pass reads `emphasis`). Vertices have no kernel name —
213 /// use [`select_vertex_by_position`](Self::select_vertex_by_position). Returns
214 /// false for an unknown `kind` or an empty `name`.
215 pub fn select_by_name(&mut self, kind: &str, name: &str) -> bool {
216 // A construction datum/plane routes to its own name-keyed selection.
217 if kind == "datum" {
218 return self.select_datum(name);
219 }
220 if name.is_empty() || !matches!(kind, "solid" | "face" | "edge") {
221 return false;
222 }
223 let had_datum = !self.emphasis.selected_datums.is_empty();
224 self.emphasis.selected_solids.clear();
225 self.emphasis.selected_faces.clear();
226 self.emphasis.selected_edges.clear();
227 self.emphasis.selected_vertices.clear();
228 self.emphasis.selected_datums.clear();
229 match kind {
230 "solid" => {
231 self.emphasis.selected_solids.insert(name.to_string());
232 }
233 "face" => {
234 self.emphasis.selected_faces.insert(name.to_string());
235 }
236 "edge" => {
237 self.emphasis.selected_edges.insert(name.to_string());
238 }
239 _ => unreachable!(),
240 }
241 self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
242 self.dirty = true;
243 if had_datum {
244 self.refresh_construction_datums();
245 }
246 true
247 }
248
249 /// Select a single vertex by its owning solid + world position — vertices have
250 /// no kernel name, so emphasis keys them by solid + position (matched with a
251 /// tolerance in the render pass). Replaces the current selection. Returns false
252 /// for an empty solid name.
253 pub fn select_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
254 if solid.is_empty() {
255 return false;
256 }
257 let had_datum = !self.emphasis.selected_datums.is_empty();
258 self.emphasis.selected_solids.clear();
259 self.emphasis.selected_faces.clear();
260 self.emphasis.selected_edges.clear();
261 self.emphasis.selected_vertices.clear();
262 self.emphasis.selected_datums.clear();
263 self.emphasis.selected_vertices.push(crate::style::VertexRef {
264 solid: solid.to_string(),
265 position,
266 });
267 self.emphasis.generation = self.emphasis.generation.wrapping_add(1);
268 self.dirty = true;
269 if had_datum {
270 self.refresh_construction_datums();
271 }
272 true
273 }
274
275 // -----------------------------------------------------------------------
276 // Scene-tree row HOVER → the viewport hover highlight
277 //
278 // The hover twin of the name-based selection above: mousing over a Scene-tree
279 // row lights the entity EXACTLY as mousing over it in the 3D view does,
280 // because it feeds the SAME `emphasis` hover buckets through the SAME
281 // `hover_candidate` bucketing the viewport's `hover_at` uses (so a hovered
282 // datum plane gets its accent re-feed, a solid lights whole, and the render
283 // pass needs no new concept). The pointer is off the viewport while it is over
284 // a row, so the viewport's pointer-left-the-viewport `clear_hover` would
285 // otherwise wipe it every frame — hence the one-frame yield flag, the twin of
286 // `take_sketch_list_hover` / `take_constraint_label_hover`.
287 // -----------------------------------------------------------------------
288
289 /// Hover-highlight by kernel NAME from a UI tree — the hover twin of
290 /// [`select_by_name`](Self::select_by_name) (`kind` is `"solid"` / `"face"` /
291 /// `"edge"` / `"datum"`; vertices carry no kernel name, so they use
292 /// [`hover_vertex_by_position`](Self::hover_vertex_by_position)).
293 ///
294 /// Deliberately does NOT consult the selection filter, matching the row's
295 /// CLICK: a row selects whatever kind it is, so its hover previews the same
296 /// entity. An unknown `kind`, an empty `name` or an unresolved datum frame is
297 /// refused without touching the current hover.
298 ///
299 /// Call it EVERY frame the row is hovered: it re-arms the one-frame
300 /// [`take_scene_tree_hover`](Self::take_scene_tree_hover) yield flag and
301 /// re-lights nothing when the hover is already this entity. Returns whether
302 /// the hover CHANGED (the [`hover_at`](Self::hover_at) convention) so the
303 /// caller can request a repaint.
304 pub fn hover_by_name(&mut self, kind: &str, name: &str) -> bool {
305 if name.is_empty() {
306 return false;
307 }
308 let pick_kind = match kind {
309 "solid" => pick::PickKind::Solid,
310 "face" => pick::PickKind::Face,
311 "edge" => pick::PickKind::Edge,
312 // A construction datum/plane hovers by FRAME name — the bucket
313 // `select_datum` and the viewport's plane picks fill.
314 "datum" => pick::PickKind::Plane,
315 _ => return false,
316 };
317 let candidate = pick::PickCandidate {
318 kind: pick_kind,
319 name: name.to_string(),
320 // A SOLID candidate resolves through `candidate_solid_name`, which
321 // prefers `solid` — and this row IS the solid.
322 solid: match pick_kind {
323 pick::PickKind::Solid => name.to_string(),
324 _ => String::new(),
325 },
326 depth: 0.0,
327 screen_dist: 0.0,
328 position: [0.0; 3],
329 };
330 self.set_scene_tree_hover(candidate)
331 }
332
333 /// Hover a single vertex by its owning solid + world position — the hover twin
334 /// of [`select_vertex_by_position`](Self::select_vertex_by_position) (vertices
335 /// have no kernel name, so emphasis keys them by solid + position). Same
336 /// per-frame contract and return as [`hover_by_name`](Self::hover_by_name).
337 pub fn hover_vertex_by_position(&mut self, solid: &str, position: [f64; 3]) -> bool {
338 if solid.is_empty() {
339 return false;
340 }
341 self.set_scene_tree_hover(pick::PickCandidate {
342 kind: pick::PickKind::Vertex,
343 // Vertices are unnamed: `solid` + `position` is the identity.
344 name: String::new(),
345 solid: solid.to_string(),
346 depth: 0.0,
347 screen_dist: 0.0,
348 position,
349 })
350 }
351
352 /// The pointer left the Scene tree's rows: drop the row-driven highlight.
353 /// Clears ONLY a hover the tree itself lit and that is STILL lit — if the
354 /// viewport has since hovered something else (it may draw before the panel in
355 /// the dock), that hover is left alone. Safe to call every frame no row is
356 /// hovered: the target is taken, so it is a no-op from the second call on.
357 /// Returns whether the hover changed.
358 pub fn scene_tree_hover_end(&mut self) -> bool {
359 match self.scene_tree_hovered.take() {
360 Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
361 _ => false,
362 }
363 }
364
365 /// Consume the one-frame "a Scene-tree row is hovering an entity" flag — the
366 /// viewport's modeling hover branch skips its pointer-off-viewport
367 /// `clear_hover` while it is set (mirrors
368 /// [`take_sketch_list_hover`](Self::take_sketch_list_hover)) so the row-driven
369 /// highlight survives the frame instead of being cleared and re-applied.
370 pub fn take_scene_tree_hover(&mut self) -> bool {
371 std::mem::take(&mut self.scene_tree_hover_active)
372 }
373
374 /// Light one Scene-tree row's candidate: arm the yield flag (every frame — the
375 /// viewport consumes it every frame), record the target so
376 /// [`scene_tree_hover_end`](Self::scene_tree_hover_end) knows what the tree
377 /// lit, and re-emphasize only when the hover actually changed (a held row must
378 /// not re-bump the emphasis generation / re-feed the datums every frame).
379 fn set_scene_tree_hover(&mut self, candidate: pick::PickCandidate) -> bool {
380 self.scene_tree_hover_active = true;
381 match self.apply_ui_hover(&candidate) {
382 // Refused (an unresolved datum frame): nothing lit, so the tree records
383 // no target and has nothing to end.
384 None => false,
385 Some(changed) => {
386 // Recorded even when unchanged: the viewport may have lit the
387 // identical entity, and the tree still owns ending it.
388 self.scene_tree_hovered = Some(candidate);
389 changed
390 }
391 }
392 }
393
394 /// Apply ONE UI-driven hover candidate to the emphasis — the shared body
395 /// behind every list→viewport highlight (the Scene tree's rows, the dialog
396 /// rows below). `None` = REFUSED, `Some(changed)` = applied, and `changed`
397 /// says whether the hover actually moved (a held row must not re-bump the
398 /// emphasis generation / re-feed the datums every frame).
399 ///
400 /// Each caller records its OWN target: that is what keeps two panes' `_end`
401 /// calls from ending each other's highlight.
402 fn apply_ui_hover(&mut self, candidate: &pick::PickCandidate) -> Option<bool> {
403 if self.hover_is(candidate) {
404 return Some(false);
405 }
406 // Only a RESOLVED datum frame hovers (the `select_datum` guard); an
407 // unresolved name would light nothing and churn the datum feed. Checked on
408 // the change path only — the dedupe above carries the held frames.
409 if candidate.kind == pick::PickKind::Plane
410 && !self.construction_frames.iter().any(|(n, _)| *n == candidate.name)
411 {
412 return None;
413 }
414 self.hover_candidate(candidate);
415 Some(true)
416 }
417}
418
419// ---------------------------------------------------------------------------
420// DIALOG row HOVER → the viewport hover highlight
421//
422// The Scene tree knows the KIND of every row it draws; a dialog does not. A
423// feature form's reference line, its read-only `Outputs` line and the picker
424// card's picked-name line all carry a bare kernel NAME, so this lane resolves the
425// kind from the scene itself and then feeds the SAME hover buckets the tree and
426// the viewport's `hover_at` fill.
427// ---------------------------------------------------------------------------
428impl EngineState {
429 /// Hover-highlight the entity a DIALOG row names — the kind-less twin of
430 /// [`hover_by_name`](Self::hover_by_name), for the lists that show a bare
431 /// kernel name (a reference line, an `Outputs` line, the picker card).
432 ///
433 /// `owner` is the pane that is hovering (`"history"`, `"constraints"`,
434 /// `"pmi"`, `"refsel"`): [`dialog_hover_end`](Self::dialog_hover_end) acts
435 /// only for the owner that set the hover, so panes that are on screen together
436 /// in a split dock cannot end each other's highlight.
437 ///
438 /// The name is resolved by [`resolve_entity_name`](Self::resolve_entity_name),
439 /// which also covers the row whose entity the feature CONSUMED — an open
440 /// fillet form is rolled to the fillet, so its `Edges` rows name edges that no
441 /// longer exist and the blend faces the kernel built from them are lit
442 /// instead. Call it EVERY frame the row is hovered: the resolution is memoized
443 /// on the row text and the emphasis re-feed is deduped, so a held hover costs
444 /// nothing. Returns whether the hover CHANGED (the
445 /// [`hover_at`](Self::hover_at) convention), so the caller can repaint.
446 pub fn hover_entity_by_name(&mut self, owner: &'static str, name: &str) -> bool {
447 if name.is_empty() {
448 return false;
449 }
450 // Armed even for a row that resolves to nothing: the pointer is over the
451 // dialog, so the viewport's pointer-left-the-viewport `clear_hover` must
452 // still yield — otherwise moving along a list of rows would strobe the
453 // highlight off on every unresolvable one.
454 self.dialog_hover_active = true;
455 let memo = match &self.dialog_hovered {
456 Some(held) if held.owner == owner && held.row == name => Some(held.candidate.clone()),
457 _ => None,
458 };
459 let candidate = match memo {
460 Some(cached) => cached,
461 None => self.resolve_entity_name(name),
462 };
463 let applied = match &candidate {
464 Some(c) => self.apply_ui_hover(c),
465 None => None,
466 };
467 let changed = match applied {
468 Some(changed) => changed,
469 // Nothing to light (the scene carries no such name, or the candidate
470 // was refused): end whatever the slot holds — WHOEVER set it. Leaving
471 // the previous row's entity standing while the pointer sits on a
472 // different row reads as "this row is that entity", and the previous
473 // row is not always this owner's: moving from a History line straight
474 // onto an unresolvable Constraints one (a component-local vertex ref)
475 // would otherwise strand the History highlight with nobody left
476 // holding the record that could end it.
477 None => self.take_dialog_hover_slot(),
478 };
479 self.dialog_hovered = Some(super::DialogHover {
480 owner,
481 row: name.to_string(),
482 candidate,
483 });
484 changed
485 }
486
487 /// The pointer left `owner`'s dialog rows: drop the row-driven highlight.
488 /// Clears ONLY a hover THIS owner lit and that is STILL lit — a pane that
489 /// never hovered a row (or whose hover the viewport has since replaced) is a
490 /// no-op, which is what lets every consumer call it unconditionally every
491 /// frame. Returns whether the hover changed.
492 pub fn dialog_hover_end(&mut self, owner: &'static str) -> bool {
493 let mine = matches!(&self.dialog_hovered, Some(held) if held.owner == owner);
494 if mine {
495 self.take_dialog_hover_slot()
496 } else {
497 false
498 }
499 }
500
501 /// Take the dialog-hover slot and drop the highlight it recorded, when that
502 /// highlight is still the live one (the viewport may have replaced it since).
503 /// Owner-AGNOSTIC: [`dialog_hover_end`](Self::dialog_hover_end) checks the
504 /// owner before calling this, while a row that lights nothing calls it
505 /// directly — the pointer is on THAT row now, so whatever the slot still
506 /// records is stale whoever set it.
507 fn take_dialog_hover_slot(&mut self) -> bool {
508 match self.dialog_hovered.take() {
509 Some(held) => match held.candidate {
510 Some(candidate) if self.hover_is(&candidate) => self.clear_hover(),
511 _ => false,
512 },
513 None => false,
514 }
515 }
516
517 /// Consume the one-frame "a dialog row is hovering an entity" flag — the
518 /// viewport's modeling hover branch skips its pointer-off-viewport
519 /// `clear_hover` while it is set (the twin of
520 /// [`take_scene_tree_hover`](Self::take_scene_tree_hover)).
521 pub fn take_dialog_hover(&mut self) -> bool {
522 std::mem::take(&mut self.dialog_hover_active)
523 }
524
525 /// Resolve one bare kernel NAME to the entity it addresses, or `None` when the
526 /// scene carries nothing by that name.
527 ///
528 /// Order — most specific identity first: a SOLID (a shown committed sketch is
529 /// a scene solid keyed by its sketch id — `refresh_committed_sketches` inserts
530 /// the sheet under the feature id an extrude's `profile` stores — so a
531 /// `SKETCH` reference lands here whenever that sheet is shown), a
532 /// construction datum FRAME, a FACE, an EDGE, then a `{solid}@x,y,z` VERTEX
533 /// ref (the position-keyed form assembly constraints and PMI store, accepted
534 /// only when it really is a vertex of that solid — a component-LOCAL ref lights
535 /// nothing rather than lighting the wrong vertex).
536 ///
537 /// # The consumed row
538 ///
539 /// A feature's form is drawn with the model rolled TO that feature, so the
540 /// feature has RUN and the entities its references name are gone: a fillet's
541 /// `Edges` rows name edges the blend replaced. The kernel names what it builds
542 /// after what it consumed — `{featureId}:BLEND:{originatingEdgeName}`, asserted
543 /// by the kernel's own `fillet_by_face_ref_rounds_the_top_ring` /
544 /// `chamfer` naming tests — so a row that resolves to nothing falls back to the
545 /// FACE whose name ends with `:{row}`: the thing the feature made from it.
546 /// Only when EXACTLY ONE face matches, so an ambiguous mapping lights nothing
547 /// rather than an arbitrary half of it. Ends-with, never `contains`: the edges
548 /// bounding that blend are named `BOX_NZ|F1:BLEND:BOX_NX|BOX_NZ[0][0]`, which
549 /// CONTAINS the row but is not what it became.
550 fn resolve_entity_name(&self, name: &str) -> Option<pick::PickCandidate> {
551 let at = |kind: pick::PickKind, entity: &str, solid: &str| pick::PickCandidate {
552 kind,
553 name: entity.to_string(),
554 solid: solid.to_string(),
555 depth: 0.0,
556 screen_dist: 0.0,
557 position: [0.0; 3],
558 };
559 let solids = self.scene.solids();
560 if solids.iter().any(|s| s.name == name) {
561 // A SOLID candidate resolves through `candidate_solid_name`, which
562 // prefers `solid` — and this row IS the solid.
563 return Some(at(pick::PickKind::Solid, name, name));
564 }
565 if self.construction_frames.iter().any(|(n, _)| n.as_str() == name) {
566 return Some(at(pick::PickKind::Plane, name, ""));
567 }
568 for solid in solids {
569 if solid.faces.iter().any(|f| f.name == name) {
570 return Some(at(pick::PickKind::Face, name, &solid.name));
571 }
572 }
573 for solid in solids {
574 if solid.edges.iter().any(|e| e.name == name) {
575 return Some(at(pick::PickKind::Edge, name, &solid.name));
576 }
577 }
578 if let Some(candidate) = self.resolve_vertex_ref(name) {
579 return Some(candidate);
580 }
581 let suffix = format!(":{name}");
582 let mut derived = solids
583 .iter()
584 .flat_map(|solid| solid.faces.iter().map(move |face| (solid, face)))
585 .filter(|(_, face)| face.name.ends_with(&suffix));
586 match (derived.next(), derived.next()) {
587 (Some((solid, face)), None) => {
588 Some(at(pick::PickKind::Face, &face.name, &solid.name))
589 }
590 _ => None,
591 }
592 }
593
594 /// A `{solid}@x,y,z` VERTEX reference → its candidate, when the position
595 /// really is a vertex of that solid within the emphasis match tolerance.
596 /// Vertices carry no kernel name, so this is the only form a dialog can list
597 /// one under; PMI stores WORLD coordinates (which resolve here), assembly
598 /// constraints store component-LOCAL ones (which do not, and so light nothing
599 /// rather than the wrong vertex).
600 fn resolve_vertex_ref(&self, name: &str) -> Option<pick::PickCandidate> {
601 /// The tolerance the render pass matches an emphasis vertex ref at.
602 const TOL: f64 = 1e-4;
603 let (solid_name, coords) = name.rsplit_once('@')?;
604 let mut parts = coords.split(',').map(|p| p.trim().parse::<f64>().ok());
605 let position = [parts.next()??, parts.next()??, parts.next()??];
606 if parts.next().is_some() {
607 return None;
608 }
609 let solid = self.scene.solids().iter().find(|s| s.name == solid_name)?;
610 solid.vertices.iter().find(|v| {
611 (v.position[0] - position[0]).abs() <= TOL
612 && (v.position[1] - position[1]).abs() <= TOL
613 && (v.position[2] - position[2]).abs() <= TOL
614 })?;
615 Some(pick::PickCandidate {
616 kind: pick::PickKind::Vertex,
617 name: String::new(),
618 solid: solid_name.to_string(),
619 depth: 0.0,
620 screen_dist: 0.0,
621 position,
622 })
623 }
624}
625
626// BREP private tests: 958f316566b43788
627
628impl EngineState {
629 /// The resident kernel handle of every solid currently displayed, keyed by
630 /// name. Obtained by replaying the CURRENT rolled-to history prefix through
631 /// [`brep_kernel::execute_history`]: after a build the incremental cache
632 /// holds exactly this prefix, so the replay is a clean cache hit — it
633 /// re-tessellates nothing and hands back the SAME handles the scene was built
634 /// from (mirrors the pipeline's `fold_history`: removals then additions).
635 /// `pub(super)`: the interference check (`engine_state::interference`) reads
636 /// the same warm main-side handle map for its non-destructive booleans.
637 pub(super) fn resident_solid_handles(&self) -> HashMap<String, u32> {
638 let request: HistoryRequest = match serde_json::from_value(self.history.prefix_request()) {
639 Ok(request) => request,
640 Err(_) => return HashMap::new(),
641 };
642 let result = brep_kernel::execute_history(&request);
643 let mut handles: HashMap<String, u32> = HashMap::new();
644 for feature in &result.results {
645 for removed in &feature.removed {
646 handles.remove(removed);
647 }
648 for added in &feature.added {
649 handles.insert(added.name.clone(), added.handle);
650 }
651 }
652 handles
653 }
654
655 /// Mass properties for the Inspector panel, from the kernel's exact
656 /// (divergence-theorem) integrator. `name = Some(solid)` reports that resident
657 /// solid; `None` reports the whole model. `density` (mass units per mm³; the
658 /// kernel length convention is millimetres) scales `mass` and the inertia
659 /// tensor — the centroid and principal axes are density-independent.
660 ///
661 /// Returns JSON:
662 /// ```json
663 /// { "ok": true, "target": "Box", "solidCount": 1, "density": 1.0,
664 /// "volume": 5738.05, "surfaceArea": 2927.79, "mass": 5738.05,
665 /// "centroid": [10.0, 10.0, 10.0],
666 /// "inertia": [[..],[..],[..]] | null,
667 /// "principalMoments": [a,b,c] | null,
668 /// "principalAxes": [[..],[..],[..]] | null }
669 /// ```
670 /// A single resolved solid carries the full centroidal inertia tensor +
671 /// principal axes/moments; a multi-solid aggregate reports summed volume /
672 /// area / mass and the volume-weighted centroid, with the tensor fields
673 /// `null` (select one solid for its inertia). `ok:false` with a `message` on
674 /// no solids / an unknown name / an integrator failure.
675 pub fn mass_properties_json(&self, name: Option<&str>, density: f64) -> String {
676 let handles = self.resident_solid_handles();
677
678 // Resolve the target solids: a named solid (must be resident) or, for the
679 // whole model, every scene solid that has resident geometry (draw order).
680 let targets: Vec<String> = match name {
681 Some(name) if handles.contains_key(name) => vec![name.to_string()],
682 Some(name) => {
683 return serde_json::json!({
684 "ok": false,
685 "message": format!("solid '{name}' has no resident geometry"),
686 })
687 .to_string();
688 }
689 None => self
690 .scene
691 .solids()
692 .iter()
693 .map(|solid| solid.name.clone())
694 .filter(|name| handles.contains_key(name))
695 .collect(),
696 };
697 if targets.is_empty() {
698 return serde_json::json!({ "ok": false, "message": "no solids" }).to_string();
699 }
700
701 // Per-solid density mass properties straight from the kernel.
702 let mut props = Vec::with_capacity(targets.len());
703 for target in &targets {
704 match brep_kernel::mass_properties_handle_native(handles[target], density) {
705 Ok(properties) => props.push(properties),
706 Err(error) => {
707 return serde_json::json!({
708 "ok": false,
709 "message": format!("{target}: {error}"),
710 })
711 .to_string();
712 }
713 }
714 }
715
716 let target_label = if targets.len() == 1 {
717 targets[0].clone()
718 } else {
719 "(whole model)".to_string()
720 };
721
722 if props.len() == 1 {
723 // Single solid: the full tensor + principal frame are meaningful.
724 let p = &props[0];
725 serde_json::json!({
726 "ok": true,
727 "target": target_label,
728 "solidCount": 1,
729 "density": p.density,
730 "volume": p.volume,
731 "surfaceArea": p.surface_area,
732 "mass": p.mass,
733 "centroid": [p.centroid.x, p.centroid.y, p.centroid.z],
734 "inertia": p.inertia,
735 "principalMoments": p.principal_moments,
736 "principalAxes": p.principal_axes,
737 })
738 .to_string()
739 } else {
740 // Aggregate: additive scalars + volume-weighted centroid. Combining
741 // the tensors needs a parallel-axis shift per solid; left to the
742 // single-solid view rather than approximated here.
743 let volume: f64 = props.iter().map(|p| p.volume).sum();
744 let surface_area: f64 = props.iter().map(|p| p.surface_area).sum();
745 let mass: f64 = props.iter().map(|p| p.mass).sum();
746 let centroid = if volume.abs() > f64::EPSILON {
747 let mut acc = [0.0f64; 3];
748 for p in &props {
749 acc[0] += p.volume * p.centroid.x;
750 acc[1] += p.volume * p.centroid.y;
751 acc[2] += p.volume * p.centroid.z;
752 }
753 [acc[0] / volume, acc[1] / volume, acc[2] / volume]
754 } else {
755 [0.0, 0.0, 0.0]
756 };
757 serde_json::json!({
758 "ok": true,
759 "target": target_label,
760 "solidCount": props.len(),
761 "density": density,
762 "volume": volume,
763 "surfaceArea": surface_area,
764 "mass": mass,
765 "centroid": centroid,
766 "inertia": serde_json::Value::Null,
767 "principalMoments": serde_json::Value::Null,
768 "principalAxes": serde_json::Value::Null,
769 })
770 .to_string()
771 }
772 }
773}
774
775// BREP private tests: 6e9ee11e6d390119
776
777// BREP private tests: 5d42b7c167a4b91a