Skip to main content

brep_kernel/abi/
display.rs

1use super::*;
2
3/// Everything the native renderer needs to display one resident solid.
4pub struct DisplaySolidPayload {
5    /// Faces in shell/face order — the index into this Vec IS the watertight
6    /// mesh's `face_ids` value for that face's triangles.
7    pub faces: Vec<(u64, Option<String>)>,
8    /// Watertight display mesh (chord-tolerance driven).
9    pub mesh: Mesh,
10    /// Non-degenerate edges `(edge_id, name, polyline)`, sorted by edge id.
11    pub edges: Vec<(u64, Option<String>, Vec<Vec3>)>,
12    /// Topology vertices `(vertex_id, point)`.
13    pub vertices: Vec<(u64, Vec3)>,
14    /// The chord tolerance actually used.
15    pub chord_tolerance: f64,
16}
17use crate::solid_tolerance::display_chord_tolerance;
18
19
20/// Native display payload for a resident solid: watertight mesh + face list (in
21/// mesh `face_ids` order) + edge polylines + vertices, all in one registry
22/// borrow. `lod_factor` scales the per-solid display chord tolerance (1.0 = the
23/// app's "Normal" preset; higher = coarser mesh). Callers pass a sanitized,
24/// finite, positive value — [`display_chord_tolerance`] multiplies it in directly.
25pub fn display_payload_handle_native(
26    handle: u32,
27    lod_factor: f64,
28) -> Result<DisplaySolidPayload, String> {
29    with_registered_solid_str(handle, |solid| display_payload_of_solid(solid, lod_factor))
30}
31
32/// [`display_payload_handle_native`] for many resident solids at once, in
33/// `handles` order.
34///
35/// **Instances are meshed once.** Solids that are rigid copies of one another
36/// (an imported assembly places each part many times: 857 instances of 174
37/// parts) share one tessellation: the copy with the finest display chord is
38/// meshed, and each other copy gets that mesh and its edge polylines carried
39/// by the rigid map between them, with its OWN face/edge ids and names and its
40/// own vertices, so picking, selection and per-instance colour see the solid
41/// they always saw. A copy is only drawn this way when everything but point
42/// positions is identical (ids, senses, knots, weights, pcurves) and one rigid
43/// map carries every vertex and control point of the meshed copy onto its own
44/// (`congruent_pose`); anything else, and every solid with no copy, gets the
45/// single call's payload exactly.
46///
47/// Under the `parallel` feature the meshed solids are copied out of this
48/// thread's registry (it is thread-local) a chunk at a time and meshed across
49/// rayon's pool. Display meshing opens no thread-local mode (the soundness
50/// scan's mode is closed on every worker), so a payload does not depend on
51/// the thread that computed it.
52pub fn display_payloads_handles_native(
53    handles: &[u32],
54    lod_factor: f64,
55) -> Vec<Result<DisplaySolidPayload, String>> {
56    // Group by everything a rigid move leaves alone; the first, finest-chord
57    // member of a group is meshed, the rest are posed when the map verifies.
58    let keys: Vec<Option<(u64, f64)>> = handles
59        .iter()
60        .map(|&handle| {
61            with_registered_solid_str(handle, |solid| {
62                Ok((congruence_signature(solid), display_chord_tolerance(solid, lod_factor)))
63            })
64            .ok()
65        })
66        .collect();
67    let mut base_of_signature: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
68    for (index, key) in keys.iter().enumerate() {
69        let Some((signature, chord)) = *key else { continue };
70        let base = base_of_signature.entry(signature).or_insert(index);
71        if chord < keys[*base].map_or(f64::INFINITY, |(_, base_chord)| base_chord) {
72            *base = index;
73        }
74    }
75    let mut posed: Vec<Option<(usize, RigidPose)>> = vec![None; handles.len()];
76    for (index, key) in keys.iter().enumerate() {
77        let Some((signature, _)) = *key else { continue };
78        let base = base_of_signature[&signature];
79        if base == index {
80            continue;
81        }
82        posed[index] = with_registered_solid_str(handles[base], |base_solid| {
83            with_registered_solid_str(handles[index], |solid| Ok(congruent_pose(base_solid, solid)))
84        })
85        .ok()
86        .flatten()
87        .map(|pose| (base, pose));
88    }
89    // Mesh every solid that is not posed (bases, unmatched copies, failures).
90    let meshed_indices: Vec<usize> = (0..handles.len()).filter(|&index| posed[index].is_none()).collect();
91    let meshed_handles: Vec<u32> = meshed_indices.iter().map(|&index| handles[index]).collect();
92    // BREP_PROFILE: how much of the batch was meshed and how much posed.
93    let profile_started = crate::profile::profile_enabled().then(web_time::Instant::now);
94    let mut payloads: Vec<Option<Result<DisplaySolidPayload, String>>> = (0..handles.len()).map(|_| None).collect();
95    for (index, payload) in meshed_indices.iter().zip(mesh_display_payloads(&meshed_handles, lod_factor)) {
96        payloads[*index] = Some(payload);
97    }
98    let mesh_ms = profile_started.map(|started| started.elapsed().as_secs_f64() * 1_000.0);
99    // Pose the copies; a copy whose base failed to mesh is meshed on its own.
100    for index in 0..handles.len() {
101        let Some((base, pose)) = posed[index].take() else { continue };
102        let result = match &payloads[base] {
103            Some(Ok(base_payload)) => {
104                with_registered_solid_str(handles[index], |solid| Ok(posed_payload(base_payload, &pose, solid)))
105            }
106            _ => display_payload_handle_native(handles[index], lod_factor),
107        };
108        payloads[index] = Some(result);
109    }
110    if let Some(started) = profile_started {
111        profile_line!(
112            "display.batch solids={} meshed={} posed={} mesh_ms={:.1} total_ms={:.1}",
113            handles.len(),
114            meshed_indices.len(),
115            handles.len() - meshed_indices.len(),
116            mesh_ms.unwrap_or(0.0),
117            started.elapsed().as_secs_f64() * 1_000.0
118        );
119    }
120    payloads.into_iter().map(|payload| payload.expect("every slot meshed or posed")).collect()
121}
122
123/// Mesh each handle's solid on its own (across the pool under `parallel`).
124fn mesh_display_payloads(handles: &[u32], lod_factor: f64) -> Vec<Result<DisplaySolidPayload, String>> {
125    #[cfg(feature = "parallel")]
126    {
127        use rayon::prelude::*;
128        // Bounded copies: a chunk of solids is resident twice at most.
129        const CHUNK: usize = 256;
130        let mut payloads = Vec::with_capacity(handles.len());
131        for chunk in handles.chunks(CHUNK) {
132            let solids: Vec<Result<BrepSolid, String>> =
133                chunk.iter().map(|&handle| registered_solid_clone(handle)).collect();
134            payloads.extend(
135                solids
136                    .into_par_iter()
137                    .with_max_len(1)
138                    .map(|solid| solid.and_then(|solid| display_payload_of_solid(&solid, lod_factor)))
139                    .collect::<Vec<_>>(),
140            );
141        }
142        payloads
143    }
144    #[cfg(not(feature = "parallel"))]
145    {
146        handles.iter().map(|&handle| display_payload_handle_native(handle, lod_factor)).collect()
147    }
148}
149
150/// A proper rigid map `p -> rotation * p + translation` (rows of `rotation`).
151#[derive(Clone, Copy, Debug)]
152struct RigidPose {
153    rotation: [[f64; 3]; 3],
154    translation: [f64; 3],
155}
156
157impl RigidPose {
158    fn point(&self, p: Vec3) -> Vec3 {
159        let r = &self.rotation;
160        Vec3::new(
161            r[0][0] * p.x + r[0][1] * p.y + r[0][2] * p.z + self.translation[0],
162            r[1][0] * p.x + r[1][1] * p.y + r[1][2] * p.z + self.translation[1],
163            r[2][0] * p.x + r[2][1] * p.y + r[2][2] * p.z + self.translation[2],
164        )
165    }
166
167    fn direction(&self, d: Vec3) -> Vec3 {
168        let r = &self.rotation;
169        Vec3::new(
170            r[0][0] * d.x + r[0][1] * d.y + r[0][2] * d.z,
171            r[1][0] * d.x + r[1][1] * d.y + r[1][2] * d.z,
172            r[2][0] * d.x + r[2][1] * d.y + r[2][2] * d.z,
173        )
174    }
175}
176
177/// A hash of everything a rigid move leaves unchanged: ids, topology, senses,
178/// degrees, knots, weights, parameter ranges and pcurves. Names are left out
179/// (instances are named apart). Equal signatures only nominate a pair;
180/// [`congruent_pose`] decides.
181fn congruence_signature(solid: &BrepSolid) -> u64 {
182    use std::hash::{Hash, Hasher};
183    let mut h = rustc_hash::FxHasher::default();
184    std::mem::discriminant(&solid.kind).hash(&mut h);
185    solid.genus.hash(&mut h);
186    solid.cells.len().hash(&mut h);
187    solid.vertices.len().hash(&mut h);
188    for vertex in &solid.vertices {
189        vertex.id.hash(&mut h);
190    }
191    solid.edges.len().hash(&mut h);
192    for edge in &solid.edges {
193        (edge.id, edge.start_vertex_id, edge.end_vertex_id, edge.degenerate).hash(&mut h);
194        (edge.t0.to_bits(), edge.t1.to_bits(), edge.curve.degree).hash(&mut h);
195        edge.curve.knots.iter().for_each(|k| k.to_bits().hash(&mut h));
196        edge.curve.control_points.iter().for_each(|c| c.w.to_bits().hash(&mut h));
197    }
198    solid.shells.len().hash(&mut h);
199    for shell in &solid.shells {
200        (shell.id, shell.faces.len()).hash(&mut h);
201        for face in &shell.faces {
202            let surface = &face.surface;
203            (face.id, face.same_sense, surface.degree_u, surface.degree_v, face.loops.len()).hash(&mut h);
204            surface.knots_u.iter().chain(&surface.knots_v).for_each(|k| k.to_bits().hash(&mut h));
205            surface.control_points.len().hash(&mut h);
206            for row in &surface.control_points {
207                row.len().hash(&mut h);
208                row.iter().for_each(|c| c.w.to_bits().hash(&mut h));
209            }
210            for loop_record in &face.loops {
211                (loop_record.id, loop_record.coedges.len()).hash(&mut h);
212                for coedge in &loop_record.coedges {
213                    (coedge.id, coedge.edge_id, coedge.forward, coedge.pcurve.degree).hash(&mut h);
214                    coedge.pcurve.knots.iter().for_each(|k| k.to_bits().hash(&mut h));
215                    for c in &coedge.pcurve.control_points {
216                        [c.x, c.y, c.z, c.w].iter().for_each(|v| v.to_bits().hash(&mut h));
217                    }
218                }
219            }
220        }
221    }
222    h.finish()
223}
224
225/// The rigid map taking `base` onto `solid`, when `solid` is `base` moved
226/// rigidly: identical in everything but point positions, and the map carries
227/// every vertex and every edge-curve and surface control point of `base` to
228/// `solid`'s within `1e-9` of the larger coordinate magnitude. `None`
229/// otherwise (a scaled, mirrored or reshaped copy, or no three points that
230/// fix a frame).
231fn congruent_pose(base: &BrepSolid, solid: &BrepSolid) -> Option<RigidPose> {
232    if !same_but_positions(base, solid) {
233        return None;
234    }
235    let points = |s: &BrepSolid| -> Option<Vec<(Vec3, f64)>> {
236        let mut out: Vec<(Vec3, f64)> = s.vertices.iter().map(|v| (v.point, 1.0)).collect();
237        for edge in &s.edges {
238            for c in &edge.curve.control_points {
239                out.push((c.point().ok()?, c.w));
240            }
241        }
242        for shell in &s.shells {
243            for face in &shell.faces {
244                for row in &face.surface.control_points {
245                    for c in row {
246                        out.push((c.point().ok()?, c.w));
247                    }
248                }
249            }
250        }
251        Some(out)
252    };
253    let from = points(base)?;
254    let to = points(solid)?;
255    if from.len() != to.len() || from.len() < 3 {
256        return None;
257    }
258    let pose = frame_pose(&from, &to)?;
259    let magnitude = from
260        .iter()
261        .chain(&to)
262        .map(|(p, _)| p.x.abs().max(p.y.abs()).max(p.z.abs()))
263        .fold(1.0f64, f64::max);
264    let tolerance = 1e-9 * magnitude;
265    from.iter()
266        .zip(&to)
267        .all(|((p, wp), (q, wq))| wp.to_bits() == wq.to_bits() && pose.point(*p).sub(*q).length() <= tolerance)
268        .then_some(pose)
269}
270
271/// The proper rigid map fixed by three well-spread points of `from` and their
272/// partners in `to`: orthonormal frames on (p0, farthest from p0, farthest
273/// from that line), rotation = frame_to * frame_fromᵀ.
274fn frame_pose(from: &[(Vec3, f64)], to: &[(Vec3, f64)]) -> Option<RigidPose> {
275    let p0 = from[0].0;
276    let (i1, d1) = from
277        .iter()
278        .enumerate()
279        .map(|(i, (p, _))| (i, p.sub(p0).length()))
280        .fold((0, 0.0), |best, next| if next.1 > best.1 { next } else { best });
281    if !(d1 > 0.0) {
282        return None;
283    }
284    let axis = from[i1].0.sub(p0).scale(1.0 / d1);
285    let (i2, d2) = from
286        .iter()
287        .enumerate()
288        .map(|(i, (p, _))| {
289            let d = p.sub(p0);
290            (i, d.sub(axis.scale(d.dot(axis))).length())
291        })
292        .fold((0, 0.0), |best, next| if next.1 > best.1 { next } else { best });
293    if !(d2 > 1e-6 * d1) {
294        return None;
295    }
296    let frame = |a: Vec3, b: Vec3, c: Vec3| -> Option<[Vec3; 3]> {
297        let e1 = b.sub(a);
298        let e1 = e1.scale(1.0 / e1.length());
299        let d = c.sub(a);
300        let e2 = d.sub(e1.scale(d.dot(e1)));
301        let length = e2.length();
302        if !(length > 0.0) {
303            return None;
304        }
305        let e2 = e2.scale(1.0 / length);
306        Some([e1, e2, e1.cross(e2)])
307    };
308    let f = frame(p0, from[i1].0, from[i2].0)?;
309    let g = frame(to[0].0, to[i1].0, to[i2].0)?;
310    // rotation = Σ_k g_k f_kᵀ
311    let mut rotation = [[0.0f64; 3]; 3];
312    for k in 0..3 {
313        let (gk, fk) = ([g[k].x, g[k].y, g[k].z], [f[k].x, f[k].y, f[k].z]);
314        for row in 0..3 {
315            for col in 0..3 {
316                rotation[row][col] += gk[row] * fk[col];
317            }
318        }
319    }
320    let mut pose = RigidPose { rotation, translation: [0.0; 3] };
321    let moved = pose.point(p0);
322    let q0 = to[0].0;
323    pose.translation = [q0.x - moved.x, q0.y - moved.y, q0.z - moved.z];
324    pose.translation.iter().all(|t| t.is_finite()).then_some(pose)
325}
326
327/// Everything but point positions (and names) equal, field by field.
328fn same_but_positions(a: &BrepSolid, b: &BrepSolid) -> bool {
329    let same_bits = |x: &[f64], y: &[f64]| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| p.to_bits() == q.to_bits());
330    let same_weights = |x: &[Vec4], y: &[Vec4]| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| p.w.to_bits() == q.w.to_bits());
331    let same_pcurve = |x: &NurbsCurve, y: &NurbsCurve| {
332        x.degree == y.degree
333            && same_bits(&x.knots, &y.knots)
334            && x.control_points.len() == y.control_points.len()
335            && x.control_points.iter().zip(&y.control_points).all(|(p, q)| {
336                [p.x, p.y, p.z, p.w].iter().zip([q.x, q.y, q.z, q.w]).all(|(u, v)| u.to_bits() == v.to_bits())
337            })
338    };
339    a.kind == b.kind
340        && a.genus == b.genus
341        && a.cells.len() == b.cells.len()
342        && a.cells.iter().zip(&b.cells).all(|(x, y)| x.id == y.id && x.void == y.void && x.faces == y.faces)
343        && a.vertices.len() == b.vertices.len()
344        && a.vertices.iter().zip(&b.vertices).all(|(x, y)| x.id == y.id)
345        && a.edges.len() == b.edges.len()
346        && a.edges.iter().zip(&b.edges).all(|(x, y)| {
347            x.id == y.id
348                && x.start_vertex_id == y.start_vertex_id
349                && x.end_vertex_id == y.end_vertex_id
350                && x.degenerate == y.degenerate
351                && x.t0.to_bits() == y.t0.to_bits()
352                && x.t1.to_bits() == y.t1.to_bits()
353                && x.curve.degree == y.curve.degree
354                && same_bits(&x.curve.knots, &y.curve.knots)
355                && same_weights(&x.curve.control_points, &y.curve.control_points)
356        })
357        && a.shells.len() == b.shells.len()
358        && a.shells.iter().zip(&b.shells).all(|(x, y)| {
359            x.id == y.id
360                && x.faces.len() == y.faces.len()
361                && x.faces.iter().zip(&y.faces).all(|(f, g)| {
362                    f.id == g.id
363                        && f.same_sense == g.same_sense
364                        && f.surface.degree_u == g.surface.degree_u
365                        && f.surface.degree_v == g.surface.degree_v
366                        && same_bits(&f.surface.knots_u, &g.surface.knots_u)
367                        && same_bits(&f.surface.knots_v, &g.surface.knots_v)
368                        && f.surface.control_points.len() == g.surface.control_points.len()
369                        && f.surface.control_points.iter().zip(&g.surface.control_points).all(|(r, s)| same_weights(r, s))
370                        && f.loops.len() == g.loops.len()
371                        && f.loops.iter().zip(&g.loops).all(|(l, m)| {
372                            l.id == m.id
373                                && l.coedges.len() == m.coedges.len()
374                                && l.coedges.iter().zip(&m.coedges).all(|(c, d)| {
375                                    c.id == d.id && c.edge_id == d.edge_id && c.forward == d.forward && same_pcurve(&c.pcurve, &d.pcurve)
376                                })
377                        })
378                })
379        })
380}
381
382/// `base`'s payload carried by `pose`, with `solid`'s own face and edge ids
383/// and names and its own vertices (the meshed copy and `solid` share every id,
384/// [`same_but_positions`]).
385fn posed_payload(base: &DisplaySolidPayload, pose: &RigidPose, solid: &BrepSolid) -> DisplaySolidPayload {
386    let mut mesh = base.mesh.clone();
387    for p in mesh.positions.chunks_exact_mut(3) {
388        let q = pose.point(Vec3::new(p[0], p[1], p[2]));
389        p.copy_from_slice(&[q.x, q.y, q.z]);
390    }
391    for n in mesh.normals.chunks_exact_mut(3) {
392        let q = pose.direction(Vec3::new(n[0], n[1], n[2]));
393        n.copy_from_slice(&[q.x, q.y, q.z]);
394    }
395    let faces = solid
396        .shells
397        .iter()
398        .flat_map(|shell| shell.faces.iter().map(|face| (face.id, face.name.clone())))
399        .collect();
400    let edge_names: std::collections::HashMap<u64, &String> =
401        solid.edges.iter().filter_map(|edge| edge.name.as_ref().map(|name| (edge.id, name))).collect();
402    let edges = base
403        .edges
404        .iter()
405        .map(|(id, _, points)| (*id, edge_names.get(id).map(|name| (*name).clone()), points.iter().map(|p| pose.point(*p)).collect()))
406        .collect();
407    let vertices = solid.vertices.iter().map(|vertex| (vertex.id, vertex.point)).collect();
408    DisplaySolidPayload { faces, mesh, edges, vertices, chord_tolerance: base.chord_tolerance }
409}
410
411/// The display payload of one solid; see [`display_payload_handle_native`].
412pub(crate) fn display_payload_of_solid(solid: &BrepSolid, lod_factor: f64) -> Result<DisplaySolidPayload, String> {
413    let chord = display_chord_tolerance(solid, lod_factor);
414    let mesh = tessellate_brep_watertight(solid, chord)?;
415    let mut faces = Vec::new();
416    for shell in &solid.shells {
417        for face in &shell.faces {
418            faces.push((face.id, face.name.clone()));
419        }
420    }
421    let edge_names: std::collections::HashMap<u64, String> = solid
422        .edges
423        .iter()
424        .filter_map(|edge| edge.name.as_ref().map(|name| (edge.id, name.clone())))
425        .collect();
426    let edges = sample_edge_polylines(solid, chord)?
427        .into_iter()
428        .map(|(id, points)| (id, edge_names.get(&id).cloned(), points))
429        .collect();
430    let vertices = solid
431        .vertices
432        .iter()
433        .map(|vertex| (vertex.id, vertex.point))
434        .collect();
435    Ok(DisplaySolidPayload {
436        faces,
437        mesh,
438        edges,
439        vertices,
440        chord_tolerance: chord,
441    })
442}
443
444/// Native display payload for a solved sketch PROFILE — the SHEET-SOLID view of a
445/// committed sketch: a planar FACE mesh + its named boundary EDGES + corner
446/// VERTICES, so a sketch is pickable / selectable / measurable through the exact
447/// same display path as a real solid. NO solid is registered — the payload is
448/// synthesized directly from the profile, so it owns no scene handle (the display
449/// carries `source_handle = 0`).
450///
451/// The FACE triangulates each region (outer boundary minus holes) via the
452/// watertight planar path, mapped to world through the profile's frame; each
453/// triangle rides face id 0 (one logical sheet face). EDGES are each boundary
454/// curve sampled to a world polyline, named from the profile's `{sketchId}:G{gid}`
455/// edge names; VERTICES are the loop corners. An empty profile (no closed region)
456/// yields an empty payload (no face, no edges) — an open/underconstrained sketch
457/// has no sheet.
458pub fn sketch_profile_display_payload(
459    profile: &crate::feature_pipeline::SketchProfile,
460) -> DisplaySolidPayload {
461    /// Samples per boundary curve — enough to resolve arcs/circles; straight
462    /// segments oversample harmlessly.
463    const SEGMENTS: usize = 24;
464    let origin = profile.origin;
465    let x_axis = profile.x_axis;
466    let y_axis = profile.y_axis;
467    let normal = profile.z_axis;
468    let to_uv = |p: Vec3| {
469        let d = p.sub(origin);
470        [d.dot(x_axis), d.dot(y_axis)]
471    };
472
473    let mut mesh = Mesh::default();
474    let mut edges: Vec<(u64, Option<String>, Vec<Vec3>)> = Vec::new();
475    let mut vertices: Vec<(u64, Vec3)> = Vec::new();
476    let mut next_edge_id: u64 = 0;
477    let mut next_vertex_id: u64 = 0;
478    let mut sketch_id: Option<String> = None;
479
480    for region in &profile.regions {
481        let Some((outer, holes)) = region.split_first() else {
482            continue;
483        };
484        // Boundary vertices (uv, world) for triangulation: sample [t0, t1) per
485        // curve so the next curve contributes the shared corner exactly once.
486        let boundary = |lp: &crate::feature_pipeline::ProfileLoop| -> Vec<([f64; 2], Vec3)> {
487            let mut out = Vec::new();
488            for curve in &lp.curves {
489                let Ok([t0, t1]) = curve.domain() else { continue };
490                for step in 0..SEGMENTS {
491                    let t = t0 + (t1 - t0) * step as f64 / SEGMENTS as f64;
492                    if let Ok(p) = curve.evaluate(t) {
493                        out.push((to_uv(p), p));
494                    }
495                }
496            }
497            out
498        };
499        let outer_b = boundary(outer);
500        let holes_b: Vec<Vec<([f64; 2], Vec3)>> = holes.iter().map(boundary).collect();
501        for [a, b, c] in watertight_tessellation::triangulate_planar_region(&outer_b, &holes_b) {
502            let base = (mesh.positions.len() / 3) as u32;
503            for p in [a, b, c] {
504                mesh.positions.extend([p.x, p.y, p.z]);
505                mesh.normals.extend([normal.x, normal.y, normal.z]);
506            }
507            mesh.indices.extend([base, base + 1, base + 2]);
508            mesh.face_ids.push(0);
509        }
510
511        // Named boundary EDGES + corner VERTICES for every loop of this region.
512        for lp in region {
513            for (index, curve) in lp.curves.iter().enumerate() {
514                let Ok([t0, t1]) = curve.domain() else { continue };
515                let mut polyline = Vec::with_capacity(SEGMENTS + 1);
516                for step in 0..=SEGMENTS {
517                    let t = t0 + (t1 - t0) * step as f64 / SEGMENTS as f64;
518                    if let Ok(p) = curve.evaluate(t) {
519                        polyline.push(p);
520                    }
521                }
522                let name = lp.edge_names.get(index).cloned().flatten();
523                if sketch_id.is_none() {
524                    // `{sketchId}:G{gid}` → the sheet's face inherits `{sketchId}`.
525                    sketch_id = name
526                        .as_deref()
527                        .and_then(|n| n.split_once(":G").map(|(id, _)| id.to_string()));
528                }
529                if polyline.len() >= 2 {
530                    edges.push((next_edge_id, name, polyline));
531                    next_edge_id += 1;
532                }
533                if let Ok(p) = curve.evaluate(t0) {
534                    vertices.push((next_vertex_id, p));
535                    next_vertex_id += 1;
536                }
537            }
538        }
539    }
540
541    // One logical sheet face (id 0), only if the mesh has triangles.
542    let faces = if mesh.face_ids.is_empty() {
543        Vec::new()
544    } else {
545        let face_name = sketch_id.map(|id| format!("{id}:FACE"));
546        vec![(0u64, face_name)]
547    };
548    DisplaySolidPayload {
549        faces,
550        mesh,
551        edges,
552        vertices,
553        chord_tolerance: 0.0,
554    }
555}
556
557/// Native display payload for a whole committed SKETCH: its profile SHEET (when
558/// the sketch closes a region) PLUS every model SEGMENT the sheet does not
559/// already draw.
560///
561/// [`sketch_profile_display_payload`] draws a sketch through its closed profile,
562/// and that is the only display a committed sketch had. A sketch that closes
563/// NOTHING — one line, an open chain, a trajectory drawn alongside a closed loop —
564/// publishes no profile at all, so it was handed to the sheet builder as `None`
565/// and drew nothing: invisible in 3D, and unpickable there (the 2026-09-02 report,
566/// *"Sketch with single edge not visible in 3D"*). Its geometry was never missing,
567/// only unaccepted — the SKETCH feature already publishes one world curve per
568/// model segment under `{sketchId}:G{gid}`, which is exactly what `segments`
569/// carries here.
570///
571/// Each such segment draws as one NAMED edge (the same name a downstream
572/// `reference_selection` stores, so picking the drawn line resolves) with its
573/// endpoints as vertices. A segment whose name the sheet already drew is SKIPPED,
574/// so a closed sketch draws each boundary edge exactly once and a mixed sketch
575/// draws its loop and its open chain side by side. Endpoints are deduped against
576/// the points already drawn — consecutive segments of one chain share a junction.
577///
578/// `points` are the sketch's standalone MODEL points (world space): a sketch
579/// with points only — a hole-placement sketch — has no segment at all, so it
580/// drew nothing and was invisible and unpickable in 3D. Each point draws as a
581/// vertex, deduped against the endpoints the segments already drew, so a point
582/// that is also a segment corner draws once.
583///
584/// Like its sheet sibling this registers no solid: the payload is synthesized
585/// directly from the profile, the curves and the points.
586pub fn sketch_display_payload(
587    profile: Option<&crate::feature_pipeline::SketchProfile>,
588    segments: &[(String, Vec<NurbsCurve>)],
589    points: &[Vec3],
590) -> DisplaySolidPayload {
591    /// Samples per segment for a simple curve — the sheet builder's own
592    /// resolution. A curve with many knot spans (a fitted helix has ~64 per
593    /// turn) gets four samples per span instead, so a long fitted curve draws
594    /// as itself rather than as a coarse polygon; capped so a pathological
595    /// knot vector cannot flood the display.
596    const SEGMENTS: usize = 24;
597    const SAMPLES_PER_SPAN: usize = 4;
598    const MAX_SEGMENTS: usize = 4096;
599    /// Two drawn endpoints closer than this are the same corner (a chain's
600    /// junction points are the SAME solved sketch point, so they agree exactly).
601    const SAME_POINT: f64 = 1e-9;
602
603    let mut payload = match profile {
604        Some(profile) => sketch_profile_display_payload(profile),
605        None => DisplaySolidPayload {
606            faces: Vec::new(),
607            mesh: Mesh::default(),
608            edges: Vec::new(),
609            vertices: Vec::new(),
610            chord_tolerance: 0.0,
611        },
612    };
613
614    let drawn: std::collections::HashSet<String> = payload
615        .edges
616        .iter()
617        .filter_map(|(_, name, _)| name.clone())
618        .collect();
619    let mut next_edge_id = payload
620        .edges
621        .iter()
622        .map(|(id, _, _)| id + 1)
623        .max()
624        .unwrap_or(0);
625    let mut next_vertex_id = payload.vertices.iter().map(|(id, _)| id + 1).max().unwrap_or(0);
626
627    for (name, curves) in segments {
628        if drawn.contains(name) {
629            continue;
630        }
631        for curve in curves {
632            let Ok([t0, t1]) = curve.domain() else { continue };
633            let spans = curve
634                .knots
635                .windows(2)
636                .filter(|pair| pair[1] > pair[0])
637                .count();
638            let segments = (spans * SAMPLES_PER_SPAN).clamp(SEGMENTS, MAX_SEGMENTS);
639            let mut polyline = Vec::with_capacity(segments + 1);
640            for step in 0..=segments {
641                let t = t0 + (t1 - t0) * step as f64 / segments as f64;
642                if let Ok(point) = curve.evaluate(t) {
643                    polyline.push(point);
644                }
645            }
646            if polyline.len() < 2 {
647                continue;
648            }
649            for end in [polyline[0], polyline[polyline.len() - 1]] {
650                if payload
651                    .vertices
652                    .iter()
653                    .any(|(_, point)| point.sub(end).length() <= SAME_POINT)
654                {
655                    continue;
656                }
657                payload.vertices.push((next_vertex_id, end));
658                next_vertex_id += 1;
659            }
660            payload.edges.push((next_edge_id, Some(name.clone()), polyline));
661            next_edge_id += 1;
662        }
663    }
664
665    // Standalone points: one vertex each, skipping any position a segment
666    // endpoint (or an earlier point) already drew.
667    for &point in points {
668        if payload
669            .vertices
670            .iter()
671            .any(|(_, drawn)| drawn.sub(point).length() <= SAME_POINT)
672        {
673            continue;
674        }
675        payload.vertices.push((next_vertex_id, point));
676        next_vertex_id += 1;
677    }
678    payload
679}
680
681/// Full mass properties of a resident solid, scaled to `density` (the native,
682/// non-wasm sibling of [`mass_properties_handle`] for the in-process renderer):
683/// volume + surface area + centroid + centroidal inertia tensor + principal
684/// axes/moments (Golovanov §8.11). The underlying geometry is unit-density; here
685/// `mass = density * volume` and every inertia quantity scales linearly with
686/// density (centroid + principal axes are density-independent). `density` is in
687/// mass units per mm³ (the kernel's length convention is millimetres); pass
688/// `1.0` for the raw geometric result (`mass == volume`). Reads the solid in one
689/// registry borrow; the topology never crosses a boundary.
690pub fn mass_properties_handle_native(
691    handle: u32,
692    density: f64,
693) -> Result<DensityMassProperties, String> {
694    with_registered_solid_str(handle, |solid| {
695        Ok(solid_mass_properties_full(solid)?.with_density(density))
696    })
697}
698
699/// Surface area and volume of a resident solid — the native sibling of
700/// [`mass_properties_handle_native`] for a caller that reads NOTHING but
701/// those two numbers (`examples/case_replay.rs` records volume and area per
702/// solid and discards the rest). The full entry runs a second station sweep
703/// over every trimmed face for the nine moment integrands, which costs as
704/// much again as the area/volume sweep: on `anotherBooleanFail`'s imported
705/// 32-face body 2.6 s against 1.3 s, and 5.3 s of that case's 12.9 s replay
706/// went to moments nobody read. The two numbers come out of the same
707/// `solid_mass_properties` call the full entry starts with, so they are
708/// bit-identical to its `volume` and `surface_area`; the full entry's
709/// refusal of a non-positive volume is kept so a caller switching over sees
710/// the same `Err` on the same solids. Reads the solid in one registry borrow.
711pub fn mass_measures_handle_native(handle: u32) -> Result<MassProperties, String> {
712    with_registered_solid_str(handle, |solid| {
713        let _caller = crate::mass_caller("abi.mass_measures");
714        let properties = solid_mass_properties(solid)?;
715        if properties.volume.abs() <= 1e-30 {
716            return Err("solid_mass_properties_full: non-positive volume".into());
717        }
718        Ok(properties)
719    })
720}
721
722/// Topology validation issues of a resident solid as `(severity, message)`
723/// pairs — the native sibling of the JSON validators, for in-process
724/// qualification tooling (`examples/case_replay.rs`). An empty Vec means the
725/// incidence checks passed; that is NOT a correctness proof: `validate()` tests
726/// neither connectivity nor face-vs-face self-intersection, and a validating
727/// solid can still be the wrong solid. Reads the solid in one registry borrow.
728pub fn validate_handle_native(handle: u32) -> Result<Vec<(String, String)>, String> {
729    with_registered_solid_str(handle, |solid| {
730        Ok(solid
731            .validate()
732            .into_iter()
733            .map(|issue| (issue.severity.to_string(), issue.message))
734            .collect())
735    })
736}
737
738/// Topology TOTALS of a resident solid as
739/// `(faces, edges, non_degenerate_edges, vertices)`, read straight off the
740/// record: every face of every shell, every edge, every edge that is not a
741/// collapsed pole boundary, every vertex.
742///
743/// The two edge counts answer different questions and both are worth
744/// recording. The RAW total is what a reader means by "15 edges" when looking
745/// at the record, and it is the right thing to diff between two runs. The
746/// NON-DEGENERATE count is the one a derivation can state from the intended
747/// construction, because it excludes the seam and pole boundaries the kernel
748/// chose as scaffolding rather than anything the shape has.
749///
750/// These are what a case gate compares. A solid can keep its volume to the
751/// last digit while gaining or losing edges — `inbox-20260909-tube-joint-edge-splits`
752/// carried "7 faces / 17 edges / 11 vertices" in prose for a month with every
753/// local assertion in its suite passing — so the totals are recorded and
754/// diffed.
755///
756/// Since 2026-09-20 they can also be STATED. The two checks answer different
757/// questions and both are kept — a diff against the baseline says "did this
758/// change", a claim says "was it ever right" — and it is the NON-degenerate
759/// count that a claim may state, for the reason above. Reads the solid in one
760/// registry borrow.
761pub fn topology_counts_native(handle: u32) -> Result<(usize, usize, usize, usize), String> {
762    with_registered_solid_str(handle, |solid| {
763        Ok((
764            solid.shells.iter().map(|shell| shell.faces.len()).sum(),
765            solid.edges.len(),
766            solid.edges.iter().filter(|edge| !edge.degenerate).count(),
767            solid.vertices.len(),
768        ))
769    })
770}
771
772/// Connectivity of a resident solid — the check `validate()` does NOT make.
773/// Per-shell edge-connected face components, edges shared across shells, and
774/// pinch vertices. Pure topology, no geometry, no tolerance; see
775/// [`crate::solid_connectivity`] for which part is a gate and which is a
776/// diagnostic. Reads the solid in one registry borrow.
777pub fn connectivity_handle_native(handle: u32) -> Result<crate::ConnectivityReport, String> {
778    with_registered_solid_str(handle, |solid| Ok(crate::solid_connectivity(solid)))
779}
780
781/// Closedness and Euler parity of a resident solid — the THIRD check
782/// `validate()` does not make on its own. Its Euler comparison reduces, on a
783/// freshly derived solid, to exactly "is the characteristic even", and it is
784/// switched off on any solid carrying a degenerate edge; this asks the question
785/// directly and on every solid. Pure counting, one registry borrow.
786pub fn euler_handle_native(handle: u32) -> Result<crate::EulerReport, String> {
787    with_registered_solid_str(handle, |solid| Ok(crate::solid_euler(solid)))
788}
789
790/// The body-kind report of a resident solid. A report beside the Euler
791/// one, not a gate: no body carries a kind yet. Pure counting, one
792/// registry borrow.
793pub fn topology_kind_handle_native(handle: u32) -> Result<crate::KindReport, String> {
794    with_registered_solid_str(handle, |solid| Ok(crate::topology_kind(solid)))
795}
796
797/// The kind a resident solid DECLARES (`BrepSolid::kind`), as distinct
798/// from the kind the report above reads from the edge census. `Solid`
799/// for every body built today.
800pub fn body_kind_handle_native(handle: u32) -> Result<crate::BodyKind, String> {
801    with_registered_solid_str(handle, |solid| Ok(solid.kind))
802}
803
804/// Face-loop self-crossing of a resident solid — the check no OTHER detector
805/// here can make. `validate()` is silent (the incidence is perfect), the
806/// face-versus-face scan has no pair to confirm (both triangles are on one
807/// face), connectivity and Euler parity count the same cells either way; the
808/// face's AREA is the only other tell. Pure parameter-space work on the trims
809/// the face already carries — no tessellation — so it is cheap enough to be a
810/// default. Reads the solid in one registry borrow.
811pub fn loop_crossings_handle_native(handle: u32) -> Result<crate::LoopCrossingReport, String> {
812    with_registered_solid_str(handle, |solid| Ok(crate::loop_self_crossings(solid)))
813}
814
815/// The vector-area closure of a resident solid: does each closed shell's
816/// TRIMS enclose the zero vector area a closed shell owes, and if not, which
817/// faces own the residual. One pass over the trims and the edge curves — no
818/// tessellation, no projection — so unlike the crossing scan it is cheap
819/// enough for a default gate. Reads the solid in one registry borrow.
820pub fn vector_area_handle_native(handle: u32) -> Result<crate::VectorAreaReport, String> {
821    with_registered_solid_str(handle, |solid| Ok(crate::shell_vector_areas(solid)))
822}
823
824/// Face-versus-face self-intersection of a resident solid — the OTHER check
825/// `validate()` does not make (its one "self-intersects" string is a uv-wire
826/// warning). Opt-in and expensive: it tessellates the solid and walks a
827/// triangle BVH, so no default gate calls it. `chord_tolerance` overrides the
828/// per-solid display density when positive. Reads the solid in one registry
829/// borrow.
830pub fn self_intersections_handle_native(
831    handle: u32,
832    chord_tolerance: f64,
833) -> Result<crate::SelfIntersectionReport, String> {
834    with_registered_solid_str(handle, |solid| {
835        let mut options = crate::SelfIntersectionOptions::for_solid(solid);
836        if chord_tolerance > 0.0 && chord_tolerance.is_finite() {
837            options.chord_tolerance = chord_tolerance;
838        }
839        crate::solid_self_intersections(solid, options)
840    })
841}
842
843/// The Transform feature's BBOX_CENTER pivot for a resident source solid.
844/// Share the kernel's vertex-bbox definition with viewport controls; display
845/// tessellation bounds would give a different pivot for curved solids.
846pub fn transform_pivot_native(handle: u32) -> Result<[f64; 3], String> {
847    with_registered_solid_str(handle, |solid| {
848        Ok(crate::feature_pipeline::transform_bbox_center(solid))
849    })
850}
851
852/// Total 3D arc length (mm) of every non-degenerate edge of a resident solid —
853/// the Properties panel's "total edge length" measurement. Native sibling of the
854/// mass-properties accessors; one short registry borrow, topology never crosses
855/// the boundary.
856pub fn solid_edge_length_total_native(handle: u32) -> Result<f64, String> {
857    with_registered_solid_str(handle, solid_edge_length_total)
858}
859
860/// `(area, boundary_edge_total_length, surface_type)` of a resident solid's
861/// named face (mm² / mm / classification): the face's surface area, the summed
862/// arc length of its boundary edges, and a short label for its underlying
863/// carrier surface (`"Plane"`, `"Cylinder"`, `"Cone"`, `"Sphere"`, `"Torus"`,
864/// `"Surface of revolution"`, or `"NURBS"` when the exact rational patch is not
865/// a recognized analytic carrier). Errs if no face carries `face_name`.
866pub fn face_measurements_native(
867    handle: u32,
868    face_name: &str,
869) -> Result<(f64, f64, &'static str), String> {
870    with_registered_solid_str(handle, |solid| {
871        let face = solid
872            .shells
873            .iter()
874            .flat_map(|shell| &shell.faces)
875            .find(|face| face.name.as_deref() == Some(face_name))
876            .ok_or_else(|| format!("face '{face_name}' not found"))?;
877        let surface_type = face
878            .surface
879            .analytic()
880            .map(|analytic| analytic.kind_label())
881            .unwrap_or("NURBS");
882        Ok((
883            face_area(face)?,
884            face_boundary_length(solid, face)?,
885            surface_type,
886        ))
887    })
888}
889
890/// 3D arc length (mm) of a resident solid's named edge. Errs if no edge carries
891/// `edge_name`.
892pub fn edge_length_native(handle: u32, edge_name: &str) -> Result<f64, String> {
893    with_registered_solid_str(handle, |solid| {
894        let edge = solid
895            .edges
896            .iter()
897            .find(|edge| edge.name.as_deref() == Some(edge_name))
898            .ok_or_else(|| format!("edge '{edge_name}' not found"))?;
899        edge_arc_length(edge)
900    })
901}
902
903/// The carrier dimensions of a resident solid's named face, for the Info
904/// panel: a cylinder's radius and diameter, a cone's half-angle, a sphere's
905/// radius, a torus's radii (see [`crate::surface_carrier_dimensions`]).
906/// `Ok(None)` for a plane or a free-form face; errs if no face carries
907/// `face_name`.
908pub fn face_carrier_dimensions_native(
909    handle: u32,
910    face_name: &str,
911) -> Result<Option<crate::CarrierDimensions>, String> {
912    with_registered_solid_str(handle, |solid| {
913        let face = solid
914            .shells
915            .iter()
916            .flat_map(|shell| &shell.faces)
917            .find(|face| face.name.as_deref() == Some(face_name))
918            .ok_or_else(|| format!("face '{face_name}' not found"))?;
919        Ok(crate::surface_carrier_dimensions(&face.surface))
920    })
921}
922
923/// The circle a resident solid's named edge lies on, when it does: radius,
924/// diameter and an arc's sweep (see [`crate::curve_carrier_dimensions`]).
925/// `Ok(None)` for a line or any other curve; errs if no edge carries
926/// `edge_name`.
927pub fn edge_carrier_dimensions_native(
928    handle: u32,
929    edge_name: &str,
930) -> Result<Option<crate::CarrierDimensions>, String> {
931    with_registered_solid_str(handle, |solid| {
932        let edge = solid
933            .edges
934            .iter()
935            .find(|edge| edge.name.as_deref() == Some(edge_name))
936            .ok_or_else(|| format!("edge '{edge_name}' not found"))?;
937        if edge.degenerate {
938            return Ok(None);
939        }
940        Ok(crate::curve_carrier_dimensions(&edge.curve, edge.t0, edge.t1))
941    })
942}
943
944/// Escape hatch: pull a resident solid's full topology across the boundary (for
945/// STEP export or JSON-only lanes during the migration). Prefer handle-native
946/// ops — this re-incurs the serialization cost the registry exists to avoid.
947#[wasm_bindgen]
948pub fn solid_handle_to_buffer(handle: u32) -> Result<WasmSolidBuffer, JsValue> {
949    with_registered_solid(handle, |solid| solid_buffer(solid, "{}".into()))
950}
951
952/// Native: export the CURRENT resident solids (by handle) to an ISO-10303-21
953/// STEP document. Reads each resident solid out of the thread-local registry —
954/// the SAME registry [`display_payload_handle_native`] reads — clones them into
955/// a `Vec<BrepSolid>`, and hands the batch to [`export_step`]. The engine-native
956/// app's Export→STEP lane calls this with the handles the pipeline left resident
957/// after the last history run, so the topology never crosses a boundary as JSON.
958/// `String` error (JsValue-free — it links + runs on native and wasm alike).
959pub fn export_step_handles(
960    handles: &[u32],
961    name: &str,
962    unit: &str,
963    timestamp: &str,
964) -> Result<String, String> {
965    if handles.is_empty() {
966        return Err("export_step_handles: no solids to export".into());
967    }
968    let mut solids = Vec::with_capacity(handles.len());
969    for &handle in handles {
970        let solid: BrepSolid = with_registered_solid_str(handle, |solid| Ok(solid.clone()))?;
971        solids.push(solid);
972    }
973    export_step(&solids, name, unit, timestamp)
974}
975
976/// [`export_step_handles`] with each body's SCENE NAME and an optional PMI
977/// block: the engine-native Export→STEP lane. Names key the
978/// `MANIFOLD_SOLID_BREP`s and the PMI reference resolution.
979pub fn export_step_named_handles(
980    named: &[(String, u32)],
981    name: &str,
982    unit: &str,
983    timestamp: &str,
984    pmi: Option<&crate::StepPmi<'_>>,
985    colors: Option<&crate::StepColors>,
986) -> Result<crate::StepExportReport, String> {
987    if named.is_empty() {
988        return Err("export_step_named_handles: no solids to export".into());
989    }
990    let mut solids = Vec::with_capacity(named.len());
991    for (solid_name, handle) in named {
992        let solid: BrepSolid = with_registered_solid_str(*handle, |solid| Ok(solid.clone()))?;
993        solids.push((solid_name.clone(), solid));
994    }
995    let borrowed: Vec<(String, &BrepSolid)> = solids
996        .iter()
997        .map(|(solid_name, solid)| (solid_name.clone(), solid))
998        .collect();
999    crate::export_step_report_named(&borrowed, name, unit, timestamp, pmi, colors)
1000}
1001
1002/// STRUCTURED export: the resident scene PLUS the document's assembly model, as
1003/// an AP242 file with real product structure — one `PRODUCT` per parts-library
1004/// entry, one `NEXT_ASSEMBLY_USAGE_OCCURRENCE` per placed instance.
1005///
1006/// `named` is the whole resident scene (component-owned bodies included — the
1007/// tree builder filters them, because their geometry is written unposed in the
1008/// part's own product instead). `components` is one entry per ACOMP instance of
1009/// the ROOT document — `(component id, parts-library entry name, live pose)` —
1010/// which only the caller knows, since a solved or gizmo-moved instance's pose
1011/// lives in the app's projection of the scene.
1012pub fn export_step_assembly_handles(
1013    document_name: &str,
1014    named: &[(String, u32)],
1015    components: &[(String, String, crate::Mat4)],
1016    unit: &str,
1017    timestamp: &str,
1018    pmi: Option<&crate::StepPmi<'_>>,
1019    colors: Option<&crate::StepColors>,
1020) -> Result<crate::StepExportReport, String> {
1021    if named.is_empty() {
1022        return Err("export_step_assembly_handles: no solids to export".into());
1023    }
1024    let mut solids = Vec::with_capacity(named.len());
1025    for (solid_name, handle) in named {
1026        let solid: BrepSolid = with_registered_solid_str(*handle, |solid| Ok(solid.clone()))?;
1027        solids.push((solid_name.clone(), solid));
1028    }
1029    let assembly = crate::assembly_export_tree(document_name, solids, components)?;
1030    crate::export_step_assembly_report(&assembly, unit, timestamp, pmi, colors)
1031}
1032
1033/// Native: export the CURRENT resident solids (by handle) to an IGES 5.3
1034/// document of trimmed NURBS surfaces. The IGES analogue of
1035/// [`export_step_handles`] — reads the resident solids out of the thread-local
1036/// registry, clones them into a `Vec<BrepSolid>`, and hands the batch to
1037/// [`export_iges`]. `String` error (JsValue-free — links on native and wasm).
1038pub fn export_iges_handles(
1039    handles: &[u32],
1040    name: &str,
1041    unit: &str,
1042    timestamp: &str,
1043) -> Result<String, String> {
1044    if handles.is_empty() {
1045        return Err("export_iges_handles: no solids to export".into());
1046    }
1047    let mut solids = Vec::with_capacity(handles.len());
1048    for &handle in handles {
1049        let solid: BrepSolid = with_registered_solid_str(handle, |solid| Ok(solid.clone()))?;
1050        solids.push(solid);
1051    }
1052    export_iges(&solids, name, unit, timestamp)
1053}