BREP_boolean 0.31.0

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Feature-scale tolerance: the boolean's identity bands scale with the part,
//! so a feature far thinner than the part's extent is merged away. Under the
//! `BREP_FEATURE_SCALE_*` switches (all default on; `=0` restores each band)
//! a band that would reach across such a feature is capped at [`FRACTION`] of
//! its size.
//!
//! This module measures the pair-derived feature size (`lfs_pair` in the
//! design): two plane faces of the two operands that are almost parallel
//! bound a sliver between them, as thin as their largest separation over
//! the region both patches cover. brep-bench tangent/wedge-a-millionth-steep:
//! the cube's top and the half-space's face 1e-6 steep bound a wedge 5e-6
//! thick at its far end.
use crate::env_read::Mode;

use crate::spatial::Aabb;
pub use crate::{BrepSolid, NurbsSurface, Vec3};

/// `BREP_FEATURE_SCALE_IMPRINT` (default on, `=0` off): the imprint's identity bands
/// (B1″, the edge-split endpoint guard, so far) are capped at the local
/// feature size.
pub fn imprint_enabled() -> bool {
    crate::switch!("BREP_FEATURE_SCALE_IMPRINT", true)
}

/// `BREP_FEATURE_SCALE_SELECT` (default on, `=0` off): selection's coincident-On
/// rescue band (B6) is capped at the local feature size. It acts only with
/// [`imprint_enabled`]: a sliver kept from the rescue but never imprinted is
/// classified whole, and the wedge then built a valid two-face solid of the
/// wrong volume (all lane switches on but `_IMPRINT`, 2026-11-07).
pub fn select_enabled() -> bool {
    crate::switch!("BREP_FEATURE_SCALE_SELECT", true) && imprint_enabled()
}

/// `BREP_FEATURE_SCALE_FRAGMENT` (default on, `=0` off): the fragmenter measures a
/// strip between two cuts as it measures one between a cut and the face's
/// boundary, and resolves the arrangement to it (B4).
pub fn fragment_enabled() -> bool {
    crate::switch!("BREP_FEATURE_SCALE_FRAGMENT", true)
}

/// The fraction of the local feature size a capped band may reach.
pub const FRACTION: f64 = 0.25;

/// Plane pairs whose normals' cross product is below this record a sliver.
const THIN_ANGLE: f64 = 1e-3;

/// A sliver between two almost parallel plane faces: `height` is the largest
/// separation of the two planes over `region`, the box both patches cover.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ThinPair {
    pub height: f64,
    pub region: Aabb,
    /// A slab of one operand's material (two of its faces facing away from
    /// each other), not a gap between the two operands' faces.
    pub same_operand: bool,
    /// `BREP_FEATURE_SCALE_OPERAND_WEDGES`: the two planes (origin, unit
    /// normal) of a TILTED pair, whose thickness runs from zero at the line
    /// where they cross to `height` at the region's far edge. Its cap is a
    /// quarter of the thickness at the point asked about, not of `height`.
    pub planes: Option<[(Vec3, Vec3); 2]>,
}

/// The local feature sizes of one boolean's operands. A cap is linear in the
/// slivers; they are measured only under a switch.
/// The longest band any capped site applies (the fuzzy-junction clamp,
/// 1.5e-3): a sliver whose [`FRACTION`] of its height is longer cannot limit one.
const LONGEST_BAND: f64 = 1.5e-3;

#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct FeatureScale {
    pub thin_pairs: Vec<ThinPair>,
    /// `(first operand's face id, second operand's face id)` of every pair
    /// registered by `BREP_FEATURE_SCALE_OPERAND_SLIVERS`: two surfaces a
    /// resolvable sliver apart, which the imprint must not read as one.
    pub operand_slivers: Vec<(u64, u64)>,
    /// The region of each of those slivers (the box both faces share).
    pub operand_sliver_regions: Vec<Aabb>,
    /// `(first operand's face id, second operand's face id)` of every tilted
    /// pair `BREP_FEATURE_SCALE_OPERAND_WEDGES` registered: only these are
    /// sectioned below the plane-pair section's usual angle floor.
    pub operand_wedges: Vec<(u64, u64)>,
}

