Skip to main content

brep_boolean/csg/boolean/
mod.rs

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