Skip to main content

brep_topology/brep/classification/
solid_classifier.rs

1use super::*;
2
3fn face_normal(face: &FaceRecord, u: f64, v: f64) -> Result<Vec3, String> {
4    let normal = match face.surface.normal(u, v) {
5        Ok(normal) => normal,
6        Err(error) => {
7            // POLE RESCUE: at a collapsed parameterization pole (sphere pole,
8            // cone apex) du×dv vanishes and `normal()` errors — which used to
9            // propagate and kill the ENTIRE boolean (trial 9: a sphere placed
10            // TANGENT at its pole dies with "Vec3.normalized: zero-length
11            // vector" before any fragment is classified). The GEOMETRIC
12            // normal is well-defined and continuous there; recover it by
13            // stepping slightly inside the domain (at the pole every azimuth
14            // shares the same limit normal, so the offset direction does not
15            // matter). Escape hatch: BREP_POLE_NORMAL_RESCUE=0.
16            if !error.contains("zero-length")
17                || std::env::var("BREP_POLE_NORMAL_RESCUE").as_deref() == Ok("0")
18            {
19                return Err(error);
20            }
21            let [u0, u1] = face.surface.domain_u()?;
22            let [v0, v1] = face.surface.domain_v()?;
23            let step_u = (u1 - u0) * 1e-4;
24            let step_v = (v1 - v0) * 1e-4;
25            let inner_u = u.clamp(u0 + step_u, u1 - step_u);
26            let inner_v = v.clamp(v0 + step_v, v1 - step_v);
27            let mut recovered = None;
28            for (cu, cv) in [(u, inner_v), (inner_u, v), (inner_u, inner_v)] {
29                if let Ok(normal) = face.surface.normal(cu, cv) {
30                    recovered = Some(normal);
31                    break;
32                }
33            }
34            match recovered {
35                Some(normal) => normal,
36                None => return Err(error),
37            }
38        }
39    };
40    Ok(if face.same_sense {
41        normal
42    } else {
43        normal.scale(-1.0)
44    })
45}
46
47/// UV band equivalent to a spatial band of `spatial` at (u, v), derived
48/// from the local surface derivative magnitudes (`tolerance.rs`
49/// `surface_uv_tolerance`).  Capped to a fraction of the smaller domain
50/// span so a pole or collapsed direction cannot widen the band into the
51/// whole face.
52fn face_uv_tolerance(face: &FaceRecord, u: f64, v: f64, spatial: f64) -> f64 {
53    surface_uv_band(&face.surface, u, v, spatial)
54}
55
56/// [`face_uv_tolerance`] for a bare carrier.
57pub fn surface_uv_band(surface: &crate::NurbsSurface, u: f64, v: f64, spatial: f64) -> f64 {
58    let Ok(derivatives) = surface.derivatives(u, v, 1) else {
59        return spatial;
60    };
61    let band = crate::tolerance::surface_uv_tolerance(
62        spatial,
63        derivatives[1][0].length(),
64        derivatives[0][1].length(),
65    );
66    let cap = match (surface.domain_u(), surface.domain_v()) {
67        (Ok([u0, u1]), Ok([v0, v1])) => ((u1 - u0).min(v1 - v0) * 0.05).max(1e-12),
68        _ => f64::INFINITY,
69    };
70    band.min(cap)
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
74#[serde(rename_all = "lowercase")]
75pub enum PointClass {
76    In,
77    Out,
78    On,
79}
80
81#[derive(Clone, Copy, Debug, Serialize)]
82pub struct PointClassification {
83    pub class: PointClass,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub on_normal: Option<Vec3>,
86}
87
88/// Per-thread counters for the classifier, printed by
89/// [`classify_profile_report`] when `BREP_PROFILE` is set: how many point
90/// queries ran, how many face projections and trim tests the On band cost,
91/// how many rays were cast and how many face intersections and trim tests
92/// they cost, and the wall time of each part. When the switch is off every
93/// counter is one thread-local flag test.
94#[derive(Default, Clone, Copy)]
95pub struct ClassifyProfile {
96    pub enabled: bool,
97    pub classify_calls: u64,
98    pub band_candidates: u64,
99    pub band_project_ms: f64,
100    pub band_trim_tests: u64,
101    pub band_trim_ms: f64,
102    pub rays: u64,
103    pub ray_faces: u64,
104    pub ray_csi_ms: f64,
105    /// Ray-face intersections the exact lane seeded (`exact_ray_enabled`) and
106    /// the ones it declined to the sampled search.
107    pub ray_exact_faces: u64,
108    pub ray_fallback_faces: u64,
109    pub ray_trim_tests: u64,
110    pub ray_trim_ms: f64,
111    pub coincident_calls: u64,
112    pub coincident_ms: f64,
113    pub classifier_builds: u64,
114    pub classifier_build_ms: f64,
115}
116
117thread_local! {
118    static CLASSIFY_PROFILE: std::cell::Cell<ClassifyProfile> =
119        const { std::cell::Cell::new(ClassifyProfile {
120            enabled: false, classify_calls: 0, band_candidates: 0, band_project_ms: 0.0,
121            band_trim_tests: 0, band_trim_ms: 0.0, rays: 0, ray_faces: 0, ray_csi_ms: 0.0,
122            ray_exact_faces: 0, ray_fallback_faces: 0, ray_trim_tests: 0, ray_trim_ms: 0.0, coincident_calls: 0, coincident_ms: 0.0,
123            classifier_builds: 0, classifier_build_ms: 0.0,
124        }) };
125}
126
127impl crate::profile::Counters for ClassifyProfile {
128    fn armed(&self) -> bool {
129        self.enabled
130    }
131}
132
133fn classify_profile(update: impl FnOnce(&mut ClassifyProfile)) {
134    crate::profile::update(&CLASSIFY_PROFILE, update)
135}
136
137fn classify_profile_started() -> Option<web_time::Instant> {
138    crate::profile::started(&CLASSIFY_PROFILE)
139}
140
141use crate::profile::elapsed_ms as classify_elapsed_ms;
142
143/// Arm the classifier counters (reset to zero) when `BREP_PROFILE` is set.
144pub fn classify_profile_begin() {
145    let enabled = crate::profile::profile_enabled();
146    CLASSIFY_PROFILE.with(|cell| {
147        cell.set(ClassifyProfile {
148            enabled,
149            ..ClassifyProfile::default()
150        })
151    });
152}
153
154/// Print the counters gathered since [`classify_profile_begin`] under
155/// `label` and disarm them. Silent when profiling is off.
156pub fn classify_profile_report(label: &str) {
157    let p = CLASSIFY_PROFILE.with(|cell| cell.get());
158    if !p.enabled {
159        return;
160    }
161    profile_line!(
162        "classify.profile {label} calls={} builds={} build_ms={:.2} band: candidates={} project_ms={:.2} trim_tests={} trim_ms={:.2} rays={} ray_faces={} csi_ms={:.2} exact_faces={} fallback_faces={} ray_trim_tests={} ray_trim_ms={:.2} coincident: calls={} ms={:.2}",
163        p.classify_calls, p.classifier_builds, p.classifier_build_ms, p.band_candidates,
164        p.band_project_ms, p.band_trim_tests, p.band_trim_ms, p.rays, p.ray_faces,
165        p.ray_csi_ms, p.ray_exact_faces, p.ray_fallback_faces, p.ray_trim_tests, p.ray_trim_ms, p.coincident_calls, p.coincident_ms,
166    );
167    CLASSIFY_PROFILE.with(|cell| cell.set(ClassifyProfile::default()));
168}
169
170/// The exact ray lane (lane B row 1, 2026-10-17): a ray against an ANALYTIC
171/// face is seeded with its closed-form roots (`crate::exact_line_surface`)
172/// instead of the sampled search's 32-sample scan, then solved and filtered
173/// by the same code. Default ON since its on/off census (production 96/96,
174/// bench 52/52 bodies and 1197/1197 lines) read identical;
175/// `BREP_CLASSIFY_EXACT_RAY=0` (or `off`) restores the sampled search.
176fn exact_ray_enabled() -> bool {
177    switch!("BREP_CLASSIFY_EXACT_RAY", true)
178}
179
180/// One ray-face intersection of the ray pass: the exact lane's seeds when it
181/// is on and the face admits them, the sampled search otherwise. Counted on
182/// the profile as `exact_faces` / `fallback_faces` (never timed).
183fn ray_face_intersections(
184    sub_ray: &NurbsCurve,
185    surface: &crate::NurbsSurface,
186    tolerance: f64,
187) -> Result<Vec<crate::CurveSurfaceIntersection>, String> {
188    if exact_ray_enabled() {
189        if let Some(seeds) = crate::exact_line_surface::exact_line_surface_seeds(sub_ray, surface, tolerance) {
190            classify_profile(|p| p.ray_exact_faces += 1);
191            return crate::curve_surface_intersection::intersect_curve_surface_from_seeds(sub_ray, surface, tolerance, seeds);
192        }
193        classify_profile(|p| p.ray_fallback_faces += 1);
194    }
195    intersect_curve_surface(sub_ray, surface, tolerance)
196}
197
198/// Point-in-solid classification with per-solid precomputation: face
199/// bounds, the solid box, and a face BVH are built once so repeated
200/// queries (boolean fragment selection asks once per fragment) prune to
201/// the few faces a probe point or ray can actually touch.
202pub struct SolidClassifier<'a> {
203    faces: Vec<&'a FaceRecord>,
204    face_boxes: Vec<Aabb>,
205    bounds: Aabb,
206    bvh: Bvh,
207    tolerance: f64,
208    /// `(region, cap)`: within `region` the On and coincident-On bands reach
209    /// at most `cap` (the feature-scale design's B6/B6′; empty unless the boolean's
210    /// `BREP_FEATURE_SCALE_SELECT` sets it with [`Self::with_coincident_caps`]).
211    coincident_caps: Vec<(Aabb, f64)>,
212}
213
214/// Clip the segment `start + s·direction, s ∈ [0, length]` to `bounds`
215/// (slab test).  Returns the clipped `[s_entry, s_exit]` span, or None when
216/// the segment misses the box.
217fn clip_segment_to_aabb(
218    start: Vec3,
219    direction: Vec3,
220    length: f64,
221    bounds: &Aabb,
222) -> Option<[f64; 2]> {
223    let mut s0 = 0.0f64;
224    let mut s1 = length;
225    for axis in 0..3 {
226        let (origin, delta, minimum, maximum) = match axis {
227            0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
228            1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
229            _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
230        };
231        if delta.abs() <= 1e-15 {
232            if origin < minimum || origin > maximum {
233                return None;
234            }
235            continue;
236        }
237        let mut near = (minimum - origin) / delta;
238        let mut far = (maximum - origin) / delta;
239        if near > far {
240            std::mem::swap(&mut near, &mut far);
241        }
242        s0 = s0.max(near);
243        s1 = s1.min(far);
244        if s0 > s1 {
245            return None;
246        }
247    }
248    Some([s0, s1])
249}
250
251impl<'a> SolidClassifier<'a> {
252    pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
253        let build_started = classify_profile_started();
254        let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
255        let face_boxes = faces
256            .iter()
257            .map(|face| Aabb::from_surface_controls(&face.surface))
258            .collect::<Result<Vec<_>, _>>()?;
259        let mut bounds = Aabb::empty();
260        for face_box in &face_boxes {
261            bounds.include(*face_box);
262        }
263        let bvh = Bvh::build(&face_boxes);
264        classify_profile(|p| {
265            p.classifier_builds += 1;
266            p.classifier_build_ms += classify_elapsed_ms(build_started);
267        });
268        Ok(Self {
269            faces,
270            face_boxes,
271            bounds,
272            bvh,
273            tolerance,
274            coincident_caps: Vec::new(),
275        })
276    }
277
278    /// Cheap On-band probe: is the point within the classifier's On
279    /// tolerance of ANY face carrier (trim not checked — conservative)?
280    /// Used to guard adjacency propagation: fragments near the other
281    /// solid's surface need the full normal-based On decision, everything
282    /// else can inherit its fate from a neighbor.
283    pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
284        let on_tolerance = self.tolerance * 10.0;
285        if !self.bounds.expanded(on_tolerance).contains(point) {
286            return Ok(false);
287        }
288        let mut candidates = Vec::new();
289        self.bvh
290            .containing_point(point, on_tolerance, &mut candidates);
291        for &index in &candidates {
292            let projection = project_point_to_surface(&self.faces[index].surface, point)?;
293            if projection.distance <= on_tolerance {
294                return Ok(true);
295            }
296        }
297        Ok(false)
298    }
299
300    /// Conservative carrier-proximity probe: is `point` within `band` of ANY
301    /// face's carrier surface (trim NOT checked)?  A strict superset of the
302    /// `On` verdict (which additionally requires the point to fall in a face's
303    /// trim), so callers that want to skip every point that *might* be on or
304    /// near the boundary — the semantic oracle's On-skip — can rely on a `true`
305    /// here to mean "not safely In/Out".  `band` is taken explicitly so the
306    /// caller can widen it to a size-relative width and absorb near-coincidence
307    /// gaps (Golovanov §4.13 derived tolerances).
308    pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
309        if !self.bounds.expanded(band).contains(point) {
310            return Ok(false);
311        }
312        let mut candidates = Vec::new();
313        self.bvh.containing_point(point, band, &mut candidates);
314        for &index in &candidates {
315            let projection = project_point_to_surface(&self.faces[index].surface, point)?;
316            if projection.distance <= band {
317                return Ok(true);
318            }
319        }
320        Ok(false)
321    }
322
323    pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
324    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
325        classify_profile(|p| p.classify_calls += 1);
326        let tolerance = self.tolerance;
327        if !self.bounds.expanded(tolerance).contains(point) {
328            return Ok(PointClassification {
329                class: PointClass::Out,
330                on_normal: None,
331            });
332        }
333        // FEATURE SCALE B6′ (`BREP_FEATURE_SCALE_SELECT`; no caps without it):
334        // the On band (1e-6) reaches across a slab 1e-6 thick, so the middle
335        // of the hairline slot's strips read On its walls, not In the saw.
336        let on_tolerance = self.capped_band(point, tolerance * 10.0);
337        if !self.coincident_caps.is_empty() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
338            eprintln!("feature_scale: classify at {point:?} on band {on_tolerance:.3e} (uncapped {:.3e}, {} caps)", tolerance * 10.0, self.coincident_caps.len());
339        }
340        let mut candidates = Vec::new();
341        self.bvh
342            .containing_point(point, on_tolerance, &mut candidates);
343        candidates.sort_unstable();
344        // All faces the point lies On, split by whether it sits in the trim
345        // interior or within the boundary band.  Where the point is on an
346        // edge or vertex shared by several faces, the classification normal
347        // is the normalized sum of their normals (Golovanov §4.11/§6.3) —
348        // a single face's normal is ambiguous there, and falling through to
349        // ray casting made the answer direction-dependent.
350        let mut interior_normals: Vec<Vec3> = Vec::new();
351        let mut boundary_normals: Vec<Vec3> = Vec::new();
352        for &index in &candidates {
353            let face = self.faces[index];
354            let project_started = classify_profile_started();
355            let projection = project_point_to_surface(&face.surface, point)?;
356            classify_profile(|p| {
357                p.band_candidates += 1;
358                p.band_project_ms += classify_elapsed_ms(project_started);
359            });
360            if projection.distance > on_tolerance {
361                continue;
362            }
363            let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
364            let trim_started = classify_profile_started();
365            let trim = parameter_point_in_face(
366                face,
367                Vec2 {
368                    x: projection.u,
369                    y: projection.v,
370                },
371                uv_tolerance,
372            )?;
373            classify_profile(|p| {
374                p.band_trim_tests += 1;
375                p.band_trim_ms += classify_elapsed_ms(trim_started);
376            });
377            match trim {
378                PolygonClass::Inside => {
379                    interior_normals.push(face_normal(face, projection.u, projection.v)?)
380                }
381                PolygonClass::Boundary => {
382                    boundary_normals.push(face_normal(face, projection.u, projection.v)?)
383                }
384                PolygonClass::Outside => {}
385            }
386        }
387        let pool = if interior_normals.is_empty() {
388            &boundary_normals
389        } else {
390            &interior_normals
391        };
392        if !pool.is_empty() {
393            let mut sum = Vec3::default();
394            for normal in pool {
395                sum = sum.add(*normal);
396            }
397            // A near-zero sum means opposed normals (knife edge, coincident
398            // back-to-back faces): genuinely ambiguous, let the ray casting
399            // below decide.
400            if sum.length() > 1e-3 {
401                return Ok(PointClassification {
402                    class: PointClass::On,
403                    on_normal: Some(sum.normalized()?),
404                });
405            }
406        }
407        let directions = [
408            Vec3::new(0.577215, 0.618034, 0.532088),
409            Vec3::new(-0.707107, 0.267949, 0.654321),
410            Vec3::new(0.316228, -0.741657, 0.585786),
411            Vec3::new(-0.414214, -0.552786, -0.723607),
412            Vec3::new(0.9482, 0.11893, -0.29456),
413            Vec3::new(-0.13947, 0.90271, -0.40718),
414            Vec3::new(0.62361, -0.33912, -0.70414),
415            Vec3::new(0.20912, 0.51293, 0.83261),
416        ];
417        let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
418        // RAY-AGREEMENT VOTING: a single ray's parity flips when the root
419        // finder loses one of two close crossings through a thin feature
420        // (trial 533's 00000231-p4: a ray pierced a curved flange twice ~3 mm
421        // apart, intersect_curve_surface returned one root, and a point 2 mm
422        // clear of the material classified In). One lost root is a
423        // direction-specific accident, so require TWO clean directions to
424        // AGREE before trusting the parity; on disagreement keep sampling
425        // directions and return the first verdict confirmed twice. Escape
426        // hatch: BREP_CLASSIFY_RAY_AGREE=0 restores first-clean-ray.
427        let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
428        let mut verdicts: Vec<PointClass> = Vec::new();
429        'directions: for direction in directions {
430            classify_profile(|p| p.rays += 1);
431            let direction = direction.normalized()?;
432            let ray_end = point.add(direction.scale(ray_length));
433            candidates.clear();
434            self.bvh
435                .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
436            candidates.sort_unstable();
437            let mut crossings = 0;
438            for &index in &candidates {
439                let face = self.faces[index];
440                // Intersect the ray with this face over the SHORT span the
441                // ray actually spends near the face's bounding box, not the
442                // whole solid-diagonal-scale ray.  The root finder seeds one
443                // Newton start per curve sample segment, so a long ray gives
444                // a small face a single seed — a ray that crosses a small
445                // curved face twice within one sample segment (e.g. a probe
446                // from a tangency line through a blend tube) silently loses
447                // a crossing and flips the parity.  Clipping the ray to the
448                // face box makes the seed density match the face scale.
449                let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
450                let Some([span_start, span_end]) = clip_segment_to_aabb(
451                    point,
452                    direction,
453                    ray_length,
454                    &self.face_boxes[index].expanded(margin),
455                ) else {
456                    continue;
457                };
458                let span_start = (span_start - margin).max(0.0);
459                let span_end = (span_end + margin).min(ray_length);
460                if span_end - span_start <= 1e-12 {
461                    continue;
462                }
463                let sub_ray = make_line(
464                    point.add(direction.scale(span_start)),
465                    point.add(direction.scale(span_end)),
466                )?;
467                let csi_started = classify_profile_started();
468                let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
469                classify_profile(|p| {
470                    p.ray_faces += 1;
471                    p.ray_csi_ms += classify_elapsed_ms(csi_started);
472                });
473                for intersection in intersections {
474                    if intersection.point.sub(point).length() <= on_tolerance {
475                        let trim_started = classify_profile_started();
476                        let trim = parameter_point_in_face(
477                            face,
478                            Vec2 {
479                                x: intersection.u,
480                                y: intersection.v,
481                            },
482                            face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
483                        )?;
484                        classify_profile(|p| {
485                            p.ray_trim_tests += 1;
486                            p.ray_trim_ms += classify_elapsed_ms(trim_started);
487                        });
488                        if trim != PolygonClass::Outside {
489                            return Ok(PointClassification {
490                                class: PointClass::On,
491                                on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
492                            });
493                        }
494                        continue;
495                    }
496                    if intersection.tangential {
497                        continue 'directions;
498                    }
499                    let trim_started = classify_profile_started();
500                    let trim_class = parameter_point_in_face(
501                        face,
502                        Vec2 {
503                            x: intersection.u,
504                            y: intersection.v,
505                        },
506                        face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
507                    )?;
508                    classify_profile(|p| {
509                        p.ray_trim_tests += 1;
510                        p.ray_trim_ms += classify_elapsed_ms(trim_started);
511                    });
512                    if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
513                        eprintln!(
514                            "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
515                            direction.x, direction.y, direction.z,
516                            face.id,
517                            intersection.point.x, intersection.point.y, intersection.point.z,
518                            intersection.point.sub(point).length(),
519                            intersection.u, intersection.v,
520                            trim_class
521                        );
522                    }
523                    match trim_class {
524                        PolygonClass::Boundary => continue 'directions,
525                        PolygonClass::Inside => crossings += 1,
526                        PolygonClass::Outside => {}
527                    }
528                }
529            }
530            let verdict = if crossings % 2 == 1 {
531                PointClass::In
532            } else {
533                PointClass::Out
534            };
535            if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
536                eprintln!(
537                    "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
538                    direction.x, direction.y, direction.z
539                );
540            }
541            if !require_agreement || verdicts.contains(&verdict) {
542                return Ok(PointClassification {
543                    class: verdict,
544                    on_normal: None,
545                });
546            }
547            verdicts.push(verdict);
548        }
549        // Every direction bailed (tangential/boundary) or, under agreement
550        // voting, the clean directions never confirmed one another. A single
551        // unconfirmed verdict is still far better than an error.
552        if let Some(&verdict) = verdicts.last() {
553            return Ok(PointClassification {
554                class: verdict,
555                on_normal: None,
556            });
557        }
558        Err("classifyPointVsSolid: no clean ray direction found".into())
559    }
560
561    /// Wider-band On probe for near-coincident faces.  A model built from
562    /// noisy input carries faces that are geometrically coincident with the
563    /// other solid's boundary yet separated by a gap that scales with the
564    /// model (a few microns), not with the absolute model tolerance.  Such a
565    /// gap slips a face fragment's interior test point past the fixed On band
566    /// (`classify`), so it reads as a stray In/Out.  This probe re-checks
567    /// whether `point` sits in the trim INTERIOR of a coincident boundary
568    /// face within a band derived from the solid's size (Golovanov §4.13
569    /// derived tolerances), returning the mean outward normal of the
570    /// coincident faces when it does.  It only ever RESCUES an On verdict —
571    /// callers keep the tight-band In/Out otherwise — so the general
572    /// classification path is unchanged.  Interior-only (boundary hits are
573    /// ignored) so it fires only on a genuine surface overlap, never on mere
574    /// proximity to an edge.
575    /// Caps the coincident-On band within each region (see
576    /// `coincident_caps`): a test point a sliver's width from the other
577    /// solid's face is a feature, not noise to rescue to On.
578    pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
579        self.coincident_caps = caps;
580        self
581    }
582
583    /// `band` capped by every `coincident_caps` region within its reach of
584    /// `point`, strictly (a point exactly at a cap's distance is a feature).
585    fn capped_band(&self, point: Vec3, band: f64) -> f64 {
586        self.coincident_caps
587            .iter()
588            .filter(|(region, _)| region.expanded(band).contains(point))
589            .fold(band, |band, &(_, cap)| band.min(cap * (1.0 - 1e-9)))
590    }
591
592    pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
593        let started = classify_profile_started();
594        let result = self.coincident_on_normal_inner(point);
595        classify_profile(|p| {
596            p.coincident_calls += 1;
597            p.coincident_ms += classify_elapsed_ms(started);
598        });
599        result
600    }
601
602    fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
603        let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
604        // A point at a capped band's edge is a feature, not noise: strictly
605        // inside the cap only (`< cap`, as the projection test below reads
606        // `> band` as off).
607        let band = self.capped_band(point, band);
608        if !self.bounds.expanded(band).contains(point) {
609            return Ok(None);
610        }
611        let mut candidates = Vec::new();
612        self.bvh.containing_point(point, band, &mut candidates);
613        let mut interior_normals: Vec<Vec3> = Vec::new();
614        for &index in &candidates {
615            let face = self.faces[index];
616            let projection = project_point_to_surface(&face.surface, point)?;
617            if projection.distance > band {
618                continue;
619            }
620            let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
621            if let PolygonClass::Inside = parameter_point_in_face(
622                face,
623                Vec2 {
624                    x: projection.u,
625                    y: projection.v,
626                },
627                uv_tolerance,
628            )? {
629                interior_normals.push(face_normal(face, projection.u, projection.v)?);
630            }
631        }
632        if interior_normals.is_empty() {
633            return Ok(None);
634        }
635        let mut sum = Vec3::default();
636        for normal in &interior_normals {
637            sum = sum.add(*normal);
638        }
639        if sum.length() <= 1e-3 {
640            return Ok(None);
641        }
642        Ok(Some(sum.normalized()?))
643    }
644}
645
646pub fn classify_point(
647    point: Vec3,
648    solid: &BrepSolid,
649    tolerance: f64,
650) -> Result<PointClassification, String> {
651    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
652    classify_profile_begin();
653    let result = SolidClassifier::new(solid, tolerance)?.classify(point);
654    classify_profile_report("classify_point");
655    result
656}