Skip to main content

brep_topology/brep/
pair_classification.rs

1use crate::{project_point_to_surface, KnotVector, NurbsSurface, Vec3};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
5#[serde(rename_all = "snake_case")]
6pub enum SurfacePairRelation {
7    Disjoint,
8    Candidate,
9    Transverse,
10    NearTangent,
11    Cosurface,
12    Singular,
13}
14
15#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
16pub struct SurfacePairClassification {
17    pub relation: SurfacePairRelation,
18    pub minimum_separation: f64,
19    pub minimum_normal_cross: f64,
20    /// Every sample within contact distance of the other surface has
21    /// PARALLEL normals there: the surfaces only touch tangentially, so
22    /// their intersection cannot contain a transverse curve.  Marching
23    /// such a pair walks the tangency band's noise (it neither closes nor
24    /// exits — the distance-0 glue-extrude runaway); the shared topology
25    /// comes from boundary-curve exchange instead.
26    pub tangential_only: bool,
27}
28
29use crate::spatial::Aabb as Bounds;
30
31fn same_surface(first: &NurbsSurface, second: &NurbsSurface, tolerance: f64) -> bool {
32    first.degree_u == second.degree_u
33        && first.degree_v == second.degree_v
34        && first.knots_u.len() == second.knots_u.len()
35        && first.knots_v.len() == second.knots_v.len()
36        && first.control_points.len() == second.control_points.len()
37        && first
38            .knots_u
39            .iter()
40            .zip(&second.knots_u)
41            .all(|(a, b)| (a - b).abs() <= tolerance)
42        && first
43            .knots_v
44            .iter()
45            .zip(&second.knots_v)
46            .all(|(a, b)| (a - b).abs() <= tolerance)
47        && first
48            .control_points
49            .iter()
50            .zip(&second.control_points)
51            .all(|(first_row, second_row)| {
52                first_row.len() == second_row.len()
53                    && first_row.iter().zip(second_row).all(|(a, b)| {
54                        (a.x - b.x).abs() <= tolerance
55                            && (a.y - b.y).abs() <= tolerance
56                            && (a.z - b.z).abs() <= tolerance
57                            && (a.w - b.w).abs() <= tolerance
58                    })
59            })
60}
61
62fn planar_support(surface: &NurbsSurface, tolerance: f64) -> Result<Option<(Vec3, Vec3)>, String> {
63    let u = KnotVector::new(surface.knots_u.clone(), surface.degree_u)?.domain();
64    let v = KnotVector::new(surface.knots_v.clone(), surface.degree_v)?.domain();
65    let origin = surface.evaluate((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0)?;
66    // A carrier with no normal at its domain centre (a cusp or pinch line
67    // through it) is no plane. `BREP_SINGULAR_CENTRE_NOT_PLANAR` (default
68    // off; `check` reports each surface) answers "not planar" instead of
69    // failing the whole pair classification.
70    let normal = match surface.normal((u[0] + u[1]) / 2.0, (v[0] + v[1]) / 2.0) {
71        Ok(normal) => normal,
72        Err(error) => {
73            let on = crate::switch!("BREP_SINGULAR_CENTRE_NOT_PLANAR", false);
74            let check = !on && env_read!("BREP_SINGULAR_CENTRE_NOT_PLANAR").as_deref() == Some("check");
75            if check {
76                eprintln!("SINGULAR_CENTRE_NOT_PLANAR: planar_support: no normal at the carrier's domain centre ({error}); the switch reads it as not planar");
77            }
78            if on {
79                return Ok(None);
80            }
81            return Err(error);
82        }
83    };
84    let controls = surface
85        .control_points
86        .iter()
87        .flatten()
88        .map(|control| control.point())
89        .collect::<Result<Vec<_>, _>>()?;
90    let scale = controls
91        .iter()
92        .map(|point| point.sub(origin).length())
93        .fold(1.0f64, f64::max);
94    let plane_tolerance = (tolerance * 100.0).max(1e-7) * scale;
95    Ok(controls
96        .iter()
97        .all(|point| point.sub(origin).dot(normal).abs() <= plane_tolerance)
98        .then_some((origin, normal)))
99}
100
101
102
103/// PLANE PAIR STRADDLE (2026-11-06; `BREP_PLANE_PAIR_STRADDLE`,
104/// default on, `=0` restores the parallel reading). Two planes within the angular tolerance of parallel are
105/// still two planes when one crosses the other inside the patches: the
106/// hair-turned cube (brep-bench `tangent/cube-turned-a-hair`, 0.001 deg =
107/// 1.7e-5 rad) has side pairs whose `|n x n'|` reads 1.7e-5 <= 1e-4 and whose
108/// midpoints stand 7.6e-10 apart, so the parallel branch called them
109/// Cosurface, while their corners stand +-8.7e-5 off each other's plane. A
110/// pair is read as crossing when some control point of either patch stands
111/// more than `band` on each side of the other's plane (a degree-1 patch lies
112/// in its control hull, so the crossing line passes through it). A pair
113/// within the band on one side keeps the parallel reading.
114pub fn plane_pair_straddle_enabled() -> bool {
115    crate::switch!("BREP_PLANE_PAIR_STRADDLE", true)
116}
117
118/// Whether the planar patches `first` (through `first_origin`, normal
119/// `first_normal`) and `second` (likewise) cross each other by more than
120/// `band` on both sides: see [`plane_pair_straddle_enabled`].
121pub fn planar_patches_straddle(
122    first: &NurbsSurface,
123    first_origin: Vec3,
124    first_normal: Vec3,
125    second: &NurbsSurface,
126    second_origin: Vec3,
127    second_normal: Vec3,
128    band: f64,
129) -> bool {
130    let straddles = |surface: &NurbsSurface, origin: Vec3, normal: Vec3| {
131        let mut below = false;
132        let mut above = false;
133        for control in surface.control_points.iter().flatten() {
134            let Ok(point) = control.point() else { return false };
135            let distance = point.sub(origin).dot(normal);
136            below |= distance < -band;
137            above |= distance > band;
138        }
139        below && above
140    };
141    straddles(second, first_origin, first_normal) || straddles(first, second_origin, second_normal)
142}
143
144fn surface_samples(surface: &NurbsSurface) -> Result<Vec<(f64, f64, Vec3)>, String> {
145    let u = surface.domain_u()?;
146    let v = surface.domain_v()?;
147    let mut samples = Vec::with_capacity(25);
148    for i in 0..=4 {
149        for j in 0..=4 {
150            let uu = u[0] + (u[1] - u[0]) * i as f64 / 4.0;
151            let vv = v[0] + (v[1] - v[0]) * j as f64 / 4.0;
152            samples.push((uu, vv, surface.evaluate(uu, vv)?));
153        }
154    }
155    Ok(samples)
156}
157
158/// Per-surface data the pair classifier needs, precomputable once per face
159/// and reused across every pair that face participates in.
160pub struct SurfaceClassifyData {
161    bounds: Bounds,
162    planar: Option<(Vec3, Vec3)>,
163    /// (u, v, point, normal); normal is None where the surface is singular
164    /// (poles) — the classifier treats close singular samples specially.
165    samples: Vec<(f64, f64, Vec3, Option<Vec3>)>,
166}
167
168thread_local! {
169    static CLASSIFY_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 2], std::rc::Rc<SurfaceClassifyData>>> = Default::default();
170    static CLASSIFY_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
171}
172
173pub fn classify_reads() -> usize { CLASSIFY_READS.with(std::cell::Cell::get) }
174
175pub fn clear_classify_memo() {
176    CLASSIFY_MEMO.with(|memo| memo.borrow_mut().clear());
177}
178
179impl SurfaceClassifyData {
180    /// Only geometry and tolerance enter this read. Renumbering a face or
181    /// moving it to the next boolean operand does not require new samples.
182    pub fn memoized(surface: &NurbsSurface, tolerance: f64) -> Result<std::rc::Rc<Self>, String> {
183        let enabled = std::env::var("BREP_CLASSIFY_MEMO").as_deref() != Ok("0");
184        let mut hash = crate::mass_properties::TwoLane::new();
185        crate::mass_properties::hash_surface(&mut hash, surface);
186        hash.f64(tolerance);
187        let key = hash.finish();
188        if enabled {
189            if let Some(data) = CLASSIFY_MEMO.with(|memo| memo.borrow().get(&key).cloned()) {
190                return Ok(data);
191            }
192        }
193        CLASSIFY_READS.with(|reads| reads.set(reads.get() + 1));
194        let data = std::rc::Rc::new(Self::build(surface, tolerance)?);
195        if enabled {
196            CLASSIFY_MEMO.with(|memo| {
197                let mut memo = memo.borrow_mut();
198                if memo.len() >= 4096 { memo.clear(); }
199                memo.insert(key, data.clone());
200            });
201        }
202        Ok(data)
203    }
204
205    pub fn build(surface: &NurbsSurface, model_tolerance: f64) -> Result<Self, String> {
206        let samples = surface_samples(surface)?
207            .into_iter()
208            .map(|(u, v, point)| (u, v, point, surface.normal(u, v).ok()))
209            .collect();
210        Ok(Self {
211            bounds: Bounds::from_surface_controls(surface)?,
212            planar: planar_support(surface, model_tolerance)?,
213            samples,
214        })
215    }
216}
217
218/// Classify a pair before generic SSI runs.  The classifier is conservative:
219/// only separated control hulls are declared disjoint; uncertain pairs stay
220/// `Candidate` rather than being incorrectly culled.
221pub fn classify_surface_pair(
222    first: &NurbsSurface,
223    second: &NurbsSurface,
224    model_tolerance: f64,
225    angular_tolerance: f64,
226) -> Result<SurfacePairClassification, String> {
227    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
228    let first_data = SurfaceClassifyData::build(first, model_tolerance)?;
229    let second_data = SurfaceClassifyData::build(second, model_tolerance)?;
230    classify_surface_pair_cached(
231        first,
232        &first_data,
233        second,
234        &second_data,
235        model_tolerance,
236        angular_tolerance,
237    )
238}
239
240/// `classify_surface_pair` with the per-surface work hoisted out — callers
241/// with many pairs per face build each face's `SurfaceClassifyData` once.
242pub fn classify_surface_pair_cached(
243    first: &NurbsSurface,
244    first_data: &SurfaceClassifyData,
245    second: &NurbsSurface,
246    second_data: &SurfaceClassifyData,
247    model_tolerance: f64,
248    angular_tolerance: f64,
249) -> Result<SurfacePairClassification, String> {
250    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
251    let first_bounds = first_data.bounds;
252    let second_bounds = second_data.bounds;
253    let hull_separation = first_bounds.separation(second_bounds);
254    let scale = first_bounds.pair_scale(second_bounds);
255    let contact = (model_tolerance * 100.0).max(scale * 1e-7);
256    if hull_separation > contact {
257        return Ok(SurfacePairClassification {
258            relation: SurfacePairRelation::Disjoint,
259            minimum_separation: hull_separation,
260            minimum_normal_cross: 1.0,
261            tangential_only: false,
262        });
263    }
264    if same_surface(first, second, model_tolerance) {
265        return Ok(SurfacePairClassification {
266            relation: SurfacePairRelation::Cosurface,
267            minimum_separation: 0.0,
268            minimum_normal_cross: 0.0,
269            tangential_only: true,
270        });
271    }
272    if let (Some((first_origin, first_normal)), Some((second_origin, second_normal))) =
273        (first_data.planar, second_data.planar)
274    {
275        let normal_cross = first_normal.cross(second_normal).length();
276        let crossing = normal_cross <= angular_tolerance
277            && plane_pair_straddle_enabled()
278            && planar_patches_straddle(first, first_origin, first_normal, second, second_origin, second_normal, contact);
279        if normal_cross <= angular_tolerance && !crossing {
280            let separation = second_origin.sub(first_origin).dot(first_normal).abs();
281            return Ok(SurfacePairClassification {
282                relation: if separation <= contact {
283                    SurfacePairRelation::Cosurface
284                } else {
285                    SurfacePairRelation::Disjoint
286                },
287                minimum_separation: separation,
288                minimum_normal_cross: normal_cross,
289                tangential_only: separation <= contact,
290            });
291        }
292        return Ok(SurfacePairClassification {
293            relation: SurfacePairRelation::Transverse,
294            minimum_separation: 0.0,
295            minimum_normal_cross: normal_cross,
296            tangential_only: false,
297        });
298    }
299
300    let cull = classify_sample_cull_enabled();
301    let reading = sampled_classification(first, first_data, second, second_data, hull_separation, contact, angular_tolerance, cull);
302    if cull && classify_sample_cull_check() {
303        let fresh = sampled_classification(first, first_data, second, second_data, hull_separation, contact, angular_tolerance, false);
304        assert!(same_reading(&reading, &fresh), "pair sample cull check: culled {reading:?} vs fresh {fresh:?}");
305    }
306    reading
307}
308
309/// The sampled reading of a pair whose control boxes meet within `contact`:
310/// every sample of each surface projected onto the other. With `cull`, a
311/// sample is not projected when its distance to the other surface's control
312/// box already exceeds `contact` ([`provably_beyond`]): the surface lies in the
313/// convex hull of its controls (finite, positive weights), so the projection's
314/// foot, a point of the surface, is at least that far away, and the sample can
315/// be neither close nor parallel. Only `minimum_separation` can differ, and only
316/// when no sample is close (`Candidate`): it is then the least of the projected
317/// distances and the culled samples' box bounds, a lower bound of the sampled
318/// reading, which the imprint reads only for grazing pairs (that always have a
319/// close sample, so there it is the same reading).
320#[allow(clippy::too_many_arguments)]
321fn sampled_classification(
322    first: &NurbsSurface,
323    first_data: &SurfaceClassifyData,
324    second: &NurbsSurface,
325    second_data: &SurfaceClassifyData,
326    hull_separation: f64,
327    contact: f64,
328    angular_tolerance: f64,
329    cull: bool,
330) -> Result<SurfacePairClassification, String> {
331    let mut minimum_separation = f64::INFINITY;
332    let mut minimum_normal_cross = f64::INFINITY;
333    let mut close_samples = 0usize;
334    let mut parallel_close_samples = 0usize;
335    let mut singular_close_sample = false;
336    for (source_data, target, target_bounds) in [(first_data, second, second_data.bounds), (second_data, first, first_data.bounds)] {
337        let hull_holds = cull && controls_bound_the_surface(target);
338        for &(_, _, point, source_normal) in &source_data.samples {
339            if hull_holds {
340                if let Some(reach) = provably_beyond(point, target_bounds, contact) {
341                    minimum_separation = minimum_separation.min(reach);
342                    continue;
343                }
344            }
345            let projection = project_point_to_surface(target, point)?;
346            minimum_separation = minimum_separation.min(projection.distance);
347            if projection.distance > contact {
348                continue;
349            }
350            close_samples += 1;
351            match (source_normal, target.normal(projection.u, projection.v)) {
352                (Some(first_normal), Ok(second_normal)) => {
353                    let cross = first_normal.cross(second_normal).length();
354                    minimum_normal_cross = minimum_normal_cross.min(cross);
355                    if cross <= angular_tolerance {
356                        parallel_close_samples += 1;
357                    }
358                }
359                _ => singular_close_sample = true,
360            }
361        }
362    }
363    if minimum_separation == f64::INFINITY {
364        minimum_separation = hull_separation;
365    }
366    if minimum_normal_cross == f64::INFINITY {
367        minimum_normal_cross = 1.0;
368    }
369    let relation = if close_samples == 0 {
370        SurfacePairRelation::Candidate
371    } else if singular_close_sample {
372        SurfacePairRelation::Singular
373    } else if close_samples >= 18 && parallel_close_samples == close_samples {
374        SurfacePairRelation::Cosurface
375    } else if minimum_normal_cross <= angular_tolerance {
376        SurfacePairRelation::NearTangent
377    } else {
378        SurfacePairRelation::Transverse
379    };
380    Ok(SurfacePairClassification {
381        relation,
382        minimum_separation,
383        minimum_normal_cross,
384        tangential_only: close_samples > 0 && parallel_close_samples == close_samples,
385    })
386}
387
388
389
390/// Whether every control of `surface` is finite with a finite, positive weight:
391/// the premise under which the surface lies in its control box.
392fn controls_bound_the_surface(surface: &NurbsSurface) -> bool {
393    surface.control_points.iter().flatten().all(|control| {
394        control.w.is_finite() && control.w > 0.0 && control.x.is_finite() && control.y.is_finite() && control.z.is_finite()
395    })
396}
397
398/// A lower bound of `point`'s distance to any point within `bounds`, when it
399/// exceeds `contact`; `None` otherwise. The box gap is cushioned for the
400/// rounding of the gap itself and of an evaluated surface point: relative
401/// 1e-9, plus 64 ulps of the coordinates' size.
402fn provably_beyond(point: Vec3, bounds: Bounds, contact: f64) -> Option<f64> {
403    let gap = (Bounds { minimum: point, maximum: point }).separation(bounds);
404    let cushion = 64.0 * f64::EPSILON * (point.length() + bounds.minimum.length() + bounds.maximum.length());
405    let reach = gap * (1.0 - 1e-9) - cushion;
406    (reach.is_finite() && reach > contact).then_some(reach)
407}
408
409/// `BREP_CLASSIFY_SAMPLE_CULL` (default on; =0 projects every sample): the pair classifier does not
410/// project a sample its box bound already places beyond the contact band
411/// ([`sampled_classification`]); every field the kernel reads is the same.
412pub fn classify_sample_cull_enabled() -> bool {
413    crate::switch!("BREP_CLASSIFY_SAMPLE_CULL", true)
414}
415
416/// `BREP_CLASSIFY_SAMPLE_CULL_CHECK=1`: classify both ways and stop on any
417/// difference in the relation, `tangential_only` or `minimum_normal_cross`,
418/// or in `minimum_separation` of a pair that is not a `Candidate`.
419fn classify_sample_cull_check() -> bool {
420    crate::switch!("BREP_CLASSIFY_SAMPLE_CULL_CHECK", false)
421}
422
423fn same_reading(culled: &Result<SurfacePairClassification, String>, fresh: &Result<SurfacePairClassification, String>) -> bool {
424    match (culled, fresh) {
425        (Ok(a), Ok(b)) => {
426            a.relation == b.relation
427                && a.tangential_only == b.tangential_only
428                && a.minimum_normal_cross.to_bits() == b.minimum_normal_cross.to_bits()
429                && (a.relation == SurfacePairRelation::Candidate || a.minimum_separation.to_bits() == b.minimum_separation.to_bits())
430        }
431        (Err(a), Err(b)) => a == b,
432        _ => false,
433    }
434}
435
436