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