brep_render/metadata.rs
1//! The Properties-panel DATA layer (UI comes later): a name-keyed metadata
2//! store, per-entity measurements, and object provenance — all engine-native,
3//! all crossing the R3 boundary as plain JSON/scalars.
4//!
5//! # Metadata store ([`MetadataStore`])
6//!
7//! `object name → { attribute → value }`, keyed by the KERNEL OBJECT NAME (a
8//! solid / face / edge name), **not** a feature id. This loose coupling is the
9//! whole point: a record survives feature edits, rollback and re-tessellation as
10//! long as the object's name persists (edge/face names ARE propagated through
11//! booleans, splits and welds by the kernel). Values are strings; the well-known
12//! `density` attribute (mass units per mm³) drives a solid's weight. The store is
13//! persisted WITH the model — [`crate::engine_state::EngineState::history_request_json`]
14//! folds it in as a top-level `metadata` field and
15//! [`crate::engine_state::EngineState::set_history_json`] lifts it back out, so it
16//! round-trips through save/open.
17//!
18//! # Measurements + provenance
19//!
20//! The [`EngineState`] methods below resolve an object NAME to its kind (solid /
21//! face / edge, via the scene) and return the right measurements from the
22//! kernel's exact integrators (volume, surface area, arc length), plus the
23//! feature that produced the object (provenance, via the history's per-feature
24//! output solids). Units are millimetres (the kernel length convention).
25
26use crate::engine_state::EngineState;
27use brep_kernel::COLOR_METADATA_KEY;
28use crate::runner::{MeasureKind, MeasureQuery};
29use serde_json::Value;
30use std::collections::BTreeMap;
31
32/// The metadata key a solid's or face's transparency is stored under: a number
33/// from 0 (opaque) to 1 (clear), or the same as a percentage (`35%`).
34pub const TRANSPARENCY_METADATA_KEY: &str = "transparency";
35
36/// A `transparency` attribute's value as the OPACITY the display draws at
37/// (0 clear .. 1 opaque). `None` for anything that is not a number.
38pub fn transparency_opacity(value: &str) -> Option<f32> {
39 let text = value.trim();
40 let fraction = match text.strip_suffix('%') {
41 Some(percent) => percent.trim().parse::<f64>().ok()? / 100.0,
42 None => text.parse::<f64>().ok()?,
43 };
44 fraction.is_finite().then(|| (1.0 - fraction.clamp(0.0, 1.0)) as f32)
45}
46
47/// The default density (mass per unit volume) when an object carries no
48/// `density` metadata: unit density, so `weight == volume`.
49pub const DEFAULT_DENSITY: f64 = 1.0;
50
51/// The name-keyed metadata store: `object name → { attribute → value }`, string
52/// values, deterministic iteration (a `BTreeMap` so the persisted JSON is
53/// stable). Empty records are never retained (removing the last attribute drops
54/// the whole record).
55#[derive(Debug, Clone, Default)]
56pub struct MetadataStore {
57 entries: BTreeMap<String, BTreeMap<String, String>>,
58 /// Names the content: every mutation takes a fresh process-wide number, and
59 /// a clone (an undo snapshot) carries its content's number with it, so two
60 /// equal stamps always hold equal records.
61 stamp: u64,
62}
63
64static STAMPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
65
66impl MetadataStore {
67 pub fn new() -> Self {
68 Self::default()
69 }
70
71 /// Whether the store holds no records at all.
72 pub fn is_empty(&self) -> bool {
73 self.entries.is_empty()
74 }
75
76 /// The content stamp: unmoved means unchanged (see the field).
77 pub fn stamp(&self) -> u64 {
78 self.stamp
79 }
80
81 fn touch(&mut self) {
82 self.stamp = STAMPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
83 }
84
85 /// Set (or overwrite) one attribute of `name`'s record. An empty object name
86 /// or key is ignored (no phantom records).
87 pub fn set_attribute(&mut self, name: &str, key: &str, value: &str) {
88 if name.is_empty() || key.is_empty() {
89 return;
90 }
91 self.touch();
92 self.entries
93 .entry(name.to_string())
94 .or_default()
95 .insert(key.to_string(), value.to_string());
96 }
97
98 /// Rename every record keyed by a name built from `old` (the id renamed to
99 /// `new`, [`brep_kernel::rename_name`]). A renamed record merges over one
100 /// already at the new name.
101 pub fn rename_names(&mut self, old: &str, new: &str, namespace: &brep_kernel::ComponentNamespace) {
102 let moved: Vec<(String, String)> = self
103 .entries
104 .keys()
105 .filter_map(|name| brep_kernel::rename_name_in(name, old, new, namespace).map(|to| (name.clone(), to)))
106 .collect();
107 if moved.is_empty() {
108 return;
109 }
110 self.touch();
111 for (from, to) in moved {
112 if let Some(record) = self.entries.remove(&from) {
113 self.entries.entry(to).or_default().extend(record);
114 }
115 }
116 }
117
118 /// Remove one attribute of `name`'s record, dropping the record if it becomes
119 /// empty. Returns whether the attribute existed.
120 pub fn remove_attribute(&mut self, name: &str, key: &str) -> bool {
121 let Some(record) = self.entries.get_mut(name) else {
122 return false;
123 };
124 let existed = record.remove(key).is_some();
125 if record.is_empty() {
126 self.entries.remove(name);
127 }
128 if existed {
129 self.touch();
130 }
131 existed
132 }
133
134 /// One attribute's value (`None` if the object or key is unknown).
135 pub fn attribute(&self, name: &str, key: &str) -> Option<&str> {
136 self.entries.get(name)?.get(key).map(String::as_str)
137 }
138
139 /// One object's whole record (empty map if the object has no metadata).
140 pub fn record(&self, name: &str) -> BTreeMap<String, String> {
141 self.entries.get(name).cloned().unwrap_or_default()
142 }
143
144 /// The whole store (all records), read-only.
145 pub fn all(&self) -> &BTreeMap<String, BTreeMap<String, String>> {
146 &self.entries
147 }
148
149 /// The resolved density (mass per mm³) for `name`: its `density` attribute
150 /// parsed as a positive finite number, else [`DEFAULT_DENSITY`].
151 pub fn density(&self, name: &str) -> f64 {
152 self.attribute(name, "density")
153 .and_then(|value| value.trim().parse::<f64>().ok())
154 .filter(|density| density.is_finite() && *density > 0.0)
155 .unwrap_or(DEFAULT_DENSITY)
156 }
157
158 /// Drop every record (a part load replaces the store wholesale).
159 pub fn clear(&mut self) {
160 self.entries.clear();
161 self.touch();
162 }
163
164 /// One object's record as a JSON object `{ key: value, ... }` (`{}` when the
165 /// object has no metadata).
166 pub fn record_json(&self, name: &str) -> String {
167 Value::Object(
168 self.record(name)
169 .into_iter()
170 .map(|(key, value)| (key, Value::String(value)))
171 .collect(),
172 )
173 .to_string()
174 }
175
176 /// The whole store as a JSON value `{ name: { key: value, ... }, ... }` — the
177 /// persisted shape and the whole-store getter.
178 pub fn to_json(&self) -> Value {
179 Value::Object(
180 self.entries
181 .iter()
182 .map(|(name, record)| {
183 let object = record
184 .iter()
185 .map(|(key, value)| (key.clone(), Value::String(value.clone())))
186 .collect();
187 (name.clone(), Value::Object(object))
188 })
189 .collect(),
190 )
191 }
192
193 /// The whole store as a JSON string (the whole-store getter's string form).
194 pub fn to_json_string(&self) -> String {
195 self.to_json().to_string()
196 }
197
198 /// Replace the whole store from a persisted `metadata` value (or `None`, which
199 /// clears it — loading a part with no metadata). Non-string leaf values are
200 /// coerced to their JSON text so a legacy document never fails the load.
201 pub fn load_json(&mut self, value: Option<&Value>) {
202 self.entries.clear();
203 self.touch();
204 let Some(Value::Object(objects)) = value else {
205 return;
206 };
207 for (name, record) in objects {
208 let Value::Object(attributes) = record else {
209 continue;
210 };
211 let map: BTreeMap<String, String> = attributes
212 .iter()
213 .map(|(key, value)| (key.clone(), value_to_string(value)))
214 .collect();
215 if !map.is_empty() {
216 self.entries.insert(name.clone(), map);
217 }
218 }
219 }
220}
221
222/// Coerce a persisted metadata leaf to a string value (strings verbatim, `null`
223/// to empty, everything else to its JSON text).
224fn value_to_string(value: &Value) -> String {
225 match value {
226 Value::String(text) => text.clone(),
227 Value::Null => String::new(),
228 other => other.to_string(),
229 }
230}
231
232/// The kind an object NAME resolves to in the current scene.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234enum ObjectKind {
235 Solid,
236 Face,
237 Edge,
238}
239
240// --- EngineState: metadata store API (a SEPARATE impl block, appended, so
241// concurrent edits to the primary block don't conflict) -------------------
242impl EngineState {
243 /// One object's metadata record as JSON `{ key: value, ... }` (`{}` if none).
244 pub fn object_metadata_json(&self, name: &str) -> String {
245 self.metadata.record_json(name)
246 }
247
248 /// Set (or overwrite) one metadata attribute of an object by NAME. String
249 /// value; the well-known `density` key drives the object's weight and the
250 /// well-known `color` key drives its shaded colour, and the well-known
251 /// `transparency` key (0 opaque .. 1 clear) how see-through it is.
252 pub fn set_metadata_attribute(&mut self, name: &str, key: &str, value: &str) {
253 self.metadata.set_attribute(name, key, value);
254 // A metadata edit (notably `density`) feeds the object-info output but does
255 // NOT trigger a history rerun, so drop this object's cached info so a
256 // re-selection re-measures with the new attribute.
257 self.info_cache.remove(name);
258 // `color` is the one attribute the VIEWPORT reads, and there is no rerun
259 // to carry it through — push it to the display right here so recolouring
260 // a body is immediate.
261 if key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY {
262 self.sync_colors_from_metadata();
263 }
264 }
265
266 /// [`Self::set_metadata_attribute`] for many `(name, value)` pairs under one
267 /// `key`, re-deriving the display colours once at the end rather than once
268 /// per object (an import colouring many bodies would otherwise walk the
269 /// whole scene for each).
270 pub fn set_metadata_attributes(&mut self, key: &str, pairs: &[(String, String)]) {
271 for (name, value) in pairs {
272 self.metadata.set_attribute(name, key, value);
273 self.info_cache.remove(name.as_str());
274 }
275 if !pairs.is_empty() && (key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY) {
276 self.sync_colors_from_metadata();
277 }
278 }
279
280 /// Remove one metadata attribute of an object. Returns whether it existed.
281 pub fn remove_metadata_attribute(&mut self, name: &str, key: &str) -> bool {
282 let existed = self.metadata.remove_attribute(name, key);
283 // Same rerun-less invalidation as `set_metadata_attribute`.
284 self.info_cache.remove(name);
285 if existed && (key == COLOR_METADATA_KEY || key == TRANSPARENCY_METADATA_KEY) {
286 self.sync_colors_from_metadata();
287 }
288 existed
289 }
290
291 /// Re-derive the display scene's colours from the metadata store — the ONE
292 /// call that connects the durable `color` attribute to the renderer (and,
293 /// the same way, the `transparency` attribute).
294 ///
295 /// Every colour the viewport shows comes from here: a STEP import's stamped
296 /// body/face colours, a colour typed or picked in the Info window, a colour
297 /// restored from a saved document. The store is the authority; the display's
298 /// `color_override` fields are a derived cache of it, rebuilt after every
299 /// history apply (`EngineState::finish_apply`), on every document load, on
300 /// a metadata edit, and whenever the display setting flips.
301 ///
302 /// [`crate::style::RenderSettings::override_model_colors`] is honoured HERE
303 /// rather than in the renderer, and it is deliberately a READ of the store,
304 /// never a write: ticking the box resolves every colour to `None` so the
305 /// viewport falls back to `faceColorMode`, while the stored attributes stay
306 /// exactly as they were. Unticking restores them from the same records.
307 ///
308 /// Returns whether anything changed, and marks the engine dirty only then —
309 /// the no-op case must stay free, since this runs after every single run.
310 pub fn sync_colors_from_metadata(&mut self) -> bool {
311 // Disjoint field borrows: the closure reads `self.metadata` while
312 // `self.scene` is borrowed mutably.
313 let ignore = self.settings.override_model_colors;
314 let metadata = &self.metadata;
315 let changed = self.scene.apply_metadata_colors(|name| {
316 if ignore {
317 return None;
318 }
319 shown_color(metadata, name)
320 .and_then(crate::style::parse_css_hex)
321 // A derived BOARD body has a colour of its own and no producing
322 // feature to have coloured it, so without this fallback the
323 // pass would resolve it to `None` and the board would draw in
324 // the name-hashed default — green substrate and copper traces
325 // are the whole point of drawing it. A stored attribute still
326 // wins, so a user may recolour the board like anything else.
327 .or_else(|| crate::engine_state::board_default_color(name))
328 });
329 // `transparency` rides the same seam. It is not a colour, so the
330 // "override model colors" setting leaves it alone: a see-through body
331 // stays see-through in whatever colour the display gives it.
332 let changed = self.scene.apply_metadata_opacity(|name| {
333 metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity)
334 }) || changed;
335 // An edge's own `color` and `transparency`: the stored attributes
336 // only (no board default), the colour hidden by the override.
337 let changed = self.scene.apply_metadata_edge_looks(
338 |name| if ignore { None } else { shown_color(metadata, name).and_then(crate::style::parse_css_hex) },
339 |name| metadata.attribute(name, TRANSPARENCY_METADATA_KEY).and_then(transparency_opacity),
340 ) || changed;
341 if changed {
342 self.dirty = true;
343 }
344 changed
345 }
346
347 /// The whole metadata store as JSON `{ name: { key: value } }`.
348 pub fn metadata_json(&self) -> String {
349 self.metadata.to_json_string()
350 }
351
352 /// [`Self::metadata_json`] as a JSON value.
353 pub fn metadata_value(&self) -> Value {
354 self.metadata.to_json()
355 }
356}
357
358/// The colour an entity shows: its own `color`, except that a Pattern
359/// Component instance's entity whose colour was not set on the instance itself
360/// (none, or still the `partColor` it took from its part) shows its SEED
361/// entity's colour, so a colour set on the seed in the assembly reaches every
362/// copy, and a copy of a copy through its own seed. A colour set on the
363/// instance wins.
364fn shown_color<'a>(metadata: &'a MetadataStore, name: &str) -> Option<&'a str> {
365 let own = metadata.attribute(name, COLOR_METADATA_KEY);
366 let set_on_instance = own.is_some() && own != metadata.attribute(name, PART_COLOR_METADATA_KEY);
367 if !set_on_instance {
368 if let Some(color) = pattern_seed_entity(name).and_then(|seed| shown_color(metadata, &seed)) {
369 return Some(color);
370 }
371 }
372 own
373}
374
375/// The marker the kernel stamps on a component entity's colour taken from
376/// its part (`assembly_component::PART_COLOR_KEY`).
377const PART_COLOR_METADATA_KEY: &str = "partColor";
378
379/// The seed entity a Pattern Component instance's entity copies:
380/// `APAT5.ACOMP3.i2:F9` → `ACOMP3:F9`; `None` for anything else.
381fn pattern_seed_entity(name: &str) -> Option<String> {
382 let (head, rest) = name.split_once(':')?;
383 let (_, seed, _) = brep_kernel::pattern_component_instance(head)?;
384 Some(format!("{seed}:{rest}"))
385}
386
387// --- EngineState: measurements + provenance (SEPARATE impl block) ------------
388impl EngineState {
389 /// Resolve an object NAME to `(kind, owning solid name)` via the display
390 /// scene: a solid resolves to itself; a face/edge resolves to its owning
391 /// solid. `None` for an empty or unknown name (vertices carry no kernel name).
392 fn resolve_object(&self, name: &str) -> Option<(ObjectKind, String)> {
393 if name.is_empty() {
394 return None;
395 }
396 if self.scene.solid(name).is_some() {
397 return Some((ObjectKind::Solid, name.to_string()));
398 }
399 for solid in self.scene.solids() {
400 if solid.faces.iter().any(|face| face.name == name) {
401 return Some((ObjectKind::Face, solid.name.clone()));
402 }
403 }
404 for solid in self.scene.solids() {
405 if solid.edges.iter().any(|edge| edge.name == name) {
406 return Some((ObjectKind::Edge, solid.name.clone()));
407 }
408 }
409 None
410 }
411
412 /// The feature that an object ORIGINATES from, as `(feature id, feature type)`.
413 /// For a FACE/EDGE this is the feature that first gave it its name (its true
414 /// origin, from the eager `entity_origin` first-writer map) — NOT the owning
415 /// solid's last producer — so "Edit owning feature" rolls back to where the
416 /// entity was born. For a SOLID it's the solid's producer (last writer, the
417 /// eager `provenance` map). `None` if the name is unknown or has no known
418 /// producer. Reads only the eager maps the last run shipped, so it never re-runs
419 /// the history — the freeze side-door `context_bar` hit every selected frame is
420 /// now O(1).
421 pub fn creating_feature(&self, name: &str) -> Option<(String, String)> {
422 let Some((kind, owner)) = self.resolve_object(name) else {
423 // A datum / construction PLANE (or one plane of a datum) is not a
424 // resident solid/face/edge — it's a named frame. Its producer is the
425 // D/P feature that emitted the frame (same fallback object_info_json
426 // uses), so "Edit owning feature" resolves for a lone plane pick too.
427 return self.datum_feature_for_name(name);
428 };
429 let id = match kind {
430 // A face/edge resolves to its ORIGIN. Fall back to the owning solid's
431 // producer when the name is somehow absent from `entity_origin` (keeps
432 // the "Edit owning feature" button from vanishing).
433 ObjectKind::Face | ObjectKind::Edge => self
434 .entity_origin
435 .get(name)
436 .cloned()
437 .or_else(|| self.provenance.get(&owner).cloned())?,
438 // A solid keeps its existing last-writer producer semantics.
439 ObjectKind::Solid => self.provenance.get(&owner)?.clone(),
440 };
441 Some((id.clone(), self.feature_type_of(&id)))
442 }
443
444 /// Whether the object `name` (a solid, or a face/edge owned by a solid) sits
445 /// on a SHEET-METAL body — its owning display solid carries the sheet-metal
446 /// marker the pipeline stamped from the resident handle's `SheetTree`. Reads
447 /// only the display scene, so it is O(1) and thread-safe (no `SheetTree`
448 /// thread-local touched on the UI thread — [`crate::scene::SolidDisplay::
449 /// is_sheet_metal`]). The gate for the sheet-metal edit features (SM Flange /
450 /// Fillet / Chamfer). `false` for an unknown name or a synthesized sketch
451 /// sheet (no resident handle, no tree).
452 pub fn is_sheet_metal_object(&self, name: &str) -> bool {
453 self.resolve_object(name)
454 .and_then(|(_, owner)| self.scene.solid(&owner))
455 .is_some_and(|solid| solid.is_sheet_metal)
456 }
457
458 /// A feature's type token by id (empty string if the id is not in the history).
459 fn feature_type_of(&self, id: &str) -> String {
460 self.history
461 .index_of(id)
462 .and_then(|index| self.history.feature_type(index))
463 .unwrap_or_default()
464 }
465
466 /// The `{ id, type }` provenance JSON for an object by NAME (or `null` if it has
467 /// no known producer). Delegates to [`creating_feature`](Self::creating_feature)
468 /// so a face/edge reports its ORIGIN (first-writer) and a solid its producer
469 /// (last-writer) — one resolver, so the Info tab and the context bar agree.
470 fn creating_feature_value(&self, name: &str) -> Value {
471 match self.creating_feature(name) {
472 Some((id, ty)) => serde_json::json!({ "id": id, "type": ty }),
473 None => Value::Null,
474 }
475 }
476
477 /// The full Properties-panel info for an object by NAME: its resolved kind,
478 /// the right measurements, and provenance. Units are millimetres.
479 ///
480 /// - **Solid** — `{ ok, name, kind:"solid", volume, surfaceArea,
481 /// edgeLengthTotal, density, weight, creatingFeature }`, where
482 /// `weight = density · volume` and `density` comes from the object's
483 /// metadata (default [`DEFAULT_DENSITY`]).
484 /// - **Face** — `{ ok, name, kind:"face", solid, surfaceType, area,
485 /// edgeLengthTotal, creatingFeature }` (`edgeLengthTotal` = its boundary
486 /// edges; `surfaceType` = the carrier-surface classification, e.g.
487 /// `"Plane"`/`"Cylinder"`/`"Cone"`/`"Sphere"`/`"Torus"`/`"NURBS"`), plus
488 /// the carrier's dimensions when it has them: `radius` + `diameter`
489 /// (cylinder, sphere), `halfAngleDeg` (cone), `majorRadius` +
490 /// `minorRadius` (torus).
491 /// - **Edge** — `{ ok, name, kind:"edge", solid, length, creatingFeature }`,
492 /// plus `curveType` (`"Circle"`/`"Arc"`), `radius`, `diameter` and an
493 /// arc's `sweepDeg` when the edge lies on a circle.
494 ///
495 /// `{ ok:false, name, message }` for an empty/unknown name, a non-resident
496 /// solid, or a kernel measurement failure.
497 ///
498 /// The real solid/face/edge MEASUREMENT is routed to the [`HistoryRunner`] (so
499 /// the warm-registry runner answers it, never the potentially-cold main side)
500 /// and CACHED here keyed by name — fired once per selection, served from the
501 /// cache every subsequent frame. For the synchronous
502 /// [`InlineRunner`](crate::runner::InlineRunner) the submit → `pump_queries`
503 /// resolves same-call, so this returns the merged JSON immediately and stays
504 /// byte-identical to the pre-seam in-process result; a background
505 /// [`ThreadRunner`](crate::runner::ThreadRunner) returns a `pending` placeholder
506 /// for the frame(s) until its reply lands (drained by `pump_queries`). The cache
507 /// is invalidated on any geometry change (`apply_run_output`) or metadata edit
508 /// (`set_metadata_attribute`).
509 ///
510 /// [`HistoryRunner`]: crate::runner::HistoryRunner
511 pub fn object_info_json(&mut self, name: &str) -> String {
512 let raw = self.object_info_raw_json(name);
513 self.with_part_mass(name, raw)
514 }
515
516 /// A SOLID's info carries the mass the part's density gives it (see
517 /// `engine_state::part_mass`): `density` (g/cm³, `null` when none
518 /// resolves), `densitySource` (`solid` | `part` | `material`), `mass` (kg)
519 /// and, with no number, `massNote` saying why. The runner's unit-density
520 /// `weight` is not reported: the BOM and this window read ONE density.
521 fn with_part_mass(&self, name: &str, raw: String) -> String {
522 let Ok(mut info) = serde_json::from_str::<Value>(&raw) else {
523 return raw;
524 };
525 if info.get("ok").and_then(Value::as_bool) != Some(true)
526 || info.get("kind").and_then(Value::as_str) != Some("solid")
527 {
528 return raw;
529 }
530 let volume = info.get("volume").and_then(Value::as_f64);
531 let resolved = self.solid_density(name);
532 if let Some(object) = info.as_object_mut() {
533 object.remove("weight");
534 object.insert(
535 "density".into(),
536 resolved.map(|(density, _)| Value::from(density)).unwrap_or(Value::Null),
537 );
538 object.insert(
539 "densitySource".into(),
540 resolved
541 .map(|(_, source)| Value::from(source.as_str()))
542 .unwrap_or(Value::Null),
543 );
544 let mass = volume.zip(resolved).map(|(v, (d, _))| v * d * 1e-6);
545 object.insert("mass".into(), mass.map(Value::from).unwrap_or(Value::Null));
546 if mass.is_none() {
547 object.insert(
548 "massNote".into(),
549 Value::from("no density: set the part's Material or Density"),
550 );
551 }
552 }
553 info.to_string()
554 }
555
556 /// [`Self::object_info_json`] without the part-density fold: the runner's
557 /// measurement as cached.
558 pub(crate) fn object_info_raw_json(&mut self, name: &str) -> String {
559 let Some((kind, owner)) = self.resolve_object(name) else {
560 // A construction datum/plane carries no resident geometry (no volume /
561 // area / length), so it never resolves as a solid/face/edge. Return a
562 // graceful minimal record — name + kind + creating feature — rather than
563 // erroring, so the Properties Info tab renders for a selected datum and
564 // its name flows into the (name-keyed) Metadata tab.
565 if let Some((feature_id, feature_type)) = self.datum_feature_for_name(name) {
566 let kind_label = if feature_type == "P" { "plane" } else { "datum" };
567 return serde_json::json!({
568 "ok": true,
569 "name": name,
570 "kind": kind_label,
571 "creatingFeature": { "id": feature_id, "type": feature_type },
572 })
573 .to_string();
574 }
575 return serde_json::json!({
576 "ok": false, "name": name, "message": "unknown object",
577 })
578 .to_string();
579 };
580 // A committed-sketch SHEET is a scene solid with NO kernel handle, so the
581 // handle-based measurement path can't serve it. Measure straight off its
582 // synthesized display (planar-mesh triangle areas / edge polylines) and
583 // report `kind:"sketch"` — no volume. Handle-less ⇒ synchronous, no query.
584 if let Some(solid) = self.scene.solid(&owner) {
585 if solid.is_sketch {
586 return self.sketch_info_json(name, kind, solid);
587 }
588 }
589
590 // Real geometry: serve from the info cache, else fire a measurement query at
591 // the runner (deduped: never submit a second query for a name already in
592 // flight), pump, and return the resolved JSON — or a pending placeholder.
593 if let Some(cached) = self.info_cache.get(name) {
594 return cached.clone();
595 }
596 if !self.pending_query.values().any(|pending| pending == name) {
597 self.next_query_id += 1;
598 let id = self.next_query_id;
599 let measure_kind = match kind {
600 ObjectKind::Solid => MeasureKind::Solid,
601 ObjectKind::Face => MeasureKind::Face,
602 ObjectKind::Edge => MeasureKind::Edge,
603 };
604 let density = self.metadata.density(name);
605 self.pending_query.insert(id, name.to_string());
606 self.runner.submit_query(MeasureQuery {
607 id,
608 kind: measure_kind,
609 owner,
610 entity: name.to_string(),
611 density,
612 });
613 }
614 self.pump_queries();
615 match self.info_cache.get(name) {
616 Some(resolved) => resolved.clone(),
617 None => serde_json::json!({ "ok": false, "name": name, "pending": true }).to_string(),
618 }
619 }
620
621 /// Drain every completed measurement reply from the runner and fold it into the
622 /// name-keyed info cache — the query counterpart of [`EngineState::pump`]. Called
623 /// once per frame from `pump` AND synchronously from
624 /// [`Self::object_info_json`] (so the Inline runner resolves same-call). Each
625 /// reply is MERGED with the main-injected `name` + `creatingFeature` (from the
626 /// eager provenance) into the final object-info JSON.
627 pub fn pump_queries(&mut self) {
628 while let Some(reply) = self.runner.poll_query() {
629 let Some(name) = self.pending_query.remove(&reply.id) else {
630 // A reply whose request was invalidated (a rerun cleared the pending
631 // set) — drop it; the re-selection re-queries against fresh geometry.
632 continue;
633 };
634 let fragment: Value = serde_json::from_str(&reply.result).unwrap_or(Value::Null);
635 let merged = self.merge_info(&name, &fragment);
636 self.info_cache.insert(name, merged);
637 }
638 }
639
640 /// Merge a runner measurement FRAGMENT with the main-side `name` +
641 /// `creatingFeature` into the final object-info JSON, preserving the exact field
642 /// ORDER the pre-seam `object_info_json` emitted (so the output is
643 /// byte-identical): `ok`, then `name`, then the fragment's remaining fields in
644 /// order (`kind`, the measurements — or `message` on error), then
645 /// `creatingFeature` (only when `ok`, since an error record carries none).
646 fn merge_info(&self, name: &str, fragment: &Value) -> String {
647 let object = fragment.as_object();
648 let ok = object
649 .and_then(|map| map.get("ok"))
650 .and_then(Value::as_bool)
651 .unwrap_or(false);
652 let mut merged = serde_json::Map::new();
653 merged.insert("ok".to_string(), Value::Bool(ok));
654 merged.insert("name".to_string(), Value::String(name.to_string()));
655 if let Some(map) = object {
656 for (key, value) in map {
657 if key == "ok" {
658 continue;
659 }
660 merged.insert(key.clone(), value.clone());
661 }
662 }
663 if ok {
664 merged.insert(
665 "creatingFeature".to_string(),
666 // Resolve by ENTITY NAME (not `owner`): a face/edge reports its
667 // ORIGIN, a solid its producer — the same correction the context bar
668 // gets, so the Info tab's `creatingFeature` agrees.
669 self.creating_feature_value(name),
670 );
671 }
672 Value::Object(merged).to_string()
673 }
674
675 /// Properties info for a committed-sketch SHEET object (the sheet solid, its
676 /// planar face, or a boundary edge), measured off the synthesized display — a
677 /// sketch carries no resident kernel geometry. `kind:"sketch"` for the whole
678 /// sheet (area + total edge length, NO volume); `"face"` for its planar face;
679 /// `"edge"` for a boundary edge. Provenance is the sketch feature itself.
680 fn sketch_info_json(
681 &self,
682 name: &str,
683 kind: ObjectKind,
684 solid: &crate::scene::SolidDisplay,
685 ) -> String {
686 let creating = serde_json::json!({
687 "id": solid.name,
688 "type": self.feature_type_of(&solid.name),
689 });
690 let edge_total: f64 = solid.edges.iter().map(|e| polyline_length(&e.polyline)).sum();
691 match kind {
692 ObjectKind::Solid => serde_json::json!({
693 "ok": true,
694 "name": name,
695 "kind": "sketch",
696 "area": sheet_mesh_area(solid),
697 "edgeLengthTotal": edge_total,
698 "creatingFeature": creating,
699 })
700 .to_string(),
701 ObjectKind::Face => serde_json::json!({
702 "ok": true,
703 "name": name,
704 "kind": "face",
705 "solid": solid.name,
706 // A committed sketch's sheet face is planar by construction.
707 "surfaceType": "Plane",
708 "area": sheet_mesh_area(solid),
709 "edgeLengthTotal": edge_total,
710 "creatingFeature": creating,
711 })
712 .to_string(),
713 ObjectKind::Edge => {
714 let length = solid
715 .edges
716 .iter()
717 .find(|e| e.name == name)
718 .map(|e| polyline_length(&e.polyline))
719 .unwrap_or(0.0);
720 serde_json::json!({
721 "ok": true,
722 "name": name,
723 "kind": "edge",
724 "solid": solid.name,
725 "length": length,
726 "creatingFeature": creating,
727 })
728 .to_string()
729 }
730 }
731 }
732}
733
734/// Total surface area (mm²) of a synthesized sheet's planar display mesh — the
735/// sum of its triangle areas.
736fn sheet_mesh_area(solid: &crate::scene::SolidDisplay) -> f64 {
737 let p = &solid.mesh.positions;
738 solid
739 .mesh
740 .indices
741 .chunks_exact(3)
742 .map(|t| {
743 let a = p[t[0] as usize];
744 let b = p[t[1] as usize];
745 let c = p[t[2] as usize];
746 let ab = [
747 (b[0] - a[0]) as f64,
748 (b[1] - a[1]) as f64,
749 (b[2] - a[2]) as f64,
750 ];
751 let ac = [
752 (c[0] - a[0]) as f64,
753 (c[1] - a[1]) as f64,
754 (c[2] - a[2]) as f64,
755 ];
756 let cross = [
757 ab[1] * ac[2] - ab[2] * ac[1],
758 ab[2] * ac[0] - ab[0] * ac[2],
759 ab[0] * ac[1] - ab[1] * ac[0],
760 ];
761 (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5
762 })
763 .sum()
764}
765
766/// Arc length (mm) of a sampled edge polyline — the sum of its segment lengths.
767fn polyline_length(polyline: &[[f32; 3]]) -> f64 {
768 polyline
769 .windows(2)
770 .map(|w| {
771 let d = [
772 (w[1][0] - w[0][0]) as f64,
773 (w[1][1] - w[0][1]) as f64,
774 (w[1][2] - w[0][2]) as f64,
775 ];
776 (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
777 })
778 .sum()
779}
780