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    // A ray proved clear of the face: the sampled search's answer is known to be empty (the check
196    // mode runs the search anyway and stops on a disagreement).
197    let check = crate::curve_clear::check_mode();
198    if check || ray_clear_enabled() {
199        let clear = crate::curve_clear::curve_clear_of_surface(sub_ray, surface, tolerance);
200        if check {
201            let hits = intersect_curve_surface(sub_ray, surface, tolerance)?;
202            if clear && !hits.is_empty() {
203                crate::curve_clear::disagreement("classifier ray", hits.len());
204            }
205            return Ok(hits);
206        }
207        if clear {
208            return Ok(Vec::new());
209        }
210    }
211    intersect_curve_surface(sub_ray, surface, tolerance)
212}
213
214/// `BREP_CLASSIFY_RAY_CLEAR` (default on since its promotion; `=0` restores the search alone): a ray the sampled search would take against a freeform
215/// face is first proved clear of it by hull boxes (`crate::curve_clear`); most such searches find
216/// nothing, each after many Newton starts that open with a global projection.
217fn ray_clear_enabled() -> bool {
218    switch!("BREP_CLASSIFY_RAY_CLEAR", true)
219}
220
221/// Point-in-solid classification with per-solid precomputation: face
222/// bounds, the solid box, and a face BVH are built once so repeated
223/// queries (boolean fragment selection asks once per fragment) prune to
224/// the few faces a probe point or ray can actually touch.
225pub struct SolidClassifier<'a> {
226    faces: Vec<&'a FaceRecord>,
227    face_boxes: Vec<Aabb>,
228    bounds: Aabb,
229    bvh: Bvh,
230    tolerance: f64,
231    /// `(region, cap)`: within `region` the On and coincident-On bands reach
232    /// at most `cap` (the feature-scale design's B6/B6′; empty unless the boolean's
233    /// `BREP_FEATURE_SCALE_SELECT` sets it with [`Self::with_coincident_caps`]).
234    coincident_caps: Vec<(Aabb, f64)>,
235}
236
237/// Clip the segment `start + s·direction, s ∈ [0, length]` to `bounds`
238/// (slab test).  Returns the clipped `[s_entry, s_exit]` span, or None when
239/// the segment misses the box.
240fn clip_segment_to_aabb(
241    start: Vec3,
242    direction: Vec3,
243    length: f64,
244    bounds: &Aabb,
245) -> Option<[f64; 2]> {
246    let mut s0 = 0.0f64;
247    let mut s1 = length;
248    for axis in 0..3 {
249        let (origin, delta, minimum, maximum) = match axis {
250            0 => (start.x, direction.x, bounds.minimum.x, bounds.maximum.x),
251            1 => (start.y, direction.y, bounds.minimum.y, bounds.maximum.y),
252            _ => (start.z, direction.z, bounds.minimum.z, bounds.maximum.z),
253        };
254        if delta.abs() <= 1e-15 {
255            if origin < minimum || origin > maximum {
256                return None;
257            }
258            continue;
259        }
260        let mut near = (minimum - origin) / delta;
261        let mut far = (maximum - origin) / delta;
262        if near > far {
263            std::mem::swap(&mut near, &mut far);
264        }
265        s0 = s0.max(near);
266        s1 = s1.min(far);
267        if s0 > s1 {
268            return None;
269        }
270    }
271    Some([s0, s1])
272}
273
274impl<'a> SolidClassifier<'a> {
275    pub fn new(solid: &'a BrepSolid, tolerance: f64) -> Result<Self, String> {
276        let build_started = classify_profile_started();
277        let faces: Vec<&FaceRecord> = solid.shells.iter().flat_map(|shell| &shell.faces).collect();
278        let face_boxes = faces
279            .iter()
280            .map(|face| Aabb::from_surface_controls(&face.surface))
281            .collect::<Result<Vec<_>, _>>()?;
282        let mut bounds = Aabb::empty();
283        for face_box in &face_boxes {
284            bounds.include(*face_box);
285        }
286        let bvh = Bvh::build(&face_boxes);
287        classify_profile(|p| {
288            p.classifier_builds += 1;
289            p.classifier_build_ms += classify_elapsed_ms(build_started);
290        });
291        Ok(Self {
292            faces,
293            face_boxes,
294            bounds,
295            bvh,
296            tolerance,
297            coincident_caps: Vec::new(),
298        })
299    }
300
301    /// The orientation a chord through `through` along `direction` reads, or
302    /// `None` when the chord cannot tell (`BREP_BOOLEAN_SIGN_CHORDS`).
303    ///
304    /// The chord runs from outside the faces' box to outside it, so a closed,
305    /// consistently oriented boundary is entered and left in turn: its hits,
306    /// ordered along the chord, alternate between outward normals against
307    /// the chord and along it, and their number is even. `Some(true)` when
308    /// they do and the first is an entry (material lies behind the normals,
309    /// as on a solid of positive volume), `Some(false)` when they do and the
310    /// first is an exit (inside out). `None` when any hit is tangential,
311    /// grazes (`|n · d|` under 1e-2), falls in a trim's boundary band, sits
312    /// within the On band of another hit, when the hits do not alternate or
313    /// are odd in number (a root the finder lost, or a face reversed against
314    /// its neighbours), or when no hit lies within the On band of `through`
315    /// (the aimed face itself was missed).
316    pub fn chord_orientation(&self, through: Vec3, direction: Vec3) -> Result<Option<bool>, String> {
317        let on_tolerance = self.tolerance * 10.0;
318        let direction = direction.normalized()?;
319        let middle = self.bounds.minimum.add(self.bounds.maximum).scale(0.5);
320        let reach = self.bounds.diagonal() + through.sub(middle).length() + 1.0;
321        let start = through.sub(direction.scale(reach));
322        let length = 2.0 * reach;
323        let end = start.add(direction.scale(length));
324        let mut candidates = Vec::new();
325        self.bvh.intersecting_segment(start, end, on_tolerance, &mut candidates);
326        candidates.sort_unstable();
327        // (distance along the chord, the outward normal along it).
328        let mut hits: Vec<(f64, bool)> = Vec::new();
329        let mut aimed = false;
330        for &index in &candidates {
331            let face = self.faces[index];
332            let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
333            let Some([span_start, span_end]) =
334                clip_segment_to_aabb(start, direction, length, &self.face_boxes[index].expanded(margin))
335            else {
336                continue;
337            };
338            let span_start = (span_start - margin).max(0.0);
339            let span_end = (span_end + margin).min(length);
340            if span_end - span_start <= 1e-12 {
341                continue;
342            }
343            let sub_ray = make_line(start.add(direction.scale(span_start)), start.add(direction.scale(span_end)))?;
344            for intersection in ray_face_intersections(&sub_ray, &face.surface, self.tolerance)? {
345                if intersection.tangential {
346                    return Ok(None);
347                }
348                let uv = Vec2 { x: intersection.u, y: intersection.v };
349                match parameter_point_in_face(face, uv, face_uv_tolerance(face, uv.x, uv.y, on_tolerance))? {
350                    PolygonClass::Outside => continue,
351                    PolygonClass::Boundary => return Ok(None),
352                    PolygonClass::Inside => {}
353                }
354                let along = face_normal(face, uv.x, uv.y)?.dot(direction);
355                if along.abs() < 1e-2 {
356                    return Ok(None);
357                }
358                if intersection.point.sub(through).length() <= on_tolerance {
359                    aimed = true;
360                }
361                hits.push((intersection.point.sub(start).dot(direction), along > 0.0));
362            }
363        }
364        if !aimed || hits.is_empty() || hits.len() % 2 == 1 {
365            return Ok(None);
366        }
367        hits.sort_by(|a, b| a.0.total_cmp(&b.0));
368        for pair in hits.windows(2) {
369            if pair[1].0 - pair[0].0 <= on_tolerance || pair[1].1 == pair[0].1 {
370                return Ok(None);
371            }
372        }
373        Ok(Some(!hits[0].1))
374    }
375
376    /// Cheap On-band probe: is the point within the classifier's On
377    /// tolerance of ANY face carrier (trim not checked — conservative)?
378    /// Used to guard adjacency propagation: fragments near the other
379    /// solid's surface need the full normal-based On decision, everything
380    /// else can inherit its fate from a neighbor.
381    pub fn near_surface(&self, point: Vec3) -> Result<bool, String> {
382        let on_tolerance = self.tolerance * 10.0;
383        if !self.bounds.expanded(on_tolerance).contains(point) {
384            return Ok(false);
385        }
386        let mut candidates = Vec::new();
387        self.bvh
388            .containing_point(point, on_tolerance, &mut candidates);
389        for &index in &candidates {
390            let projection = project_point_to_surface(&self.faces[index].surface, point)?;
391            if projection.distance <= on_tolerance {
392                return Ok(true);
393            }
394        }
395        Ok(false)
396    }
397
398    /// Conservative carrier-proximity probe: is `point` within `band` of ANY
399    /// face's carrier surface (trim NOT checked)?  A strict superset of the
400    /// `On` verdict (which additionally requires the point to fall in a face's
401    /// trim), so callers that want to skip every point that *might* be on or
402    /// near the boundary — the semantic oracle's On-skip — can rely on a `true`
403    /// here to mean "not safely In/Out".  `band` is taken explicitly so the
404    /// caller can widen it to a size-relative width and absorb near-coincidence
405    /// gaps (Golovanov §4.13 derived tolerances).
406    pub fn within_band(&self, point: Vec3, band: f64) -> Result<bool, String> {
407        if !self.bounds.expanded(band).contains(point) {
408            return Ok(false);
409        }
410        let mut candidates = Vec::new();
411        self.bvh.containing_point(point, band, &mut candidates);
412        for &index in &candidates {
413            let projection = project_point_to_surface(&self.faces[index].surface, point)?;
414            if projection.distance <= band {
415                return Ok(true);
416            }
417        }
418        Ok(false)
419    }
420
421    pub fn classify(&self, point: Vec3) -> Result<PointClassification, String> {
422    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
423        classify_profile(|p| p.classify_calls += 1);
424        let tolerance = self.tolerance;
425        if !self.bounds.expanded(tolerance).contains(point) {
426            return Ok(PointClassification {
427                class: PointClass::Out,
428                on_normal: None,
429            });
430        }
431        // FEATURE SCALE B6′ (`BREP_FEATURE_SCALE_SELECT`; no caps without it):
432        // the On band (1e-6) reaches across a slab 1e-6 thick, so the middle
433        // of the hairline slot's strips read On its walls, not In the saw.
434        let on_tolerance = self.capped_band(point, tolerance * 10.0);
435        if !self.coincident_caps.is_empty() && env_read!("BREP_DEBUG_FEATURE_SCALE").is_some() {
436            eprintln!("feature_scale: classify at {point:?} on band {on_tolerance:.3e} (uncapped {:.3e}, {} caps)", tolerance * 10.0, self.coincident_caps.len());
437        }
438        let mut candidates = Vec::new();
439        self.bvh
440            .containing_point(point, on_tolerance, &mut candidates);
441        candidates.sort_unstable();
442        // All faces the point lies On, split by whether it sits in the trim
443        // interior or within the boundary band.  Where the point is on an
444        // edge or vertex shared by several faces, the classification normal
445        // is the normalized sum of their normals (Golovanov §4.11/§6.3) —
446        // a single face's normal is ambiguous there, and falling through to
447        // ray casting made the answer direction-dependent.
448        let mut interior_normals: Vec<Vec3> = Vec::new();
449        let mut boundary_normals: Vec<Vec3> = Vec::new();
450        for &index in &candidates {
451            let face = self.faces[index];
452            let project_started = classify_profile_started();
453            let projection = project_point_to_surface(&face.surface, point)?;
454            classify_profile(|p| {
455                p.band_candidates += 1;
456                p.band_project_ms += classify_elapsed_ms(project_started);
457            });
458            if projection.distance > on_tolerance {
459                continue;
460            }
461            let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, on_tolerance);
462            let trim_started = classify_profile_started();
463            let trim = parameter_point_in_face(
464                face,
465                Vec2 {
466                    x: projection.u,
467                    y: projection.v,
468                },
469                uv_tolerance,
470            )?;
471            classify_profile(|p| {
472                p.band_trim_tests += 1;
473                p.band_trim_ms += classify_elapsed_ms(trim_started);
474            });
475            match trim {
476                PolygonClass::Inside => {
477                    interior_normals.push(face_normal(face, projection.u, projection.v)?)
478                }
479                PolygonClass::Boundary => {
480                    boundary_normals.push(face_normal(face, projection.u, projection.v)?)
481                }
482                PolygonClass::Outside => {}
483            }
484        }
485        let pool = if interior_normals.is_empty() {
486            &boundary_normals
487        } else {
488            &interior_normals
489        };
490        if !pool.is_empty() {
491            let mut sum = Vec3::default();
492            for normal in pool {
493                sum = sum.add(*normal);
494            }
495            // A near-zero sum means opposed normals (knife edge, coincident
496            // back-to-back faces): genuinely ambiguous, let the ray casting
497            // below decide.
498            if sum.length() > 1e-3 {
499                return Ok(PointClassification {
500                    class: PointClass::On,
501                    on_normal: Some(sum.normalized()?),
502                });
503            }
504        }
505        let directions = [
506            Vec3::new(0.577215, 0.618034, 0.532088),
507            Vec3::new(-0.707107, 0.267949, 0.654321),
508            Vec3::new(0.316228, -0.741657, 0.585786),
509            Vec3::new(-0.414214, -0.552786, -0.723607),
510            Vec3::new(0.9482, 0.11893, -0.29456),
511            Vec3::new(-0.13947, 0.90271, -0.40718),
512            Vec3::new(0.62361, -0.33912, -0.70414),
513            Vec3::new(0.20912, 0.51293, 0.83261),
514        ];
515        let ray_length = self.bounds.diagonal() * 3.0 + 1.0;
516        // RAY-AGREEMENT VOTING: a single ray's parity flips when the root
517        // finder loses one of two close crossings through a thin feature
518        // (trial 533's 00000231-p4: a ray pierced a curved flange twice ~3 mm
519        // apart, intersect_curve_surface returned one root, and a point 2 mm
520        // clear of the material classified In). One lost root is a
521        // direction-specific accident, so require TWO clean directions to
522        // AGREE before trusting the parity; on disagreement keep sampling
523        // directions and return the first verdict confirmed twice. Escape
524        // hatch: BREP_CLASSIFY_RAY_AGREE=0 restores first-clean-ray.
525        let require_agreement = std::env::var("BREP_CLASSIFY_RAY_AGREE").as_deref() != Ok("0");
526        let mut verdicts: Vec<PointClass> = Vec::new();
527        'directions: for direction in directions {
528            classify_profile(|p| p.rays += 1);
529            let direction = direction.normalized()?;
530            let ray_end = point.add(direction.scale(ray_length));
531            candidates.clear();
532            self.bvh
533                .intersecting_segment(point, ray_end, on_tolerance, &mut candidates);
534            candidates.sort_unstable();
535            let mut crossings = 0;
536            for &index in &candidates {
537                let face = self.faces[index];
538                // Intersect the ray with this face over the SHORT span the
539                // ray actually spends near the face's bounding box, not the
540                // whole solid-diagonal-scale ray.  The root finder seeds one
541                // Newton start per curve sample segment, so a long ray gives
542                // a small face a single seed — a ray that crosses a small
543                // curved face twice within one sample segment (e.g. a probe
544                // from a tangency line through a blend tube) silently loses
545                // a crossing and flips the parity.  Clipping the ray to the
546                // face box makes the seed density match the face scale.
547                let margin = on_tolerance.max(self.face_boxes[index].diagonal() * 1e-3);
548                let Some([span_start, span_end]) = clip_segment_to_aabb(
549                    point,
550                    direction,
551                    ray_length,
552                    &self.face_boxes[index].expanded(margin),
553                ) else {
554                    continue;
555                };
556                let span_start = (span_start - margin).max(0.0);
557                let span_end = (span_end + margin).min(ray_length);
558                if span_end - span_start <= 1e-12 {
559                    continue;
560                }
561                let sub_ray = make_line(
562                    point.add(direction.scale(span_start)),
563                    point.add(direction.scale(span_end)),
564                )?;
565                let csi_started = classify_profile_started();
566                let intersections = ray_face_intersections(&sub_ray, &face.surface, tolerance)?;
567                classify_profile(|p| {
568                    p.ray_faces += 1;
569                    p.ray_csi_ms += classify_elapsed_ms(csi_started);
570                });
571                for intersection in intersections {
572                    if intersection.point.sub(point).length() <= on_tolerance {
573                        let trim_started = classify_profile_started();
574                        let trim = parameter_point_in_face(
575                            face,
576                            Vec2 {
577                                x: intersection.u,
578                                y: intersection.v,
579                            },
580                            face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
581                        )?;
582                        classify_profile(|p| {
583                            p.ray_trim_tests += 1;
584                            p.ray_trim_ms += classify_elapsed_ms(trim_started);
585                        });
586                        if trim != PolygonClass::Outside {
587                            return Ok(PointClassification {
588                                class: PointClass::On,
589                                on_normal: Some(face_normal(face, intersection.u, intersection.v)?),
590                            });
591                        }
592                        continue;
593                    }
594                    if intersection.tangential {
595                        continue 'directions;
596                    }
597                    let trim_started = classify_profile_started();
598                    let trim_class = parameter_point_in_face(
599                        face,
600                        Vec2 {
601                            x: intersection.u,
602                            y: intersection.v,
603                        },
604                        face_uv_tolerance(face, intersection.u, intersection.v, on_tolerance),
605                    )?;
606                    classify_profile(|p| {
607                        p.ray_trim_tests += 1;
608                        p.ray_trim_ms += classify_elapsed_ms(trim_started);
609                    });
610                    if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
611                        eprintln!(
612                            "classify ray dir=({:.3},{:.3},{:.3}) face={} hit=({:.4},{:.4},{:.4}) t3d={:.4} uv=({:.6},{:.6}) trim={:?}",
613                            direction.x, direction.y, direction.z,
614                            face.id,
615                            intersection.point.x, intersection.point.y, intersection.point.z,
616                            intersection.point.sub(point).length(),
617                            intersection.u, intersection.v,
618                            trim_class
619                        );
620                    }
621                    match trim_class {
622                        PolygonClass::Boundary => continue 'directions,
623                        PolygonClass::Inside => crossings += 1,
624                        PolygonClass::Outside => {}
625                    }
626                }
627            }
628            let verdict = if crossings % 2 == 1 {
629                PointClass::In
630            } else {
631                PointClass::Out
632            };
633            if std::env::var("BREP_DEBUG_CLASSIFY").is_ok() {
634                eprintln!(
635                    "classify verdict dir=({:.3},{:.3},{:.3}) crossings={crossings} -> {verdict:?}",
636                    direction.x, direction.y, direction.z
637                );
638            }
639            if !require_agreement || verdicts.contains(&verdict) {
640                return Ok(PointClassification {
641                    class: verdict,
642                    on_normal: None,
643                });
644            }
645            verdicts.push(verdict);
646        }
647        // Every direction bailed (tangential/boundary) or, under agreement
648        // voting, the clean directions never confirmed one another. A single
649        // unconfirmed verdict is still far better than an error.
650        if let Some(&verdict) = verdicts.last() {
651            return Ok(PointClassification {
652                class: verdict,
653                on_normal: None,
654            });
655        }
656        Err("classifyPointVsSolid: no clean ray direction found".into())
657    }
658
659    /// Wider-band On probe for near-coincident faces.  A model built from
660    /// noisy input carries faces that are geometrically coincident with the
661    /// other solid's boundary yet separated by a gap that scales with the
662    /// model (a few microns), not with the absolute model tolerance.  Such a
663    /// gap slips a face fragment's interior test point past the fixed On band
664    /// (`classify`), so it reads as a stray In/Out.  This probe re-checks
665    /// whether `point` sits in the trim INTERIOR of a coincident boundary
666    /// face within a band derived from the solid's size (Golovanov §4.13
667    /// derived tolerances), returning the mean outward normal of the
668    /// coincident faces when it does.  It only ever RESCUES an On verdict —
669    /// callers keep the tight-band In/Out otherwise — so the general
670    /// classification path is unchanged.  Interior-only (boundary hits are
671    /// ignored) so it fires only on a genuine surface overlap, never on mere
672    /// proximity to an edge.
673    /// Caps the coincident-On band within each region (see
674    /// `coincident_caps`): a test point a sliver's width from the other
675    /// solid's face is a feature, not noise to rescue to On.
676    pub fn with_coincident_caps(mut self, caps: Vec<(Aabb, f64)>) -> Self {
677        self.coincident_caps = caps;
678        self
679    }
680
681    /// `band` capped by every `coincident_caps` region within its reach of
682    /// `point`, strictly (a point exactly at a cap's distance is a feature).
683    fn capped_band(&self, point: Vec3, band: f64) -> f64 {
684        self.coincident_caps
685            .iter()
686            .filter(|(region, _)| region.expanded(band).contains(point))
687            .fold(band, |band, &(_, cap)| band.min(cap * (1.0 - 1e-9)))
688    }
689
690    pub fn coincident_on_normal(&self, point: Vec3) -> Result<Option<Vec3>, String> {
691        let started = classify_profile_started();
692        let result = self.coincident_on_normal_inner(point);
693        classify_profile(|p| {
694            p.coincident_calls += 1;
695            p.coincident_ms += classify_elapsed_ms(started);
696        });
697        result
698    }
699
700    fn coincident_on_normal_inner(&self, point: Vec3) -> Result<Option<Vec3>, String> {
701        let band = (self.tolerance * 10.0).max(self.bounds.diagonal() * 1e-7);
702        // A point at a capped band's edge is a feature, not noise: strictly
703        // inside the cap only (`< cap`, as the projection test below reads
704        // `> band` as off).
705        let band = self.capped_band(point, band);
706        if !self.bounds.expanded(band).contains(point) {
707            return Ok(None);
708        }
709        let mut candidates = Vec::new();
710        self.bvh.containing_point(point, band, &mut candidates);
711        let mut interior_normals: Vec<Vec3> = Vec::new();
712        for &index in &candidates {
713            let face = self.faces[index];
714            let projection = project_point_to_surface(&face.surface, point)?;
715            if projection.distance > band {
716                continue;
717            }
718            let uv_tolerance = face_uv_tolerance(face, projection.u, projection.v, band);
719            if let PolygonClass::Inside = parameter_point_in_face(
720                face,
721                Vec2 {
722                    x: projection.u,
723                    y: projection.v,
724                },
725                uv_tolerance,
726            )? {
727                interior_normals.push(face_normal(face, projection.u, projection.v)?);
728            }
729        }
730        if interior_normals.is_empty() {
731            return Ok(None);
732        }
733        let mut sum = Vec3::default();
734        for normal in &interior_normals {
735            sum = sum.add(*normal);
736        }
737        if sum.length() <= 1e-3 {
738            return Ok(None);
739        }
740        Ok(Some(sum.normalized()?))
741    }
742}
743
744pub fn classify_point(
745    point: Vec3,
746    solid: &BrepSolid,
747    tolerance: f64,
748) -> Result<PointClassification, String> {
749    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::CLASSIFY);
750    classify_profile_begin();
751    let result = SolidClassifier::new(solid, tolerance)?.classify(point);
752    classify_profile_report("classify_point");
753    result
754}
755