impl FeatureScale {
    /// Every sliver between two almost parallel plane faces (normals' cross
    /// product under [`THIN_ANGLE`], exactly parallel included):
    /// - of the two operands: the wedge's top and the half-space's face 1e-6
    ///   steep. Two such planes no farther apart than the imprint's coincidence
    ///   band (`max(10·tolerance, COINCIDENCE_DISTANCE_FLOOR)`, as
    ///   `coplanar_pair` reads it) over the region are one surface, not a
    ///   sliver: mirrored or transformed coplanar faces differ by round-off
    ///   (cross 1e-16, height 1e-15 on the 2026-10-09 mirrored shell history),
    ///   and the coplanar lanes treat them;
    /// - of one operand, facing away from each other: the two walls of a slab
    ///   of material (the hairline saw, 1e-6 thick). A solid's opposite walls
    ///   are never one surface, so these count once apart by more than the
    ///   tolerance.
    ///
    /// Only slivers thin enough to limit a band are kept ([`FRACTION`] of the
    /// height under [`LONGEST_BAND`]). The region is the box the two patches
    /// share; where they do not overlap along an axis (the saw's walls, at
    /// x = 5 and x = 5.000001) it spans the gap between them, when that gap
    /// is within the longest band's reach.
    pub fn between(first_solid: &BrepSolid, second_solid: &BrepSolid, tolerance: f64) -> Result<Self, String> {
        let coincident = (tolerance * 10.0).max(crate::tolerance::COINCIDENCE_DISTANCE_FLOOR);
        let mut planes: Vec<(u8, Vec3, Vec3, Aabb, &crate::FaceRecord)> = Vec::new();
        for (operand, solid) in [(0u8, first_solid), (1u8, second_solid)] {
            for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
                if let Some((origin, normal)) = plane_of(&face.surface)? {
                    planes.push((operand, origin, normal, Aabb::from_surface_controls(&face.surface)?, face));
                }
            }
        }
        let reach = 4.0 * LONGEST_BAND;
        let mut thin_pairs = Vec::new();
        let mut operand_slivers = Vec::new();
        let mut operand_wedges = Vec::new();
        let mut operand_sliver_regions = Vec::new();
        for (i, &(a_operand, a_origin, a_normal, a_box, a_face)) in planes.iter().enumerate() {
            for &(b_operand, b_origin, b_normal, b_box, b_face) in &planes[i + 1..] {
                let same_operand = a_operand == b_operand;
                if same_operand && a_normal.dot(b_normal) >= 0.0 {
                    continue;
                }
                if a_normal.cross(b_normal).length() >= THIN_ANGLE {
                    continue;
                }
                let span = |lo_a: f64, hi_a: f64, lo_b: f64, hi_b: f64| -> Option<(f64, f64)> {
                    let (lo, hi) = (lo_a.max(lo_b), hi_a.min(hi_b));
                    if lo <= hi {
                        Some((lo, hi))
                    } else if lo - hi <= reach {
                        Some((hi, lo))
                    } else {
                        None
                    }
                };
                let (Some(x), Some(y), Some(z)) = (
                    span(a_box.minimum.x, a_box.maximum.x, b_box.minimum.x, b_box.maximum.x),
                    span(a_box.minimum.y, a_box.maximum.y, b_box.minimum.y, b_box.maximum.y),
                    span(a_box.minimum.z, a_box.maximum.z, b_box.minimum.z, b_box.maximum.z),
                ) else {
                    continue;
                };
                let region = Aabb { minimum: Vec3::new(x.0, y.0, z.0), maximum: Vec3::new(x.1, y.1, z.1) };
                // The region's corners, put onto each plane, measured from the
                // other: the largest is the sliver's thickness over the region.
                let mut height = 0.0f64;
                // The smallest corner reading too: a uniform sliver reads the
                // same at every corner, a tilted one does not.
                let mut lowest = f64::INFINITY;
                // The signed reading of the second plane over the first at
                // each corner: a pair that CROSSES inside the region reads
                // both signs (a wedge), a tapered gap one.
                let (mut below, mut above) = (0.0f64, 0.0f64);
                for corner in corners(region) {
                    let signed = corner.sub(a_normal.scale(corner.sub(a_origin).dot(a_normal))).sub(b_origin).dot(b_normal);
                    below = below.min(signed);
                    above = above.max(signed);
                    for (on_origin, on_normal, other_origin, other_normal) in [
                        (a_origin, a_normal, b_origin, b_normal),
                        (b_origin, b_normal, a_origin, a_normal),
                    ] {
                        let on_plane = corner.sub(on_normal.scale(corner.sub(on_origin).dot(on_normal)));
                        let reading = on_plane.sub(other_origin).dot(other_normal).abs();
                        height = height.max(reading);
                        lowest = lowest.min(reading);
                    }
                }
                let floor = if same_operand { tolerance } else { coincident };
                let registered = height > floor
                    && FRACTION * height < LONGEST_BAND
                    && faces_overlap(a_face, b_face, region)?
                    && (same_operand || !crate::imprint::reads_as_one_surface(&a_face.surface, &b_face.surface, tolerance)?);
                // OPERAND SLIVERS (`BREP_FEATURE_SCALE_OPERAND_SLIVERS`, default
                // on, =0 restores; `check` prints the pairs it would add): two operands'
                // parallel planes whose height over their shared region the
                // imprint can resolve (a quarter of it at least the tolerance,
                // and over the model floor, 1e-7) bound a real sliver, even
                // where the surface-pair classifier reads them as one surface.
                // A thinner pair stays one surface (the coincident reading):
                // registered, it would make the whole boolean refuse as a
                // sliver below the section's resolution. The height is exact: it is read at the corners of
                // the region the two patches share, and a plane's distance from
                // another is linear over that box, so its maximum is at a
                // corner. The pair must overlap. Without it, two boxes whose
                // faces stand 1e-5 apart (100 times the model tolerance) read
                // as one surface here, no band is capped, and the imprint's
                // vertex registry (1.2e-5 at tolerance 1e-7) merged the corners
                // of the 1e-5 slab the coincident-pair offset had built between
                // them; its pieces vanished and the boolean was refused.
                // Only a UNIFORM sliver between parallel planes: its thickness
                // the same at every corner of the region to 1e-3 of itself. A
                // tilted pair (a wedge of planes 1e-6 rad apart, coplanar tool
                // walls a few 1e-6 off over their extent) keeps the one-surface
                // reading its fixtures were built on.
                let uniform = height - lowest <= 1e-3 * height;
                let crosses = below < -tolerance && above > tolerance;
                // OPERAND WEDGES (`BREP_FEATURE_SCALE_OPERAND_WEDGES`, default
                // off; `check` prints): a TILTED pair of the two operands that
                // the route above registers (it does not read as one surface)
                // and whose planes CROSS inside the region (the second plane's
                // signed reading over the first takes both signs at its
                // corners: a box against a copy of itself turned a few 1e-6
                // rad about its centre) is a wedge-shaped sliver as thick as
                // `height` at its far edge and of no thickness where the planes
                // cross. Its bands are capped at a quarter of the LOCAL
                // thickness ([`ThinPair::local_cap`]) rather than of the
                // far-edge height, which reached across the crossing line and
                // merged the wedge's corners, and the imprint sections the pair
                // below the plane-pair section's usual angle floor
                // ([`FeatureScale::operand_wedge`]). Pairs that do not register
                // (revolve side-plane copies, coplanar tool walls a few 1e-6
                // off) keep the one-surface reading their fixtures were built on,
                // even where they cross.
                // (Crossing alone: a pair crossing at the middle of its region
                // reads the same height at every corner, as a uniform slab does.)
                let operand_wedge = registered && !same_operand && crosses;
                if operand_wedge && operand_wedges_mode() == Mode::Check {
                    eprintln!(
                        "BREP_FEATURE_SCALE_OPERAND_WEDGES check: faces {}/{} height {height:.3e} signed {below:.3e}..{above:.3e} over {:?}..{:?}",
                        a_face.id, b_face.id, region.minimum, region.maximum
                    );
                }
                let wedge_on = operand_wedge && operand_wedges_mode() == Mode::On;
                let operand_sliver = !registered
                    && !same_operand
                    && uniform
                    && operand_slivers_mode() != Mode::Off
                    && FRACTION * height >= tolerance
                    && height > OPERAND_SLIVER_FLOOR
                    && FRACTION * height < LONGEST_BAND
                    && faces_overlap(a_face, b_face, region)?;
                if operand_sliver && operand_slivers_mode() == Mode::Check {
                    eprintln!(
                        "BREP_FEATURE_SCALE_OPERAND_SLIVERS check: faces {}/{} height {height:.3e} would cap bands at {:.3e} over {:?}..{:?}",
                        a_face.id, b_face.id, FRACTION * height, region.minimum, region.maximum
                    );
                }
                if operand_sliver && operand_slivers_mode() == Mode::On {
                    // The planes are gathered operand 0 first, so `a` is the
                    // first operand's face.
                    operand_slivers.push((a_face.id, b_face.id));
                    operand_sliver_regions.push(region);
                }
                if registered || (operand_sliver && operand_slivers_mode() == Mode::On) {
                    if env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
                        eprintln!(
                            "feature_scale: sliver faces {}/{} height={height:.3e} same_operand={same_operand} region={:?}..{:?}",
                            a_face.id, b_face.id, region.minimum, region.maximum
                        );
                    }
                    let planes = wedge_on.then_some([(a_origin, a_normal), (b_origin, b_normal)]);
                    if wedge_on {
                        operand_wedges.push((a_face.id, b_face.id));
                    }
                    thin_pairs.push(ThinPair { height, region, same_operand, planes });
                }
            }
        }
        Ok(Self { thin_pairs, operand_slivers, operand_sliver_regions, operand_wedges })
    }

    /// Whether the first operand's face `first` and the second's `second`
    /// stand a resolvable sliver apart (`BREP_FEATURE_SCALE_OPERAND_SLIVERS`).
    pub fn operand_sliver(&self, first: u64, second: u64) -> bool {
        self.operand_slivers.contains(&(first, second))
    }

    /// Whether the pair (first operand's face, second operand's face) is a
    /// registered operand wedge.
    pub fn operand_wedge(&self, first: u64, second: u64) -> bool {
        self.operand_wedges.contains(&(first, second))
    }

    /// Whether any feature limits a band (no work at the cap sites when not).
    pub fn is_empty(&self) -> bool {
        self.thin_pairs.is_empty()
    }

    /// `uncapped`, capped at [`FRACTION`] of every sliver whose region lies
    /// within `uncapped` of `point` (a band that cannot reach a sliver is not
    /// limited by it).
    pub fn cap(&self, point: Vec3, uncapped: f64) -> f64 {
        self.thin_pairs
            .iter()
            .filter(|pair| pair.region.expanded(uncapped).contains(point))
            .fold(uncapped, |cap, pair| cap.min(pair.local_cap(point)))
    }

    /// [`Self::cap`] by the slabs of one operand's material alone. The
    /// residual merge (B3) takes its cap from these: its identity-proof band
    /// (2·weld·extent, 2e-4 on a 10-unit part) is wider than many a gap
    /// between two operands' near-coplanar faces (1.8e-4 on the revolve pole
    /// fixtures), whose near-tangent junctions it exists to merge, while the
    /// hairline saw's walls are one operand's slab.
    pub fn cap_by_slabs(&self, point: Vec3, uncapped: f64) -> f64 {
        self.thin_pairs
            .iter()
            .filter(|pair| pair.same_operand && pair.region.expanded(uncapped).contains(point))
            .fold(uncapped, |cap, pair| cap.min(FRACTION * pair.height))
    }

    /// `(region, cap)` for every sliver, for the solid classifier's
    /// coincident-On band.
    pub fn regions(&self) -> Vec<(Aabb, f64)> {
        self.thin_pairs.iter().map(|pair| (pair.region, FRACTION * pair.height)).collect()
    }

    /// The thinnest sliver, for the resolution floor.
    pub fn thinnest(&self) -> Option<f64> {
        self.thin_pairs.iter().map(|pair| pair.height).min_by(f64::total_cmp)
    }
}

