Skip to main content

brep_boolean/csg/
imprint.rs

1use crate::classification::{parameter_point_in_face, PolygonClass};
2use crate::curve::KNOT_IDENTITY_TOL;
3pub use crate::spatial::{Aabb, Bvh};
4use crate::solid_scale;
5use crate::tolerance::{
6    assembler_weld, merge_scale, COINCIDENCE_DISTANCE_FLOOR, WELD_FLOOR,
7};
8pub use crate::topology::{BrepSolid, EdgeRecord, FaceRecord};
9pub use crate::{
10    build_pcurve_on_surface, classify_surface_pair_cached,
11    fit_polyline_of_degree, PolylineFit,
12    intersect_curves, project_point_to_curve,
13    project_point_to_surface, project_point_to_surface_seeded, KnotVector, NurbsCurve, NurbsSurface,
14    SurfaceClassifyData,
15    SurfaceIntersectionOptions, SurfacePairClassification, SurfacePairRelation, Vec2, Vec3, Vec4,
16};
17pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
18use serde::{Deserialize, Serialize};
19use std::time::Duration;
20use web_time::Instant;
21
22// The profile line buffer, `profile_line!` and `profile_enabled` live in
23// `crate::profile` (consolidation I8); these paths stay for their callers.
24pub use crate::profile::{profile_emit, profile_enabled, ProfileSink};
25
26/// Per-step wall-clock accumulators for `build_imprints`, printed to stderr
27/// when `BREP_PROFILE` is set. Native-only in practice (no env vars in wasm).
28#[derive(Default)]
29struct ImprintProfile {
30    enabled: bool,
31    pairs: u64,
32    marched_pairs: u64,
33    whole_reading_reuses: u64,
34    classify: Duration,
35    cosurface: Duration,
36    lies_on: Duration,
37    planar_iso: Duration,
38    analytic: Duration,
39    seeds: Duration,
40    march: Duration,
41    clip_and_fit: Duration,
42    process_curve: Duration,
43    /// `clip_and_fit` split: the swapped-order rescue marches, the trim clip,
44    /// the shared-boundary test, the polyline fit, and `process_curve`.
45    rescue_march: Duration,
46    clip: Duration,
47    shared_boundary: Duration,
48    fit: Duration,
49    process: Duration,
50    hermite_runs: u64,
51    fit_runs: u64,
52    hermite: Duration,
53    /// Appended at the end.
54    pairs_fits: u64,
55    exact_lane_fits: u64,
56    /// Slice 1: planar-iso sections whose exact pcurves were handed to the
57    /// builder, and those declined (a lifted chart, or no pcurve built).
58    exact_iso_sections: u64,
59    exact_iso_declined: u64,
60}
61
62impl ImprintProfile {
63    fn new() -> Self {
64        Self {
65            enabled: profile_enabled(),
66            ..Self::default()
67        }
68    }
69
70    fn lap(&self, started: &mut Option<Instant>) -> Duration {
71        crate::profile::lap(self.enabled, started)
72    }
73
74    fn report(&self) {
75        if !self.enabled {
76            return;
77        }
78        profile_line!("imprint.whole_reading_reuses count={}", self.whole_reading_reuses);
79        let ms = |d: Duration| d.as_secs_f64() * 1_000.0;
80        profile_line!(
81            "imprint.profile pairs={} marched={} classify={:.2} cosurface={:.2} lies_on={:.2} planar_iso={:.2} analytic={:.2} seeds={:.2} march={:.2} clip_fit={:.2} process_curve={:.2}",
82            self.pairs,
83            self.marched_pairs,
84            ms(self.classify),
85            ms(self.cosurface),
86            ms(self.lies_on),
87            ms(self.planar_iso),
88            ms(self.analytic),
89            ms(self.seeds),
90            ms(self.march),
91            ms(self.clip_and_fit),
92            ms(self.process_curve),
93        );
94        profile_line!(
95            "imprint.clip_fit rescue_march={:.2} clip={:.2} shared_boundary={:.2} fit={:.2} process={:.2} hermite={:.2} hermite_runs={} fit_runs={}",
96            ms(self.rescue_march),
97            ms(self.clip),
98            ms(self.shared_boundary),
99            ms(self.fit),
100            ms(self.process),
101            ms(self.hermite),
102            self.hermite_runs,
103            self.fit_runs,
104        );
105        profile_line!(
106            "imprint.fits pairs={} exact_lanes={} exact_iso_sections={} exact_iso_declined={}",
107            self.pairs_fits,
108            self.exact_lane_fits,
109            self.exact_iso_sections,
110            self.exact_iso_declined,
111        );
112        driver::fit_split_report();
113    }
114}
115
116/// Lane P3b row 0 (2026-10-26): where `process_curve`'s crossing loop, the
117/// lies-on span search and the boundary-reuse pass spend their time, read only
118/// under `BREP_PROFILE` and printed once per `build_imprints` as
119/// `imprint.split`. Thread-local because the builder and the support
120/// functions have no profile handle; `take` drains it for the report.
121#[derive(Default, Clone, Copy)]
122pub struct ImprintSplit {
123    pub pierce: Duration,
124    pub pierce_edges: u64,
125    pub overlap: Duration,
126    pub overlap_edges: u64,
127    pub crossing: Duration,
128    pub crossing_edges: u64,
129    pub recover: Duration,
130    pub recover_pierces: u64,
131    pub lies_whole: Duration,
132    pub lies_whole_calls: u64,
133    pub lies_whole_hits: u64,
134    pub lies_span: Duration,
135    pub lies_span_calls: u64,
136    pub reuse_edges: u64,
137}
138thread_local! {
139    static IMPRINT_SPLIT: std::cell::Cell<ImprintSplit> = const { std::cell::Cell::new(ImprintSplit {
140        pierce: Duration::ZERO, pierce_edges: 0, overlap: Duration::ZERO, overlap_edges: 0,
141        crossing: Duration::ZERO, crossing_edges: 0, recover: Duration::ZERO, recover_pierces: 0,
142        lies_whole: Duration::ZERO, lies_whole_calls: 0, lies_whole_hits: 0,
143        lies_span: Duration::ZERO, lies_span_calls: 0, reuse_edges: 0,
144    }) };
145}
146pub fn imprint_split_add(update: impl FnOnce(&mut ImprintSplit)) {
147    IMPRINT_SPLIT.with(|cell| { let mut split = cell.get(); update(&mut split); cell.set(split); });
148}
149pub fn imprint_split_take() -> ImprintSplit {
150    IMPRINT_SPLIT.with(|cell| cell.replace(ImprintSplit::default()))
151}
152
153/// Coarse observation of optional contact/graph calls, including early
154/// declines. It owns no geometry and does not change caller diagnostics.
155struct ImprintSubphaseClock {
156    started: Option<Instant>,
157    label: &'static str,
158}
159impl ImprintSubphaseClock {
160    fn new(label: &'static str) -> Self {
161        Self { started: profile_enabled().then(Instant::now), label }
162    }
163}
164impl Drop for ImprintSubphaseClock {
165    fn drop(&mut self) {
166        if let Some(started) = self.started {
167            profile_line!("imprint.subphase label={} ms={:.3}", self.label, started.elapsed().as_secs_f64() * 1000.0);
168        }
169    }
170}
171
172#[derive(Clone, Debug, Deserialize)]
173pub struct ImprintOptions {
174    #[serde(default = "default_tolerance")]
175    pub tolerance: f64,
176    #[serde(default = "default_maximum_fit_points")]
177    pub maximum_fit_points: usize,
178    #[serde(default)]
179    pub local_fit: bool,
180    #[serde(default)]
181    pub fit_chunk_points: Option<usize>,
182    pub maximum_ssi_step: Option<f64>,
183    /// `None`, the default, marches exactly as before. `BREP_SPAN_BUDGET`
184    /// overrides either way: `fit` is the pair's `intersection_fit` at the
185    /// operands' scale, a number is an absolute budget, `off` is none.
186    /// `BREP_SPAN_CENSUS=<file>` appends one line per clipped section with its
187    /// stations, deviation and refine route (`span-budget census:`), labelled
188    /// by `BREP_CENSUS_LABEL`.
189    #[serde(default)]
190    pub span_budget: Option<f64>,
191    /// Implies a span budget of the pair's `intersection_fit` when none is
192    /// set. Off by default; `BREP_HERMITE_SECTIONS` overrides either way (`0`
193    /// off, anything else on).
194    #[serde(default)]
195    pub hermite_sections: bool,
196    /// The TANGENT-CURVE lane: where an exact lane proves a pair's transverse
197    /// intersection empty, or the tangential-only gate would skip it, and the
198    /// pair classification reads near-tangent, look for an EXTENDED contact
199    /// (`crate::tangent_curve`), march it with one planar carrier, and record it
200    /// as a typed tangent section ([`ImprintResultRecord::tangent_sections`]).
201    /// The boolean then names the contact in any refusal it raises on the pair
202    /// instead of leaking the arrangement's own message. On by default since the
203    /// census of 2026-10-10 (every manifest leaf identical with the lane on and
204    /// off, `hlr_tests` green both ways); the section is recorded, never
205    /// imprinted, so nothing the boolean builds changes.
206    /// `BREP_TANGENT_CURVE_LANE=0` is the escape hatch. Appended at the end of
207    /// the struct (2026-10-10).
208    #[serde(default = "default_tangent_curve_lane")]
209    pub tangent_curve_lane: bool,
210    /// EXACT PCURVES FOR THE PLANAR-ISO LANE (slice 1, 2026-10-11, the
211    /// catalogue's P3 applied to the exact lane): a section the planar-iso
212    /// lane answers is an iso-curve of the ruled carrier and an affine image
213    /// on the plane, so both pcurves are written down on the curve's own
214    /// knots (`support::planar_iso_section`) instead of fitted, and the
215    /// junction pass moves their ends instead of re-marching them. Off by
216    /// default (the fitted pcurves are the shipped bytes);
217    /// `BREP_EXACT_ISO_PCURVES` overrides either way: `0`/`off`, `on`, or
218    /// `check`, which fits as before and appends one census line per pcurve
219    /// comparing the fitted and the exact one in 3-D
220    /// (`BREP_EXACT_ISO_CENSUS=<file>`, labelled by `BREP_CENSUS_LABEL`). A
221    /// face read in a lifted chart declines the exact pcurve (the iso line
222    /// is in the carrier's frame). Appended at the end of the struct.
223    #[serde(default)]
224    pub exact_iso_pcurves: bool,
225    /// MARCH STARTS: every surface/surface march the imprint runs traces
226    /// its starts in order (explicit trim-boundary pierces first, the most
227    /// transverse first, a run-through start consumed with a snapped
228    /// station) and seeds its interior candidates from the two carriers'
229    /// knot-span leaves instead of a fixed grid
230    /// ([`SurfaceIntersectionOptions::ordered_starts`],
231    /// [`SurfaceIntersectionOptions::tree_seeds`]). Off by default (the
232    /// grid-then-seeds march is the shipped one, byte for byte);
233    /// `BREP_MARCH_STARTS` overrides either way: `0`/`off`, `order` (A3's
234    /// ordering alone), `snap` (the ordering with run-through starts
235    /// consumed), `tree` (A4 alone), `order+tree`, anything else all three.
236    /// Appended at the end of the struct.
237    #[serde(default)]
238    pub march_starts: bool,
239    /// Candidates for one junction are captured within the wide residual
240    /// band; two combine only when they are connected (share a support face)
241    /// and lie within the strict radius built from their own evidence radii;
242    /// the surviving position is the lowest-dimensional candidate's, an
243    /// operand vertex over an operand edge's crossing over a section end on
244    /// two carriers. Off by default until the census in the record promotes
245    /// it; `BREP_JUNCTION_COMBINE` overrides either way (`0`/`off`, `check`
246    /// for the census that logs every junction's candidates to
247    /// `BREP_JUNCTION_CENSUS` without moving anything, anything else on).
248    /// Appended at the end of the struct (2026-10-11).
249    #[serde(default)]
250    pub two_radius_junctions: bool,
251    /// IMPRINT THE TANGENT SECTION (the pinched result): a planar-carrier
252    /// contact the tangent-curve lane traced is also IMPRINTED —
253    /// `process_curve` on the clipped run, so the contact becomes a section
254    /// piece on both carriers, the operand edges its ends lie on are split
255    /// there, and every earlier piece the ends lie on (the through-bore's cap
256    /// circles) is split at them — and its piece ids are recorded in
257    /// [`TangentSectionRecord::piece_ids`]. The boolean's assembler then
258    /// pairs the four coedges of such a piece by MATERIAL SIDE (two edge
259    /// records on one locus, each manifold) instead of by arrival, so the
260    /// grazing through-bore builds as one shell whose tangent edge is carried
261    /// twice. On by default since the census of 2026-10-11 (the battery
262    /// moving only the pins that asserted the old refusal and the recentre
263    /// pin whose unguarded far fillet now completes);
264    /// `BREP_TANGENT_CURVE_IMPRINT=0` is the escape hatch. Requires
265    /// `tangent_curve_lane`. Appended at the end of the struct (2026-10-11).
266    #[serde(default = "default_tangent_curve_imprint")]
267    pub tangent_curve_imprint: bool,
268}
269
270pub fn default_tolerance() -> f64 {
271    1e-7
272}
273
274fn default_tangent_curve_lane() -> bool {
275    switch!(live "BREP_TANGENT_CURVE_LANE", true)
276}
277
278fn default_tangent_curve_imprint() -> bool {
279    switch!(live "BREP_TANGENT_CURVE_IMPRINT", true)
280}
281
282fn default_maximum_fit_points() -> usize {
283    80
284}
285
286/// Angular band inside which two surface normals count as PARALLEL when a face
287/// pair is classified (`|n_a × n_b| <= PAIR_ANGULAR_TOLERANCE` ⇒ the carriers
288/// graze rather than cross there).  Single source for the pair classifier's
289/// angular tolerance and for the near-tangency test that picks the march step.
290pub const PAIR_ANGULAR_TOLERANCE: f64 = 1e-4;
291
292/// Whether the imprint reads `first` and `second` as ONE surface (the
293/// sampled pair classification's `Cosurface`, or `cosurface_pair`) and
294/// exchanges boundary curves across them instead of intersecting them. The
295/// feature-scale measure (`crate::feature_scale`) records no sliver between
296/// such a pair: the revolve pole fixtures' side planes and their copies stand
297/// 3.8e-6 apart over the region and follow the coincident-face rule.
298pub fn reads_as_one_surface(first: &NurbsSurface, second: &NurbsSurface, tolerance: f64) -> Result<bool, String> {
299    let relation = crate::classify_surface_pair(first, second, tolerance, PAIR_ANGULAR_TOLERANCE)?.relation;
300    Ok(relation == SurfacePairRelation::Cosurface
301        || support::cosurface_pair(first, second, tolerance).map_err(|refusal| refusal.message)?)
302}
303
304/// Fraction of the part extent used as the FLOOR of the near-tangency march
305/// step when the two carriers actually touch (`minimum_separation == 0`), so
306/// the reachable curve length is a fixed fraction of the model rather than an
307/// absolute distance.  See `march_maximum_step`.
308const NEAR_TANGENT_STEP_FRACTION: f64 = 1e-3;
309
310/// Span band for the B2 shared-section-edge decision, as a FRACTION of the part
311/// extent (so it tracks feature size, not an absolute distance). A SSI section
312/// is declared coincident with an existing boundary edge only when it lies
313/// within `SHARED_SECTION_BAND_FRACTION * extent` of that edge along its whole
314/// span in BOTH directions AND their endpoints already coincide within the weld
315/// radius. Sized to admit a genuine near-tangent GRAZE (the marched/analytic
316/// section drifts from the vendor edge by a graze-scale gap two-three orders
317/// above the fit residual — the B1-falsification measurement) while staying far
318/// below the feature scale at which a distinct same-endpoint edge diverges.
319/// Measured on fixture 09 (extent ~3.23, band ~3.23e-3): the two genuine graze
320/// gaps are 8.2e-4 and 1.67e-3 (ratios 2.5e-4 / 5.2e-4) — comfortably inside;
321/// fixtures 12/04 (the wrong-reuse tripwires) produce ZERO reuses and the
322/// prim×prim fuzz shows 0/2800 outcome changes, so the band is well separated
323/// from any distinct-edge scale.
324const SHARED_SECTION_BAND_FRACTION: f64 = 1e-3;
325
326/// Maximum march step for one face pair.
327///
328/// A NEAR-TANGENT pair marches finely: where the carriers graze, the corrector
329/// can hop between the two sheets of the contact, so the step stays inside the
330/// separation band.  Two things that step must NOT be:
331///
332/// * **applied to a pair that only crosses.** A pair is classified `Singular`
333///   when any sample near the contact has a DEGENERATE normal (a pole of a
334///   revolution carrier) — that says nothing about tangency, and the pair can
335///   cross at 90°.  Marching a transverse crossing at the tangency step crawls,
336///   and a curve longer than `maximum_steps × step` then dies as "trace
337///   exhausted" (2026-08-06 report: a draft-angle extrude wall against a
338///   revolve-of-revolve face — a 2.0-unit curve needing 4014 steps of 4000,
339///   10 points once marched at its own scale).  The step is therefore gated on
340///   the classification's own tangency evidence, not on the relation label.
341/// * **an absolute distance.** A fixed floor is a different fraction of every
342///   model, so the reachable curve length depended on part size.  The floor is
343///   a fraction of the part extent instead; `solid_scale` is at least 1, so
344///   unit-scale parts keep the historical `1e-3` exactly.
345pub fn march_maximum_step(
346    classification: &SurfacePairClassification,
347    requested: Option<f64>,
348    scale: f64,
349) -> Option<f64> {
350    let grazes = matches!(
351        classification.relation,
352        SurfacePairRelation::NearTangent | SurfacePairRelation::Singular
353    ) && classification.minimum_normal_cross <= PAIR_ANGULAR_TOLERANCE;
354    if !grazes {
355        return requested;
356    }
357    Some(
358        requested.unwrap_or(
359            classification
360                .minimum_separation
361                .max(NEAR_TANGENT_STEP_FRACTION * scale),
362        ) * 0.5,
363    )
364}
365
366impl Default for ImprintOptions {
367    fn default() -> Self {
368        Self {
369            tolerance: default_tolerance(),
370            maximum_fit_points: default_maximum_fit_points(),
371            local_fit: false,
372            fit_chunk_points: None,
373            maximum_ssi_step: None,
374            span_budget: None,
375            hermite_sections: false,
376            tangent_curve_lane: default_tangent_curve_lane(),
377            tangent_curve_imprint: default_tangent_curve_imprint(),
378            exact_iso_pcurves: false,
379            march_starts: false,
380            two_radius_junctions: false,
381        }
382    }
383}
384
385#[derive(Clone, Debug, Deserialize, Serialize)]
386pub struct ImprintVertex {
387    pub id: u64,
388    pub point: Vec3,
389}
390
391#[derive(Clone, Debug, Deserialize, Serialize)]
392pub struct FacePcurve {
393    pub operand: u8,
394    pub face_id: u64,
395    pub pcurve: NurbsCurve,
396}
397
398#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize)]
399pub struct FaceKey {
400    pub operand: u8,
401    pub face_id: u64,
402}
403
404/// Ephemeral evidence bound to the exact minted curve and ordered supports.
405/// Serialized imprints deliberately discard it; geometric refits cannot inherit it.
406#[derive(Clone, Debug)]
407pub struct CertifiedRulingPiece {
408    pub(super) piece_id: u64,
409    pub(super) parameters: [f64; 2],
410    pub(super) vertices: [u64; 2],
411    pub(super) certificate: brep_geometry::certified_planar::ruling::CertifiedRuling,
412    pub(super) minted_curve: NurbsCurve,
413    pub(super) minted_pcurves: Vec<FacePcurve>,
414    pub(super) support_faces: [FaceKey; 2],
415}
416
417impl ImprintPieceRecord {
418    /// A freshly minted section piece: the curve over `[t0, t1]` from vertex
419    /// `[start, end]`, with its pcurves on the two support faces. It shares no
420    /// existing edge and carries no certified ruling side; set `shared_edge`
421    /// (or call [`Self::with_shared_edge`]) when it reuses a boundary edge.
422    pub fn new(
423        id: u64,
424        curve: NurbsCurve,
425        [t0, t1]: [f64; 2],
426        [start_vertex_id, end_vertex_id]: [u64; 2],
427        pcurves: Vec<FacePcurve>,
428        support_faces: [FaceKey; 2],
429    ) -> Self {
430        Self {
431            id,
432            curve,
433            t0,
434            t1,
435            start_vertex_id,
436            end_vertex_id,
437            pcurves,
438            support_faces,
439            shared_edge: None,
440            certified_ruling_side: None,
441        }
442    }
443
444    /// This piece resolved to the existing boundary edge `(operand, edge_id,
445    /// aligned)`, or to none.
446    pub fn with_shared_edge(mut self, shared_edge: Option<(u8, u64, bool)>) -> Self {
447        self.shared_edge = shared_edge;
448        self
449    }
450
451    pub fn certified_ruling(&self, supports: [FaceKey; 2], charts: [&NurbsSurface; 2])
452        -> Option<&brep_geometry::certified_planar::ruling::CertifiedRuling>
453    {
454        let evidence = self.certified_ruling_side.as_ref()?;
455        (self.shared_edge.is_none() && evidence.piece_id == self.id
456            && evidence.parameters == [self.t0, self.t1]
457            && evidence.vertices == [self.start_vertex_id, self.end_vertex_id]
458            && self.support_faces == supports
459            && evidence.support_faces == supports
460            && brep_geometry::certified_planar::ruling::same_curve(&self.curve, &evidence.minted_curve)
461            && self.pcurves.len() == evidence.minted_pcurves.len()
462            && self.pcurves.iter().zip(&evidence.minted_pcurves).all(|(a,b)|
463                a.operand == b.operand && a.face_id == b.face_id
464                && brep_geometry::certified_planar::ruling::same_curve(&a.pcurve, &b.pcurve))
465            && evidence.certificate.accepts_subcurve(&self.curve)
466            && evidence.certificate.matches_surfaces(charts[0], charts[1]))
467            .then_some(&evidence.certificate)
468    }
469}
470
471/// Not exhaustive: a new field is not a breaking change. Outside this crate,
472/// build one with `ImprintPieceRecord::new`.
473#[derive(Clone, Debug, Deserialize, Serialize)]
474#[non_exhaustive]
475pub struct ImprintPieceRecord {
476    pub id: u64,
477    pub curve: NurbsCurve,
478    pub t0: f64,
479    pub t1: f64,
480    pub start_vertex_id: u64,
481    pub end_vertex_id: u64,
482    pub pcurves: Vec<FacePcurve>,
483    pub support_faces: [FaceKey; 2],
484    /// OCCT common-block / `IsExistingPaveBlock` (B2): when this SSI section
485    /// curve was found to COINCIDE along its whole span with an EXISTING
486    /// boundary edge of one of its support faces, the section is not a new
487    /// 1-cell — it IS that boundary edge. Records `(operand, edge_id, aligned)`
488    /// of the existing edge to REUSE; `aligned` is whether the section's
489    /// start→end runs the same direction as the edge's start→end. The
490    /// assembler then resolves this piece to the shared boundary edge's
491    /// identity so both operands reference ONE edge (no duplicate section /
492    /// one-use edge). `None` = an ordinary freshly-minted section (the
493    /// historical behaviour; also what `BREP_SHARED_SECTION_EDGE=0` forces).
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub shared_edge: Option<(u8, u64, bool)>,
496    #[serde(skip)]
497    pub certified_ruling_side: Option<CertifiedRulingPiece>,
498}
499
500/// Not exhaustive: a new field is not a breaking change. Outside this crate,
501/// build one with `EdgeSplitRecord::new`.
502#[derive(Clone, Debug, Deserialize, Serialize)]
503#[non_exhaustive]
504pub struct EdgeSplitRecord {
505    pub operand: u8,
506    pub edge_id: u64,
507    pub parameters: Vec<f64>,
508}
509
510impl EdgeSplitRecord {
511    /// Split `operand`'s edge `edge_id` at `parameters`.
512    pub fn new(operand: u8, edge_id: u64, parameters: Vec<f64>) -> Self {
513        Self { operand, edge_id, parameters }
514    }
515}
516
517#[derive(Clone, Debug, Deserialize, Serialize)]
518pub struct FaceImprints {
519    pub operand: u8,
520    pub face_id: u64,
521    pub piece_ids: Vec<u64>,
522}
523
524/// Not exhaustive: a new field is not a breaking change. Outside this crate,
525/// start from `ImprintResultRecord::default()` and set the fields you need.
526#[derive(Clone, Debug, Default, Deserialize, Serialize)]
527#[non_exhaustive]
528pub struct ImprintResultRecord {
529    pub vertices: Vec<ImprintVertex>,
530    pub pieces: Vec<ImprintPieceRecord>,
531    pub by_face: Vec<FaceImprints>,
532    pub edge_splits: Vec<EdgeSplitRecord>,
533    /// Operand edges geometrically OVERLAPPED by a section curve (the
534    /// cosurface/coincident locus: an inscribed sphere's contact circle
535    /// riding a cap ring). Fragment-selection fate must never flood across
536    /// them — the two sides of such an edge can lie on opposite sides of
537    /// the other operand (the cap disc inside, the wall outside).
538    #[serde(default)]
539    pub barrier_edges: Vec<(u8, u64)>,
540    /// Every ISOLATED TANGENT NODE the imprint admitted: a point where the two
541    /// carriers touch with parallel normals and the section crosses itself, so
542    /// the pair was marched rather than refused (see
543    /// `imprint/tangent_contact.rs`). The boolean attributes a later tearing to
544    /// these rather than reporting an anonymous degeneracy — the second-order
545    /// filter cannot decide a third-order singularity, so the assembly is the
546    /// authority on whether a node it admitted was really imprintable.
547    #[serde(default)]
548    pub tangent_nodes: Vec<Vec3>,
549    /// True when the imprint saw ANY surface-contact evidence — an accepted
550    /// pierce seed, a traced SSI branch (even one later clipped away), or a
551    /// minted piece. Pure material disjointness leaves none, while a
552    /// silently-lost section always leaves at least the upstream evidence, so
553    /// the boolean's legitimate-empty adjudication requires this to be false.
554    #[serde(default)]
555    pub section_evidence: bool,
556    /// Every face pair the imprint read as ONE surface and exchanged boundary
557    /// curves across instead of intersecting (`cosurface_pair`, or the sampled
558    /// pair classification's `Cosurface`). Selection holds a fragment whose
559    /// point lies in such a partner's trim On against it, so the coincidence
560    /// the sections were built on is the one the fragments are kept by.
561    #[serde(default)]
562    pub cosurface_pairs: Vec<(FaceKey, FaceKey)>,
563    /// `BREP_FEATURE_SCALE_OPERAND_SLIVERS`: the regions (minimum, maximum) of
564    /// the slivers FeatureScale registered between the two operands' faces.
565    /// The fragmenter narrows its endpoint bands on a face that meets one.
566    #[serde(default)]
567    pub operand_sliver_regions: Vec<([f64; 3], [f64; 3])>,
568    /// Every EXTENDED tangential contact the tangent-curve lane recognised
569    /// ([`ImprintOptions::tangent_curve_lane`]): the carriers touch along a
570    /// curve inside both trims. A planar-carrier contact is marched and the
571    /// clipped run described; a curved/curved contact is named at its point
572    /// and not traced. None of these is imprinted yet — the record exists so
573    /// the boolean can attribute a refusal on the pair to the contact by name.
574    /// Appended at the end of the struct (2026-10-10).
575    #[serde(default)]
576    pub tangent_sections: Vec<TangentSectionRecord>,
577    /// The faces of either operand that stand in at least one cross-operand
578    /// face pair the imprint did NOT positively prove apart: every pair whose
579    /// face boxes met and was neither classified `Disjoint` (control-hull or
580    /// parallel-plane separation) nor proved apart by the trim windows' span
581    /// hulls. A face absent from it was proved clear of every face of the
582    /// other operand (its box met none, or each pair it met was proved apart),
583    /// so nothing the operation added can cross it. `None` wherever the
584    /// imprint did not run its plain two-operand pair loop (a self-imprint,
585    /// a record assembled elsewhere): then no face may be read as proved.
586    #[serde(default)]
587    pub faces_in_unproved_pairs: Option<Vec<FaceKey>>,
588}
589
590/// One extended tangential contact the imprint recognised (see
591/// [`ImprintResultRecord::tangent_sections`]).
592#[derive(Clone, Debug, Deserialize, Serialize)]
593pub struct TangentSectionRecord {
594    pub first: FaceKey,
595    pub second: FaceKey,
596    /// Ends of the longest run of the traced contact inside both trims (the
597    /// contact point itself when the contact was not traced).
598    pub start: Vec3,
599    pub end: Vec3,
600    /// Chord length of that run.
601    pub length: f64,
602    /// The run is the whole traced curve and the curve closed on itself.
603    pub closed: bool,
604    /// Stations of the run.
605    pub stations: usize,
606    /// One carrier is a plane: the branch the lane traces. `false` names a
607    /// curved/curved contact the lane recognises but does not trace.
608    pub planar: bool,
609    /// The faces the contact INVOLVES: the two carriers' faces, and every face
610    /// of either operand that shares an edge the run's ends lie on (the
611    /// through-bore's contact line ends on the wall's top and bottom edges,
612    /// so the box's top and bottom faces are involved; a blind pocket's ends
613    /// lie on the bore's cap rings, so the caps are). The boolean's
614    /// attribution rewrites a refusal only when a face it names is in here.
615    #[serde(default)]
616    pub faces: Vec<FaceKey>,
617    /// The section pieces the contact was imprinted as
618    /// ([`ImprintOptions::tangent_curve_imprint`]): `process_curve`'s pieces
619    /// on the clipped run, in mint order. Empty when the section was recorded
620    /// only. The assembler pairs the coedges of these pieces by material side.
621    /// Appended at the end of the struct (2026-10-11).
622    #[serde(default, skip_serializing_if = "Vec::is_empty")]
623    pub piece_ids: Vec<u64>,
624    /// GRAZING PIERCES WITHOUT A SECTION (2026-10-17, the revolve-into-bore
625    /// report): a trim edge of one face pierces the other carrier INSIDE both
626    /// trims, but at an angle below the seed gate, and the march found no
627    /// branch for the pair. The pierce proves a section crosses the faces
628    /// there; the empty march says the crossing is too near tangency to walk
629    /// (a third-order contact: the branch is born tangent to a contact curve
630    /// on a shared boundary, `boolean::attribute_to_tangent_node`). Each
631    /// entry is the pierce point and its `|edge_tangent · normal|`. Such a
632    /// record is attribution only — nothing is imprinted — and names the
633    /// contact when the assembly tears downstream of it. Appended at the end
634    /// of the struct.
635    #[serde(default, skip_serializing_if = "Vec::is_empty")]
636    pub grazing: Vec<(Vec3, f64)>,
637}
638
639impl TangentSectionRecord {
640    /// A record standing on its grazing pierces ALONE — the lane found no
641    /// contact to name, so the driver set its ends to the pierces (its
642    /// `start` IS the first pierce, bit for bit, and nothing was traced). The
643    /// boolean's attribution reads such a record only as a fallback: a
644    /// contact the lane found, or a tangent node the imprint classified, is
645    /// the nearer cause and keeps its own wording.
646    pub fn pierce_only(&self) -> bool {
647        self.stations == 0
648            && self
649                .grazing
650                .first()
651                .is_some_and(|(point, _)| point.sub(self.start).length() == 0.0)
652    }
653}
654
655#[path = "imprint/ruled_torus.rs"]
656mod ruled_torus;
657pub use ruled_torus::{circular_revolution_profile, construct_ruled_torus};
658
659#[path = "imprint/support.rs"]
660pub mod support;
661#[path = "imprint/builder.rs"]
662pub mod builder;
663#[path = "imprint/junctions.rs"]
664mod junctions;
665#[path = "imprint/self_touch.rs"]
666pub mod self_touch;
667#[path = "imprint/sections.rs"]
668pub mod sections;
669#[path = "imprint/tangent_contact.rs"]
670mod tangent_contact;
671#[path = "imprint/driver.rs"]
672pub mod driver;
673
674#[path = "imprint/work_profile.rs"]
675pub mod work_profile;
676#[path = "imprint/reuse_profile.rs"]
677pub use crate::reuse_profile;
678#[path = "imprint/hermite.rs"]
679mod hermite;
680pub use hermite::{carried_uv_enabled, carried_uv_min_stations};
681
682#[path = "imprint/gate_census.rs"]
683pub mod gate_census;
684
685use builder::*;
686pub use junctions::*;
687pub use sections::*;
688pub use support::*;
689
690#[path = "imprint/section_graph.rs"]
691mod section_graph;
692pub use section_graph::{plane_section_graph, plane_section_graph_range, plane_section_graph_range_bounded};
693
694/// Reuse imprint's exact ruled-carrier section at the assembly repair boundary.
695/// This exposes the construction, not its arrangement or acceptance policy.
696pub fn planar_carrier_section(
697    first: &NurbsSurface,
698    second: &NurbsSurface,
699    tolerance: f64,
700) -> Result<Option<NurbsCurve>, crate::KernelRefusal> {
701    support::planar_iso_intersection(first,second,tolerance)
702}
703
704use tangent_contact::classify_tangent_contact;
705
706pub use driver::build_imprints;
707pub use driver::{build_carrier_imprints, build_carrier_imprints_within, take_rescue_firings};
708pub use self_touch::self_touch_edge_splits;
709pub use support::clear_window_memo;
710pub use self_touch::clear_touch_memo;
711
712
713
714#[path = "imprint/pcurve_cache.rs"]
715mod pcurve_cache;
716use pcurve_cache::cached_build_pcurve as build_pcurve_on_surface_marched;
717
718#[path = "imprint/pierce_clear.rs"]
719mod pierce_clear;
720#[path = "imprint/intersection_cache.rs"]
721pub mod intersection_cache;
722use intersection_cache::intersect as intersect_curve_surface;
723