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