/// Whether the two faces' trimmed material covers a common area of
/// `region`: some point of a 3×3×3 grid over it, projected onto each face's
/// carrier, lies inside that face's trim. Carrier boxes alone overlap for
/// faces that only stand side by side: fixture `10_regression_step269_cone`
/// carries faces 5e-6 apart in z over different areas (a step, not a slab
/// of material), and treating them as a sliver blocked its near-tangent
/// residual merges.
fn faces_overlap(first: &crate::FaceRecord, second: &crate::FaceRecord, region: Aabb) -> Result<bool, String> {
    use crate::classification::{parameter_point_in_face, PolygonClass};
    let inside = |face: &crate::FaceRecord, point: Vec3| -> Result<bool, String> {
        let projection = crate::project_point_to_surface(&face.surface, point)?;
        Ok(matches!(
            parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, 1e-9)?,
            PolygonClass::Inside
        ))
    };
    let (lo, hi) = (region.minimum, region.maximum);
    for fx in [0.1, 0.5, 0.9] {
        for fy in [0.1, 0.5, 0.9] {
            for fz in [0.1, 0.5, 0.9] {
                let point = Vec3::new(lo.x + (hi.x - lo.x) * fx, lo.y + (hi.y - lo.y) * fy, lo.z + (hi.z - lo.z) * fz);
                if inside(first, point)? && inside(second, point)? {
                    return Ok(true);
                }
            }
        }
    }
    Ok(false)
}

