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