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    pub fn certified_ruling(&self, supports: [FaceKey; 2], charts: [&NurbsSurface; 2])
419        -> Option<&brep_geometry::certified_planar::ruling::CertifiedRuling>
420    {
421        let evidence = self.certified_ruling_side.as_ref()?;
422        (self.shared_edge.is_none() && evidence.piece_id == self.id
423            && evidence.parameters == [self.t0, self.t1]
424            && evidence.vertices == [self.start_vertex_id, self.end_vertex_id]
425            && self.support_faces == supports
426            && evidence.support_faces == supports
427            && brep_geometry::certified_planar::ruling::same_curve(&self.curve, &evidence.minted_curve)
428            && self.pcurves.len() == evidence.minted_pcurves.len()
429            && self.pcurves.iter().zip(&evidence.minted_pcurves).all(|(a,b)|
430                a.operand == b.operand && a.face_id == b.face_id
431                && brep_geometry::certified_planar::ruling::same_curve(&a.pcurve, &b.pcurve))
432            && evidence.certificate.accepts_subcurve(&self.curve)
433            && evidence.certificate.matches_surfaces(charts[0], charts[1]))
434            .then_some(&evidence.certificate)
435    }
436}
437
438#[derive(Clone, Debug, Deserialize, Serialize)]
439pub struct ImprintPieceRecord {
440    pub id: u64,
441    pub curve: NurbsCurve,
442    pub t0: f64,
443    pub t1: f64,
444    pub start_vertex_id: u64,
445    pub end_vertex_id: u64,
446    pub pcurves: Vec<FacePcurve>,
447    pub support_faces: [FaceKey; 2],
448    /// OCCT common-block / `IsExistingPaveBlock` (B2): when this SSI section
449    /// curve was found to COINCIDE along its whole span with an EXISTING
450    /// boundary edge of one of its support faces, the section is not a new
451    /// 1-cell — it IS that boundary edge. Records `(operand, edge_id, aligned)`
452    /// of the existing edge to REUSE; `aligned` is whether the section's
453    /// start→end runs the same direction as the edge's start→end. The
454    /// assembler then resolves this piece to the shared boundary edge's
455    /// identity so both operands reference ONE edge (no duplicate section /
456    /// one-use edge). `None` = an ordinary freshly-minted section (the
457    /// historical behaviour; also what `BREP_SHARED_SECTION_EDGE=0` forces).
458    #[serde(default, skip_serializing_if = "Option::is_none")]
459    pub shared_edge: Option<(u8, u64, bool)>,
460    #[serde(skip)]
461    pub certified_ruling_side: Option<CertifiedRulingPiece>,
462}
463
464#[derive(Clone, Debug, Deserialize, Serialize)]
465pub struct EdgeSplitRecord {
466    pub operand: u8,
467    pub edge_id: u64,
468    pub parameters: Vec<f64>,
469}
470
471#[derive(Clone, Debug, Deserialize, Serialize)]
472pub struct FaceImprints {
473    pub operand: u8,
474    pub face_id: u64,
475    pub piece_ids: Vec<u64>,
476}
477
478/// Not exhaustive: a new field is not a breaking change. Outside this crate,
479/// start from `ImprintResultRecord::default()` and set the fields you need.
480#[derive(Clone, Debug, Default, Deserialize, Serialize)]
481#[non_exhaustive]
482pub struct ImprintResultRecord {
483    pub vertices: Vec<ImprintVertex>,
484    pub pieces: Vec<ImprintPieceRecord>,
485    pub by_face: Vec<FaceImprints>,
486    pub edge_splits: Vec<EdgeSplitRecord>,
487    /// Operand edges geometrically OVERLAPPED by a section curve (the
488    /// cosurface/coincident locus: an inscribed sphere's contact circle
489    /// riding a cap ring). Fragment-selection fate must never flood across
490    /// them — the two sides of such an edge can lie on opposite sides of
491    /// the other operand (the cap disc inside, the wall outside).
492    #[serde(default)]
493    pub barrier_edges: Vec<(u8, u64)>,
494    /// Every ISOLATED TANGENT NODE the imprint admitted: a point where the two
495    /// carriers touch with parallel normals and the section crosses itself, so
496    /// the pair was marched rather than refused (see
497    /// `imprint/tangent_contact.rs`). The boolean attributes a later tearing to
498    /// these rather than reporting an anonymous degeneracy — the second-order
499    /// filter cannot decide a third-order singularity, so the assembly is the
500    /// authority on whether a node it admitted was really imprintable.
501    #[serde(default)]
502    pub tangent_nodes: Vec<Vec3>,
503    /// True when the imprint saw ANY surface-contact evidence — an accepted
504    /// pierce seed, a traced SSI branch (even one later clipped away), or a
505    /// minted piece. Pure material disjointness leaves none, while a
506    /// silently-lost section always leaves at least the upstream evidence, so
507    /// the boolean's legitimate-empty adjudication requires this to be false.
508    #[serde(default)]
509    pub section_evidence: bool,
510    /// Every face pair the imprint read as ONE surface and exchanged boundary
511    /// curves across instead of intersecting (`cosurface_pair`, or the sampled
512    /// pair classification's `Cosurface`). Selection holds a fragment whose
513    /// point lies in such a partner's trim On against it, so the coincidence
514    /// the sections were built on is the one the fragments are kept by.
515    #[serde(default)]
516    pub cosurface_pairs: Vec<(FaceKey, FaceKey)>,
517    /// `BREP_FEATURE_SCALE_OPERAND_SLIVERS`: the regions (minimum, maximum) of
518    /// the slivers FeatureScale registered between the two operands' faces.
519    /// The fragmenter narrows its endpoint bands on a face that meets one.
520    #[serde(default)]
521    pub operand_sliver_regions: Vec<([f64; 3], [f64; 3])>,
522    /// Every EXTENDED tangential contact the tangent-curve lane recognised
523    /// ([`ImprintOptions::tangent_curve_lane`]): the carriers touch along a
524    /// curve inside both trims. A planar-carrier contact is marched and the
525    /// clipped run described; a curved/curved contact is named at its point
526    /// and not traced. None of these is imprinted yet — the record exists so
527    /// the boolean can attribute a refusal on the pair to the contact by name.
528    /// Appended at the end of the struct (2026-10-10).
529    #[serde(default)]
530    pub tangent_sections: Vec<TangentSectionRecord>,
531    /// The faces of either operand that stand in at least one cross-operand
532    /// face pair the imprint did NOT positively prove apart: every pair whose
533    /// face boxes met and was neither classified `Disjoint` (control-hull or
534    /// parallel-plane separation) nor proved apart by the trim windows' span
535    /// hulls. A face absent from it was proved clear of every face of the
536    /// other operand (its box met none, or each pair it met was proved apart),
537    /// so nothing the operation added can cross it. `None` wherever the
538    /// imprint did not run its plain two-operand pair loop (a self-imprint,
539    /// a record assembled elsewhere): then no face may be read as proved.
540    #[serde(default)]
541    pub faces_in_unproved_pairs: Option<Vec<FaceKey>>,
542}
543
544/// One extended tangential contact the imprint recognised (see
545/// [`ImprintResultRecord::tangent_sections`]).
546#[derive(Clone, Debug, Deserialize, Serialize)]
547pub struct TangentSectionRecord {
548    pub first: FaceKey,
549    pub second: FaceKey,
550    /// Ends of the longest run of the traced contact inside both trims (the
551    /// contact point itself when the contact was not traced).
552    pub start: Vec3,
553    pub end: Vec3,
554    /// Chord length of that run.
555    pub length: f64,
556    /// The run is the whole traced curve and the curve closed on itself.
557    pub closed: bool,
558    /// Stations of the run.
559    pub stations: usize,
560    /// One carrier is a plane: the branch the lane traces. `false` names a
561    /// curved/curved contact the lane recognises but does not trace.
562    pub planar: bool,
563    /// The faces the contact INVOLVES: the two carriers' faces, and every face
564    /// of either operand that shares an edge the run's ends lie on (the
565    /// through-bore's contact line ends on the wall's top and bottom edges,
566    /// so the box's top and bottom faces are involved; a blind pocket's ends
567    /// lie on the bore's cap rings, so the caps are). The boolean's
568    /// attribution rewrites a refusal only when a face it names is in here.
569    #[serde(default)]
570    pub faces: Vec<FaceKey>,
571    /// The section pieces the contact was imprinted as
572    /// ([`ImprintOptions::tangent_curve_imprint`]): `process_curve`'s pieces
573    /// on the clipped run, in mint order. Empty when the section was recorded
574    /// only. The assembler pairs the coedges of these pieces by material side.
575    /// Appended at the end of the struct (2026-10-11).
576    #[serde(default, skip_serializing_if = "Vec::is_empty")]
577    pub piece_ids: Vec<u64>,
578    /// GRAZING PIERCES WITHOUT A SECTION (2026-10-17, the revolve-into-bore
579    /// report): a trim edge of one face pierces the other carrier INSIDE both
580    /// trims, but at an angle below the seed gate, and the march found no
581    /// branch for the pair. The pierce proves a section crosses the faces
582    /// there; the empty march says the crossing is too near tangency to walk
583    /// (a third-order contact: the branch is born tangent to a contact curve
584    /// on a shared boundary, `boolean::attribute_to_tangent_node`). Each
585    /// entry is the pierce point and its `|edge_tangent · normal|`. Such a
586    /// record is attribution only — nothing is imprinted — and names the
587    /// contact when the assembly tears downstream of it. Appended at the end
588    /// of the struct.
589    #[serde(default, skip_serializing_if = "Vec::is_empty")]
590    pub grazing: Vec<(Vec3, f64)>,
591}
592
593impl TangentSectionRecord {
594    /// A record standing on its grazing pierces ALONE — the lane found no
595    /// contact to name, so the driver set its ends to the pierces (its
596    /// `start` IS the first pierce, bit for bit, and nothing was traced). The
597    /// boolean's attribution reads such a record only as a fallback: a
598    /// contact the lane found, or a tangent node the imprint classified, is
599    /// the nearer cause and keeps its own wording.
600    pub fn pierce_only(&self) -> bool {
601        self.stations == 0
602            && self
603                .grazing
604                .first()
605                .is_some_and(|(point, _)| point.sub(self.start).length() == 0.0)
606    }
607}
608
609#[path = "imprint/ruled_torus.rs"]
610mod ruled_torus;
611pub use ruled_torus::{circular_revolution_profile, construct_ruled_torus};
612
613#[path = "imprint/support.rs"]
614pub mod support;
615#[path = "imprint/builder.rs"]
616pub mod builder;
617#[path = "imprint/junctions.rs"]
618mod junctions;
619#[path = "imprint/self_touch.rs"]
620pub mod self_touch;
621#[path = "imprint/sections.rs"]
622pub mod sections;
623#[path = "imprint/tangent_contact.rs"]
624mod tangent_contact;
625#[path = "imprint/driver.rs"]
626pub mod driver;
627
628#[path = "imprint/work_profile.rs"]
629pub mod work_profile;
630#[path = "imprint/reuse_profile.rs"]
631pub use crate::reuse_profile;
632#[path = "imprint/hermite.rs"]
633mod hermite;
634pub use hermite::{carried_uv_enabled, carried_uv_min_stations};
635
636#[path = "imprint/gate_census.rs"]
637pub mod gate_census;
638
639use builder::*;
640pub use junctions::*;
641pub use sections::*;
642pub use support::*;
643
644#[path = "imprint/section_graph.rs"]
645mod section_graph;
646pub use section_graph::{plane_section_graph, plane_section_graph_range, plane_section_graph_range_bounded};
647
648/// Reuse imprint's exact ruled-carrier section at the assembly repair boundary.
649/// This exposes the construction, not its arrangement or acceptance policy.
650pub fn planar_carrier_section(
651    first: &NurbsSurface,
652    second: &NurbsSurface,
653    tolerance: f64,
654) -> Result<Option<NurbsCurve>, crate::KernelRefusal> {
655    support::planar_iso_intersection(first,second,tolerance)
656}
657
658use tangent_contact::classify_tangent_contact;
659
660pub use driver::build_imprints;
661pub use driver::{build_carrier_imprints, build_carrier_imprints_within, take_rescue_firings};
662pub use self_touch::self_touch_edge_splits;
663pub use support::clear_window_memo;
664pub use self_touch::clear_touch_memo;
665
666
667
668#[path = "imprint/pcurve_cache.rs"]
669mod pcurve_cache;
670use pcurve_cache::cached_build_pcurve as build_pcurve_on_surface_marched;
671
672#[path = "imprint/pierce_clear.rs"]
673mod pierce_clear;
674#[path = "imprint/intersection_cache.rs"]
675pub mod intersection_cache;
676use intersection_cache::intersect as intersect_curve_surface;
677