/// An affine carrier's plane: a point on it and its unit normal.
pub fn plane_of(surface: &NurbsSurface) -> Result<Option<(Vec3, Vec3)>, String> {
    if !surface.is_affine()? {
        return Ok(None);
    }
    let [u0, u1] = surface.domain_u()?;
    let [v0, v1] = surface.domain_v()?;
    let (u, v) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
    Ok(Some((surface.evaluate(u, v)?, surface.normal(u, v)?)))
}

fn corners(region: Aabb) -> [Vec3; 8] {
    let (lo, hi) = (region.minimum, region.maximum);
    [
        Vec3::new(lo.x, lo.y, lo.z),
        Vec3::new(hi.x, lo.y, lo.z),
        Vec3::new(lo.x, hi.y, lo.z),
        Vec3::new(hi.x, hi.y, lo.z),
        Vec3::new(lo.x, lo.y, hi.z),
        Vec3::new(hi.x, lo.y, hi.z),
        Vec3::new(lo.x, hi.y, hi.z),
        Vec3::new(hi.x, hi.y, hi.z),
    ]
}

impl ThinPair {
    /// The cap at `point`: a quarter of the height, or for a wedge a quarter of
    /// its thickness there (the larger distance from the point to either plane,
    /// at most the height), never under the model floor.
    pub fn local_cap(&self, point: Vec3) -> f64 {
        match self.planes {
            None => FRACTION * self.height,
            Some([(a_origin, a_normal), (b_origin, b_normal)]) => {
                let thickness = point.sub(a_origin).dot(a_normal).abs().max(point.sub(b_origin).dot(b_normal).abs()).min(self.height);
                (FRACTION * thickness).max(OPERAND_SLIVER_FLOOR)
            }
        }
    }
}

/// `BREP_FEATURE_SCALE_OPERAND_WEDGES` (default on; `=0` restores, `check`
/// prints), see [`FeatureScale::between`].
pub fn operand_wedges_mode() -> Mode {
    crate::mode_switch!(live "BREP_FEATURE_SCALE_OPERAND_WEDGES", true)
}


/// Two operands' planes at most this far apart are one surface whatever the
/// tolerance (the model tolerance): an operand sliver must exceed it.
const OPERAND_SLIVER_FLOOR: f64 = 1e-7;

/// `BREP_FEATURE_SCALE_OPERAND_SLIVERS` (default on since 2026-11-24; `0|off`
/// restores; `check` prints and registers nothing), see [`FeatureScale::between`].
pub fn operand_slivers_mode() -> Mode {
    crate::mode_switch!(live "BREP_FEATURE_SCALE_OPERAND_SLIVERS", true)
}