Skip to main content

brep_boolean/csg/boolean/
mod.rs

1pub mod profile;
2pub use crate::arrangement::Vec2;
3use crate::classification::{classify_point, parameter_point_in_face, PolygonClass};
4pub use crate::fragment::{FaceFragmentRecord, FragmentEdgeSource};
5pub use crate::imprint::{
6    EdgeSplitRecord, FaceImprints, FaceKey, ImprintOptions, ImprintPieceRecord,
7    ImprintResultRecord, ImprintVertex,
8};
9use crate::tolerance::{assembler_weld, commit_weld};
10pub use crate::topology::{
11    adaptive_coedge_error, BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord,
12    ShellRecord, VertexRecord,
13};
14pub use crate::{
15    KernelRefusal, OrRefuse, RefusalClass,
16    apply_edge_splits, apply_edge_splits_with_map, build_imprints, build_pcurve_on_surface,
17    build_pcurve_on_surface_range, classify_surface_pair,
18    fragment_solid, interpolate_curve, merge_curve_continuation_edges,
19    merge_same_surface_faces_excluding, merge_same_surface_faces_scoped,
20    project_point_to_curve, project_point_to_surface, solid_signed_volume, solid_signed_volume_for_sign, AffineTransform,
21    DiagnosticSeverity, KernelDiagnostics, KernelOutcome, KernelStage, KernelTolerances, NurbsCurve,
22    PointClass, SolidClassifier, SurfacePairRelation, Vec3,
23};
24pub use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
25use serde::{Deserialize, Serialize};
26pub use web_time::Instant;
27
28thread_local! {
29    /// Running count (per thread) of one-use edges the EDGE-CONFORMANCE
30    /// repair lanes merged or bridged.  The lanes only fire on an assembly
31    /// that would otherwise refuse, so a zero delta across an operation is
32    /// an honest witness that the boolean assembled cleanly without the
33    /// repair.  Test-observable; not part of any result.
34    pub static CONFORMANCE_REPAIRS: std::cell::Cell<u64> =
35        const { std::cell::Cell::new(0) };
36}
37
38#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum BooleanOperation {
41    Union,
42    Intersect,
43    Subtract,
44}
45
46#[derive(Clone, Debug, Deserialize)]
47pub struct BooleanOptions {
48    #[serde(default = "default_tolerance")]
49    pub tolerance: f64,
50    /// Optional complete accuracy/search policy.  `tolerance` remains the
51    /// backwards-compatible model-identity shorthand when this is absent.
52    #[serde(default)]
53    pub tolerances: Option<KernelTolerances>,
54    #[serde(default)]
55    pub imprint: ImprintOptions,
56    /// Coalesce adjacent result fragments after assembly. This defaults to
57    /// true to preserve the kernel's normal clean-boundary behavior.
58    #[serde(default = "default_true")]
59    pub merge_coplanar_faces: bool,
60    /// Face-name substrings that PIN a result face out of the coplanar/cosurface
61    /// merge (only consulted when [`Self::merge_coplanar_faces`] is on). A face whose
62    /// `name` CONTAINS any of these is emitted unchanged instead of being
63    /// coalesced with a mergeable neighbour; faces matching none merge exactly as
64    /// before. Default empty — no caller sees a behavior change unless it opts
65    /// in. Sheet metal uses this to keep every thickness/side wall face per
66    /// outline segment in the folded solid (so a flange can still attach to a
67    /// specific segment: fusing two collinear thickness faces would erase the
68    /// segment boundary).
69    #[serde(default)]
70    pub keep_unmerged_name_substrs: Vec<String>,
71    /// On by default since the 2026-10-10 census read the 94-case manifest
72    /// unchanged with it; `BREP_UNTOUCHED_PASSTHROUGH` overrides either way
73    /// (`0` off, anything else on).
74    #[serde(default = "default_true")]
75    pub untouched_passthrough: bool,
76    /// On by default since the 2026-10-10 census;
77    /// `BREP_DISJOINT_FAST_PATH` overrides either way (`0` off, anything
78    /// else on).
79    #[serde(default = "default_true")]
80    pub disjoint_fast_path: bool,
81    /// Lane X row 12: when, in at least two axes, one operand's control-net
82    /// box ends at or before the other's begins (exactly, no band), the
83    /// operands can share no interior and touch on a line or at a point: the
84    /// disjoint path's answers hold. Every control weight must be positive
85    /// (the hull property), both operands plain solids, and the caller must
86    /// say what follows (`seam_reseat_later_references` is `Some`), so a
87    /// caller that cannot keeps today's ids. On by default since the row 12
88    /// census; `BREP_CONTACT_FAST_PATH` overrides either way (`0` off,
89    /// anything else on).
90    #[serde(default = "default_true")]
91    pub contact_fast_path: bool,
92    /// OFF by default: the 94-case census read unchanged with it, but the
93    /// kernel battery's `offset_subtract_fixture` pins a result whose
94    /// untouched planar face carries an open trim joint of 8.7e-4 from its
95    /// coarse polyline operand, which the whole-solid joints pass closes and
96    /// the scoped pass leaves as the operand had it; and the row buys no
97    /// measurable time (the record of 2026-10-10). `BREP_TOUCHED_ASSEMBLY`
98    /// overrides either way (`0` off, anything else on).
99    #[serde(default)]
100    pub touched_assembly: bool,
101    /// On by default since the 2026-10-11 census (the whole kernel battery,
102    /// the 94-case manifest and `hlr_tests` green with it on, every manifest
103    /// fragment the sector decides agreeing with the ray cast);
104    /// `BREP_SECTOR_CLASS` overrides either way (`0`/`off` the escape hatch,
105    /// `check` for the differential run that logs disagreements to
106    /// `BREP_SECTOR_CENSUS`, anything else on). Appended at the end of the
107    /// struct (2026-10-11).
108    #[serde(default = "default_true")]
109    pub sector_classification: bool,
110    /// Non-manifold plan 1.6: trim a declared Sheet by a Solid with Intersect.
111    /// On after the 2026-10-14 Sheet census and whole-kernel qualification.
112    /// BREP_SHEET_TRIM overrides this option (1 enables, 0 disables).
113    #[serde(default = "default_true")]
114    pub sheet_trim: bool,
115    /// Preserve the closed operand regions at a lower-dimensional union
116    /// contact as explicit cells. Opt-in pending the Cellular census.
117    /// BREP_KEEP_CELLS overrides this option (1 enables, 0 disables).
118    #[serde(default)]
119    pub keep_cells: bool,
120    /// The references later features hold (their `inputParams` text), when
121    /// the caller knows them: `Some` admits the operand seam re-seat
122    /// (`BREP_SEAM_RESEAT`, lane X row 11b) for every cylinder wall none of
123    /// them names; `None` (the caller cannot tell) never re-seats.
124    #[serde(default)]
125    pub seam_reseat_later_references: Option<Vec<String>>,
126    /// The references later features hold, as for
127    /// [`Self::seam_reseat_later_references`]: `Some` admits the seam rejoin
128    /// (`BREP_FACE_MERGE_RESEAM`), which joins two pieces of one cylinder or
129    /// frustum split only along the carrier's seam, unless a reference that
130    /// names something on the body as merged would name something else, or
131    /// nothing, on the joined one; `None` never rejoins.
132    #[serde(default)]
133    pub seam_rejoin_later_references: Option<Vec<String>>,
134}
135
136thread_local! {
137    static WITHOUT_PERTURBATION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
138}
139
140/// Runs `action` with this thread's booleans refusing a degenerate exact
141/// arrangement where they would retry it on rigidly perturbed operands (the
142/// perturbation ladder, the last resort after the exact recoveries, which
143/// still run): for a caller with a fallback of its own (another layout of the
144/// same cut), which comes back with the ladder only where every fallback
145/// refused.
146pub fn without_perturbation<T>(action: impl FnOnce() -> T) -> T {
147    struct Restore(bool);
148    impl Drop for Restore {
149        fn drop(&mut self) {
150            WITHOUT_PERTURBATION.with(|cell| cell.set(self.0));
151        }
152    }
153    let _restore = Restore(WITHOUT_PERTURBATION.with(|cell| cell.replace(true)));
154    action()
155}
156
157/// [`BooleanOptions::touched_assembly`] under its environment override.
158fn touched_assembly(options: &BooleanOptions) -> bool {
159    match std::env::var("BREP_TOUCHED_ASSEMBLY").as_deref() {
160        Ok("0") => false,
161        Ok(_) => true,
162        Err(_) => options.touched_assembly,
163    }
164}
165
166/// [`BooleanOptions::disjoint_fast_path`] under its environment override.
167fn disjoint_fast_path(options: &BooleanOptions) -> bool {
168    match std::env::var("BREP_DISJOINT_FAST_PATH").as_deref() {
169        Ok("0") => false,
170        Ok(_) => true,
171        Err(_) => options.disjoint_fast_path,
172    }
173}
174
175/// [`BooleanOptions::contact_fast_path`] under its environment override.
176fn contact_fast_path(options: &BooleanOptions) -> bool {
177    match std::env::var("BREP_CONTACT_FAST_PATH").as_deref() {
178        Ok("0") => false,
179        Ok(_) => true,
180        Err(_) => options.contact_fast_path,
181    }
182}
183
184/// [`BooleanOptions::untouched_passthrough`] under its environment override.
185fn untouched_passthrough(options: &BooleanOptions) -> bool {
186    match std::env::var("BREP_UNTOUCHED_PASSTHROUGH").as_deref() {
187        Ok("0") => false,
188        Ok(_) => true,
189        Err(_) => options.untouched_passthrough,
190    }
191}
192
193fn default_tolerance() -> f64 {
194    1e-7
195}
196
197fn default_true() -> bool {
198    true
199}
200
201impl Default for BooleanOptions {
202    fn default() -> Self {
203        Self {
204            tolerance: default_tolerance(),
205            tolerances: None,
206            imprint: ImprintOptions::default(),
207            merge_coplanar_faces: true,
208            keep_unmerged_name_substrs: Vec::new(),
209            untouched_passthrough: true,
210            disjoint_fast_path: true,
211            contact_fast_path: true,
212            touched_assembly: false,
213            sector_classification: true,
214            sheet_trim: true,
215            keep_cells: false,
216            seam_reseat_later_references: None,
217            seam_rejoin_later_references: None,
218        }
219    }
220}
221
222mod select;
223mod sheet;
224mod cellular;
225pub mod sector;
226pub mod assemble;
227mod operand_state;
228mod rim;
229mod coincident;
230mod touch;
231pub(crate) mod reseat;
232mod ball_align;
233mod rejoin;
234mod window_retry;
235
236pub use rim::*;
237use select::*;
238use coincident::*;
239use touch::TouchCensus;
240pub use assemble::{
241    assemble_fragments, assemble_open_fragments, commit_nearby_edge_endpoints,
242    clear_candidate_memo, edge_interior_lies_on, finalize_assembled_solid, refresh_derived_genus,
243};
244use assemble::{assemble_fragments_scoped, AssemblyScope};
245// Currently referenced only inside `assemble`, so the re-export is unused.
246#[allow(unused_imports)]
247pub use assemble::apply_assembly_heal_chain;
248
249
250/// A boolean's operands at the working scale (`brep/rescale.rs`): unless `BREP_WORKING_SCALE=0`, operands whose combined box diagonal
251/// is below 1/16 are scaled up by a power of two, and the result is scaled back.
252/// Under `BREP_LARGE_WORKING_SCALE`, a refused large operation also tries a
253/// smaller working scale. Its successful original result always takes precedence.
254struct WorkingScale {
255    factor: f64,
256    solids: Vec<BrepSolid>,
257    options: BooleanOptions,
258}
259
260thread_local! {
261    // The original attempt includes its nested boolean calls. Only after it
262    // refuses do we try the large-model working scale; unwind restores it.
263    static ORIGINAL_WORKING_SCALE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
264}
265
266impl WorkingScale {
267    fn of(operands: &[&BrepSolid], options: &BooleanOptions) -> Result<Option<Self>, KernelRefusal> {
268        let Some(bounds) = crate::rescale::bounds_of(operands.iter().copied()) else {
269            return Ok(None);
270        };
271        let Some(factor) = crate::rescale::guard_factor(bounds).or_else(|| {
272            if ORIGINAL_WORKING_SCALE.with(|state| state.get()) { None }
273            else { crate::rescale::large_guard_factor(bounds) }
274        }) else {
275            return Ok(None);
276        };
277        crate::rescale::profile_fired("boolean", factor, bounds);
278        let solids = operands
279            .iter()
280            .map(|solid| crate::rescale::scale_operand(solid, factor, "boolean"))
281            .collect::<Result<Vec<_>, _>>()?;
282        // The one length the options carry in model units.
283        let mut options = options.clone();
284        options.imprint.maximum_ssi_step = options.imprint.maximum_ssi_step.map(|step| step * factor);
285        Ok(Some(Self { factor, solids, options }))
286    }
287
288    /// Retain the original successful result bit for bit. A failed fallback
289    /// retains the original refusal too, rather than replacing its evidence.
290    fn run<T>(
291        &self,
292        original: impl FnOnce() -> Result<T, KernelRefusal>,
293        scaled: impl FnOnce() -> Result<T, KernelRefusal>,
294    ) -> Result<T, KernelRefusal> {
295        if self.factor >= 1.0 { return scaled(); }
296        struct Restore(bool);
297        impl Drop for Restore {
298            fn drop(&mut self) { ORIGINAL_WORKING_SCALE.with(|state| state.set(self.0)); }
299        }
300        let answer = {
301            let _restore = Restore(ORIGINAL_WORKING_SCALE.with(|state| state.replace(true)));
302            original()
303        };
304        match answer {
305            Ok(value) => Ok(value),
306            Err(original) => scaled().or(Err(original)),
307        }
308    }
309
310    fn back(&self, solid: &BrepSolid) -> Result<BrepSolid, KernelRefusal> {
311        crate::rescale::scale_operand(solid, 1.0 / self.factor, "boolean")
312    }
313
314    fn refusal(&self, error: KernelRefusal) -> KernelRefusal {
315        crate::rescale::name_scale(error, self.factor)
316    }
317}
318
319pub fn boolean_operation(
320    first: &BrepSolid,
321    second: &BrepSolid,
322    operation: BooleanOperation,
323    options: &BooleanOptions,
324) -> Result<BrepSolid, KernelRefusal> {
325    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
326        return scaled.run(
327            || boolean_operation(first, second, operation, options),
328            || boolean_operation(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
329                .map_err(|error| scaled.refusal(error))
330                .and_then(|solid| scaled.back(&solid)),
331        );
332    }
333    boolean_operation_unscaled(first, second, operation, options)
334        .or_else(|refused| window_retry::retry(first, second, operation, options, refused, boolean_operation_unscaled))
335}
336
337/// [`boolean_operation`] on operands already at their working scale.
338fn boolean_operation_unscaled(
339    first: &BrepSolid,
340    second: &BrepSolid,
341    operation: BooleanOperation,
342    options: &BooleanOptions,
343) -> Result<BrepSolid, KernelRefusal> {
344    match boolean_operation_with_diagnostics(first, second, operation, options) {
345        Ok(outcome) => {
346            // An empty difference or common part of two solids whose faces only
347            // nearly coincide is the near pair read as one, not the answer.
348            if below_tolerance_refusal_enabled()
349                && outcome.value.shells.iter().all(|shell| shell.faces.is_empty())
350                && !matches!(operation, BooleanOperation::Union)
351            {
352                if let Some(refusal) = below_tolerance_refusal(first, second, None) {
353                    if let Some(answer) = below_tolerance_answer(first, second, operation) {
354                        return Ok(answer);
355                    }
356                    if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
357                        return Ok(answer);
358                    }
359                    return Err(refusal);
360                }
361            }
362            if unresolved_merge_refusal_enabled() && !matches!(operation, BooleanOperation::Subtract) {
363                if let Some(refusal) = unresolved_merge_refusal(first, second) {
364                    return Err(refusal);
365                }
366            }
367            // A union or common part the exact lane did write over a near pair
368            // welds the slivers between the pair partly; the inclusion is exact.
369            if below_tolerance_slivers_enabled()
370                && !matches!(operation, BooleanOperation::Subtract)
371                && [first, second].iter().all(|solid| face_count(solid) <= SLIVER_ANSWER_FACES)
372                && near_coincident_planar_faces(first, second).is_some()
373            {
374                if let Some(answer) = below_tolerance_answer(first, second, operation) {
375                    return Ok(answer);
376                }
377            }
378            Ok(outcome.value)
379        }
380        Err(error) => {
381            if below_tolerance_refusal_enabled() {
382                if let Some(refusal) = below_tolerance_refusal(first, second, Some(&error)) {
383                    if let Some(answer) = below_tolerance_answer(first, second, operation) {
384                        return Ok(answer);
385                    }
386                    if let Some(answer) = below_tolerance_rescaled(first, second, operation, options) {
387                        return Ok(answer);
388                    }
389                    return Err(refusal);
390                }
391            }
392            // Perturbation-fallback lane (Simulation of Simplicity). The exact
393            // arrangement only errs on a DEGENERACY here (coincident /
394            // near-tangent carrier faces make it structurally inconsistent) —
395            // e.g. a partial torus whose equatorial circles lie exactly in a box
396            // face. Retry once on a rigidly perturbed second operand; accept only
397            // an oracle-clean, volume-consistent result. See
398            // `perturbation_retry`.
399            if std::env::var("BREP_NO_PERTURB").as_deref() == Ok("1")
400                || !error.class.perturbation_eligible()
401            {
402                return Err(error);
403            }
404            // OPERAND-CONSISTENCY GATE. A rigid nudge lifts a coincidence
405            // BETWEEN the operands; it cannot reconcile an operand with
406            // itself. A planar face whose straight boundary sits farther off
407            // its plane than the assembly weld — the shape the STEP importer's
408            // planar split repairs, so it reaches here only on a body built
409            // some other way — fails the exact arrangement for every rung
410            // alike: the 2026-09-12 mesh-import report paid twenty ~7 s rungs
411            // for one 3.4e-3 gap before the import split existed. Name the
412            // gap and stop. The predicate is deliberately the splitter's own,
413            // not a pcurve-error band: vendor bodies whose fitted edges stand
414            // a few 1e-4 off curved faces are legitimate input (per-entity
415            // tolerances) and keep every rung.
416            // OPERAND-CLOSURE GATE. A boolean of a body that is not a closed
417            // shell has no solid answer, exact or nudged: its inside is not
418            // defined, and its volume depends on the reference point. The
419            // slimmed fuzz fixtures (13, 14 and 15, operand A cut from a larger
420            // part by a box filter) carry 54, 97 and 66 edges that bound one
421            // face; every one of their 20 rungs refused on the exact lane, and
422            // 15's identity was read from an intersection with the open shell.
423            // Only consulted on the failure path, so nothing that succeeds
424            // today changes. Escape hatch: BREP_OPEN_OPERAND_GATE=0.
425            if std::env::var("BREP_OPEN_OPERAND_GATE").as_deref() != Ok("0") {
426                if let Some((operand, open)) = [first, second]
427                    .iter()
428                    .enumerate()
429                    .find_map(|(operand, solid)| {
430                        let open = one_use_edges(solid);
431                        (open > 0).then_some((operand, open))
432                    })
433                {
434                    return Err(error.with_message(|message| format!(
435                        "{message}; operand {operand} is not a closed shell: {open} of its edges bound \
436                         only one face, so no boolean of it encloses a solid and no perturbation \
437                         can close it"
438                    )));
439                }
440            }
441            if let Some((operand, face_id, deviation, weld)) =
442                planar_operand_off_its_plane(first, second, options)
443            {
444                return Err(error.with_message(|message| format!(
445                    "{message}; operand {operand} face {face_id} is a plane whose straight \
446                     boundary sits {deviation:.3e} off it (assembly weld {weld:.1e}), which \
447                     no perturbation can reconcile — the body's planes must contain their \
448                     boundary before it can take part in an exact boolean"
449                )));
450            }
451            // INTERNAL-TANGENCY PINCH GATE. Perturbation is only legitimate
452            // where the exact arrangement is UNSTABLE but its ANSWER is not:
453            // the nearby transversal case must carry the same topology the
454            // degenerate one does. An internal tangency in a DIFFERENCE breaks
455            // exactly that premise — the exact `A − B` pinches to zero
456            // thickness along the contact, so an epsilon either tears the wall
457            // open (a through-slot where the exact answer has intact material)
458            // or leaves a sub-micron web. Both are within epsilon in Hausdorff
459            // distance and in volume, so neither the oracle (boundary skip
460            // band) nor the 1% CSG volume bound can see them, and the lane
461            // would ship the tolerant-kernel sliver this kernel refuses. Only
462            // consulted on the failure path, so nothing that succeeds today can
463            // change; the honest exact-path error is returned instead.
464            // Escape hatch for tamper-verification: BREP_PINCH_GATE=0.
465            if matches!(operation, BooleanOperation::Subtract)
466                && std::env::var("BREP_PINCH_GATE").as_deref() != Ok("0")
467                && subtract_pinches_at_internal_tangency(first, second, options.tolerance)
468                    .unwrap_or(false)
469            {
470                // The exact answer exists where the contact only touches: see
471                // `subtract_through_the_common_part`. Not a perturbation.
472                if let Some(solid) = subtract_through_the_common_part(first, second, options) {
473                    return Ok(solid);
474                }
475                return Err(error.with_message(|message| format!(
476                    "{message}; internal tangency: the operands touch tangentially with \
477                     co-directed normals, so the exact difference pinches to zero thickness \
478                     (non-manifold, unrepresentable in a boundary model) — refusing rather \
479                     than returning a perturbed sliver"
480                )));
481            }
482            // TANGENT-NODE GATE, same doctrine as the pinch gate above and for
483            // the same reason. A 4-valent tangent node is refused because the
484            // kernel cannot imprint it, and perturbation is only legitimate
485            // where the exact arrangement is UNSTABLE but its ANSWER is not:
486            // the nudged configuration resolves the kiss one way or the other
487            // and the kernel has no claim on which. Until 2026-09-13 the ladder
488            // could not produce a candidate here at all; with `fit_polyline`
489            // measuring its own result the equal-radius torus pair's LAST rung
490            // (3.0e-3 of scale) assembles, validates, and passes the semantic
491            // oracle at 399 samples with a zero disagreement rate, reading
492            // 299.4998500 against the ideal union's 299.6 — a 0.03% error that
493            // is the nudge's, not the kernel's answer. Shipping that would
494            // answer a question this class exists to decline, so the class does
495            // not take the ladder. Escape hatch for measuring it:
496            // BREP_TANGENT_NODE_GATE=0.
497            if matches!(error.class, RefusalClass::TangentNodeSingularity)
498                && std::env::var("BREP_TANGENT_NODE_GATE").as_deref() != Ok("0")
499            {
500                return Err(error);
501            }
502            // The union of two bodies tangent inside one another has an exact
503            // answer the arrangement of the difference reaches: see
504            // `union_through_the_difference`. Not a perturbation.
505            if matches!(operation, BooleanOperation::Union) {
506                if let Some(solid) = union_through_the_difference(first, second, options) {
507                    return Ok(solid);
508                }
509            }
510            // The ladder itself: not under `without_perturbation`.
511            if WITHOUT_PERTURBATION.with(|cell| cell.get()) {
512                return Err(error);
513            }
514            match perturbation_retry(first, second, operation, options) {
515                Ok(solid) => Ok(solid),
516                Err(refused) if refused.is_empty() => Err(error),
517                Err(refused) => {
518                    Err(error.with_message(|message| format!("{message}; {}", refused.join("; "))))
519                }
520            }
521        }
522    }
523}
524
525/// Grid resolution (per parameter direction, endpoints included) used to probe a
526/// face pair for a tangential contact. Endpoints and the midpoint are both
527/// sampled, so a contact sitting on a periodic seam (a cylinder's `u = 0`
528/// ruling) and one sitting at a face's parametric centre are both hit exactly.
529const PINCH_PROBE_STEPS: usize = 8;
530
531/// `|n_a × n_b|` bound below which two unit normals count as parallel — the same
532/// bound `csg::imprint`'s pair classifier uses (`PAIR_ANGULAR_TOLERANCE`).
533const PINCH_ANGULAR_TOLERANCE: f64 = 1e-4;
534
535/// Parameter-space step (fraction of the domain span) taken around a contact
536/// sample to prove the contact is LOWER-DIMENSIONAL — a tangency curve/point
537/// rather than a cosurface patch.
538const PINCH_SEPARATION_STEP: f64 = 1e-2;
539
540/// `first − second` as `first − (first ∩ second)`, on the exact lane only, for a
541/// difference the pinch gate is about to refuse (`BREP_PINCH_COMMON_RETRY`,
542/// default on; `=0` leaves the refusal).
543///
544/// The two are the same set, and the second form is often the arrangement the
545/// exact lane can build where the first is not. A cylinder cut by a smaller one
546/// tangent to it inside along a ruling, the cutter running on past both caps
547/// (a crescent; brep-bench probe 2026-11-12): each cap's section circle is
548/// tangent to the cap's own rim, the cap's loops do not close, and the cut
549/// refused; with the cutter flush with the caps it built, exact. The common part
550/// IS the cutter made flush, it is built without trouble (it has no thin wall),
551/// and cutting it away meets the first operand only in faces they share.
552///
553/// Nothing is nudged, so the pinch gate's reason for refusing a PERTURBED
554/// answer does not apply; what is accepted is an exact-lane body that validates
555/// and whose volume is `V(first) − V(first ∩ second)` to the drift bar. Any
556/// other outcome returns `None` and the gate's refusal stands.
557fn subtract_through_the_common_part(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
558    // With the tangent imprint switched off the caller has asked for the
559    // recorded-only lane, whose answer to a pinch is its refusal.
560    if !switch!("BREP_PINCH_COMMON_RETRY", true) || !options.imprint.tangent_curve_imprint {
561        return None;
562    }
563    let common = boolean_operation_with_diagnostics(first, second, BooleanOperation::Intersect, options).ok()?.value;
564    if common.shells.iter().all(|shell| shell.faces.is_empty()) {
565        return None;
566    }
567    let cut = boolean_operation_with_diagnostics(first, &common, BooleanOperation::Subtract, options).ok()?.value;
568    if !cut.validate().is_empty() {
569        return None;
570    }
571    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
572    let (whole, taken, left) = (volume(first)?, volume(&common)?, volume(&cut)?);
573    ((left - (whole - taken)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(cut)
574}
575
576/// `first ∪ second` as `second ∪ (first − second)`, on the exact lane only, for
577/// a union that failed where the operands touch tangentially with co-directed
578/// normals (`BREP_TANGENT_UNION_DIFFERENCE_RETRY`, default on; `=0` leaves the
579/// union to the paths it had).
580///
581/// The two are the same set. A cylinder holding a smaller one tangent to it
582/// inside along a ruling, the smaller running on past a cap: the union's
583/// arrangement leaves the cap's section circle tangent to the cap's own rim and
584/// the shell does not close, while the difference builds (the crescent) and the
585/// smaller body joins it along faces the two share. Accepted only when it
586/// validates and its volume is `V(first − second) + V(second)` to the drift bar;
587/// any other outcome returns `None` and the union goes on as before.
588fn union_through_the_difference(first: &BrepSolid, second: &BrepSolid, options: &BooleanOptions) -> Option<BrepSolid> {
589    if !switch!("BREP_TANGENT_UNION_DIFFERENCE_RETRY", true) || !options.imprint.tangent_curve_imprint {
590        return None;
591    }
592    let pinches = |a: &BrepSolid, b: &BrepSolid| subtract_pinches_at_internal_tangency(a, b, options.tolerance).unwrap_or(false);
593    if !pinches(first, second) && !pinches(second, first) {
594        return None;
595    }
596    let difference = match boolean_operation_with_diagnostics(first, second, BooleanOperation::Subtract, options) {
597        Ok(outcome) => outcome.value,
598        Err(_) => subtract_through_the_common_part(first, second, options)?,
599    };
600    if difference.shells.iter().all(|shell| shell.faces.is_empty()) || !difference.validate().is_empty() {
601        return None;
602    }
603    let union = boolean_operation_with_diagnostics(second, &difference, BooleanOperation::Union, options).ok()?.value;
604    if !union.validate().is_empty() {
605        return None;
606    }
607    let volume = |solid: &BrepSolid| crate::solid_mass_properties(solid).ok().map(|mass| mass.volume);
608    let (left, added, whole) = (volume(&difference)?, volume(second)?, volume(&union)?);
609    ((whole - (left + added)).abs() <= 1e-9 * whole.abs().max(1.0)).then_some(union)
610}
611
612/// Would the exact `first − second` PINCH to zero thickness at a tangential
613/// contact?
614///
615/// True when some face of `first` and some face of `second` touch tangentially
616/// (surfaces within the contact band, normals parallel) with CO-DIRECTED outward
617/// normals, at a contact that is lower-dimensional (the surfaces separate as you
618/// step away from it).
619///
620/// Co-directed outward normals at a tangency mean one solid lies locally INSIDE
621/// the other: subtracting leaves material on both sides of the contact that
622/// meets there at zero thickness — a non-manifold pinch no boundary model can
623/// represent. Anti-directed normals are the harmless EXTERNAL tangency (a
624/// cylinder resting against a wall): the difference simply keeps `first` intact.
625/// The lower-dimensionality requirement excludes a CO-SURFACE contact (a pocket
626/// wall flush with an outer wall — co-directed normals, but the surfaces stay
627/// coincident in every direction), where the difference is perfectly well
628/// behaved.
629///
630/// Conservative by construction: it only reports a pinch it can actually witness
631/// on the probe grid, and a miss just leaves the perturbation lane to its
632/// existing gates.
633pub fn subtract_pinches_at_internal_tangency(
634    first: &BrepSolid,
635    second: &BrepSolid,
636    tolerance: f64,
637) -> Result<bool, KernelRefusal> {
638    // Same contact band the imprint pair classifier uses for its sampled
639    // "these carriers touch" verdict.
640    let contact = (tolerance * 100.0).max(1e-12);
641    let probes_a = first
642        .shells
643        .iter()
644        .flat_map(|shell| &shell.faces)
645        .map(PinchProbe::of)
646        .collect::<Result<Vec<_>, _>>()?;
647    let probes_b = second
648        .shells
649        .iter()
650        .flat_map(|shell| &shell.faces)
651        .map(PinchProbe::of)
652        .collect::<Result<Vec<_>, _>>()?;
653    for probe_a in &probes_a {
654        for probe_b in &probes_b {
655            // Sampled-hull cull, so the (failure-path-only) cost stays linear in
656            // the faces that actually touch rather than quadratic in every face.
657            // The hull is built from the probe grid, so it can under-cover a
658            // curved carrier between samples: pad it by a percent of the pair's
659            // size before culling. Over-keeping a pair only costs a probe that
660            // finds nothing.
661            let pad = 1e-2 * probe_a.extent().max(probe_b.extent());
662            if probe_a.separation(probe_b) > contact + pad {
663                continue;
664            }
665            // CO-SURFACE contacts are 2-dimensional, not tangencies: two flush
666            // walls (a pocket's side coincident with an outer wall, a cylinder
667            // cap lying in a box face) have co-directed normals wherever the
668            // solids nest, yet the difference there is perfectly well behaved.
669            // Only a LOWER-dimensional contact pinches, so drop the pair the
670            // pair classifier calls cosurface before probing it.
671            if classify_surface_pair(
672                &probe_a.face.surface,
673                &probe_b.face.surface,
674                tolerance,
675                PINCH_ANGULAR_TOLERANCE,
676            ).or_refuse(KernelStage::Validate, "csg.boolean.mod")?
677            .relation
678                == SurfacePairRelation::Cosurface
679            {
680                continue;
681            }
682            if faces_touch_with_codirected_normals(probe_a, probe_b, contact)? {
683                return Ok(true);
684            }
685        }
686    }
687    Ok(false)
688}
689
690/// A face's probe grid plus the grid's bounding box, built once per face so the
691/// pair loop only pays for a hull comparison.
692struct PinchProbe<'a> {
693    face: &'a FaceRecord,
694    /// `(u, v, point)` on the face's carrier surface.
695    samples: Vec<(f64, f64, Vec3)>,
696    minimum: [f64; 3],
697    maximum: [f64; 3],
698}
699
700impl<'a> PinchProbe<'a> {
701    fn of(face: &'a FaceRecord) -> Result<Self, KernelRefusal> {
702        let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
703        let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
704        let steps = PINCH_PROBE_STEPS as f64;
705        let mut samples = Vec::with_capacity((PINCH_PROBE_STEPS + 1).pow(2));
706        let mut minimum = [f64::INFINITY; 3];
707        let mut maximum = [f64::NEG_INFINITY; 3];
708        for i in 0..=PINCH_PROBE_STEPS {
709            let u = u0 + (u1 - u0) * i as f64 / steps;
710            for j in 0..=PINCH_PROBE_STEPS {
711                let v = v0 + (v1 - v0) * j as f64 / steps;
712                let Ok(point) = face.surface.evaluate(u, v) else {
713                    continue;
714                };
715                for (axis, value) in [point.x, point.y, point.z].into_iter().enumerate() {
716                    minimum[axis] = minimum[axis].min(value);
717                    maximum[axis] = maximum[axis].max(value);
718                }
719                samples.push((u, v, point));
720            }
721        }
722        Ok(Self {
723            face,
724            samples,
725            minimum,
726            maximum,
727        })
728    }
729
730    /// Largest side of the sampled hull (0 when nothing sampled).
731    fn extent(&self) -> f64 {
732        (0..3)
733            .map(|axis| self.maximum[axis] - self.minimum[axis])
734            .fold(0.0f64, f64::max)
735    }
736
737    /// Axis-aligned gap between the two sampled hulls (0 when they overlap).
738    fn separation(&self, other: &Self) -> f64 {
739        let mut gap: f64 = 0.0;
740        for axis in 0..3 {
741            gap = gap.max(self.minimum[axis] - other.maximum[axis]);
742            gap = gap.max(other.minimum[axis] - self.maximum[axis]);
743        }
744        gap
745    }
746}
747
748/// One face pair of [`subtract_pinches_at_internal_tangency`]: probe both
749/// surfaces on a grid, keep samples that land on the other surface inside BOTH
750/// trims with parallel co-directed outward normals, and accept only where the
751/// contact provably separates nearby.
752fn faces_touch_with_codirected_normals(
753    probe_a: &PinchProbe<'_>,
754    probe_b: &PinchProbe<'_>,
755    contact: f64,
756) -> Result<bool, KernelRefusal> {
757    for (probe, other) in [(probe_a, probe_b), (probe_b, probe_a)] {
758        let source = probe.face;
759        let target = other.face;
760        for &(u, v, point) in &probe.samples {
761            let projection = project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?;
762            if projection.distance > contact {
763                continue;
764            }
765            // A pole (collapsed du × dv) has no reliable orientation here;
766            // skipping it keeps the predicate conservative.
767            let (Ok(source_normal), Ok(target_normal)) = (
768                source.surface.normal(u, v),
769                target.surface.normal(projection.u, projection.v),
770            ) else {
771                continue;
772            };
773            let source_outward = outward_normal(source_normal, source.same_sense);
774            let target_outward = outward_normal(target_normal, target.same_sense);
775            if source_outward.cross(target_outward).length() > PINCH_ANGULAR_TOLERANCE
776                || source_outward.dot(target_outward) <= 0.0
777            {
778                continue;
779            }
780            if parameter_point_in_face(source, Vec2 { x: u, y: v }, 1e-6).or_refuse(KernelStage::Validate, "parameter_point_in_face")?
781                == PolygonClass::Outside
782                || parameter_point_in_face(
783                    target,
784                    Vec2 {
785                        x: projection.u,
786                        y: projection.v,
787                    },
788                    1e-6,
789                ).or_refuse(KernelStage::Validate, "csg.boolean.mod")? == PolygonClass::Outside
790            {
791                continue;
792            }
793            if contact_separates_locally(source, target, u, v, contact)? {
794                return Ok(true);
795            }
796        }
797    }
798    Ok(false)
799}
800
801fn outward_normal(normal: Vec3, same_sense: bool) -> Vec3 {
802    if same_sense {
803        normal
804    } else {
805        normal.scale(-1.0)
806    }
807}
808
809/// Does the contact at `source(u, v)` LEAVE the contact band when you step away
810/// from it in parameter space? A tangency curve or point does (stepping across
811/// the tangency separates the surfaces quadratically); a cosurface patch does
812/// not (it stays coincident in every direction). Steps are clamped into the
813/// domain, so a sample on a seam or a domain edge probes only inward.
814fn contact_separates_locally(
815    source: &FaceRecord,
816    target: &FaceRecord,
817    u: f64,
818    v: f64,
819    contact: f64,
820) -> Result<bool, KernelRefusal> {
821    let [u0, u1] = source.surface.domain_u().or_refuse(KernelStage::Validate, "domain_u")?;
822    let [v0, v1] = source.surface.domain_v().or_refuse(KernelStage::Validate, "domain_v")?;
823    let step_u = (u1 - u0) * PINCH_SEPARATION_STEP;
824    let step_v = (v1 - v0) * PINCH_SEPARATION_STEP;
825    for (probe_u, probe_v) in [
826        ((u + step_u).min(u1), v),
827        ((u - step_u).max(u0), v),
828        (u, (v + step_v).min(v1)),
829        (u, (v - step_v).max(v0)),
830    ] {
831        if (probe_u - u).abs() < f64::EPSILON && (probe_v - v).abs() < f64::EPSILON {
832            continue;
833        }
834        let Ok(point) = source.surface.evaluate(probe_u, probe_v) else {
835            continue;
836        };
837        // A generous multiple of the band: the step must clear it decisively,
838        // never on projection noise.
839        if project_point_to_surface(&target.surface, point).or_refuse(KernelStage::Validate, "project_point_to_surface")?.distance > contact * 10.0 {
840            return Ok(true);
841        }
842    }
843    Ok(false)
844}
845
846/// Deterministic perturbation-fallback (Simulation of Simplicity), the textbook
847/// CAD answer to an exact/near-tangent arrangement degeneracy, adopted after six
848/// incremental arrangement/imprint/fragment fixes for the near-tangent class were
849/// each falsified, rather than attempting a seventh. Rigidly TRANSLATE the second operand by a tiny
850/// epsilon so the degenerate contact becomes a clean transversal crossing, redo
851/// the boolean, and accept the result ONLY if it is (a) topologically valid —
852/// guaranteed by `assemble`'s own gate returning `Ok` — (b) semantically equal to
853/// the exact CSG of the ORIGINAL operands (the point-classification oracle), and
854/// (c) volume-consistent with the CSG inequality bounds. A wrong perturbed result
855/// is rejected on (b)/(c), so this lane preserves the engine's fail-safe property:
856/// it can only turn a degeneracy-error into a CORRECT solid, never a wrong one.
857///
858/// INVARIANT — no recursion: this calls `boolean_operation_with_diagnostics`
859/// (the EXACT path), never `boolean_operation`, so the fallback can never
860/// re-enter itself. A future refactor must preserve that.
861///
862/// (d) THE IDENTITY. Where the exact lane answers one of the other operations
863/// on the same operands, inclusion–exclusion names the volume this result
864/// must have, and a rung that misses it by more than the case gate's own drift
865/// band (`VOLUME_DRIFT_REL` of that volume, `VOLUME_DRIFT_ABS` floor) is
866/// refused by name. (c)'s 1% of the operands' total cannot see an error in a
867/// small removed volume: on the helmet's cutter − helmet (2026-09-15) the rung
868/// at fraction 3e-4 moved the helmet 5.2e-3, 2.3% of its size, passed the
869/// oracle at 1 in 336, and read 999.999899266 against V(cutter) − V(cutter ∩
870/// helmet) = 999.999905792: 6.9% too much material removed. Where no other
871/// operation clears on the exact lane there is no identity to hold, and the
872/// rung is held to (e) instead. Escape hatch for measuring it:
873/// BREP_PERTURB_IDENTITY=0 (which also lifts (e)).
874///
875/// (e) THE MIRROR. Where no exact-lane boolean of the operands clears in
876/// either order, the rung is held to itself moved the other way: the same
877/// operation, or failing that any sibling reading, on the second operand moved
878/// by −offset, with V(first) and V(second) from the mass integrator and the
879/// operation's sign, names the volume the mirrored rung encloses. A rigid
880/// translation changes the answer to first order in the offset, so half the
881/// difference between the rung's body and its mirror is the body's
882/// first-order translation error, and it must clear the same drift band. A
883/// rung whose mirror clears no boolean at all has nothing to check it and is
884/// refused by name. On 22_sag_boundary_identity_t164 (2026-09-15) the four
885/// shipped rescues at offset 9.7e-4 disagreed with each other through V(∩) by
886/// 4.3e-2 (the difference moves the part; the others move the sphere), against
887/// a bar of 5e-6. Escape hatch: BREP_PERTURB_MIRROR=0.
888///
889/// (d) and (e) run before (b), the oracle, which costs more than either.
890///
891/// (f) THE EARLY EXIT. Along one direction the mirror's error grows with the
892/// offset (`MirrorTrend` states the law and its measurement), so a direction
893/// whose two refused rungs read one sign, growing, is not tried at larger
894/// offsets, and the refusal names it. booleanIssue's refusal walked 20 rungs,
895/// each with its mirror, in 40.5 s against the case's 30 s. Escape hatch:
896/// BREP_MIRROR_EARLY_EXIT=0.
897///
898/// `Err` carries one sentence per rung refused on (d), empty when none was.
899fn perturbation_retry(
900    first: &BrepSolid,
901    second: &BrepSolid,
902    operation: BooleanOperation,
903    options: &BooleanOptions,
904) -> Result<BrepSolid, Vec<String>> {
905    // Generic translation directions: each has a substantial component on ALL
906    // three axes, so whatever axis the coincidence normal lies along (an
907    // equatorial plane flush with a box face, a cap plane flush with a side
908    // face, …) at least one direction has a component that lifts the contact off
909    // exact tangency. Axis-aligned directions are deliberately excluded — a nudge
910    // parallel to the coincident plane leaves the degeneracy in place (verified:
911    // pure ±X / ±Z never rescue the flush-torus case). Fixed, not hash-seeded
912    // as the lane was first sketched: the seeding's only purpose was to rule out
913    // RNG/clock nondeterminism, which fixed vectors already satisfy, and four
914    // diverse directions cover any axis-aligned normal.
915    const DIRECTIONS: [[f64; 3]; 4] = [
916        [0.4034, 0.7973, 0.4491],
917        [0.7973, 0.4491, 0.4034],
918        [0.4491, 0.4034, 0.7973],
919        [0.5774, -0.5774, 0.5774],
920    ];
921    // Fractions of operand scale, ordered SMALLEST-FIRST so the accepted solid
922    // carries the least geometric offset. Sized above the near-tangent sliver
923    // dead zone and below local feature size; the ladder + accept-gate make the
924    // exact magnitude non-critical (a rung that lands in a dead zone simply fails
925    // the gate and the next rung is tried).
926    const FRACTIONS: [f64; 5] = PERTURBATION_FRACTIONS;
927
928    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
929    let scale = crate::solid_tolerance::solid_scale(first)
930        .max(crate::solid_tolerance::solid_scale(second))
931        .max(1.0);
932
933    // Original operand volumes for the CSG inequality backstop (the oracle skips
934    // points near boundaries, so a wrong thin shell hugging the flush face is
935    // invisible to it but shows up here).
936    let _caller = crate::mass_caller("boolean.perturbation_rescue");
937    let va = solid_signed_volume(first).ok().map(f64::abs);
938    let vb = solid_signed_volume(second).ok().map(f64::abs);
939    let hold_identity = std::env::var("BREP_PERTURB_IDENTITY").as_deref() != Ok("0");
940    // (e) is held only with (d): `BREP_PERTURB_MIRROR=0` alone ships a rung
941    // with no identity on (a)–(c), as before.
942    let hold_mirror = hold_identity && std::env::var("BREP_PERTURB_MIRROR").as_deref() != Ok("0");
943    // (f) A direction whose mirror errors say no larger offset can clear is
944    // closed. Escape hatch: `BREP_MIRROR_EARLY_EXIT=0` walks every rung.
945    let early_exit = std::env::var("BREP_MIRROR_EARLY_EXIT").as_deref() != Ok("0");
946    let mut trends = [MirrorTrend::default(); 4];
947    // Measured once, on the first rung that clears (a)–(c).
948    let mut identity: Option<Option<InclusionExclusion>> = None;
949    let mut refused = Vec::new();
950    // `BREP_DEBUG_PERTURB_LADDER=1`: every rung's disposition on stderr, and
951    // for every rung that builds, its miss against the identity, measured
952    // before the ladder starts. Changes no decision.
953    let ladder = std::env::var("BREP_DEBUG_PERTURB_LADDER").is_ok();
954    let ladder_start = web_time::Instant::now();
955    if ladder {
956        let measured = inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
957        match &measured {
958            Some(identity) => eprintln!(
959                "[ladder] identity {} = {:.9} from the exact lane's {} ({:.9}); V(first) {:?} V(second) {:?}",
960                identity.formula, identity.expected, identity.reading, identity.read, va, vb
961            ),
962            None => eprintln!("[ladder] no identity: no exact-lane boolean of these operands clears in either order"),
963        }
964        identity = Some(measured);
965    }
966    let rung_miss = |identity: &Option<Option<InclusionExclusion>>, candidate: &BrepSolid| -> String {
967        let volume = body_volume(candidate);
968        match (identity, volume) {
969            (Some(Some(identity)), Some(volume)) => format!(
970                "volume {volume:.9} miss {:+.3e} bar {:.3e}",
971                volume - identity.expected,
972                crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * identity.expected.abs())
973            ),
974            (_, Some(volume)) => format!("volume {volume:.9}"),
975            _ => "no volume".to_string(),
976        }
977    };
978
979    for &fraction in &FRACTIONS {
980        let magnitude = scale * fraction;
981        for (direction, dir) in DIRECTIONS.iter().enumerate() {
982            if trends[direction].closed {
983                if ladder {
984                    eprintln!("[ladder] dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}: not tried, its direction is closed");
985                }
986                continue;
987            }
988            let offset = [dir[0] * magnitude, dir[1] * magnitude, dir[2] * magnitude];
989            let translate = match AffineTransform::new([
990                1.0, 0.0, 0.0, offset[0], //
991                0.0, 1.0, 0.0, offset[1], //
992                0.0, 0.0, 1.0, offset[2], //
993                0.0, 0.0, 0.0, 1.0,
994            ]) {
995                Ok(transform) => transform,
996                Err(_) => continue,
997            };
998            let moved = match crate::transform_brep(second, translate, false) {
999                Ok(solid) => solid,
1000                Err(_) => continue,
1001            };
1002            let rung = format!("dir={dir:?} fraction={fraction:.1e} offset {magnitude:.3e}");
1003            let rung_start = web_time::Instant::now();
1004            let candidate =
1005                match boolean_operation_with_diagnostics(first, &moved, operation, options) {
1006                    Ok(outcome) => outcome.value,
1007                    Err(error) => {
1008                        if ladder {
1009                            eprintln!("[ladder] {rung}: exact lane refused {:?}", error.class);
1010                        }
1011                        continue;
1012                    }
1013                };
1014            let built = rung_start.elapsed();
1015            // A perturbation must not "rescue" a case into emptiness.
1016            if candidate.shells.is_empty() {
1017                if ladder {
1018                    eprintln!("[ladder] {rung}: empty");
1019                }
1020                continue;
1021            }
1022            // (c) Volume must satisfy the CSG inequality for the ORIGINAL
1023            // operands (generous 1% relative slack: catches gross wrongness —
1024            // doubled/halved bodies, missing lobes — without rejecting the
1025            // legitimate sub-micron offset).
1026            if let (Some(va), Some(vb)) = (va, vb) {
1027                if let Ok(vr) = solid_signed_volume(&candidate) {
1028                    if !volume_within_csg_bounds(operation, va, vb, vr.abs()) {
1029                        if ladder {
1030                            eprintln!("[ladder] {rung}: outside the CSG bound, {}", rung_miss(&identity, &candidate));
1031                        }
1032                        continue;
1033                    }
1034                }
1035            }
1036            // (d) and (e) run before (b): each costs a volume, and (e) one
1037            // exact-lane boolean, where the oracle classifies 400 points. A
1038            // rung ships only when every gate clears, so the order decides
1039            // which gate names a refusal, never which rung ships.
1040            let bounded = rung_start.elapsed();
1041            // (d) The exact lane's inclusion–exclusion identity.
1042            if hold_identity {
1043                let identity = identity.get_or_insert_with(|| {
1044                    let identity =
1045                        inclusion_exclusion_volume(first, second, operation, options, va, vb, false);
1046                    if debug && identity.is_none() {
1047                        eprintln!(
1048                            "[perturb] no exact-lane boolean of these operands clears in either \
1049                             order; no identity to hold"
1050                        );
1051                    }
1052                    identity
1053                });
1054                if let Some(identity) = identity {
1055                    let expected = identity.expected;
1056                    let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * expected.abs());
1057                    let volume = body_volume(&candidate);
1058                    let miss = volume.map(|volume| (volume - expected).abs());
1059                    if !miss.is_some_and(|miss| miss <= bar) {
1060                        let sentence = format!(
1061                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1062                             (offset {magnitude:.3e}) refused: its body reads {} against the \
1063                             inclusion–exclusion identity {} = {expected:.9} (the exact lane's \
1064                             {} reads {:.9}), a miss of {} beyond the volume drift bar {bar:.3e}",
1065                            volume.map_or("no volume".to_string(), |volume| format!("{volume:.9}")),
1066                            identity.formula,
1067                            identity.reading,
1068                            identity.read,
1069                            miss.map_or("unmeasured".to_string(), |miss| format!("{miss:.3e}")),
1070                        );
1071                        if debug {
1072                            eprintln!("[perturb] {sentence}");
1073                        }
1074                        if ladder {
1075                            eprintln!(
1076                                "[ladder] {rung}: refused by the identity, volume {} miss {} bar {bar:.3e}",
1077                                volume.map_or("none".to_string(), |volume| format!("{volume:.9}")),
1078                                volume.map_or("unmeasured".to_string(), |volume| format!("{:+.3e}", volume - expected)),
1079                            );
1080                        }
1081                        refused.push(sentence);
1082                        continue;
1083                    }
1084                } else if hold_mirror {
1085                    // (e) No exact reading of these operands: the rung's
1086                    // mirror.
1087                    let mirror_start = web_time::Instant::now();
1088                    let mirrored = AffineTransform::new([
1089                        1.0, 0.0, 0.0, -offset[0], //
1090                        0.0, 1.0, 0.0, -offset[1], //
1091                        0.0, 0.0, 1.0, -offset[2], //
1092                        0.0, 0.0, 0.0, 1.0,
1093                    ])
1094                    .ok()
1095                    .and_then(|transform| crate::transform_brep(second, transform, false).ok());
1096                    let mirror = mirrored.as_ref().and_then(|mirrored| {
1097                        inclusion_exclusion_volume(first, mirrored, operation, options, va, vb, true)
1098                    });
1099                    let mirror_time = mirror_start.elapsed();
1100                    let volume = body_volume(&candidate);
1101                    let mut measured = None;
1102                    let verdict = match (&mirror, volume) {
1103                        (Some(mirror), Some(volume)) => {
1104                            let bar = crate::VOLUME_DRIFT_ABS.max(crate::VOLUME_DRIFT_REL * mirror.expected.abs());
1105                            let miss = 0.5 * (volume - mirror.expected).abs();
1106                            measured = Some((0.5 * (volume - mirror.expected), bar));
1107                            if ladder {
1108                                eprintln!(
1109                                    "[ladder] {rung}: mirror at −offset reads {} = {:.9} (the mirrored {} {:.9}); body {volume:.9}, first-order translation error {:+.3e} bar {bar:.3e}",
1110                                    mirror.formula, mirror.expected, mirror.reading, mirror.read, 0.5 * (volume - mirror.expected)
1111                                );
1112                            }
1113                            (miss > bar).then(|| format!(
1114                                "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1115                                 (offset {magnitude:.3e}) refused: no exact-lane boolean of the \
1116                                 operands clears, so the rung is held to its mirror: its body reads \
1117                                 {volume:.9} with the second operand moved +offset and {} = {:.9} \
1118                                 with it moved −offset (the mirrored {} reads {:.9}), a first-order \
1119                                 translation error of {miss:.3e} beyond the volume drift bar {bar:.3e}",
1120                                mirror.formula, mirror.expected, mirror.reading, mirror.read
1121                            ))
1122                        }
1123                        _ => Some(format!(
1124                            "perturbation rung dir={dir:?} fraction={fraction:.1e} \
1125                             (offset {magnitude:.3e}) refused: no exact-lane boolean of the operands \
1126                             clears, and none clears with the second operand moved −offset either, \
1127                             so nothing checks the rung's body{}",
1128                            volume.map_or(String::new(), |volume| format!(" ({volume:.9})"))
1129                        )),
1130                    };
1131                    match verdict {
1132                        None => trends[direction].cleared(),
1133                        Some(sentence) => {
1134                            if debug {
1135                                eprintln!("[perturb] {sentence}");
1136                            }
1137                            if ladder {
1138                                eprintln!(
1139                                    "[ladder] {rung}: refused by its mirror (rung {:.0} ms: built {:.0}, bound {:.0}, mirror {:.0} ms; ladder {:.1} s)",
1140                                    rung_start.elapsed().as_secs_f64() * 1e3,
1141                                    built.as_secs_f64() * 1e3,
1142                                    (bounded - built).as_secs_f64() * 1e3,
1143                                    mirror_time.as_secs_f64() * 1e3,
1144                                    ladder_start.elapsed().as_secs_f64()
1145                                );
1146                            }
1147                            refused.push(sentence);
1148                            // (f) Two refused rungs of one sign, growing, close
1149                            // the direction.
1150                            let closure = measured.and_then(|(error, bar)| {
1151                                let earlier = trends[direction].refused(magnitude, error, early_exit)?;
1152                                Some((earlier, error, bar))
1153                            });
1154                            if let Some(((earlier_offset, earlier_error), error, bar)) = closure {
1155                                let closed = format!(
1156                                    "perturbation direction dir={dir:?} closed after offset {magnitude:.3e}: its \
1157                                     rungs' first-order translation errors read {earlier_error:+.3e} at offset \
1158                                     {earlier_offset:.3e} and {error:+.3e} at {magnitude:.3e}, one sign and \
1159                                     growing, so no larger offset along it comes back to the volume drift bar \
1160                                     {bar:.3e}"
1161                                );
1162                                if debug {
1163                                    eprintln!("[perturb] {closed}");
1164                                }
1165                                if ladder {
1166                                    eprintln!("[ladder] {closed}");
1167                                }
1168                                refused.push(closed);
1169                            }
1170                            continue;
1171                        }
1172                    }
1173                }
1174            }
1175            // (b) Semantic agreement with the exact CSG of the ORIGINAL
1176            // operands. Reject a vacuous verdict (skip-band swallowed every
1177            // sample so nothing was actually checked).
1178            match crate::oracle::boolean_semantic_disagreement(
1179                first, second, operation, &candidate, 400,
1180            ) {
1181                Ok(report) if report.considered >= 30 && !report.is_flagged() => {
1182                    if ladder {
1183                        eprintln!(
1184                            "[ladder] {rung}: accepted (oracle {} considered, rate {:.4}), {}",
1185                            report.considered, report.disagreement_rate, rung_miss(&identity, &candidate)
1186                        );
1187                    }
1188                    if debug {
1189                        eprintln!(
1190                            "[perturb] rescued {operation:?}: dir={dir:?} fraction={fraction:.1e} \
1191                             magnitude={magnitude:.3e} offset={offset:?} \
1192                             (oracle considered={} rate={:.4})",
1193                            report.considered, report.disagreement_rate
1194                        );
1195                    }
1196                    return Ok(candidate);
1197                }
1198                report => {
1199                    if ladder {
1200                        let verdict = match &report {
1201                            Ok(report) => format!("oracle {} considered, rate {:.4}", report.considered, report.disagreement_rate),
1202                            Err(error) => format!("oracle error {error:?}"),
1203                        };
1204                        eprintln!("[ladder] {rung}: refused by the oracle ({verdict}), {}", rung_miss(&identity, &candidate));
1205                    }
1206                    continue;
1207                }
1208            }
1209        }
1210    }
1211    if debug {
1212        eprintln!("[perturb] ladder exhausted for {operation:?}; no rung produced a clean result");
1213    }
1214    Err(refused)
1215}
1216
1217/// The perturbation ladder's offsets, as fractions of the operands' scale,
1218/// smallest first.
1219pub const PERTURBATION_FRACTIONS: [f64; 5] = [3e-5, 1e-4, 3e-4, 1e-3, 3e-3];
1220
1221/// (f) One ladder direction's rungs refused by their mirrors.
1222///
1223/// Along one direction a rung's signed first-order translation error, half
1224/// its body less its mirror's reading, reads s(δ) = kδ + r: a slope k from the
1225/// translation, and a remainder r from the degeneracy the rung steps over,
1226/// which does not grow with the offset. Two refused rungs at δ₁ < δ₂ with one
1227/// sign and |s(δ₂)| ≥ |s(δ₁)| fix k's sign as theirs, so every larger offset
1228/// reads farther from zero than s(δ₂), which is already beyond the drift bar:
1229/// the direction is closed. Rungs of one sign that shrink toward zero, or that
1230/// change sign, say nothing about k, and the direction stays open; a rung whose
1231/// mirror clears starts the direction's record again.
1232///
1233/// Measured 2026-09-15 (`BREP_DEBUG_PERTURB_LADDER=1` prints s). On
1234/// 22_sag_boundary_identity_t164, all four operations and all four
1235/// directions, s/δ keeps one sign and holds to 3.6% over the ladder's 100× of
1236/// offset (r ≈ 0; −22.23 .. −22.34 on the intersection's first direction). On
1237/// booleanIssue's flush partial torus union, s/δ holds to 0.5% and 8.5% on two
1238/// directions, and to 1.2% on a third past its smallest rung, whose remainder
1239/// reads −43.4 against the slope's −24.5. The first direction's smallest rung
1240/// reads −1.891e-2 where its slope, +2.3 .. +2.6, gives +3.5e-3 (r ≈ −2.2e-2),
1241/// and its next measured rung +3.510e-2: a change of sign, which keeps it open.
1242/// A closed direction's skipped rung would have had to fall to the bar, 8.3e2 ..
1243/// 1.5e6 times below the smallest refused |s| on those rows, to have cleared.
1244#[derive(Clone, Copy, Default)]
1245pub struct MirrorTrend {
1246    /// The last rung refused by its mirror: its offset and signed error.
1247    last: Option<(f64, f64)>,
1248    pub closed: bool,
1249}
1250
1251impl MirrorTrend {
1252    /// Records a rung refused by its mirror at `offset` with signed error
1253    /// `error`. When it and the direction's last refused rung close the
1254    /// direction, and `close` allows it, the direction is closed and the
1255    /// earlier rung's (offset, signed error) returned.
1256    pub fn refused(&mut self, offset: f64, error: f64, close: bool) -> Option<(f64, f64)> {
1257        let earlier = self
1258            .last
1259            .filter(|&(_, earlier)| earlier.signum() == error.signum() && error.abs() >= earlier.abs())
1260            .filter(|_| close);
1261        self.last = Some((offset, error));
1262        self.closed |= earlier.is_some();
1263        earlier
1264    }
1265
1266    /// A rung whose mirror clears: the direction's record starts again.
1267    pub fn cleared(&mut self) {
1268        self.last = None;
1269    }
1270}
1271
1272/// Non-degenerate edges a solid's faces use exactly once.
1273/// BELOW-TOLERANCE REFUSAL (`BREP_BELOW_TOLERANCE_REFUSAL`, default on, `=0` off). Two
1274/// planar faces, one of each operand, that are nearly parallel and stand no
1275/// farther apart over their shared extent than [`BELOW_TOLERANCE_BAND`] but not
1276/// exactly on one another are a configuration the kernel cannot resolve: its
1277/// weld floor is 1e-5 and its face arrangements resolve a few 1e-5, so the
1278/// slivers between such faces fall under the modelling tolerance. A cube
1279/// against a copy turned 1e-4 deg moves its corners 1.2e-5 to 2.5e-5: the exact
1280/// arrangement failed, and the perturbation ladder then answered a nudged pair
1281/// 8.5e-5 out in volume; at 1e-6 deg the face pairs read as coincident and the
1282/// difference came back empty. Consulted only where the exact lane failed or
1283/// returned an empty difference or common part, so nothing that answers today
1284/// changes; the refusal names the pair and the modelling tolerance instead of
1285/// shipping a nudged or empty solid.
1286pub fn below_tolerance_refusal_enabled() -> bool {
1287    crate::switch!("BREP_BELOW_TOLERANCE_REFUSAL", true)
1288}
1289
1290/// `BREP_BELOW_TOLERANCE_SLIVERS` (default on; `=0` refuses or keeps the exact
1291/// lane's answer as before): where the below-tolerance
1292/// refusal would name a pair, an operand whose difference from the other is
1293/// all sliver ([`difference_all_sliver`]) is read as lying inside it, and the
1294/// boolean answers by that inclusion: `first - second` is empty when it is all
1295/// sliver; `first ∪ second` is the operand the other lies inside; `first ∩
1296/// second` is the operand lying inside the other. A box less a copy of itself
1297/// moved 5.4e-6 and turned 8e-7 rad holds 1.1e-4 against a bar of 1.6e-4 and
1298/// was refused (the exact lane had no boundary face left to write); a box
1299/// united with a copy whose top stands 1e-5 under its own and whose other
1300/// faces stand within 2e-7 of its own came back with open loops where the
1301/// 1e-5 strips of the side faces welded shut. A union or common part the
1302/// exact lane did write over such a pair takes the inclusion's answer too: the
1303/// common part of that box and copy read 8e-5 apart in the two orders, both
1304/// above the copy's own volume. Anything else still refuses by name, or keeps
1305/// the exact lane's answer.
1306pub fn below_tolerance_slivers_enabled() -> bool {
1307    crate::switch!("BREP_BELOW_TOLERANCE_SLIVERS", true)
1308}
1309
1310/// The most faces an operand of [`below_tolerance_answer`] may have: the
1311/// polyhedral reads are quadratic in the faces.
1312const SLIVER_ANSWER_FACES: usize = 64;
1313
1314fn face_count(solid: &BrepSolid) -> usize {
1315    solid.shells.iter().map(|shell| shell.faces.len()).sum()
1316}
1317
1318/// The answer [`below_tolerance_slivers_enabled`] gives `operation`, if any.
1319fn below_tolerance_answer(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<BrepSolid> {
1320    if !below_tolerance_slivers_enabled() || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES) {
1321        return None;
1322    }
1323    if ![first, second].iter().all(|solid| closed_single_shell(solid)) {
1324        return None;
1325    }
1326    let inside = |x: &BrepSolid, y: &BrepSolid| difference_all_sliver(x, y);
1327    if matches!(operation, BooleanOperation::Subtract) {
1328        return inside(first, second).then(empty_solid);
1329    }
1330    let (first_in, second_in) = (inside(first, second), inside(second, first));
1331    // Each inside the other: both answers hold at the tolerance; the union
1332    // takes the larger and the common part the smaller, whichever comes first.
1333    let first_larger = || match (body_volume(first), body_volume(second)) {
1334        (Some(a), Some(b)) => a >= b,
1335        _ => true,
1336    };
1337    let outer_is_first = match (first_in, second_in) {
1338        (false, false) => return None,
1339        (true, false) => false,
1340        (false, true) => true,
1341        (true, true) => first_larger(),
1342    };
1343    let (outer, inner) = if outer_is_first { (first, second) } else { (second, first) };
1344    Some(match operation {
1345        BooleanOperation::Union => outer.clone(),
1346        _ => inner.clone(),
1347    })
1348}
1349
1350/// One shell of a solid, every proper edge used by exactly two coedges.
1351fn closed_single_shell(solid: &BrepSolid) -> bool {
1352    if !solid.kind.is_solid() || solid.shells.len() != 1 {
1353        return false;
1354    }
1355    let mut uses: HashMap<u64, usize> = HashMap::default();
1356    for coedge in solid.shells[0].faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1357        *uses.entry(coedge.edge_id).or_default() += 1;
1358    }
1359    !uses.is_empty() && uses.values().all(|&count| count == 2) && solid.edges.iter().all(|edge| uses.contains_key(&edge.id))
1360}
1361
1362/// Whether `first - second` is all sliver: `second` a convex polyhedron and
1363/// `first` a polyhedron (planar faces, straight edges) standing past no face
1364/// plane of `second` by more than [`BELOW_TOLERANCE_BAND`], and the part of
1365/// `first` beyond `second`'s face planes, summed plane by plane (an upper bound
1366/// on V(first - second), since `second` is the intersection of their inner
1367/// half-spaces), at most `first`'s area times the coincidence distance
1368/// (1e-6): spread over the boundary, the material is thinner than two faces
1369/// the kernel reads as one surface. Each plane's part is exact: `first`'s face
1370/// polygons clipped to the plane's outer side, their volume read about a
1371/// point of the plane, where the cut's own cap adds nothing.
1372fn difference_all_sliver(first: &BrepSolid, second: &BrepSolid) -> bool {
1373    let Some(bounds) = difference_bounds(first, second) else {
1374        return false;
1375    };
1376    let Ok(properties) = crate::solid_mass_properties(first) else {
1377        return false;
1378    };
1379    bounds.out <= BELOW_TOLERANCE_BAND
1380        && bounds.upper.is_finite()
1381        && bounds.upper <= crate::tolerance::COINCIDENCE_DISTANCE_FLOOR * properties.surface_area
1382}
1383
1384/// Bounds on V(first - second) for a polyhedral `first` and a convex
1385/// polyhedral `second`, from `first`'s parts beyond each face plane of
1386/// `second` (exact, see [`difference_all_sliver`]): each part lies in the
1387/// difference, so the largest is a lower bound, and the difference is their
1388/// union, so their sum is an upper one.
1389struct DifferenceBounds {
1390    lower: f64,
1391    upper: f64,
1392    /// How far `first` stands past `second`'s face planes at most.
1393    out: f64,
1394}
1395
1396fn difference_bounds(first: &BrepSolid, second: &BrepSolid) -> Option<DifferenceBounds> {
1397    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1398    let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1399    let vertices_b: Vec<Vec3> = second.vertices.iter().map(|vertex| vertex.point).collect();
1400    let vertices_a: Vec<Vec3> = first.vertices.iter().map(|vertex| vertex.point).collect();
1401    let flat = 1e-9 * scale;
1402    let mut bounds = DifferenceBounds { lower: 0.0, upper: 0.0, out: 0.0 };
1403    for polygon in &polygons_b {
1404        let (origin, normal) = polygon_plane(polygon)?;
1405        // Convex: every vertex of `second` on the inner side of its face plane.
1406        if vertices_b.iter().any(|vertex| vertex.sub(origin).dot(normal) > flat) {
1407            return None;
1408        }
1409        let out = vertices_a.iter().map(|vertex| vertex.sub(origin).dot(normal)).fold(0.0f64, f64::max);
1410        bounds.out = bounds.out.max(out);
1411        if out <= 0.0 {
1412            continue;
1413        }
1414        let part: f64 = polygons_a.iter().map(|face| clipped_cone_volume(face, origin, normal)).sum();
1415        bounds.lower = bounds.lower.max(part);
1416        bounds.upper += part;
1417    }
1418    Some(bounds)
1419}
1420
1421/// `BREP_BELOW_TOLERANCE_RESCALE` (default off): a
1422/// boolean the below-tolerance refusal would name, over two closed convex
1423/// polyhedra, is run again on both operands scaled up 100 (then 1000) times, so that faces a
1424/// weld floor apart (1e-5) stand clear of it, and the answer scaled back is
1425/// kept when its volume and area are the exact ones of the two convex
1426/// polyhedra ([`convex_pair_measures`]) to a part in 1e9: a cube less a copy
1427/// turned 1e-4 degrees came back right in volume but 1e-3 over in area (a
1428/// sliver's face too many), and refuses. A box less a copy whose top stands 1e-5 under its own
1429/// leaves a slab 1e-5 thick, a valid body: refused, it came back exact.
1430pub fn below_tolerance_rescale_enabled() -> bool {
1431    crate::switch!("BREP_BELOW_TOLERANCE_RESCALE", false)
1432}
1433
1434fn below_tolerance_rescaled(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions) -> Option<BrepSolid> {
1435    if !below_tolerance_rescale_enabled()
1436        || options.tolerances.is_some()
1437        || [first, second].iter().any(|solid| face_count(solid) > SLIVER_ANSWER_FACES || !closed_single_shell(solid))
1438    {
1439        return None;
1440    }
1441    let (volume_exact, area_exact) = convex_pair_measures(first, second, operation)?;
1442    let volume_slack = 1e-9 * body_volume(first)?.max(body_volume(second)?);
1443    let area_slack = 1e-9 * area_exact.max(1.0);
1444    for factor in [100.0, 1000.0] {
1445        let scaled = |solid: &BrepSolid| crate::rescale::scale_operand(solid, factor, "boolean").ok();
1446        let (Some(a), Some(b)) = (scaled(first), scaled(second)) else {
1447            continue;
1448        };
1449        let mut scaled_options = options.clone();
1450        scaled_options.imprint.maximum_ssi_step = scaled_options.imprint.maximum_ssi_step.map(|step| step * factor);
1451        let Ok(outcome) = boolean_operation_with_diagnostics(&a, &b, operation, &scaled_options) else {
1452            continue;
1453        };
1454        let Ok(answer) = crate::rescale::scale_operand(&outcome.value, 1.0 / factor, "boolean") else {
1455            continue;
1456        };
1457        let Ok(properties) = crate::solid_mass_properties(&answer) else {
1458            continue;
1459        };
1460        if (properties.volume.abs() - volume_exact).abs() <= volume_slack
1461            && (properties.surface_area - area_exact).abs() <= area_slack
1462            && !answer.validate().iter().any(|issue| issue.severity == "error")
1463        {
1464            return Some(answer);
1465        }
1466    }
1467    None
1468}
1469
1470/// The exact volume and area of `operation` on two convex polyhedra: each
1471/// face polygon clipped to the other's inner half-spaces is the part of it
1472/// inside the other, the common part is closed by those parts of both, and
1473/// the union and difference follow from the parts inside and the rest. `None`
1474/// unless both are convex polyhedra.
1475fn convex_pair_measures(first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation) -> Option<(f64, f64)> {
1476    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1477    let (polygons_a, polygons_b) = (face_polygons(first, scale)?, face_polygons(second, scale)?);
1478    let (planes_a, planes_b) = (convex_planes(&polygons_a, scale)?, convex_planes(&polygons_b, scale)?);
1479    let zero = Vec3::new(0.0, 0.0, 0.0);
1480    // (volume of the cones over the parts inside, area of the polygons, area of the parts inside)
1481    let read = |polygons: &[Vec<Vec3>], planes: &[(Vec3, Vec3)]| {
1482        let (mut cone, mut area, mut inside_area) = (0.0, 0.0, 0.0);
1483        for polygon in polygons {
1484            area += vector_area(polygon, zero).length();
1485            let mut inside = polygon.clone();
1486            for &(origin, normal) in planes {
1487                inside = clip_polygon(&inside, origin, normal.scale(-1.0));
1488                if inside.len() < 3 {
1489                    break;
1490                }
1491            }
1492            if inside.len() >= 3 {
1493                let vector = vector_area(&inside, zero);
1494                cone += inside[0].dot(vector) / 3.0;
1495                inside_area += vector.length();
1496            }
1497        }
1498        (cone, area, inside_area)
1499    };
1500    let (cone_a, area_a, inside_a) = read(&polygons_a, &planes_b);
1501    let (cone_b, area_b, inside_b) = read(&polygons_b, &planes_a);
1502    let (volume_a, volume_b) = (body_volume(first)?, body_volume(second)?);
1503    let common = cone_a + cone_b;
1504    Some(match operation {
1505        BooleanOperation::Intersect => (common, inside_a + inside_b),
1506        BooleanOperation::Union => (volume_a + volume_b - common, (area_a - inside_a) + (area_b - inside_b)),
1507        BooleanOperation::Subtract => (volume_a - common, (area_a - inside_a) + inside_b),
1508    })
1509}
1510
1511/// A convex polyhedron's face planes (a point and the outward unit normal),
1512/// `None` when some vertex stands outside one of them.
1513fn convex_planes(polygons: &[Vec<Vec3>], scale: f64) -> Option<Vec<(Vec3, Vec3)>> {
1514    let planes = polygons.iter().map(|polygon| polygon_plane(polygon)).collect::<Option<Vec<_>>>()?;
1515    let flat = 1e-9 * scale;
1516    let convex = planes.iter().all(|&(origin, normal)| polygons.iter().flatten().all(|vertex| vertex.sub(origin).dot(normal) <= flat));
1517    convex.then_some(planes)
1518}
1519
1520/// The part of `polygon` on the side of the plane through `origin` that
1521/// `normal` points to (Sutherland-Hodgman).
1522fn clip_polygon(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> Vec<Vec3> {
1523    let side = |point: Vec3| point.sub(origin).dot(normal);
1524    let mut kept = Vec::with_capacity(polygon.len() + 2);
1525    for (index, &point) in polygon.iter().enumerate() {
1526        let next = polygon[(index + 1) % polygon.len()];
1527        let (here, there) = (side(point), side(next));
1528        if here >= 0.0 {
1529            kept.push(point);
1530        }
1531        if (here >= 0.0) != (there >= 0.0) {
1532            let t = here / (here - there);
1533            kept.push(point.add(next.sub(point).scale(t)));
1534        }
1535    }
1536    kept
1537}
1538
1539/// Every loop of `solid` as a polygon of its vertices, ordered so the
1540/// polygons' vector areas point out of the solid; `None` unless every face is
1541/// a plane and every edge a straight segment.
1542fn face_polygons(solid: &BrepSolid, scale: f64) -> Option<Vec<Vec<Vec3>>> {
1543    let vertex = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1544    let mut polygons = Vec::new();
1545    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
1546        if !face.surface.is_affine().ok()? {
1547            return None;
1548        }
1549        for lp in &face.loops {
1550            let mut polygon = Vec::with_capacity(lp.coedges.len());
1551            for coedge in &lp.coedges {
1552                let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
1553                let (start, end) = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
1554                let chord = end.sub(start);
1555                let length = chord.length();
1556                if edge.degenerate || length <= 1e-12 * scale {
1557                    return None;
1558                }
1559                for control in &edge.curve.control_points {
1560                    let offset = control.point().ok()?.sub(start);
1561                    if offset.cross(chord).length() / length > 1e-9 * scale {
1562                        return None;
1563                    }
1564                }
1565                polygon.push(if coedge.forward { start } else { end });
1566            }
1567            polygons.push(polygon);
1568        }
1569    }
1570    // Orient by the enclosed volume's sign.
1571    let volume: f64 = polygons.iter().map(|polygon| clipped_cone_volume(polygon, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0))).sum();
1572    if !(volume.abs() > 0.0) {
1573        return None;
1574    }
1575    if volume < 0.0 {
1576        for polygon in &mut polygons {
1577            polygon.reverse();
1578        }
1579    }
1580    Some(polygons)
1581}
1582
1583/// A polygon's plane: a point of it and its unit outward normal.
1584fn polygon_plane(polygon: &[Vec3]) -> Option<(Vec3, Vec3)> {
1585    let origin = *polygon.first()?;
1586    Some((origin, vector_area(polygon, origin).normalized().ok()?))
1587}
1588
1589fn vector_area(polygon: &[Vec3], origin: Vec3) -> Vec3 {
1590    let mut area = Vec3::new(0.0, 0.0, 0.0);
1591    for (index, point) in polygon.iter().enumerate() {
1592        let next = polygon[(index + 1) % polygon.len()];
1593        area = area.add(point.sub(origin).cross(next.sub(origin)));
1594    }
1595    area.scale(0.5)
1596}
1597
1598/// The volume of the cone from `origin` over the part of `polygon` on the
1599/// outer side of the plane through `origin` with `normal` (all of it for a
1600/// zero normal). Summed over a closed polyhedron's polygons, it is the volume
1601/// of the polyhedron beyond that plane: the cut's cap lies in the plane and
1602/// adds nothing about a point of it.
1603fn clipped_cone_volume(polygon: &[Vec3], origin: Vec3, normal: Vec3) -> f64 {
1604    let clipped: Vec<Vec3> = if normal.length() == 0.0 { polygon.to_vec() } else { clip_polygon(polygon, origin, normal) };
1605    if clipped.len() < 3 {
1606        return 0.0;
1607    }
1608    clipped[0].sub(origin).dot(vector_area(&clipped, origin)) / 3.0
1609}
1610
1611/// Ten weld floors: the separation under which two near-coincident planar faces
1612/// are read as below the modelling tolerance.
1613const BELOW_TOLERANCE_BAND: f64 = 10.0 * crate::tolerance::WELD_FLOOR;
1614
1615/// UNRESOLVED-MERGE REFUSAL (`BREP_UNRESOLVED_MERGE_REFUSAL`, default off). A
1616/// union or common part that SUCCEEDS over two planar faces, one of each
1617/// operand, standing farther apart than the coincidence band (1e-6: closer
1618/// faces are one surface by the kernel's definition) but no farther than the
1619/// weld floor (1e-5) has welded the two faces into one: a unit cube united
1620/// with a copy raised 3e-6 came back as the cube, valid, 2e-6 out in volume,
1621/// where the difference of the same pair already refuses by this name. The
1622/// step between such faces is neither a coincidence nor resolvable, so the
1623/// answer is the refusal.
1624pub fn unresolved_merge_refusal_enabled() -> bool {
1625    crate::switch!("BREP_UNRESOLVED_MERGE_REFUSAL", false)
1626}
1627
1628/// SLIVER SHELLS (`BREP_SLIVER_SHELL_DROP`, default on, `=0` off). A solid
1629/// result of several shells, one of which is closed and encloses no material
1630/// (its volume over its area, the thickness of the slab it would be, under
1631/// [`SLIVER_SHELL_THICKNESS`] of the body's size: round-off), carries a sheet the arrangement could not
1632/// resolve, left closed on itself: a measure-zero set, not a void. A cylinder
1633/// of radius 5 with a coaxial one of radius 4.99999 between the same end
1634/// planes gave their common part the inner cylinder plus 64 closed sheets
1635/// over the 1e-5 rings at its ends, 6e-4 over in area and refused by STEP
1636/// export ("a void shell lies inside no outward shell"). Such shells are
1637/// dropped, with the edges and vertices only they used; the point set is
1638/// unchanged. Sheet and other non-solid bodies, open shells, and a body whose
1639/// every shell would go are left as they are.
1640pub fn sliver_shell_drop_enabled() -> bool {
1641    crate::switch!("BREP_SLIVER_SHELL_DROP", true)
1642}
1643
1644/// The thickness, as a fraction of the body's size, under which a closed shell
1645/// encloses nothing: round-off. The sheets read 0 and 7e-17 thick; a real
1646/// slab 1e-7 thick beside a unit cube is material and stays.
1647const SLIVER_SHELL_THICKNESS: f64 = 1e-12;
1648
1649/// `BREP_SLIVER_SHELL_FAST` (on by default; `=0` reads every shell in full):
1650/// a shell is kept without its full
1651/// mass properties when its volume, read for its sign against the floor
1652/// times an upper bound on its area ([`face_area_upper_bound`]), proves it
1653/// thicker than the floor (only where every face's trim lies within its
1654/// carrier's knot domain). The reading's verdict is the exact check's, and
1655/// an area above the shell's makes the bar higher than the exact one, so a
1656/// shell kept this way is one the exact reading keeps. Everything else (a void,
1657/// whose volume is negative, a real sliver, a face without a bound) is read
1658/// in full as before. The reading reuses the face terms the assembly's sign
1659/// check retained: on a screw wall crossed by a box, the check of four shells
1660/// fell from about 300 ms to a few. `BREP_SLIVER_SHELL_FAST_CHECK` reads both
1661/// and counts the shells whose verdicts differ
1662/// ([`sliver_shell_fast_check_take`]), keeping the full reading's.
1663pub fn sliver_shell_fast_on() -> bool {
1664    crate::switch!("BREP_SLIVER_SHELL_FAST", true)
1665}
1666
1667fn sliver_shell_fast_check_on() -> bool {
1668    crate::switch!("BREP_SLIVER_SHELL_FAST_CHECK", false)
1669}
1670
1671thread_local! {
1672    static SLIVER_FAST_CHECK: std::cell::Cell<(u64, u64, u64)> = const { std::cell::Cell::new((0, 0, 0)) };
1673}
1674
1675/// (shells read both ways, verdicts that differed, shells the fast reading
1676/// kept) on this thread since the last call.
1677pub fn sliver_shell_fast_check_take() -> (u64, u64, u64) {
1678    SLIVER_FAST_CHECK.with(|cell| cell.replace((0, 0, 0)))
1679}
1680
1681fn sliver_fast_record(compared: u64, differed: u64, kept: u64) {
1682    SLIVER_FAST_CHECK.with(|cell| {
1683        let (a, b, c) = cell.get();
1684        cell.set((a + compared, b + differed, c + kept));
1685    });
1686}
1687
1688/// An upper bound on the area of `surface` over its whole parameter domain
1689/// (so on any face trimmed from it). `|S_u × S_v| ≤ |S_u| |S_v|`, and with
1690/// `S = P / w` (homogeneous `P`, weight `w`) `|S_u| ≤ (|P_u| w_max + |P|
1691/// |w_u|) / w_min²`. Each factor is bounded by the convex hull of its control
1692/// net: `|P|` and the weights by the control points, `P_u` and `w_u` by the
1693/// hodograph's points `p (Q_{i+1} − Q_i) / (u_{i+p+1} − u_{i+1})`. `None`
1694/// for a weight that is not positive or a bound that is not finite.
1695fn face_area_upper_bound(surface: &crate::NurbsSurface) -> Option<f64> {
1696    let net = &surface.control_points;
1697    let rows = net.len();
1698    let columns = net.first()?.len();
1699    if rows < 2 || columns < 2 || net.iter().any(|row| row.len() != columns) {
1700        return None;
1701    }
1702    let (p, q) = (surface.degree_u, surface.degree_v);
1703    let (us, vs) = (&surface.knots_u, &surface.knots_v);
1704    if us.len() != rows + p + 1 || vs.len() != columns + q + 1 {
1705        return None;
1706    }
1707    let mut w_min = f64::INFINITY;
1708    let mut w_max = 0.0f64;
1709    let mut point_max = 0.0f64;
1710    for c in net.iter().flatten() {
1711        if !(c.w > 0.0) {
1712            return None;
1713        }
1714        w_min = w_min.min(c.w);
1715        w_max = w_max.max(c.w);
1716        point_max = point_max.max((c.x * c.x + c.y * c.y + c.z * c.z).sqrt());
1717    }
1718    // (max |P_u|, max |w_u|) over the hodograph in one direction.
1719    let hodograph = |along_u: bool| -> Option<(f64, f64)> {
1720        let (count, degree, knots) = if along_u { (rows, p, us) } else { (columns, q, vs) };
1721        let (mut dp, mut dw) = (0.0f64, 0.0f64);
1722        for i in 0..count - 1 {
1723            let span = knots[i + degree + 1] - knots[i + 1];
1724            if !(span > 0.0) {
1725                continue;
1726            }
1727            let scale = degree as f64 / span;
1728            let others = if along_u { columns } else { rows };
1729            for j in 0..others {
1730                let (a, b) = if along_u { (net[i][j], net[i + 1][j]) } else { (net[j][i], net[j][i + 1]) };
1731                let (x, y, z) = (b.x - a.x, b.y - a.y, b.z - a.z);
1732                dp = dp.max(scale * (x * x + y * y + z * z).sqrt());
1733                dw = dw.max(scale * (b.w - a.w).abs());
1734            }
1735        }
1736        Some((dp, dw))
1737    };
1738    let (pu, wu) = hodograph(true)?;
1739    let (pv, wv) = hodograph(false)?;
1740    let su = (pu * w_max + point_max * wu) / (w_min * w_min);
1741    let sv = (pv * w_max + point_max * wv) / (w_min * w_min);
1742    let extent_u = us[us.len() - 1] - us[0];
1743    let extent_v = vs[vs.len() - 1] - vs[0];
1744    let bound = su * sv * extent_u * extent_v;
1745    bound.is_finite().then_some(bound)
1746}
1747
1748/// [`face_area_upper_bound`] of `face`'s carrier, when its trim lies within
1749/// the carrier's knot domain: every pcurve control point (whose convex hull
1750/// holds the pcurve) inside it, to `1e-12` of the domain's own extent (a circle's
1751/// corner points land a rounding outside). A trim reaching further is
1752/// measured on the carrier's extension, which the control net does not
1753/// bound: `None`. The bound is doubled to cover that rounding's sliver of
1754/// extension (the carrier's own polynomial continued).
1755pub fn trimmed_face_area_upper_bound(face: &crate::topology::FaceRecord) -> Option<f64> {
1756    let s = &face.surface;
1757    let (u0, u1) = (*s.knots_u.first()?, *s.knots_u.last()?);
1758    let (v0, v1) = (*s.knots_v.first()?, *s.knots_v.last()?);
1759    // (relative to the domain alone: a tiny chart's allowance stays tiny)
1760    let (du, dv) = (1e-12 * (u1 - u0).abs(), 1e-12 * (v1 - v0).abs());
1761    if !(du > 0.0 && dv > 0.0) {
1762        return None;
1763    }
1764    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1765        for c in &coedge.pcurve.control_points {
1766            if !(c.w > 0.0) {
1767                return None;
1768            }
1769            let (u, v) = (c.x / c.w, c.y / c.w);
1770            if !(u >= u0 - du && u <= u1 + du && v >= v0 - dv && v <= v1 + dv) {
1771                return None;
1772            }
1773        }
1774    }
1775    face_area_upper_bound(s).map(|bound| 2.0 * bound)
1776}
1777
1778/// Drops the sliver shells of `solid` (see [`sliver_shell_drop_enabled`]) and
1779/// returns how many went.
1780fn drop_sliver_shells(solid: &mut BrepSolid) -> usize {
1781    if !sliver_shell_drop_enabled() || !solid.kind.is_solid() || solid.shells.len() < 2 {
1782        return 0;
1783    }
1784    let floor = SLIVER_SHELL_THICKNESS * crate::solid_tolerance::solid_scale(solid).max(1.0);
1785    let degenerate: std::collections::HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
1786    let mut drop = vec![false; solid.shells.len()];
1787    for (index, shell) in solid.shells.iter().enumerate() {
1788        if shell.faces.is_empty() {
1789            continue;
1790        }
1791        // Closed: every proper edge the shell uses, used exactly twice by it.
1792        let mut uses: HashMap<u64, usize> = HashMap::default();
1793        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
1794            if !degenerate.contains(&coedge.edge_id) {
1795                *uses.entry(coedge.edge_id).or_default() += 1;
1796            }
1797        }
1798        if uses.is_empty() || uses.values().any(|&count| count != 2) {
1799            continue;
1800        }
1801        let alone = BrepSolid { shells: vec![shell.clone()], mass_properties_cache: Default::default(), ..solid.clone() };
1802        let (fast, check) = (sliver_shell_fast_on(), sliver_shell_fast_check_on());
1803        let kept_fast = (fast || check)
1804            && shell
1805                .faces
1806                .iter()
1807                .map(trimmed_face_area_upper_bound)
1808                .sum::<Option<f64>>()
1809                .map(|area| floor * area)
1810                .filter(|bar| bar.is_finite() && *bar > 0.0)
1811                .and_then(|bar| crate::solid_signed_volume_for_sign(&alone, bar).ok().map(|volume| volume > bar))
1812                .unwrap_or(false);
1813        if kept_fast && !check {
1814            sliver_fast_record(0, 0, 1);
1815            continue;
1816        }
1817        let Ok(mass) = crate::solid_mass_properties(&alone) else {
1818            continue;
1819        };
1820        let thickness = mass.volume.abs() / mass.surface_area.max(f64::MIN_POSITIVE);
1821        if env_read!("BREP_DEBUG_SLIVER_SHELL").is_some() {
1822            eprintln!(
1823                "sliver-shell: shell {index} of {}: volume {:.6e} area {:.6e} thickness {thickness:.3e}",
1824                solid.shells.len(),
1825                mass.volume,
1826                mass.surface_area
1827            );
1828        }
1829        drop[index] = thickness < floor;
1830        if check {
1831            sliver_fast_record(1, u64::from(kept_fast && drop[index]), u64::from(kept_fast));
1832        }
1833    }
1834    let dropped = drop.iter().filter(|&&d| d).count();
1835    if dropped == 0 || dropped == solid.shells.len() {
1836        return 0;
1837    }
1838    let mut index = 0;
1839    solid.shells.retain(|_| {
1840        let keep = !drop[index];
1841        index += 1;
1842        keep
1843    });
1844    let used_edges: std::collections::HashSet<u64> = solid
1845        .shells
1846        .iter()
1847        .flat_map(|shell| &shell.faces)
1848        .flat_map(|face| &face.loops)
1849        .flat_map(|lp| &lp.coedges)
1850        .map(|coedge| coedge.edge_id)
1851        .collect();
1852    solid.edges.retain(|edge| used_edges.contains(&edge.id));
1853    let used_vertices: std::collections::HashSet<u64> =
1854        solid.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
1855    solid.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
1856    solid.mass_properties_cache = Default::default();
1857    // A dropped shell may have carried handles: the genus is read again.
1858    refresh_derived_genus(solid);
1859    dropped
1860}
1861
1862fn unresolved_merge_refusal(first: &BrepSolid, second: &BrepSolid) -> Option<KernelRefusal> {
1863    let (lower, upper) = (crate::tolerance::COINCIDENCE_DISTANCE_FLOOR, crate::tolerance::WELD_FLOOR);
1864    let (face_a, face_b, separation) = planar_faces_apart_within(first, second, lower, upper)?;
1865    Some(KernelRefusal::unsupported(
1866        KernelStage::Intersect,
1867        "below_modelling_tolerance",
1868        format!(
1869            "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1870             another, {separation:.3e} apart at most over their shared extent: farther than a coincidence \
1871             ({lower:.0e}) and closer than the kernel resolves ({upper:.0e}), so the step between them would be \
1872             welded away"
1873        ),
1874    ))
1875}
1876
1877fn below_tolerance_refusal(first: &BrepSolid, second: &BrepSolid, error: Option<&KernelRefusal>) -> Option<KernelRefusal> {
1878    let (face_a, face_b, separation) = near_coincident_planar_faces(first, second)?;
1879    let message = format!(
1880        "boolean: face {face_a} of the first operand and face {face_b} of the second are planes nearly on one \
1881         another, {separation:.3e} apart at most over their shared extent: the slivers between them are below the \
1882         modelling tolerance ({BELOW_TOLERANCE_BAND:.0e}), so the kernel cannot resolve them{}",
1883        error.map(|error| format!(" (the exact arrangement said: {})", error.message.chars().take(160).collect::<String>())).unwrap_or_default()
1884    );
1885    Some(KernelRefusal::unsupported(KernelStage::Intersect, "below_modelling_tolerance", message))
1886}
1887
1888/// The first pair of planar faces (one per operand) whose planes are nearly
1889/// parallel and whose boundaries stand within [`BELOW_TOLERANCE_BAND`] of the
1890/// other's plane, with overlapping extents, but which are not one plane.
1891fn near_coincident_planar_faces(first: &BrepSolid, second: &BrepSolid) -> Option<(u64, u64, f64)> {
1892    let scale = crate::solid_tolerance::solid_scale(first).max(crate::solid_tolerance::solid_scale(second)).max(1.0);
1893    planar_faces_apart_within(first, second, 1e-9 * scale, BELOW_TOLERANCE_BAND)
1894}
1895
1896/// The first pair of nearly parallel planar faces (one per operand) with
1897/// overlapping extents whose largest separation is above `lower` and at most
1898/// `upper`.
1899fn planar_faces_apart_within(first: &BrepSolid, second: &BrepSolid, lower: f64, upper: f64) -> Option<(u64, u64, f64)> {
1900    struct Planar {
1901        id: u64,
1902        origin: Vec3,
1903        normal: Vec3,
1904        corners: Vec<Vec3>,
1905        bounds: crate::spatial::Aabb,
1906    }
1907    let read = |solid: &BrepSolid| -> Vec<Planar> {
1908        let at = |id: u64| solid.vertices.iter().find(|vertex| vertex.id == id).map(|vertex| vertex.point);
1909        solid
1910            .shells
1911            .iter()
1912            .flat_map(|shell| &shell.faces)
1913            .filter_map(|face| {
1914                if !face.surface.is_affine().ok()? {
1915                    return None;
1916                }
1917                let origin = face.surface.control_points[0][0].point().ok()?;
1918                let a = face.surface.control_points[1][0].point().ok()?.sub(origin);
1919                let b = face.surface.control_points[0][1].point().ok()?.sub(origin);
1920                let normal = a.cross(b).normalized().ok()?;
1921                let corners: Vec<Vec3> = face
1922                    .loops
1923                    .iter()
1924                    .flat_map(|lp| &lp.coedges)
1925                    .filter_map(|coedge| solid.edges.iter().find(|edge| edge.id == coedge.edge_id))
1926                    .flat_map(|edge| [at(edge.start_vertex_id), at(edge.end_vertex_id)])
1927                    .flatten()
1928                    .collect();
1929                if corners.is_empty() {
1930                    return None;
1931                }
1932                let bounds = crate::spatial::Aabb::from_points(corners.clone());
1933                Some(Planar { id: face.id, origin, normal, corners, bounds })
1934            })
1935            .collect()
1936    };
1937    let (faces_a, faces_b) = (read(first), read(second));
1938    for a in &faces_a {
1939        for b in &faces_b {
1940            if a.normal.cross(b.normal).length() > 1e-3 {
1941                continue;
1942            }
1943            if !a.bounds.intersects(b.bounds, upper) {
1944                continue;
1945            }
1946            let separation = a
1947                .corners
1948                .iter()
1949                .map(|corner| corner.sub(b.origin).dot(b.normal).abs())
1950                .chain(b.corners.iter().map(|corner| corner.sub(a.origin).dot(a.normal).abs()))
1951                .fold(0.0f64, f64::max);
1952            if separation > lower && separation <= upper {
1953                return Some((a.id, b.id, separation));
1954            }
1955        }
1956    }
1957    None
1958}
1959
1960pub fn one_use_edges(solid: &BrepSolid) -> usize {
1961    let mut uses: HashMap<u64, usize> = HashMap::default();
1962    for coedge in solid
1963        .shells
1964        .iter()
1965        .flat_map(|shell| &shell.faces)
1966        .flat_map(|face| &face.loops)
1967        .flat_map(|loop_record| &loop_record.coedges)
1968    {
1969        *uses.entry(coedge.edge_id).or_default() += 1;
1970    }
1971    solid
1972        .edges
1973        .iter()
1974        .filter(|edge| !edge.degenerate && uses.get(&edge.id) == Some(&1))
1975        .count()
1976}
1977
1978/// A body's enclosed volume, zero for an empty one.
1979fn body_volume(solid: &BrepSolid) -> Option<f64> {
1980    if solid.shells.is_empty() {
1981        return Some(0.0);
1982    }
1983    solid_signed_volume(solid).ok().map(f64::abs)
1984}
1985
1986/// What the exact lane's other operations say `operation` on these operands
1987/// must enclose.
1988struct InclusionExclusion {
1989    /// The rescued operation's volume in terms of V(first), V(second) and
1990    /// V(first ∩ second).
1991    formula: &'static str,
1992    /// The exact-lane boolean that supplied V(first ∩ second).
1993    reading: &'static str,
1994    /// That boolean's enclosed volume.
1995    read: f64,
1996    /// The volume `formula` gives.
1997    expected: f64,
1998}
1999
2000/// The volume `operation` on these operands must have, by inclusion–exclusion.
2001/// Any one exact-lane boolean of the same two operands fixes V(first ∩ second),
2002/// and with the operands' own volumes that fixes all four operations. The
2003/// readings are tried intersection, union, then difference, each in both
2004/// operand orders: the exact lane is not order-symmetric (the helmet's cutter
2005/// ∩ helmet refuses where helmet ∩ cutter clears). The rescued operation itself,
2006/// in its own order, is skipped, since it is the one that refused, unless
2007/// `own_first` asks for it to be read first (a rung's mirror, where it is a
2008/// different pair of operands). `None` when no reading clears or an operand has
2009/// no volume.
2010fn inclusion_exclusion_volume(
2011    first: &BrepSolid,
2012    second: &BrepSolid,
2013    operation: BooleanOperation,
2014    options: &BooleanOptions,
2015    va: Option<f64>,
2016    vb: Option<f64>,
2017    own_first: bool,
2018) -> Option<InclusionExclusion> {
2019    use BooleanOperation::{Intersect, Subtract, Union};
2020    let (va, vb) = (va?, vb?);
2021    let own = match operation {
2022        Intersect => (Intersect, false, "first ∩ second"),
2023        Union => (Union, false, "first ∪ second"),
2024        Subtract => (Subtract, false, "first − second"),
2025    };
2026    let readings = [
2027        (Intersect, false, "first ∩ second"),
2028        (Intersect, true, "second ∩ first"),
2029        (Union, false, "first ∪ second"),
2030        (Union, true, "second ∪ first"),
2031        (Subtract, false, "first − second"),
2032        (Subtract, true, "second − first"),
2033    ];
2034    let own_reading = own_first.then_some(own);
2035    let leading = usize::from(own_first);
2036    for (index, (other, swapped, reading)) in own_reading.into_iter().chain(readings).enumerate() {
2037        if index >= leading && !swapped && std::mem::discriminant(&other) == std::mem::discriminant(&operation) {
2038            continue;
2039        }
2040        let (x, y) = if swapped { (second, first) } else { (first, second) };
2041        let Some(read) = boolean_operation_with_diagnostics(x, y, other, options)
2042            .ok()
2043            .and_then(|outcome| body_volume(&outcome.value))
2044        else {
2045            continue;
2046        };
2047        let intersection = match (other, swapped) {
2048            (Intersect, _) => read,
2049            (Union, _) => va + vb - read,
2050            (Subtract, false) => va - read,
2051            (Subtract, true) => vb - read,
2052        };
2053        let (formula, expected) = match operation {
2054            Intersect => ("V(first ∩ second)", intersection),
2055            Union => ("V(first) + V(second) − V(first ∩ second)", va + vb - intersection),
2056            Subtract => ("V(first) − V(first ∩ second)", va - intersection),
2057        };
2058        return Some(InclusionExclusion { formula, reading, read, expected });
2059    }
2060    None
2061}
2062
2063/// The worst planar face of either operand whose STRAIGHT boundary sits
2064/// farther off its plane than the assembly weld radius:
2065/// `(operand index, face id, gap, weld)`. Mirrors the STEP importer's planar
2066/// split predicate (`step_import::builder::planar_split`) on a finished
2067/// solid: a plane, a single loop of straight non-degenerate edges, and a
2068/// boundary vertex beyond the weld. `None` means no such face, so a failure
2069/// may still be a genuine degeneracy worth a perturbation rung. Only
2070/// consulted on the failure path.
2071fn planar_operand_off_its_plane(
2072    first: &BrepSolid,
2073    second: &BrepSolid,
2074    options: &BooleanOptions,
2075) -> Option<(u8, u64, f64, f64)> {
2076    let policy = options
2077        .tolerances
2078        .clone()
2079        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
2080    let weld = crate::tolerance::assembler_weld(policy.model);
2081    let mut worst: Option<(u8, u64, f64)> = None;
2082    for (operand, solid) in [(0u8, first), (1u8, second)] {
2083        let vertex_point = |id: u64| solid.vertices.iter().find(|v| v.id == id).map(|v| v.point);
2084        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
2085            let Some(crate::AnalyticSurface::Plane {
2086                origin,
2087                u_dir,
2088                v_dir,
2089                ..
2090            }) = face.surface.analytic()
2091            else {
2092                continue;
2093            };
2094            let [loop_record] = face.loops.as_slice() else {
2095                continue;
2096            };
2097            let Ok(normal) = u_dir.cross(*v_dir).normalized() else {
2098                continue;
2099            };
2100            let mut off_plane = 0.0f64;
2101            let mut straight = true;
2102            for coedge in &loop_record.coedges {
2103                let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
2104                    straight = false;
2105                    break;
2106                };
2107                let (Some(start), Some(end)) =
2108                    (vertex_point(edge.start_vertex_id), vertex_point(edge.end_vertex_id))
2109                else {
2110                    straight = false;
2111                    break;
2112                };
2113                let chord = end.sub(start);
2114                let length = chord.length();
2115                if edge.degenerate || length <= weld {
2116                    straight = false;
2117                    break;
2118                }
2119                let direction = chord.scale(1.0 / length);
2120                for fraction in [0.25, 0.5, 0.75] {
2121                    let Ok(point) = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction) else {
2122                        straight = false;
2123                        break;
2124                    };
2125                    let delta = point.sub(start);
2126                    let along = delta.dot(direction);
2127                    if delta.sub(direction.scale(along)).length() > weld
2128                        || along < -weld
2129                        || along > length + weld
2130                    {
2131                        straight = false;
2132                        break;
2133                    }
2134                }
2135                if !straight {
2136                    break;
2137                }
2138                off_plane = off_plane.max(start.sub(*origin).dot(normal).abs());
2139            }
2140            if straight && off_plane > weld && worst.is_none_or(|(_, _, gap)| off_plane > gap) {
2141                worst = Some((operand, face.id, off_plane));
2142            }
2143        }
2144    }
2145    worst.map(|(operand, face_id, gap)| (operand, face_id, gap, weld))
2146}
2147
2148/// CSG volume inequality bounds (no extra boolean needed) with 1% relative slack.
2149/// `va`, `vb`, `vr` are absolute volumes of operand A, operand B, and the result.
2150fn volume_within_csg_bounds(operation: BooleanOperation, va: f64, vb: f64, vr: f64) -> bool {
2151    let slack = 1e-2 * (va + vb).max(1.0);
2152    match operation {
2153        // max(A,B) ≤ A∪B ≤ A+B
2154        BooleanOperation::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
2155        // A−B ≤ A (and ≥ 0)
2156        BooleanOperation::Subtract => vr <= va + slack && vr >= -slack,
2157        // A∩B ≤ min(A,B)
2158        BooleanOperation::Intersect => vr <= va.min(vb) + slack && vr >= -slack,
2159    }
2160}
2161
2162// ---------------------------------------------------------------------------
2163// N-ary booleans (Golovanov T4.4)
2164//
2165// Union / intersect / subtract of N solids in ONE imprint+fragment pass.  This
2166// is a NEW ADDITIVE entry point: the binary `boolean_operation` above is left
2167// byte-identical.  The pipeline mirrors the binary one but generalizes the two
2168// operand-specific stages to N operands:
2169//
2170//   1. Imprint EVERY unordered pair (i, j) so every mutual intersection edge is
2171//      present on both operands' faces, and accumulate all pairs into ONE global
2172//      imprint (operand indices remapped to 0..N, piece/vertex ids made globally
2173//      unique, per-face piece lists and per-edge split parameters merged).
2174//   2. Split + fragment each operand by that single global imprint, so each
2175//      operand's faces are cut by ALL of its intersections at once.
2176//   3. Select fragments in one pass: the per-fragment keep decision generalizes
2177//      from "vs one other solid" to "vs the SET of other solids" (see
2178//      `nary_keep`).  Because every pair is imprinted, a fragment's interior lies
2179//      wholly inside or wholly outside each other operand, so a single interior
2180//      test point per (fragment, other-solid) is an exact membership verdict.
2181//   4. Assemble with the same machinery (`assemble_fragments`), then merge and
2182//      validate exactly as the binary path does.
2183// ---------------------------------------------------------------------------
2184
2185/// Reverse a fragment's orientation (surface sense + every coedge), the same
2186/// transform the binary Subtract path applies to the second operand's kept
2187/// fragments.  Extracted so the n-ary selector can reuse it verbatim.
2188fn reverse_fragment(fragment: &mut FaceFragmentRecord) -> Result<(), KernelRefusal> {
2189    fragment.same_sense = !fragment.same_sense;
2190    for loop_record in &mut fragment.loops {
2191        loop_record.coedges.reverse();
2192        for coedge in &mut loop_record.coedges {
2193            coedge.forward = !coedge.forward;
2194            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Validate, "reversed")?;
2195        }
2196    }
2197    Ok(())
2198}
2199
2200/// Imprint every unordered pair of operands and fold the pairwise
2201/// `ImprintResultRecord`s into ONE global imprint whose operand indices are the
2202/// operands' global positions (0..N).  Piece and vertex ids are re-based to be
2203/// globally unique; `by_face` piece lists and `edge_splits` parameter lists are
2204/// MERGED per key so `fragment_face` (which takes the first `by_face` match) and
2205/// `apply_edge_splits` (which collects one entry per edge) see every cut.
2206fn build_nary_imprint(
2207    operands: &[BrepSolid],
2208    options: &ImprintOptions,
2209) -> Result<ImprintResultRecord, KernelRefusal> {
2210    let mut section_evidence = false;
2211    let mut vertices: Vec<ImprintVertex> = Vec::new();
2212    let mut pieces: Vec<ImprintPieceRecord> = Vec::new();
2213    let mut by_face: HashMap<(u8, u64), Vec<u64>> = HashMap::default();
2214    let mut edge_splits: HashMap<(u8, u64), Vec<f64>> = HashMap::default();
2215    let mut next_vertex_id: u64 = 1;
2216    let mut next_piece_id: u64 = 1;
2217
2218    for i in 0..operands.len() {
2219        for j in (i + 1)..operands.len() {
2220            let pair = build_imprints(&operands[i], &operands[j], options)?;
2221            let remap = |operand: u8| -> u8 {
2222                if operand == 0 {
2223                    i as u8
2224                } else {
2225                    j as u8
2226                }
2227            };
2228
2229            section_evidence = section_evidence || pair.section_evidence;
2230            let mut vertex_map: HashMap<u64, u64> = HashMap::default();
2231            for vertex in &pair.vertices {
2232                let global = next_vertex_id;
2233                next_vertex_id += 1;
2234                vertex_map.insert(vertex.id, global);
2235                vertices.push(ImprintVertex {
2236                    id: global,
2237                    point: vertex.point,
2238                });
2239            }
2240
2241            let mut piece_map: HashMap<u64, u64> = HashMap::default();
2242            for piece in &pair.pieces {
2243                let global = next_piece_id;
2244                next_piece_id += 1;
2245                piece_map.insert(piece.id, global);
2246                let mut mapped = piece.clone();
2247                mapped.id = global;
2248                mapped.start_vertex_id = *vertex_map
2249                    .get(&piece.start_vertex_id)
2250                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2251                mapped.end_vertex_id = *vertex_map
2252                    .get(&piece.end_vertex_id)
2253                    .ok_or_else(|| KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: piece references unknown vertex"))?;
2254                for pcurve in &mut mapped.pcurves {
2255                    pcurve.operand = remap(pcurve.operand);
2256                }
2257                mapped.support_faces = [
2258                    FaceKey {
2259                        operand: remap(piece.support_faces[0].operand),
2260                        face_id: piece.support_faces[0].face_id,
2261                    },
2262                    FaceKey {
2263                        operand: remap(piece.support_faces[1].operand),
2264                        face_id: piece.support_faces[1].face_id,
2265                    },
2266                ];
2267                pieces.push(mapped);
2268            }
2269
2270            for entry in &pair.by_face {
2271                let list = by_face
2272                    .entry((remap(entry.operand), entry.face_id))
2273                    .or_default();
2274                for piece_id in &entry.piece_ids {
2275                    let global = *piece_map.get(piece_id).ok_or_else(|| {
2276                        KernelRefusal::internal(KernelStage::Intersect, "nary.imprint", "n-ary imprint: by_face references unknown piece")
2277                    })?;
2278                    list.push(global);
2279                }
2280            }
2281
2282            for split in &pair.edge_splits {
2283                edge_splits
2284                    .entry((remap(split.operand), split.edge_id))
2285                    .or_default()
2286                    .extend(split.parameters.iter().copied());
2287            }
2288        }
2289    }
2290
2291    Ok(ImprintResultRecord {
2292        faces_in_unproved_pairs: None,
2293        vertices,
2294        pieces,
2295        tangent_nodes: Vec::new(),
2296        barrier_edges: Vec::new(),
2297        section_evidence,
2298        cosurface_pairs: Vec::new(),
2299        operand_sliver_regions: Vec::new(),
2300        tangent_sections: Vec::new(),
2301        by_face: by_face
2302            .into_iter()
2303            .map(|((operand, face_id), piece_ids)| FaceImprints {
2304                operand,
2305                face_id,
2306                piece_ids,
2307            })
2308            .collect(),
2309        edge_splits: edge_splits
2310            .into_iter()
2311            .map(|((operand, edge_id), parameters)| EdgeSplitRecord {
2312                operand,
2313                edge_id,
2314                parameters,
2315            })
2316            .collect(),
2317    })
2318}
2319
2320/// N-ary union / intersect / subtract of `operands` in ONE imprint+fragment
2321/// pass (Golovanov T4.4).  Additive: does not touch the binary path.
2322///
2323/// - `Union`   : the boundary of `∪ operands`.
2324/// - `Intersect`: the boundary of `∩ operands`.
2325/// - `Subtract`: `operands[0]` minus the union of `operands[1..]`.
2326///
2327/// `N = 1` returns the sole operand; `N = 2` runs the same general pipeline and
2328/// reproduces the binary result (same volume, valid).  Returns a clear `Err`
2329/// when the operands cannot assemble into a closed, valid solid.
2330pub fn boolean_operation_nary(
2331    operands: &[BrepSolid],
2332    operation: BooleanOperation,
2333) -> Result<BrepSolid, KernelRefusal> {
2334    boolean_operation_nary_with_options(operands, operation, &BooleanOptions::default())
2335}
2336
2337/// [`boolean_operation_nary`] under the caller's [`BooleanOptions`]: the
2338/// tolerance, the coplanar-face merge and its `keep_unmerged_name_substrs`
2339/// list are honoured exactly as the binary path honours them, so a caller that
2340/// falls back from a sequence of binary unions to one arrangement (the sheet
2341/// metal walk with adjacent bends) keeps the same face partition contract.
2342pub fn boolean_operation_nary_with_options(
2343    operands: &[BrepSolid],
2344    operation: BooleanOperation,
2345    options: &BooleanOptions,
2346) -> Result<BrepSolid, KernelRefusal> {
2347    // More operands than one arrangement takes (255): folded a chunk at a
2348    // time, the result so far the next chunk's first operand. Union and
2349    // intersection are associative, and a difference takes the first operand
2350    // less all the rest, so the answer is the one arrangement's would be.
2351    let most = nary_chunk();
2352    if operands.len() > most && nary_chunks_on() {
2353        let mut whole = boolean_operation_nary_with_options(&operands[..most], operation, options)?;
2354        for chunk in operands[most..].chunks(most - 1) {
2355            // A last chunk of one operand is the binary boolean of the two
2356            // (as every two-operand call is answered by the pairwise path).
2357            if let [only] = chunk {
2358                whole = boolean_operation(&whole, only, operation, options)?;
2359                continue;
2360            }
2361            let mut next = Vec::with_capacity(chunk.len() + 1);
2362            next.push(whole);
2363            next.extend_from_slice(chunk);
2364            whole = boolean_operation_nary_with_options(&next, operation, options)?;
2365        }
2366        return Ok(whole);
2367    }
2368    let arranged = boolean_operation_nary_arranged(operands, operation, options);
2369    match arranged {
2370        Err(error) if nary_sequential_fallback_enabled() && operands.len() > 2 && error.message.contains("boolean assembly") => {
2371            // The binary path, operand by operand: each step is the pairwise
2372            // boolean every other caller makes.
2373            let mut whole = operands[0].clone();
2374            for operand in &operands[1..] {
2375                whole = match boolean_operation(&whole, operand, operation, options) {
2376                    Ok(solid) => solid,
2377                    Err(_) => return Err(error),
2378                };
2379            }
2380            Ok(whole)
2381        }
2382        other => other,
2383    }
2384}
2385
2386/// `BREP_NARY_SEQUENTIAL_FALLBACK` (default on; `=0` refuses as before): an n-ary boolean whose single
2387/// arrangement fails to assemble is answered by the binary boolean applied
2388/// operand by operand, and refuses as before only if that fails too. A disc
2389/// less a counterbore, a hole and a countersink whose tops lie on the
2390/// counterbore's floor (three faces on one plane, the countersink's rim
2391/// crossing the counterbore wall's foot) left an open loop as one arrangement
2392/// and builds cut by cut.
2393/// The operands one n-ary arrangement takes.
2394const NARY_MOST: usize = 255;
2395
2396/// The operands a fold takes a chunk at a time: `NARY_MOST` (a test may set
2397/// fewer on its thread).
2398fn nary_chunk() -> usize {
2399    NARY_MOST
2400}
2401
2402
2403/// `BREP_NARY_CHUNKS` (on unless =0): an n-ary boolean of more operands than
2404/// one arrangement takes is folded a chunk at a time instead of refused.
2405fn nary_chunks_on() -> bool {
2406    crate::switch!("BREP_NARY_CHUNKS", true)
2407}
2408
2409fn nary_sequential_fallback_enabled() -> bool {
2410    crate::switch!("BREP_NARY_SEQUENTIAL_FALLBACK", true)
2411}
2412
2413fn boolean_operation_nary_arranged(
2414    operands: &[BrepSolid],
2415    operation: BooleanOperation,
2416    options: &BooleanOptions,
2417) -> Result<BrepSolid, KernelRefusal> {
2418    if operands.len() > 1 {
2419        if let Some(scaled) = WorkingScale::of(&operands.iter().collect::<Vec<_>>(), options)? {
2420            return scaled.run(
2421                || boolean_operation_nary_with_options(operands, operation, options),
2422                || boolean_operation_nary_with_options(&scaled.solids, operation, &scaled.options)
2423                    .map_err(|error| scaled.refusal(error))
2424                    .and_then(|solid| scaled.back(&solid)),
2425            );
2426        }
2427    }
2428    if operands.is_empty() {
2429        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: no operands provided"));
2430    }
2431    if operands.len() == 1 {
2432        return Ok(operands[0].clone());
2433    }
2434    if operands.len() > nary_chunk() {
2435        return Err(KernelRefusal::input(KernelStage::Collect, "operands", "boolean_operation_nary: at most 255 operands supported"));
2436    }
2437    // Each whole ball turned onto the one line the others cut it about
2438    // (`ball_align`); the turned set runs once more and is then left as it is.
2439    if let Some(aligned) = ball_align::align_balls_nary(operands, operation, options.tolerance) {
2440        return boolean_operation_nary_with_options(&aligned, operation, options);
2441    }
2442    let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
2443
2444    // One tolerance policy for the whole set: the largest-scale operand's policy
2445    // dominates (every derived band is monotonic in scale), matching how the
2446    // binary path takes `for_pair` = max of the two scales.
2447    let mut policy = KernelTolerances::for_solid(&operands[0], options.tolerance);
2448    for operand in &operands[1..] {
2449        let candidate = KernelTolerances::for_solid(operand, options.tolerance);
2450        if candidate.sew_search > policy.sew_search {
2451            policy = candidate;
2452        }
2453    }
2454    policy.check().or_input(KernelStage::Collect, "tolerances")?;
2455    let tolerance = policy.model;
2456
2457    // Per-operand fuse-first healing, exactly as the binary path (a no-op on
2458    // clean input, so clean operands are untouched).
2459    let mut healed = operands.to_vec();
2460    for operand in &mut healed {
2461        crate::heal::heal_operands(operand, &policy)?;
2462        // Then refit any inherited trim off the pcurve construction contract
2463        // whose edge lies on every carrier (a no-op without one).
2464        crate::heal::refit_inherited_trims_reused(operand, &policy)?;
2465        // Same operand normalization as the binary path: seam edges for
2466        // seamless full-period band faces.
2467        normalize_operand_band_seams(operand)?;
2468    }
2469
2470    // 1. Imprint every pair into one global imprint.
2471    let mut imprint_options = options.imprint.clone();
2472    imprint_options.tolerance = tolerance;
2473    let imprint = build_nary_imprint(&healed, &imprint_options)?;
2474
2475    // 2. Split every operand's edges, then fragment its faces, by that imprint.
2476    let mut split = Vec::with_capacity(healed.len());
2477    for (index, operand) in healed.iter().enumerate() {
2478        split.push(apply_edge_splits(operand, index as u8, &imprint)?);
2479    }
2480    let mut fragments = Vec::with_capacity(split.len());
2481    for (index, solid) in split.iter().enumerate() {
2482        fragments.push(fragment_solid(solid, index as u8, &imprint)?);
2483    }
2484
2485    // 3. Select fragments in one pass against the set of other operands.
2486    let selected = select_fragments_nary(&fragments, &healed, operation, tolerance, debug)?;
2487
2488    // 4. Assemble + normalize + validate, mirroring the binary tail.
2489    let solids: HashMap<u8, &BrepSolid> = split
2490        .iter()
2491        .enumerate()
2492        .map(|(index, solid)| (index as u8, solid))
2493        .collect();
2494    let solid = assemble_fragments(selected, &solids, &imprint, tolerance)?;
2495    let solid = if options.merge_coplanar_faces
2496        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
2497    {
2498        let merged = merge_same_surface_faces_excluding(
2499            &solid,
2500            tolerance,
2501            &options.keep_unmerged_name_substrs,
2502        )?;
2503        let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
2504        rejoin::rejoin_unless_referenced(merged, options, tolerance)
2505    } else {
2506        solid
2507    };
2508    let validation = solid.validate_detailed(&policy);
2509    if !validation.issues.is_empty() {
2510        return Err(KernelRefusal::new(
2511            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
2512            KernelStage::Validate,
2513            format!(
2514            "boolean_operation_nary: invalid result: {:?}",
2515            validation.issues
2516        )));
2517    }
2518    if debug {
2519        if let Ok(report) =
2520            crate::oracle::boolean_semantic_disagreement_nary(&healed, operation, &solid, 300)
2521        {
2522            if report.is_flagged() {
2523                eprintln!(
2524                    "[oracle] n-ary semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
2525                    report.disagreement_rate,
2526                    report.disagreements.len(),
2527                    report.considered,
2528                    report.sample_disagreement()
2529                );
2530            }
2531        }
2532    }
2533    Ok(solid)
2534}
2535
2536/// TANGENT-NODE ATTRIBUTION.
2537///
2538/// The imprint's second-order filter decides which tangential contacts are
2539/// isolated NODES the arrangement can carve, and marches those instead of
2540/// refusing. It cannot decide a THIRD-order singularity — where the transverse
2541/// branch is tangent to a contact curve, every second-order quantity vanishes
2542/// together and the contact reads as a clean saddle at every stopping rule
2543/// (`imprint/tangent_contact.rs`). The assembly is the authority on whether an
2544/// admitted node was really imprintable, so a tear downstream of one is
2545/// reported AGAINST THE NODE rather than as an anonymous degeneracy: same
2546/// refusal class the whole tangent-node family carries, naming the point.
2547///
2548/// Only classes that are ALREADY perturbation-eligible are re-attributed, so a
2549/// refusal that could never take the ladder still cannot. The stage's own
2550/// message — the one-use edges, the genus — is NOT carried into the refusal:
2551/// `tangent_node_assembly` and `torus_torus_singular_refusal` hold the
2552/// tangent-node refusal to naming its cause without the arrangement's
2553/// symptom text ("open between", "genus", "pcurve"), the policy the class
2554/// exists for. It is printed under `BREP_DEBUG_BOOL` instead, so what the
2555/// assembly actually read is still there for a reader of the trace.
2556///
2557/// It does decide WHICH refusals are retried, though, and since 2026-09-13 that
2558/// matters: `boolean_operation`'s failure arm gates `TangentNodeSingularity` out
2559/// of the perturbation ladder (the TANGENT-NODE GATE there) and reads the class
2560/// AFTER this rewrite. So a tear downstream of an ADMITTED node — whatever class
2561/// the pipeline actually raised — declines the ladder along with the tangent-node
2562/// family proper. That is the conservative direction and the same claim the class
2563/// makes (a tear after a node is the node proving unimprintable). Anything added
2564/// to this rewrite widens that gate: read the gate when you touch the
2565/// attribution.
2566fn attribute_to_tangent_node(error: KernelRefusal, nodes: &[Vec3]) -> KernelRefusal {
2567    let Some(node) = nodes.first() else {
2568        return error;
2569    };
2570    if !error.class.perturbation_eligible()
2571        || matches!(error.class, RefusalClass::TangentNodeSingularity)
2572    {
2573        return error;
2574    }
2575    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
2576        eprintln!(
2577            "boolean: tear downstream of the tangent node at ({:.6},{:.6},{:.6}) attributed to it; the stage read: {}",
2578            node.x, node.y, node.z, error.message
2579        );
2580    }
2581    KernelRefusal::new(
2582        RefusalClass::TangentNodeSingularity,
2583        error.stage,
2584        format!(
2585            "boolean: unsupported singular/tangent-node surface intersection \
2586             at the tangent node at ({:.6},{:.6},{:.6}): the section through it did not \
2587             assemble into a closed shell",
2588            node.x, node.y, node.z
2589        ),
2590    )
2591}
2592
2593/// The tangent-curve lane's attribution: an ASSEMBLY refusal whose faces the
2594/// imprint found touching along a CURVE is reported against that contact, by
2595/// its faces and its ends, in the tangent-node class — the arrangement's own
2596/// message (an open loop, a one-use edge) is the symptom, the contact is the
2597/// cause, and the class keeps the refusal out of the perturbation ladder
2598/// exactly as an admitted node's tear is kept out
2599/// (`attribute_to_tangent_node`). The original message is carried along so
2600/// nothing the stage said is hidden.
2601///
2602/// REACH: the faces the refusal names, and only those. `origins` maps the
2603/// assembled result's face ids (minted one per selected fragment, from 1, in
2604/// order) back to operand faces; the ids are read off the message's
2605/// `face <id>` (validate's open-loop issues) and `on faces [<id> '…`
2606/// (one-use edges) entries, and the rewrite happens only when one of them is
2607/// a face the section INVOLVES (`TangentSectionRecord::faces`: the carriers'
2608/// faces and the faces across the edges its ends lie on). A refusal naming no
2609/// face, or only faces the contact does not touch — a model with a benign
2610/// recorded contact (a blind pocket touching a wall) that fails elsewhere —
2611/// keeps its class and enters the ladder as it always did. With
2612/// `ImprintOptions::tangent_curve_lane` off the sections are empty and
2613/// nothing is rewritten.
2614pub fn attribute_to_tangent_section(
2615    error: KernelRefusal,
2616    sections: &[crate::imprint::TangentSectionRecord],
2617    origins: &[FaceKey],
2618) -> KernelRefusal {
2619    if sections.is_empty()
2620        || !error.class.perturbation_eligible()
2621        || matches!(error.class, RefusalClass::TangentNodeSingularity)
2622    {
2623        return error;
2624    }
2625    let named = refusal_result_faces(&error.message)
2626        .into_iter()
2627        .filter_map(|id| origins.get(id.checked_sub(1)? as usize).copied())
2628        .collect::<Vec<FaceKey>>();
2629    // A record the lane's own sites minted before one the grazing-pierce
2630    // path minted (`TangentSectionRecord::grazing`): the sprocket slit star's
2631    // cutter names its traced contact, not the pierce of a neighbouring pair.
2632    let involving = |fallback: bool| {
2633        sections.iter().find(|section| {
2634            section.grazing.is_empty() != fallback && named.iter().any(|face| section.faces.contains(face))
2635        })
2636    };
2637    let Some(section) = involving(false).or_else(|| involving(true)) else {
2638        return error;
2639    };
2640    // A clipped end sits on a trim at round-off, and `-0.000000` names no
2641    // place: print what six decimals can show.
2642    let at = |point: Vec3| {
2643        let shown = |value: f64| if value.abs() < 5e-7 { 0.0 } else { value };
2644        format!("({:.6},{:.6},{:.6})", shown(point.x), shown(point.y), shown(point.z))
2645    };
2646    // The grazing pierces (`imprint/driver.rs`, 2026-10-17): trim edges that
2647    // pierce the other carrier inside both trims below the seed gate while
2648    // the pair marched nothing. A record the lane built stands on its contact
2649    // and carries them as a note; a record standing on the pierces ALONE
2650    // (its `start` IS the first pierce) is named by them.
2651    let pierces = (!section.grazing.is_empty()).then(|| {
2652        let shown = section.grazing.len().min(4);
2653        let mut listed = section.grazing[..shown]
2654            .iter()
2655            .map(|(point, tangency)| format!("{} at |tan·n| = {tangency:.4}", at(*point)))
2656            .collect::<Vec<_>>()
2657            .join(", ");
2658        if section.grazing.len() > shown {
2659            listed.push_str(&format!(" and {} more", section.grazing.len() - shown));
2660        }
2661        listed
2662    });
2663    let pierce_only = section.pierce_only();
2664    let shape = if let (true, Some(pierces)) = (pierce_only, pierces.as_deref()) {
2665        format!(
2666            "cross at a grazing angle: a trim edge pierces the other carrier inside both \
2667             trims at {pierces}, below the marcher's start gate, and no transverse section was \
2668             marched between the pierces — a near-tangent crossing born on a tangent contact \
2669             (a third-order singularity) the imprint does not build yet"
2670        )
2671    } else if section.planar {
2672        format!(
2673            "touch along a tangent curve from {} to {} (length {:.6}, {} stations{}) which the \
2674             imprint does not build yet",
2675            at(section.start),
2676            at(section.end),
2677            section.length,
2678            section.stations,
2679            if section.closed { ", closed" } else { "" }
2680        )
2681    } else {
2682        format!(
2683            "touch along a curve through {} with neither carrier planar, a curved/curved \
2684             tangent contact the lane does not trace yet",
2685            at(section.start)
2686        )
2687    };
2688    let shape = match (pierce_only, pierces) {
2689        (false, Some(pierces)) => format!(
2690            "{shape}; a trim edge also pierces the other carrier inside both trims at {pierces}, \
2691             below the marcher's start gate, with no transverse section marched"
2692        ),
2693        _ => shape,
2694    };
2695    let involved = named
2696        .iter()
2697        .filter(|face| section.faces.contains(face))
2698        .map(|face| format!("{}/{}", face.operand, face.face_id))
2699        .collect::<Vec<_>>()
2700        .join(", ");
2701    KernelRefusal::new(
2702        RefusalClass::TangentNodeSingularity,
2703        error.stage,
2704        format!(
2705            "boolean: unsupported tangent-curve surface intersection between faces {}/{} and {}/{}: \
2706             the carriers {shape}; the refusal names face(s) {involved} the contact involves; {}",
2707            section.first.operand, section.first.face_id, section.second.operand, section.second.face_id,
2708            error.message
2709        ),
2710    )
2711}
2712
2713/// The RESULT face ids an assembly refusal names: every `face <id>` (the
2714/// validator's "loop … of face `<id>` is open …") and every `<id> '` entry of an
2715/// `on faces [...]` list (the one-use edge census). Nothing else in the
2716/// message is read.
2717pub fn refusal_result_faces(message: &str) -> Vec<u64> {
2718    let mut ids = Vec::new();
2719    let digits_after = |text: &str| -> Option<u64> {
2720        let end = text.find(|c: char| !c.is_ascii_digit()).unwrap_or(text.len());
2721        text[..end].parse().ok()
2722    };
2723    for (index, _) in message.match_indices("face ") {
2724        if let Some(id) = digits_after(&message[index + "face ".len()..]) {
2725            ids.push(id);
2726        }
2727    }
2728    if let Some(start) = message.find("on faces [") {
2729        let rest = &message[start + "on faces [".len()..];
2730        let list = &rest[..rest.find(']').unwrap_or(rest.len())];
2731        for entry in list.split(", ") {
2732            let entry = entry.trim_start();
2733            if let Some(id) = digits_after(entry) {
2734                if entry[id.to_string().len()..].starts_with(" '") {
2735                    ids.push(id);
2736                }
2737            }
2738        }
2739    }
2740    ids.sort_unstable();
2741    ids.dedup();
2742    ids
2743}
2744
2745pub fn boolean_operation_with_diagnostics(
2746    first: &BrepSolid,
2747    second: &BrepSolid,
2748    operation: BooleanOperation,
2749    options: &BooleanOptions,
2750) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2751    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
2752        return scaled.run(
2753            || boolean_operation_with_diagnostics(first, second, operation, options),
2754            || {
2755                let mut outcome = boolean_operation_with_diagnostics(&scaled.solids[0], &scaled.solids[1], operation, &scaled.options)
2756                    .map_err(|error| scaled.refusal(error))?;
2757                outcome.value = scaled.back(&outcome.value)?;
2758                outcome.diagnostics.count_n("working_scale.fired", 1);
2759                outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
2760                Ok(outcome)
2761            },
2762        );
2763    }
2764    let _account = profile::Scope::new("boolean.other");
2765    // A whole ball turned onto the line the other operand cuts it about
2766    // (`ball_align`): its sections become latitudes.
2767    let (first_aligned, second_aligned) = ball_align::align_balls(first, second, operation, options.tolerance);
2768    let (first, second) = (first_aligned.as_ref(), second_aligned.as_ref());
2769    let closed_inputs = matches!(std::env::var("BREP_CLOSED_OPERAND_INPUT").as_deref(), Err(_) | Ok("1") | Ok("on"));
2770    if let (true, Some(later)) = (reseat::seam_reseat_enabled(), &options.seam_reseat_later_references) {
2771        let started = Instant::now();
2772        let (first, second) = reseat::reseat_tangent_seams(first, second, later, options.tolerance);
2773        profile_stage("seam_prepare_ms", started.elapsed().as_secs_f64() * 1000.0);
2774        return boolean_operation_with_diagnostics_impl(&first, &second, operation, options, closed_inputs).map(without_sliver_shells);
2775    }
2776    // CYLINDER CONTACTS (`reseat::seam_reseat_cylinders_mode`): with no later
2777    // references stated, only the cylinder-against-cylinder re-seat runs.
2778    let cylinders = reseat::seam_reseat_cylinders_mode();
2779    if reseat::seam_reseat_enabled() && cylinders != crate::env_read::Mode::Off {
2780        let kinds = reseat::ContactKinds { planes: false, cylinders: true };
2781        let volume = |result: &Result<KernelOutcome<BrepSolid>, KernelRefusal>| {
2782            result.as_ref().ok().and_then(|outcome| crate::solid_mass_properties(&outcome.value).ok()).map(|mass| mass.volume)
2783        };
2784        if reseat::seam_reseat_retry_enabled() {
2785            // RETRY: the operands as given first; the re-seated ones (with the
2786            // tangent-cylinder cosurface exchange) only when that refuses, so a
2787            // body built without a re-seat stays the operand of the next cut as
2788            // it would be without the switch. `check` reports what the retry
2789            // would give and returns the first attempt.
2790            let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2791            if plain.is_ok() {
2792                return plain;
2793            }
2794            let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2795            let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2796            if !moved {
2797                return plain;
2798            }
2799            let reseated = crate::imprint::driver::with_tangent_cylinder_filter(|| {
2800                boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells)
2801            });
2802            if cylinders == crate::env_read::Mode::Check {
2803                eprintln!(
2804                    "boolean.seam_reseat_cylinders check: plain refused, reseated retry {} volume {:?}",
2805                    if reseated.is_ok() { "built" } else { "refused" },
2806                    volume(&reseated)
2807                );
2808                return plain;
2809            }
2810            return match reseated {
2811                Ok(mut outcome) => {
2812                    outcome.diagnostics.count_n("seam_reseat_cylinders.retry_built", 1);
2813                    Ok(outcome)
2814                }
2815                Err(_) => plain,
2816            };
2817        }
2818        let (reseated_first, reseated_second) = reseat::reseat_tangent_seams_of(first, second, &[], options.tolerance, kinds);
2819        let moved = matches!(reseated_first, std::borrow::Cow::Owned(_)) || matches!(reseated_second, std::borrow::Cow::Owned(_));
2820        if moved {
2821            let reseated = boolean_operation_with_diagnostics_impl(&reseated_first, &reseated_second, operation, options, closed_inputs).map(without_sliver_shells);
2822            if cylinders == crate::env_read::Mode::On {
2823                return reseated;
2824            }
2825            let plain = boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells);
2826            eprintln!(
2827                "boolean.seam_reseat_cylinders check: plain {} volume {:?}, reseated {} volume {:?}",
2828                if plain.is_ok() { "built" } else { "refused" },
2829                volume(&plain),
2830                if reseated.is_ok() { "built" } else { "refused" },
2831                volume(&reseated)
2832            );
2833            return plain;
2834        }
2835    }
2836    boolean_operation_with_diagnostics_impl(first, second, operation, options, closed_inputs).map(without_sliver_shells)
2837}
2838
2839/// [`drop_sliver_shells`] on a boolean's outcome, counted in its diagnostics.
2840fn without_sliver_shells(mut outcome: KernelOutcome<BrepSolid>) -> KernelOutcome<BrepSolid> {
2841    let dropped = drop_sliver_shells(&mut outcome.value);
2842    if dropped > 0 {
2843        outcome.diagnostics.count_n("sliver_shell.dropped", dropped as u64);
2844    }
2845    outcome
2846}
2847
2848pub fn boolean_operation_with_diagnostics_impl(
2849    first: &BrepSolid,
2850    second: &BrepSolid,
2851    operation: BooleanOperation,
2852    options: &BooleanOptions,
2853    closed_inputs: bool,
2854) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2855    // One coedge-check memo per operation: the
2856    // assembly, face-merge and closing validations re-read coedges unchanged.
2857    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
2858    // Plan 1.6: only a declared Sheet enters the trim path. The unchanged
2859    // Solid path continues below; no kind is inferred from failed closure.
2860    if matches!(operation, BooleanOperation::Intersect)
2861        && [first, second].iter().any(|body| body.kind == crate::BodyKind::Sheet)
2862        && match std::env::var("BREP_SHEET_TRIM").as_deref() {
2863            Ok("1") => true,
2864            Ok("0") => false,
2865            _ => options.sheet_trim,
2866        }
2867    {
2868        return sheet::trim(first, second, options);
2869    }
2870    // OPERAND-KIND GATE. A body that DECLARES itself a Sheet has no
2871    // inside, so a union or subtract with it has no solid answer; the
2872    // survey (record 2026-10-12, table 2) measured the arrangement
2873    // returning a validating solid of volume 3.5 when the sheet's opening
2874    // lay outside the other operand. Read from the declaration only,
2875    // before any arrangement work (nothing infers a kind from the edge
2876    // census; an undeclared open body is the closure gate's below).
2877    // Intersect is not gated here.
2878    if matches!(operation, BooleanOperation::Union | BooleanOperation::Subtract) {
2879        if let Some(operand) = [first, second]
2880            .iter()
2881            .position(|solid| solid.kind == crate::BodyKind::Sheet)
2882        {
2883            return Err(KernelRefusal::input(
2884                KernelStage::Collect,
2885                "sheet_operand",
2886                format!(
2887                    "boolean: operand {operand} is a Sheet, which encloses no solid; union and \
2888                     subtract of a sheet are refused; Intersect trims a Sheet by a Solid"
2889                ),
2890            ));
2891        }
2892    }
2893    // Inside/outside is undefined for an open operand, even if its opening
2894    // misses the other operand and the constructed result happens to validate.
2895    // Count existing edge uses, without modifying/healing either operand.
2896    // Keep failures on their original path and preserve their class/evidence;
2897    // the existing perturbation gate already diagnoses open failed operands.
2898    let mut outcome = boolean_operation_with_diagnostics_core(first, second, operation, options)?;
2899    let closure_started = closed_inputs.then(Instant::now);
2900    if closed_inputs {
2901        for (operand, solid) in [first, second].into_iter().enumerate() {
2902            let open = one_use_edges(solid);
2903            if open > 0 {
2904                return Err(KernelRefusal::input(KernelStage::Collect, "operand_closure", format!(
2905                    "boolean: operand {operand} is not a closed shell: {open} of its edges bound only one face, so its inside is undefined"
2906                )));
2907            }
2908        }
2909    }
2910    if let Some(started) = closure_started {
2911        let ms = started.elapsed().as_secs_f64() * 1000.0;
2912        profile_stage("operand_closure_ms", ms);
2913        outcome.diagnostics.measure_max("timing.operand_closure_ms", ms);
2914    }
2915    Ok(outcome)
2916}
2917
2918fn boolean_operation_with_diagnostics_core(
2919    first: &BrepSolid, second: &BrepSolid, operation: BooleanOperation, options: &BooleanOptions,
2920) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2921
2922    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
2923    // the outermost entry runs the operation on translated operands.
2924    if let Some(offset) = crate::recentre::control_offset_at_entry() {
2925        return boolean_operation_with_diagnostics_at_offset(first, second, operation, options, offset);
2926    }
2927    // The recentre guard: operands far from the origin in their own
2928    // units run at the origin.
2929    let mut bounds = operand_bounds(first);
2930    bounds.include(operand_bounds(second));
2931    if let Some(offset) = crate::recentre::guard_offset(bounds) {
2932        crate::recentre::profile_fired("boolean", offset, bounds);
2933        let mut outcome = boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Guard)?;
2934        outcome.diagnostics.count_n("recentre.fired", 1);
2935        outcome.diagnostics.measure_max("recentre.distance", offset.length());
2936        return Ok(outcome);
2937    }
2938    let mut tangent_nodes = Vec::new();
2939    let (mut outcome, soundness_candidates) =
2940        boolean_pipeline(first, second, operation, options, &mut tangent_nodes)
2941            .map_err(|error| attribute_to_tangent_node(error, &tangent_nodes))?;
2942    // The assembly's single exit. A boolean can hand back a body whose walls
2943    // pass through each other while `validate()` is silent and the volume
2944    // measures right, which is exactly the failure a regularized boolean must
2945    // not report as success. A crossing the OPERANDS already had is theirs and
2946    // passes through — the defect came in with the input and refusing it here
2947    // would blame the wrong operation — so the operands are only scanned when
2948    // the result is flagged, and the common case pays for one scan. The
2949    // acceptance's refusal is typed at its origin (an `UnsoundResult` naming
2950    // the defect and the faces); it was classed `Internal` here while
2951    // `accept_sound_against` still returned text. Timed as its own stage: the
2952    // record's phase split read only the pipeline's `timing.*` measures, and
2953    // on a 108-face disjoint union this scan was 185 of 226 ms end to end.
2954    let stage_started = Instant::now();
2955    let accepted = match &soundness_candidates {
2956        // Pass-through: the faces the operation touched, their
2957        // neighbours and every face whose box reaches the other operand.
2958        Some(candidates) => crate::accept_sound_against_scoped(&[first, second], outcome.value, "boolean", candidates),
2959        None => crate::accept_sound_against(&[first, second], outcome.value, "boolean"),
2960    };
2961    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
2962    profile_stage("soundness_ms", stage_ms);
2963    outcome.diagnostics.measure_max("timing.soundness_ms", stage_ms);
2964    outcome.value = accepted?;
2965    Ok(outcome)
2966}
2967
2968/// [`boolean_operation_with_diagnostics`] with both operands translated by
2969/// `offset` for the operation and the result translated back. Refusal
2970/// messages name the translated coordinates.
2971pub fn boolean_operation_with_diagnostics_at_offset(
2972    first: &BrepSolid,
2973    second: &BrepSolid,
2974    operation: BooleanOperation,
2975    options: &BooleanOptions,
2976    offset: Vec3,
2977) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2978    boolean_translated(first, second, operation, options, offset, crate::recentre::EntryKind::Control)
2979}
2980
2981/// The translated run behind the control and the guard.
2982fn boolean_translated(
2983    first: &BrepSolid,
2984    second: &BrepSolid,
2985    operation: BooleanOperation,
2986    options: &BooleanOptions,
2987    offset: Vec3,
2988    kind: crate::recentre::EntryKind,
2989) -> Result<KernelOutcome<BrepSolid>, KernelRefusal> {
2990    let _entry = crate::recentre::TranslatedEntry::open(kind);
2991    let translate = |solid: &BrepSolid, offset: Vec3| {
2992        crate::recentre::translate_solid(solid, offset).map_err(|message| {
2993            KernelRefusal::internal(
2994                KernelStage::Collect,
2995                "translation_control",
2996                format!("boolean: the translation control could not move an operand: {message}"),
2997            )
2998        })
2999    };
3000    let moved_first = translate(first, offset)?;
3001    let moved_second = translate(second, offset)?;
3002    let outcome = boolean_operation_with_diagnostics(&moved_first, &moved_second, operation, options)?;
3003    let value = translate(&outcome.value, offset.scale(-1.0))?;
3004    Ok(KernelOutcome { value, diagnostics: outcome.diagnostics })
3005}
3006
3007/// Stage wall-clock line on stderr when `BREP_PROFILE` is set — the same switch
3008/// `imprint.profile` and `assemble.*_ms` use — so a REFUSED boolean, whose
3009/// `KernelDiagnostics` never reach a caller, still shows where its time went.
3010fn profile_stage(code: &str, ms: f64) {
3011    let row = match code {
3012        "heal_ms" => Some("boolean.operand_prepare"),
3013        "imprint_ms" => Some("boolean.imprint"),
3014        "edge_split_ms" => Some("boolean.edge_split"),
3015        "fragment_ms" => Some("boolean.fragment"),
3016        "select_ms" => Some("boolean.select"),
3017        "assemble_ms" => Some("boolean.assemble"),
3018        "face_merge_ms" => Some("boolean.face_merge"),
3019        "soundness_ms" => Some("boolean.soundness"),
3020        "operand_closure_ms" => Some("boolean.operand_closure"),
3021        "seam_prepare_ms" => Some("boolean.seam_prepare"),
3022        "final_validate_ms" => Some("boolean.final_validate"),
3023        _ => None,
3024    };
3025    if let Some(row) = row { profile::record(row, ms); }
3026    if crate::profile::profile_enabled() {
3027        profile_line!("boolean.{code}={ms:.2}");
3028    }
3029}
3030
3031/// `BREP_BOOLEAN_DUMP` names a directory. Every binary boolean then writes its
3032/// stages there as JSON — the two split operands, the selected fragments, the
3033/// assembled solid and the merged one — numbered per process, so a probe can
3034/// read a face's loops at each stage without replaying the document.
3035struct BooleanStageDump {
3036    directory: std::path::PathBuf,
3037    serial: usize,
3038}
3039
3040impl BooleanStageDump {
3041    fn open() -> Option<Self> {
3042        static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
3043        let directory = std::env::var("BREP_BOOLEAN_DUMP").ok().filter(|value| !value.is_empty())?;
3044        let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3045        Some(Self { directory: directory.into(), serial })
3046    }
3047
3048    fn write<T: Serialize + ?Sized>(&self, stage: &str, value: &T) {
3049        let path = self.directory.join(format!("{:03}-{stage}.json", self.serial));
3050        match serde_json::to_string(value) {
3051            Ok(text) => {
3052                if let Err(error) = std::fs::write(&path, text) {
3053                    eprintln!("BREP_BOOLEAN_DUMP {}: {error}", path.display());
3054                }
3055            }
3056            Err(error) => eprintln!("BREP_BOOLEAN_DUMP {stage}: {error}"),
3057        }
3058    }
3059}
3060
3061/// The tolerance policy a binary boolean of `first` and `second` runs under.
3062pub fn boolean_policy(
3063    first: &BrepSolid,
3064    second: &BrepSolid,
3065    options: &BooleanOptions,
3066) -> Result<KernelTolerances, KernelRefusal> {
3067    let policy = options
3068        .tolerances
3069        .unwrap_or_else(|| KernelTolerances::for_pair(first, second, options.tolerance));
3070    policy.check().or_input(KernelStage::Collect, "tolerances")?;
3071    Ok(policy)
3072}
3073
3074/// The operands as the imprint reads them: healed, with their band seams
3075/// normalized.
3076fn prepared_operands(
3077    first: &BrepSolid,
3078    second: &BrepSolid,
3079    policy: &KernelTolerances,
3080) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3081    // Fuse-first operand healing (Lever A): before any intersection touches the
3082    // operands, snap each one's near-coincident / off-plane vertices to exact
3083    // and re-anchor the incident edge curves onto them, so noisy
3084    // near-degenerate input (points that should coincide but drifted, vertices
3085    // a few microns off a planar face) cannot tip a fixed downstream band over
3086    // the edge.  Healing is per-operand, validate-gated, and — because a clean
3087    // operand has no vertices within `heal_tol` and none off its planes — a
3088    // no-op that leaves the boolean output byte-identical on clean inputs.
3089    let stage_started = Instant::now();
3090    let mut first_owned = first.clone();
3091    let mut second_owned = second.clone();
3092    crate::heal::heal_operands(&mut first_owned, policy)?;
3093    crate::heal::heal_operands(&mut second_owned, policy)?;
3094    profile_stage("heal.operands_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3095    // Then refit, on each operand's own carriers, any inherited trim off the
3096    // pcurve construction contract whose edge lies on every incident carrier
3097    // (`heal::refit_inherited_trims`; a byte-identical no-op without one).
3098    let refit_started = Instant::now();
3099    crate::heal::refit_inherited_trims_reused(&mut first_owned, policy)?;
3100    crate::heal::refit_inherited_trims_reused(&mut second_owned, policy)?;
3101    profile_stage("heal.refit_ms", refit_started.elapsed().as_secs_f64() * 1_000.0);
3102    if crate::profile::profile_enabled() {
3103        let (hits, misses) = crate::reading_memo::counts();
3104        profile_line!("boolean.reading_memo hits={hits} misses={misses}");
3105        let (served, stored) = crate::heal::refit_memo_counts_served_stored();
3106        profile_line!("boolean.refit_memo served={served} stored={stored}");
3107        let (served, stored, mismatches) = crate::heal::claim_record_memo_counts();
3108        profile_line!("boolean.claim_record_memo served={served} stored={stored} check_mismatches={mismatches}");
3109    }
3110    profile_stage("heal_ms", stage_started.elapsed().as_secs_f64() * 1_000.0);
3111    // Seamless full-period band faces (STEP import) break the seam-aware
3112    // imprint/arrangement machinery; normalize them to the seam-carrying
3113    // topology native periodic faces use. No-op on operands without such
3114    // faces. See `insert_periodic_band_seam_edges`.
3115    normalize_operand_band_seams(&mut first_owned)?;
3116    normalize_operand_band_seams(&mut second_owned)?;
3117    Ok((first_owned, second_owned))
3118}
3119
3120fn boolean_imprint_options(options: &BooleanOptions, tolerance: f64) -> ImprintOptions {
3121    let mut imprint_options = options.imprint.clone();
3122    imprint_options.tolerance = tolerance;
3123    imprint_options
3124}
3125
3126/// The two operands a binary boolean's arrangement reads: prepared as the
3127/// boolean prepares them, with every boundary edge split where the imprint's
3128/// sections meet it. These are the `NNN-first` and `NNN-second` stages
3129/// `BREP_BOOLEAN_DUMP` writes, not the operands at the boolean's entry.
3130///
3131/// A boolean must read the same on these as on the operands it split them
3132/// from: the splits are vertices its own imprint puts on those edges anyway.
3133/// Where it does not, an imprint lane is deciding on what the input happens to
3134/// have split, and that is a defect.
3135pub fn boolean_split_operands(
3136    first: &BrepSolid,
3137    second: &BrepSolid,
3138    options: &BooleanOptions,
3139) -> Result<(BrepSolid, BrepSolid), KernelRefusal> {
3140    if let Some(scaled) = WorkingScale::of(&[first, second], options)? {
3141        return scaled.run(
3142            || boolean_split_operands(first, second, options),
3143            || {
3144                let (split_first, split_second) = boolean_split_operands(&scaled.solids[0], &scaled.solids[1], &scaled.options)
3145                    .map_err(|error| scaled.refusal(error))?;
3146                Ok((scaled.back(&split_first)?, scaled.back(&split_second)?))
3147            },
3148        );
3149    }
3150    let policy = boolean_policy(first, second, options)?;
3151    let (first, second) = prepared_operands(first, second, &policy)?;
3152    let imprint = build_imprints(&first, &second, &boolean_imprint_options(options, policy.model))?;
3153    let (split_first, _) = apply_edge_splits_with_map(&first, 0, &imprint)?;
3154    let (split_second, _) = apply_edge_splits_with_map(&second, 1, &imprint)?;
3155    Ok((split_first, split_second))
3156}
3157
3158/// Conservative bounds of an operand: its vertices and every face's control
3159/// net (a NURBS lies in the hull of its controls). A control net that cannot
3160/// be read bounds everything, so nothing is left out for want of a reading.
3161fn operand_bounds(solid: &BrepSolid) -> crate::Aabb {
3162    let mut bounds = crate::Aabb::from_points(solid.vertices.iter().map(|vertex| vertex.point));
3163    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3164        match crate::Aabb::from_surface_controls(&face.surface) {
3165            Ok(face_bounds) => bounds.include(face_bounds),
3166            Err(_) => {
3167                return crate::Aabb {
3168                    minimum: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY),
3169                    maximum: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY),
3170                }
3171            }
3172        }
3173    }
3174    bounds
3175}
3176
3177/// Row 12's gate: the boxes are separated or touch exactly in at least two
3178/// axes. A trimmed face lies in its carrier's control-net box when every
3179/// weight is positive, so a point interior to both operands would lie
3180/// strictly inside both boxes in every axis; two such axes leave a line or a
3181/// point of contact, which has no area to merge.
3182fn line_or_point_contact(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3183    apart_axes(bounds) >= 2 && plain_hull_solid(first) && plain_hull_solid(second)
3184}
3185
3186/// One apart axis: no point can be interior to both operands (see
3187/// [`line_or_point_contact`]), though the boxes may share a face's area.
3188fn boxes_share_no_interior(first: &BrepSolid, second: &BrepSolid, bounds: [crate::Aabb; 2]) -> bool {
3189    apart_axes(bounds) >= 1 && plain_hull_solid(first) && plain_hull_solid(second)
3190}
3191
3192/// The axes in which the boxes are separated or touch exactly (no band).
3193fn apart_axes([a, b]: [crate::Aabb; 2]) -> usize {
3194    let apart = |a_min: f64, a_max: f64, b_min: f64, b_max: f64| a_max <= b_min || b_max <= a_min;
3195    [
3196        apart(a.minimum.x, a.maximum.x, b.minimum.x, b.maximum.x),
3197        apart(a.minimum.y, a.maximum.y, b.minimum.y, b.maximum.y),
3198        apart(a.minimum.z, a.maximum.z, b.minimum.z, b.maximum.z),
3199    ]
3200    .into_iter()
3201    .filter(|&apart| apart)
3202    .count()
3203}
3204
3205/// A plain solid whose faces lie in their control-net boxes: every weight positive.
3206fn plain_hull_solid(solid: &BrepSolid) -> bool {
3207    solid.kind == crate::BodyKind::Solid
3208        && solid.cells.is_empty()
3209        && solid.shells.iter().flat_map(|shell| &shell.faces).all(|face| {
3210            face.surface.control_points.iter().flatten().all(|control| control.w > 0.0 && control.w.is_finite())
3211        })
3212}
3213
3214/// `BREP_SCOPE_PROVED_APART` (default on since the 2026-11-19 promotion;
3215/// `=0` scans every face whose box reaches the other operand): see
3216/// [`soundness_candidates`].
3217fn scope_proved_apart_on() -> bool {
3218    switch!(live "BREP_SCOPE_PROVED_APART", true)
3219}
3220
3221/// The result faces the soundness scan reads under pass-through: the
3222/// examined faces (touched and their neighbours) and every other face whose
3223/// control-net box reaches the OTHER operand's bounds within `band`. A face
3224/// outside both is an operand's own, clear of everything the operation added.
3225///
3226/// PROVED APART (`BREP_SCOPE_PROVED_APART`): with `unproved` (the imprint's
3227/// [`crate::ImprintResultRecord::faces_in_unproved_pairs`]) and both operands
3228/// plain hull solids, a face whose box reaches the other operand is still
3229/// left out when the imprint PROVED it clear of every face of the other
3230/// operand (its box met none, or each pair it met was classified `Disjoint`
3231/// or proved apart by span hulls). A pair the imprint skipped, marched to
3232/// nothing, or could not prove keeps the face in. A whole-body scan of a body
3233/// nested inside the other operand's box (a closed hollow: the source less
3234/// its inward offset, untouched) read every face of both for that alone.
3235fn soundness_candidates(
3236    solid: &BrepSolid,
3237    scope: &AssemblyScope,
3238    bounds: [crate::Aabb; 2],
3239    band: f64,
3240    unproved: Option<&HashSet<crate::imprint::FaceKey>>,
3241) -> HashSet<u64> {
3242    let mut candidates = HashSet::default();
3243    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
3244        if scope.examined.contains(&face.id) {
3245            candidates.insert(face.id);
3246            continue;
3247        }
3248        let Some(&operand) = scope.operand_of.get(&face.id) else {
3249            candidates.insert(face.id);
3250            continue;
3251        };
3252        let other = bounds[usize::from(operand == 0)];
3253        match crate::Aabb::from_surface_controls(&face.surface) {
3254            Ok(face_bounds) if !face_bounds.intersects(other, band) => {}
3255            _ => {
3256                let proved_clear = unproved.is_some_and(|unproved| {
3257                    scope.source_of.get(&face.id).is_some_and(|key| !unproved.contains(key))
3258                });
3259                if !proved_clear {
3260                    candidates.insert(face.id);
3261                }
3262            }
3263        }
3264    }
3265    candidates
3266}
3267
3268
3269/// `BREP_TOUCHING_EMPTY` (default on; =0 refuses as before): an intersection
3270/// or difference of operands that only touch, which selects no fragment,
3271/// returns the empty solid on the sample witnesses and an inclusion-exclusion
3272/// volume of zero (`boolean_pipeline`). brep-conformance's touching families
3273/// (boxes face to face, flush pockets, contact along a line) refused with
3274/// "operation produced no boundary faces" where the regularized result is
3275/// empty.
3276fn touching_empty_enabled() -> bool {
3277    switch!("BREP_TOUCHING_EMPTY", true)
3278}
3279
3280thread_local! {
3281    /// Set while a touching-empty proof reads another boolean of its pair, so
3282    /// that reading cannot itself be rescued as empty.
3283    static TOUCHING_PROOF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3284}
3285
3286/// Whether a cylinder face of `first` and one of `second`, or a ball of each,
3287/// reach into each other by more than `tolerance`: the closed-form depth of
3288/// their lens (radii against the closest distance of the axes, at any angle,
3289/// or of the centres; outer or nested), counted only where the two faces'
3290/// boxes overlap by more than `tolerance` along every axis (two cylinders
3291/// meeting end to end through their caps do not count).
3292fn hair_deep_overlap(first: &BrepSolid, second: &BrepSolid, tolerance: f64) -> bool {
3293    use crate::AnalyticSurface as A;
3294    fn faces(solid: &BrepSolid) -> Vec<(&crate::AnalyticSurface, crate::spatial::Aabb, &crate::NurbsSurface, &crate::FaceRecord)> {
3295        solid
3296            .shells
3297            .iter()
3298            .flat_map(|shell| &shell.faces)
3299            .filter_map(|face| Some((face.surface.analytic()?, crate::Aabb::from_surface_controls(&face.surface).ok()?, &face.surface, face)))
3300            .collect()
3301    }
3302    // A face's extent along `axis`: its control points' (the hull holds it).
3303    let along = |surface: &crate::NurbsSurface, axis: Vec3| {
3304        surface.control_points.iter().flatten().filter_map(|control| control.point().ok()).fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
3305            let at = point.dot(axis);
3306            (low.min(at), high.max(at))
3307        })
3308    };
3309    let crossing = |distance: f64, ra: f64, rb: f64| {
3310        let outer = ra + rb - distance;
3311        let nested = distance - (ra - rb).abs();
3312        outer > tolerance && nested > tolerance
3313    };
3314    let boxes_overlap = |a: &crate::spatial::Aabb, b: &crate::spatial::Aabb| {
3315        (a.maximum.x.min(b.maximum.x) - a.minimum.x.max(b.minimum.x)) > tolerance
3316            && (a.maximum.y.min(b.maximum.y) - a.minimum.y.max(b.minimum.y)) > tolerance
3317            && (a.maximum.z.min(b.maximum.z) - a.minimum.z.max(b.minimum.z)) > tolerance
3318    };
3319    for (a, box_a, surface_a, face_a) in faces(first) {
3320        for (b, box_b, surface_b, face_b) in faces(second) {
3321            if !boxes_overlap(&box_a, &box_b) {
3322                continue;
3323            }
3324            match (a, b) {
3325                (A::RuledRevolution { frame: fa, rho0: a0, rho1: a1, .. }, A::RuledRevolution { frame: fb, rho0: b0, rho1: b1, .. })
3326                    if (a0 - a1).abs() <= tolerance && (b0 - b1).abs() <= tolerance =>
3327                {
3328                    let offset = fb.origin.sub(fa.origin);
3329                    let normal = fa.axis.cross(fb.axis);
3330                    // Parallel walls meet only where their extents along the
3331                    // axis overlap (two cylinders end to end touch at a cap).
3332                    if normal.length() <= 1e-12 {
3333                        let (low_a, high_a) = along(surface_a, fa.axis);
3334                        let (low_b, high_b) = along(surface_b, fa.axis);
3335                        if high_a.min(high_b) - low_a.max(low_b) <= tolerance {
3336                            continue;
3337                        }
3338                    }
3339                    let apart = if normal.length() <= 1e-12 {
3340                        offset.sub(fa.axis.scale(offset.dot(fa.axis))).length()
3341                    } else {
3342                        offset.dot(normal).abs() / normal.length()
3343                    };
3344                    if crossing(apart, a0.abs(), b0.abs()) {
3345                        return true;
3346                    }
3347                }
3348                (A::Sphere { frame: fa, radius: ra }, A::Sphere { frame: fb, radius: rb }) => {
3349                    // The two balls' lens meets the faces only along the
3350                    // circle where the spheres cross; a face that circle is
3351                    // proven off (a part of a cavity the circle passes
3352                    // beside) holds no lens, however deep the carriers' is.
3353                    if crossing(fb.origin.sub(fa.origin).length(), *ra, *rb)
3354                        && !circle_off_face(face_a, first, (fa.origin, *ra), (fb.origin, *rb), tolerance)
3355                        && !circle_off_face(face_b, second, (fb.origin, *rb), (fa.origin, *ra), tolerance)
3356                    {
3357                        return true;
3358                    }
3359                }
3360                _ => {}
3361            }
3362        }
3363    }
3364    false
3365}
3366
3367/// Whether the circle where the sphere `own` (centre, radius), carrying
3368/// `face`, crosses the sphere `other` is proven to lie off `face`: every edge
3369/// of the face stands clear of `other` by more than `tolerance` (its control
3370/// hull, halved where it does not decide, wholly inside or wholly outside),
3371/// so the circle, which lies on `other`, never meets the face's boundary and
3372/// is wholly on the face or wholly off it; and one point of it is outside the
3373/// face's trim. A face with no trim, or anything unproven, is not off.
3374fn circle_off_face(face: &crate::FaceRecord, solid: &BrepSolid, own: (Vec3, f64), other: (Vec3, f64), tolerance: f64) -> bool {
3375    use crate::classification::{parameter_point_in_face, PolygonClass};
3376    let ((ca, ra), (cb, rb)) = (own, other);
3377    if face.loops.iter().all(|lp| lp.coedges.is_empty()) {
3378        return false;
3379    }
3380    // A curve's points on [t0, t1] all inside or all outside the other ball:
3381    // its control points (positive weights: the hull holds the curve) all
3382    // within `rb - tolerance` of the centre, or their box farther than
3383    // `rb + tolerance` from it; otherwise each half, a few times over.
3384    fn clear(curve: &crate::NurbsCurve, depth: u32, centre: Vec3, radius: f64, tolerance: f64) -> bool {
3385        let points: Option<Vec<Vec3>> = curve.control_points.iter().map(|control| if control.w > 0.0 { control.point().ok() } else { None }).collect();
3386        let Some(points) = points else { return false };
3387        if points.iter().all(|point| point.sub(centre).length() < radius - tolerance) {
3388            return true;
3389        }
3390        let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
3391        for point in &points {
3392            low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
3393            high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
3394        }
3395        let near = Vec3::new(centre.x.clamp(low.x, high.x), centre.y.clamp(low.y, high.y), centre.z.clamp(low.z, high.z));
3396        if near.sub(centre).length() > radius + tolerance {
3397            return true;
3398        }
3399        if depth == 0 {
3400            return false;
3401        }
3402        let Ok([t0, t1]) = curve.domain() else { return false };
3403        match curve.split(0.5 * (t0 + t1)) {
3404            Ok((left, right)) => clear(&left, depth - 1, centre, radius, tolerance) && clear(&right, depth - 1, centre, radius, tolerance),
3405            Err(_) => false,
3406        }
3407    }
3408    for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
3409        let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false };
3410        let Ok([d0, d1]) = edge.curve.domain() else { return false };
3411        // The edge's own span of its curve.
3412        let mut span = edge.curve.clone();
3413        if edge.t1 < d1 {
3414            match span.split(edge.t1) {
3415                Ok((left, _)) => span = left,
3416                Err(_) => return false,
3417            }
3418        }
3419        if edge.t0 > d0 {
3420            match span.split(edge.t0) {
3421                Ok((_, right)) => span = right,
3422                Err(_) => return false,
3423            }
3424        }
3425        if !clear(&span, 10, cb, rb, tolerance) {
3426            return false;
3427        }
3428    }
3429    let axis = cb.sub(ca);
3430    let distance = axis.length();
3431    let Ok(n) = axis.normalized() else { return false };
3432    let along = (distance * distance + ra * ra - rb * rb) / (2.0 * distance);
3433    let across = ra * ra - along * along;
3434    let Ok(side) = n.perpendicular() else { return false };
3435    if !(across > 0.0) {
3436        return false;
3437    }
3438    let point = ca.add(n.scale(along)).add(side.scale(across.sqrt()));
3439    let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false };
3440    matches!(parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9), Ok(PolygonClass::Outside))
3441}
3442
3443
3444/// The empty solid a legitimately empty boolean returns.
3445fn empty_solid() -> BrepSolid {
3446    BrepSolid {
3447        mass_properties_cache: Default::default(),
3448        cells: Default::default(),
3449        id: 0,
3450        vertices: Vec::new(),
3451        edges: Vec::new(),
3452        shells: Vec::new(),
3453        genus: 0,
3454        kind: crate::BodyKind::Solid,
3455    }
3456}
3457
3458/// The two operands as one solid, shell by shell: ids minted afresh in the
3459/// assembler's order (the first operand's faces, then the second's), the
3460/// second operand's face names suffixed where they clash with the first's
3461/// as the assembler suffixes a split face, geometry copied byte for byte,
3462/// genus the sum. Nothing is welded: the operands are disjoint.
3463fn concatenate_disjoint(first: &BrepSolid, second: &BrepSolid) -> BrepSolid {
3464    let mut vertices = Vec::new();
3465    let mut edges = Vec::new();
3466    let mut shells = Vec::new();
3467    let mut used_face_names = HashSet::<String>::default();
3468    let (mut next_face_id, mut next_loop_id, mut next_coedge_id) = (1u64, 1u64, 1u64);
3469    for operand in [first, second] {
3470        let vertex_base = vertices.len() as u64;
3471        let edge_base = edges.len() as u64;
3472        let mut vertex_ids: HashMap<u64, u64> = HashMap::default();
3473        for (index, vertex) in operand.vertices.iter().enumerate() {
3474            let id = vertex_base + index as u64 + 1;
3475            vertex_ids.insert(vertex.id, id);
3476            vertices.push(VertexRecord { id, point: vertex.point });
3477        }
3478        let mut edge_ids: HashMap<u64, u64> = HashMap::default();
3479        for (index, edge) in operand.edges.iter().enumerate() {
3480            let id = edge_base + index as u64 + 1;
3481            edge_ids.insert(edge.id, id);
3482            edges.push(EdgeRecord {
3483                id,
3484                curve: edge.curve.clone(),
3485                t0: edge.t0,
3486                t1: edge.t1,
3487                start_vertex_id: vertex_ids.get(&edge.start_vertex_id).copied().unwrap_or(edge.start_vertex_id),
3488                end_vertex_id: vertex_ids.get(&edge.end_vertex_id).copied().unwrap_or(edge.end_vertex_id),
3489                degenerate: edge.degenerate,
3490                name: edge.name.clone(),
3491            });
3492        }
3493        for shell in &operand.shells {
3494            let mut faces = Vec::with_capacity(shell.faces.len());
3495            for face in &shell.faces {
3496                let loops = face
3497                    .loops
3498                    .iter()
3499                    .map(|loop_record| {
3500                        let coedges = loop_record
3501                            .coedges
3502                            .iter()
3503                            .map(|coedge| {
3504                                let id = next_coedge_id;
3505                                next_coedge_id += 1;
3506                                CoedgeRecord {
3507                                    id,
3508                                    edge_id: edge_ids.get(&coedge.edge_id).copied().unwrap_or(coedge.edge_id),
3509                                    forward: coedge.forward,
3510                                    pcurve: coedge.pcurve.clone(),
3511                                }
3512                            })
3513                            .collect();
3514                        let id = next_loop_id;
3515                        next_loop_id += 1;
3516                        LoopRecord { id, coedges }
3517                    })
3518                    .collect();
3519                let name = face.name.clone().map(|base| {
3520                    if used_face_names.insert(base.clone()) {
3521                        base
3522                    } else {
3523                        let mut suffix = 1usize;
3524                        loop {
3525                            let candidate = format!("{base}_{suffix}");
3526                            if used_face_names.insert(candidate.clone()) {
3527                                break candidate;
3528                            }
3529                            suffix += 1;
3530                        }
3531                    }
3532                });
3533                faces.push(FaceRecord {
3534                    id: next_face_id,
3535                    surface: face.surface.clone(),
3536                    same_sense: face.same_sense,
3537                    loops,
3538                    name,
3539                });
3540                next_face_id += 1;
3541            }
3542            shells.push(ShellRecord { id: shells.len() as u64 + 1, faces });
3543        }
3544    }
3545    BrepSolid {
3546        mass_properties_cache: Default::default(),
3547        cells: Default::default(),
3548        id: 1,
3549        vertices,
3550        edges,
3551        shells,
3552        genus: first.genus + second.genus,
3553        kind: crate::BodyKind::Solid,
3554    }
3555}
3556
3557/// The binary boolean. The second value is the soundness scan's candidate
3558/// faces under pass-through (`None` reads the whole result).
3559fn boolean_pipeline(
3560    first: &BrepSolid,
3561    second: &BrepSolid,
3562    operation: BooleanOperation,
3563    options: &BooleanOptions,
3564    tangent_nodes: &mut Vec<Vec3>,
3565) -> Result<(KernelOutcome<BrepSolid>, Option<HashSet<u64>>), KernelRefusal> {
3566    let _work = crate::imprint::work_profile::Scope::open("boolean");
3567    let replaced_operands = operand_state::replace_operands(first, second, operation, options);
3568    let (first, second) = match &replaced_operands {
3569        Some((first, second)) => (first, second),
3570        None => (first, second),
3571    };
3572    let policy = boolean_policy(first, second, options)?;
3573    let tolerance = policy.model;
3574    // DISJOINT FAST PATH. A box test on the control-net hulls, not "no
3575    // section evidence": a tool inside the other operand also leaves no
3576    // evidence and must stay on the pipeline, where a union is the outer
3577    // operand, a subtract the outer with a void shell and an intersect the
3578    // tool. Operands clear of each other by more than the search band can
3579    // touch nothing, so nothing is prepared, imprinted, assembled or
3580    // scanned: a union is the two operands side by side, a subtract the
3581    // first operand, an intersect the legitimate-empty result below. The
3582    // soundness scan is skipped as well (an empty candidate set): the
3583    // operands cannot cross each other, and a crossing an operand carried in
3584    // passes through the full acceptance unrepaired exactly the same.
3585    //
3586    // CONTACT FAST PATH (row 12): boxes that only meet along a line or at a
3587    // point, read exactly; see `line_or_point_contact`.
3588    let bounds = [operand_bounds(first), operand_bounds(second)];
3589    let disjoint = disjoint_fast_path(options) && !bounds[0].intersects(bounds[1], policy.sew_search);
3590    let contact = !disjoint
3591        && contact_fast_path(options)
3592        && options.seam_reseat_later_references.is_some()
3593        && line_or_point_contact(first, second, bounds);
3594    // One apart axis already leaves no common interior, so an intersect is
3595    // empty even where the boxes share a face's area (which is why a union or
3596    // a subtract stays on the pipeline). Nothing survives to carry an id, so
3597    // no caller has to say what follows.
3598    let contact = contact
3599        || (!disjoint
3600            && matches!(operation, BooleanOperation::Intersect)
3601            && contact_fast_path(options)
3602            && boxes_share_no_interior(first, second, bounds));
3603    if disjoint || contact {
3604        let operation_started = Instant::now();
3605        let mut diagnostics = KernelDiagnostics::default();
3606        diagnostics.count_n(
3607            "collect.faces",
3608            first.shells.iter().chain(&second.shells).map(|shell| shell.faces.len() as u64).sum(),
3609        );
3610        diagnostics.count(if contact { "boolean.contact_fast_path" } else { "boolean.disjoint_fast_path" });
3611        diagnostics.measure_max("tolerance.model", policy.model);
3612        diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3613        let value = match operation {
3614            BooleanOperation::Union => concatenate_disjoint(first, second),
3615            BooleanOperation::Subtract => first.clone(),
3616            BooleanOperation::Intersect => {
3617                diagnostics.event(
3618                    DiagnosticSeverity::Info,
3619                    KernelStage::Select,
3620                    "boolean.empty_result",
3621                    format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3622                );
3623                empty_solid()
3624            }
3625        };
3626        let stage_ms = operation_started.elapsed().as_secs_f64() * 1_000.0;
3627        profile_stage("disjoint_fast_path_ms", stage_ms);
3628        diagnostics.measure_max("timing.total_ms", stage_ms);
3629        return Ok((KernelOutcome { value, diagnostics }, Some(HashSet::default())));
3630    }
3631    let heal_started = Instant::now();
3632    let (first_owned, second_owned) = prepared_operands(first, second, &policy)?;
3633    let heal_ms = heal_started.elapsed().as_secs_f64() * 1_000.0;
3634    let first = &first_owned;
3635    let second = &second_owned;
3636
3637    let mut diagnostics = KernelDiagnostics::default();
3638    // Operand preparation ran before `timing.total_ms` opens and was absent
3639    // from every phase split; it is 1.6 of a disjoint box union's 7.2 ms.
3640    diagnostics.measure_max("timing.heal_ms", heal_ms);
3641    // Every pcurve fit made while this scope is open — the imprint's sections,
3642    // the assembler's rebuilt trims, the merge's re-fits — is tallied, so the
3643    // outcome can say whether every curved trim reached its floor instead of
3644    // letting a sample-ceiling exit pass for a met one (`pcurve.unmet_floor`).
3645    let fit_scope = crate::PcurveFitScope::open();
3646    // And every POLYLINE fit: a marched section's interpolant is measured
3647    // against the tolerance it was given, so `fit.polyline.unmet_tolerance`
3648    // reports a section that could not reach it (`geometry/fit.rs`).
3649    let polyline_scope = crate::PolylineFitScope::open();
3650    let operation_started = Instant::now();
3651    diagnostics.count_n(
3652        "collect.faces",
3653        first
3654            .shells
3655            .iter()
3656            .chain(&second.shells)
3657            .map(|shell| shell.faces.len() as u64)
3658            .sum(),
3659    );
3660    diagnostics.measure_max("tolerance.model", policy.model);
3661    diagnostics.measure_max("tolerance.sew_search", policy.sew_search);
3662
3663    let imprint_options = boolean_imprint_options(options, tolerance);
3664    let stage_started = Instant::now();
3665    let imprint = build_imprints(first, second, &imprint_options)?;
3666    tangent_nodes.extend_from_slice(&imprint.tangent_nodes);
3667    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
3668        for piece in &imprint.pieces {
3669            let start = piece.curve.evaluate(piece.t0);
3670            let end = piece.curve.evaluate(piece.t1);
3671            eprintln!(
3672                "piece {} supports={:?} t=[{:.6},{:.6}] start={:?} end={:?}",
3673                piece.id, piece.support_faces, piece.t0, piece.t1, start, end
3674            );
3675        }
3676        for entry in &imprint.by_face {
3677            eprintln!(
3678                "by_face operand={} face={} pieces={:?}",
3679                entry.operand, entry.face_id, entry.piece_ids
3680            );
3681        }
3682        for split in &imprint.edge_splits {
3683            eprintln!(
3684                "edge_split operand={} edge={} params={:?}",
3685                split.operand, split.edge_id, split.parameters
3686            );
3687        }
3688    }
3689    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3690    profile_stage("imprint_ms", stage_ms);
3691    diagnostics.measure_max("timing.imprint_ms", stage_ms);
3692    diagnostics.count_n("intersect.pieces", imprint.pieces.len() as u64);
3693    diagnostics.count_n("intersect.vertices", imprint.vertices.len() as u64);
3694    diagnostics.count_n("intersect.edge_splits", imprint.edge_splits.len() as u64);
3695    let (march_swap_rescues, clip_swap_rescues) = crate::imprint::take_rescue_firings();
3696    diagnostics.count_n("intersect.march_swap_rescue", march_swap_rescues);
3697    diagnostics.count_n("intersect.clip_swap_rescue", clip_swap_rescues);
3698    let touch = TouchCensus::build([first, second], &imprint);
3699    touch.report(&mut diagnostics);
3700    let stage_started = Instant::now();
3701    let (split_first, split_map_first) = apply_edge_splits_with_map(first, 0, &imprint)?;
3702    let (split_second, split_map_second) = apply_edge_splits_with_map(second, 1, &imprint)?;
3703    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3704    profile_stage("edge_split_ms", stage_ms);
3705    diagnostics.measure_max("timing.edge_split_ms", stage_ms);
3706    let stage_started = Instant::now();
3707    crate::classification::classify_profile_begin();
3708    let fragments_a = crate::fragment::fragment_solid_against(&split_first, 0, &imprint, crate::fragment::bounded_carriers(second).then_some((bounds[1], policy.sew_search)))?;
3709    let fragments_b = crate::fragment::fragment_solid_against(&split_second, 1, &imprint, crate::fragment::bounded_carriers(first).then_some((bounds[0], policy.sew_search)))?;
3710    crate::classification::classify_profile_report("fragment");
3711    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3712    profile_stage("fragment_ms", stage_ms);
3713    diagnostics.measure_max("timing.fragment_ms", stage_ms);
3714    diagnostics.count_n(
3715        "fragment.candidates",
3716        (fragments_a.len() + fragments_b.len()) as u64,
3717    );
3718    touch.report_fragments(&[&fragments_a, &fragments_b], &mut diagnostics);
3719    // Operand surface samples for the LEGITIMATE-EMPTY adjudication below:
3720    // every fragment test point is a 3D point ON its operand's boundary and
3721    // inside its face trim, so they witness where the operands' materials sit
3722    // relative to each other without extra geometry work.
3723    let a_surface_samples: Vec<Vec3> = fragments_a
3724        .iter()
3725        .flat_map(|fragment| {
3726            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3727        })
3728        .collect();
3729    let b_surface_samples: Vec<Vec3> = fragments_b
3730        .iter()
3731        .flat_map(|fragment| {
3732            std::iter::once(fragment.test_point).chain(fragment.extra_test_points.iter().copied())
3733        })
3734        .collect();
3735    let stage_started = Instant::now();
3736    let mut barrier_edges: HashSet<(u8, u64)> = imprint
3737        .pieces
3738        .iter()
3739        .filter_map(|piece| piece.shared_edge.map(|(operand, edge_id, _)| (operand, edge_id)))
3740        .collect();
3741    barrier_edges.extend(imprint.barrier_edges.iter().copied());
3742    // The barrier set is keyed on ORIGINAL edge ids, but a barrier edge the
3743    // imprint also SPLIT (rotated equator-tangency: the overlapped cap ring
3744    // gains a junction at the sphere-seam crossing) reaches fragment
3745    // selection as its minted sub-edge ids. Remap the barrier through the
3746    // split ledger — keeping the originals too for unsplit references.
3747    for (operand, split_map) in [(0u8, &split_map_first), (1u8, &split_map_second)] {
3748        let minted: Vec<(u8, u64)> = barrier_edges
3749            .iter()
3750            .filter(|(barrier_operand, _)| *barrier_operand == operand)
3751            .filter_map(|(_, edge_id)| split_map.get(edge_id))
3752            .flat_map(|sub_ids| sub_ids.iter().map(|sub_id| (operand, *sub_id)))
3753            .collect();
3754        barrier_edges.extend(minted);
3755    }
3756    crate::classification::classify_profile_begin();
3757    let coincident = coincident_pairs(
3758        &fragments_a,
3759        &fragments_b,
3760        first,
3761        second,
3762        &imprint.cosurface_pairs,
3763        tolerance,
3764    )?;
3765    let sector_mode = sector::sector_mode(options);
3766    let mut select_census = sector::SelectCensus::default();
3767    let mut selected = select_fragments(
3768        fragments_a,
3769        fragments_b,
3770        first,
3771        second,
3772        operation,
3773        tolerance,
3774        &barrier_edges,
3775        &imprint,
3776        &coincident,
3777        sector_mode,
3778        &mut select_census,
3779    )?;
3780    let resewn = resew_coincident_rims(
3781        &mut selected,
3782        [&split_first, &split_second],
3783        [first, second],
3784        &imprint.cosurface_pairs,
3785        operation,
3786        tolerance,
3787    )?;
3788    diagnostics.count_n("select.coincident_pairs", coincident.len() as u64);
3789    diagnostics.count_n("select.rims_resewn", resewn as u64);
3790    crate::classification::classify_profile_report("select");
3791    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
3792    profile_stage("select_ms", stage_ms);
3793    diagnostics.measure_max("timing.select_ms", stage_ms);
3794    diagnostics.count_n("select.fragments", selected.len() as u64);
3795    // One census line per selection as well.
3796    diagnostics.count_n("select.sector_eligible", select_census.eligible);
3797    diagnostics.count_n("select.sector_primary", select_census.sector_primary);
3798    diagnostics.count_n("select.sector_fallback", select_census.sector_fallback);
3799    diagnostics.count_n("select.sector_disagree", select_census.disagree);
3800    diagnostics.count_n("select.ray_casts", select_census.ray_casts);
3801    diagnostics.count_n("select.on_votes", select_census.on_votes);
3802    diagnostics.count_n("select.overturns", select_census.overturns);
3803    if sector_mode != sector::SectorMode::Off || std::env::var_os("BREP_SECTOR_CENSUS").is_some() {
3804        sector::sector_census_line(|| {
3805            format!(
3806                "selection mode={sector_mode:?} select_ms={stage_ms:.3} selected={} eligible={} primary={} fallback={} disagree={} ray_casts={} on_votes={} overturns={}",
3807                selected.len(),
3808                select_census.eligible,
3809                select_census.sector_primary,
3810                select_census.sector_fallback,
3811                select_census.disagree,
3812                select_census.ray_casts,
3813                select_census.on_votes,
3814                select_census.overturns
3815            )
3816        });
3817    }
3818    // LEGITIMATE-EMPTY RESULTS: an intersect of DISJOINT operands (or a
3819    // subtract whose left operand is entirely CONSUMED by the right) selects
3820    // zero fragments, and assembly used to refuse with "operation produced no
3821    // boundary faces" — 384 of the 474 post-wrapped-band pool errors were
3822    // this, not bugs. Empty is only blessed on TWO independent proofs:
3823    //   (a) the imprint recorded NO section evidence (no accepted pierce
3824    //       seed, no traced SSI branch, no minted piece) — a silently-lost
3825    //       section (the trial-489 class) always leaves upstream evidence
3826    //       even when every downstream sub-segment is clipped away, while
3827    //       pure material disjointness leaves none (verified: 489's
3828    //       recreated silent-miss state keeps erroring; per-face surface
3829    //       samples ALONE missed its 235 mm³ pocket, which is why (a) is
3830    //       required and sampling alone was rejected);
3831    //   (b) the operands' surface samples agree (every fragment test point
3832    //       classified against the other solid):
3833    //       intersect — no sample of either operand strictly inside the
3834    //       other; subtract — no left-operand sample strictly outside the
3835    //       right.
3836    // Contact/graze pairs (evidence exists, material still disjoint) stay
3837    // errors — conservative by design. Escape hatch: BREP_EMPTY_BOOLEAN=0
3838    // restores the unconditional error.
3839    if selected.is_empty()
3840        && !imprint.section_evidence
3841        && std::env::var("BREP_EMPTY_BOOLEAN").as_deref() != Ok("0")
3842    {
3843        let strictly_inside = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3844            for &sample in samples {
3845                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::In {
3846                    return Ok(true);
3847                }
3848            }
3849            Ok(false)
3850        };
3851        let outside_witness = |samples: &[Vec3], other: &BrepSolid| -> Result<bool, KernelRefusal> {
3852            for &sample in samples {
3853                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == PointClass::Out {
3854                    return Ok(true);
3855                }
3856            }
3857            Ok(false)
3858        };
3859        let legitimate = match operation {
3860            BooleanOperation::Intersect => {
3861                !strictly_inside(&a_surface_samples, second)?
3862                    && !strictly_inside(&b_surface_samples, first)?
3863            }
3864            BooleanOperation::Subtract => !outside_witness(&a_surface_samples, second)?,
3865            BooleanOperation::Union => false,
3866        };
3867        if legitimate {
3868            diagnostics.event(
3869                DiagnosticSeverity::Info,
3870                KernelStage::Select,
3871                "boolean.empty_result",
3872                format!("{operation:?} of witnessed-non-overlapping operands is empty"),
3873            );
3874            fit_scope.close().report_into(&mut diagnostics);
3875            polyline_scope.close().report_into(&mut diagnostics);
3876            diagnostics.measure_max(
3877                "timing.total_ms",
3878                operation_started.elapsed().as_secs_f64() * 1_000.0,
3879            );
3880            return Ok((
3881                KernelOutcome {
3882                    value: empty_solid(),
3883                    diagnostics,
3884                },
3885                None,
3886            ));
3887        }
3888    }
3889    // TOUCHING-EMPTY RESULTS (`BREP_TOUCHING_EMPTY`): operands that only
3890    // touch (faces in contact, a flush pocket's tool inside its block) leave
3891    // section evidence, so the legitimate-empty proof above does not apply,
3892    // and the regularized intersection or difference is empty all the same.
3893    // Empty is blessed here on two independent proofs: the same surface-sample
3894    // witnesses as above, and inclusion-exclusion over another exact-lane
3895    // boolean of the same pair, which must put this one's volume at zero to
3896    // a billionth of the larger operand's.
3897    if selected.is_empty()
3898        && imprint.section_evidence
3899        && !matches!(operation, BooleanOperation::Union)
3900        && touching_empty_enabled()
3901        && !TOUCHING_PROOF.with(std::cell::Cell::get)
3902    {
3903        let strict = |samples: &[Vec3], other: &BrepSolid, class: PointClass| -> Result<bool, KernelRefusal> {
3904            for &sample in samples {
3905                if classify_point(sample, other, tolerance).or_refuse(KernelStage::Validate, "classify_point")?.class == class {
3906                    return Ok(true);
3907                }
3908            }
3909            Ok(false)
3910        };
3911        let witnessed = match operation {
3912            BooleanOperation::Intersect => {
3913                !strict(&a_surface_samples, second, PointClass::In)? && !strict(&b_surface_samples, first, PointClass::In)?
3914            }
3915            BooleanOperation::Subtract => !strict(&a_surface_samples, second, PointClass::Out)?,
3916            BooleanOperation::Union => false,
3917        };
3918        // Two cylinders, or two balls, can meet in a lens a hair deep
3919        // (parallel cylinders 1.8e-6 into each other) that the
3920        // imprint misses and every other boolean of the pair also reads as a
3921        // touch. Their depth is closed form; one beyond the model tolerance
3922        // is a real body, which is not empty.
3923        let overlap_free = !hair_deep_overlap(first, second, tolerance);
3924        if witnessed && overlap_free {
3925            TOUCHING_PROOF.with(|flag| flag.set(true));
3926            let proof = inclusion_exclusion_volume(first, second, operation, options, body_volume(first), body_volume(second), false);
3927            TOUCHING_PROOF.with(|flag| flag.set(false));
3928            // Touching operands read zero to rounding (about 1e-13 here); a
3929            // band in model tolerances over the area would also bless a
3930            // genuine overlap by a hair (parallel cylinders a few microns
3931            // deep), so it is a billionth of the larger operand's volume.
3932            let volume = |solid: &BrepSolid| body_volume(solid).unwrap_or(f64::INFINITY);
3933            let band = 1e-9 * volume(first).max(volume(second));
3934            if let Some(proof) = proof.filter(|proof| proof.expected.is_finite() && proof.expected.abs() <= band) {
3935                diagnostics.event(
3936                    DiagnosticSeverity::Info,
3937                    KernelStage::Select,
3938                    "boolean.empty_touching",
3939                    format!(
3940                        "{operation:?} of touching operands is empty: {} reads {:.3e} by {} (band {band:.3e})",
3941                        proof.formula, proof.expected, proof.reading
3942                    ),
3943                );
3944                fit_scope.close().report_into(&mut diagnostics);
3945                polyline_scope.close().report_into(&mut diagnostics);
3946                diagnostics.measure_max("timing.total_ms", operation_started.elapsed().as_secs_f64() * 1_000.0);
3947                return Ok((KernelOutcome { value: empty_solid(), diagnostics }, None));
3948            }
3949        }
3950    }
3951    let solids = [(0, &split_first), (1, &split_second)]
3952        .into_iter()
3953        .collect::<HashMap<_, _>>();
3954    let dump = BooleanStageDump::open();
3955    if let Some(dump) = &dump {
3956        dump.write("first", &split_first);
3957        dump.write("second", &split_second);
3958        dump.write("selected", &selected);
3959    }
3960    let stage_started = Instant::now();
3961    // Result face `k` is minted from `selected[k - 1]` (one face per fragment,
3962    // ids from 1 in order): the map the tangent-section attribution reads a
3963    // refusal's face ids through.
3964    let assembled_origins: Vec<FaceKey> = if imprint.tangent_sections.is_empty() {
3965        Vec::new()
3966    } else {
3967        selected
3968            .iter()
3969            .map(|fragment| FaceKey { operand: fragment.operand, face_id: fragment.source_face_id })
3970            .collect()
3971    };
3972    // A record the grazing-pierce path minted (`TangentSectionRecord::
3973    // grazing` non-empty, whether or not the lane then found a contact to
3974    // name) yields to a tangent NODE the imprint classified: the node is the
3975    // nearer cause and `attribute_to_tangent_node` names it on the way out
3976    // (the G1 elbow over its own-radius arm: the arm's cap circle also
3977    // pierces the elbow under the seed gate, and the lane sees the join).
3978    let attributable: Vec<crate::imprint::TangentSectionRecord> = imprint
3979        .tangent_sections
3980        .iter()
3981        .filter(|section| imprint.tangent_nodes.is_empty() || section.grazing.is_empty())
3982        .cloned()
3983        .collect();
3984    let attribute = |error: KernelRefusal| {
3985        attribute_to_tangent_section(error, &attributable, &assembled_origins)
3986    };
3987    let cellular_result = matches!(operation, BooleanOperation::Union)
3988        && cellular::enabled(options)
3989        && cellular::complete_contact(first, second, &selected, tolerance);
3990    let (solid, scope) = if cellular_result {
3991        (assemble::assemble_cellular_fragments(selected, &solids, &imprint, tolerance)
3992            .map_err(attribute)?, None)
3993    } else if untouched_passthrough(options) {
3994        assemble_fragments_scoped(selected, &solids, &imprint, tolerance, &touch, touched_assembly(options))
3995            .map_err(attribute)?
3996    } else {
3997        (assemble_fragments(selected, &solids, &imprint, tolerance).map_err(attribute)?, None)
3998    };
3999    if let Some(scope) = &scope {
4000        diagnostics.count_n("passthrough.faces_examined", scope.examined.len() as u64);
4001    }
4002    if let Some(dump) = &dump {
4003        dump.write("assembled", &solid);
4004    }
4005    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4006    profile_stage("assemble_ms", stage_ms);
4007    diagnostics.measure_max("timing.assemble_ms", stage_ms);
4008    let stage_started = Instant::now();
4009    let declines_before = crate::face_merge::declines_served();
4010    let area_checks_before = crate::face_merge::boundary_area_checks();
4011    if std::env::var("BREP_DEBUG_PREMERGE_VALIDATE").is_ok() {
4012        let issues = solid.validate();
4013        eprintln!(
4014            "pre-merge validation: {} issue(s){}",
4015            issues.len(),
4016            issues
4017                .first()
4018                .map(|issue| format!(" — first: {}", issue.message))
4019                .unwrap_or_default()
4020        );
4021    }
4022    let solid = if solid.kind != crate::BodyKind::Cellular && options.merge_coplanar_faces
4023        && std::env::var("BREP_COPLANAR_MERGE").as_deref() != Ok("0")
4024    {
4025        let merged = match &scope {
4026            // Every pair merges as before (an operand's own coplanar
4027            // neighbours included); the closing validation reads the
4028            // examined faces and the merged ones.
4029            Some(scope) => merge_same_surface_faces_scoped(
4030                &solid,
4031                tolerance,
4032                &options.keep_unmerged_name_substrs,
4033                &scope.examined,
4034            )?,
4035            None => merge_same_surface_faces_excluding(
4036                &solid,
4037                tolerance,
4038                &options.keep_unmerged_name_substrs,
4039            )?,
4040        };
4041        // Face merging can make previously separate collinear boundary
4042        // segments incident to the same pair of faces. Run continuation
4043        // cleanup again, matching the post-merge normalization performed by
4044        // the former assembly pipeline.
4045        let merged = merge_curve_continuation_edges(&merged, tolerance).map_err(|refusal| KernelRefusal { stage: KernelStage::Validate, ..refusal })?;
4046        rejoin::rejoin_unless_referenced(merged, options, tolerance)
4047    } else {
4048        solid
4049    };
4050    if let Some(dump) = &dump {
4051        dump.write("merged", &solid);
4052    }
4053    let stage_ms = stage_started.elapsed().as_secs_f64() * 1_000.0;
4054    profile_stage("face_merge_ms", stage_ms);
4055    if crate::profile::profile_enabled() {
4056        profile_line!("boolean.merge_declines served={}", crate::face_merge::declines_served() - declines_before);
4057        let area_checks = crate::face_merge::boundary_area_checks();
4058        if area_checks != area_checks_before {
4059            profile_line!("boolean.merge_area_checks boundary={} integrated={}", area_checks.0 - area_checks_before.0, area_checks.1 - area_checks_before.1);
4060        }
4061    }
4062    diagnostics.measure_max("timing.face_merge_ms", stage_ms);
4063    let validation_started = Instant::now();
4064    let validation = solid.validate_detailed_scoped(&policy, scope.as_ref().map(|scope| &scope.examined));
4065    profile_stage("final_validate_ms", validation_started.elapsed().as_secs_f64() * 1000.0);
4066    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4067    diagnostics.count_n(
4068        "validate.wire_warnings",
4069        validation.wire_warnings.len() as u64,
4070    );
4071    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4072    for warning in &validation.wire_warnings {
4073        diagnostics.event(
4074            DiagnosticSeverity::Warning,
4075            KernelStage::Validate,
4076            "validate.uv_wire",
4077            warning.message.clone(),
4078        );
4079    }
4080    for issue in &validation.issues {
4081        diagnostics.event(
4082            DiagnosticSeverity::Error,
4083            KernelStage::Validate,
4084            "validate.brep",
4085            issue.message.clone(),
4086        );
4087    }
4088    fit_scope.close().report_into(&mut diagnostics);
4089    polyline_scope.close().report_into(&mut diagnostics);
4090    diagnostics.measure_max(
4091        "timing.total_ms",
4092        operation_started.elapsed().as_secs_f64() * 1_000.0,
4093    );
4094    if !validation.issues.is_empty() {
4095        return Err(KernelRefusal::new(
4096            RefusalClass::InvalidResultTopology { issues: validation.issues.len() as u32 },
4097            KernelStage::Validate,
4098            format!(
4099            "boolean_operation: invalid result: {:?}",
4100            validation.issues
4101        )));
4102    }
4103    // Optional semantic oracle (off by default, no perf hit): under
4104    // BREP_DEBUG_BOOL, cross-check the well-formed result against the CSG
4105    // point-membership expectation and scan for residual coincident-but-unwelded
4106    // geometry. Purely diagnostic and NON-rejecting — a statistical check must
4107    // never fail a valid op (see oracle.rs) — so it only ever warns.
4108    if std::env::var("BREP_DEBUG_BOOL").is_ok() {
4109        if let Ok(report) =
4110            crate::oracle::boolean_semantic_disagreement(first, second, operation, &solid, 200)
4111        {
4112            if report.is_flagged() {
4113                eprintln!(
4114                    "[oracle] semantic disagreement rate {:.4} ({} of {} decidable points); sample {:?}",
4115                    report.disagreement_rate,
4116                    report.disagreements.len(),
4117                    report.considered,
4118                    report.sample_disagreement()
4119                );
4120            }
4121        }
4122        let fusable_band = crate::tolerance::assembler_weld(policy.model);
4123        let fusables = crate::oracle::boolean_residual_fusables(&solid, fusable_band);
4124        if !fusables.is_empty() {
4125            eprintln!(
4126                "[oracle] {} residual fusable(s) after weld; sample {:?}",
4127                fusables.len(),
4128                fusables.first()
4129            );
4130        }
4131    }
4132    let candidates = scope.as_ref().map(|scope| {
4133        let unproved = (scope_proved_apart_on() && plain_hull_solid(first) && plain_hull_solid(second))
4134            .then(|| imprint.faces_in_unproved_pairs.as_ref())
4135            .flatten()
4136            .map(|faces| faces.iter().copied().collect::<HashSet<_>>());
4137        let candidates = soundness_candidates(
4138            &solid,
4139            scope,
4140            [operand_bounds(first), operand_bounds(second)],
4141            policy.sew_search,
4142            unproved.as_ref(),
4143        );
4144        diagnostics.count_n("passthrough.soundness_candidates", candidates.len() as u64);
4145        crate::soundness::census::profile_operation(&solid, &[first, second], Some(&scope.touched), "boolean");
4146        candidates
4147    });
4148    Ok((
4149        KernelOutcome {
4150            value: solid,
4151            diagnostics,
4152        },
4153        candidates,
4154    ))
4155}
4156
4157