Skip to main content

brep_kernel/brep/soundness/
resolve.rs

1//! Resolving the scan's UNDECIDED candidates on the exact carriers (lane K2
2//! row scan-undecided, 2026-10-16). A candidate the mesh confirmation cannot
3//! decide (its witness is not a point both trims own, or the pierce lane could
4//! not evaluate a projection or a normal) is asked again of the carriers
5//! themselves: points of the two carriers' common curve near the mesh
6//! crossing, found by Newton on both surfaces at once, are classified by both
7//! trims at their OWN parameters (no fresh projection). A point both faces own
8//! where the carriers cross transversally, straddled past the band in both
9//! directions, confirms a crossing; points that all lie on an edge the two
10//! faces share, or outside a trim, clear it. Anything else stays undecided,
11//! and the budget is bounded: `SEEDS` points per candidate, `ITERATIONS`
12//! Newton steps per point, `MAX_RESOLVED` candidates per scan.
13use super::*;
14use crate::projection::project_point_to_curve;
15
16/// On by default (2026-10-16); `BREP_SOUNDNESS_RESOLVE=0` (any value but
17/// 1/on) restores the scan without resolution, for an on/off census, and
18/// keeps the acceptance from refusing on an undecided scan.
19pub(crate) fn enabled() -> bool {
20    switch!("BREP_SOUNDNESS_RESOLVE", true)
21}
22
23/// Off by default (2026-10-16): `BREP_SOUNDNESS_REFUSE_UNDECIDED=1|on` makes
24/// the acceptance refuse a result whose scan stays undecided after resolution
25/// (`accept_refuses_undecided_crossing_20261016`). Default-off until the lib
26/// battery reads no correct body refused: a near-tangent contact (a sphere
27/// tangent family) still ends undecided there. The report lists them either
28/// way.
29pub(crate) fn refuse_enabled() -> bool {
30    switch!("BREP_SOUNDNESS_REFUSE_UNDECIDED", false)
31}
32
33/// Seeds along the mesh crossing segment (both ends included).
34pub(super) const SEEDS: usize = 5;
35/// Newton steps per seed.
36const ITERATIONS: usize = 24;
37/// Candidates resolved per scan; the rest stay undecided.
38pub(super) const MAX_RESOLVED: usize = 256;
39/// Smallest sine between the carriers' normals read as a transversal crossing.
40const MIN_SINE: f64 = 1e-3;
41
42/// Why the mesh confirmation left a candidate undecided.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
44#[serde(rename_all = "snake_case")]
45pub enum CrossingUndecidedCause {
46    /// The crossing's witness is not a point both faces own.
47    Witness,
48    /// The pierce lane could not evaluate a projection or a normal.
49    Pierce,
50    /// A triangle's face index is not in the body.
51    MissingFace,
52}
53
54/// One candidate the scan could not decide, after resolution.
55#[derive(Clone, Debug, Serialize)]
56pub struct UndecidedCrossing {
57    pub face_a: u64,
58    pub face_b: u64,
59    pub cause: CrossingUndecidedCause,
60    /// Midpoint of the mesh crossing segment.
61    pub point: Vec3,
62}
63
64/// What the carriers say about one candidate.
65pub(super) enum Resolution {
66    /// A transversal crossing at a point both faces own, with its straddle.
67    Crossing { point: Vec3, straddle: f64 },
68    /// The carriers meet only on a shared edge or outside a trim here.
69    Clear,
70    Undecided,
71}
72
73/// One common point of the two carriers: `(point, (ua, va), (ub, vb))`.
74type Common = (Vec3, (f64, f64), (f64, f64));
75
76/// Minimum-norm Newton on `S_a(ua, va) = S_b(ub, vb)` from both feet of `seed`.
77fn common_point(a: &NurbsSurface, b: &NurbsSurface, seed: Vec3, tolerance: f64, reach: f64) -> Option<Common> {
78    let (fa, fb) = (project_point_to_surface(a, seed).ok()?, project_point_to_surface(b, seed).ok()?);
79    let (da_u, da_v) = (a.domain_u().ok()?, a.domain_v().ok()?);
80    let (db_u, db_v) = (b.domain_u().ok()?, b.domain_v().ok()?);
81    let (mut ua, mut va, mut ub, mut vb) = (fa.u, fa.v, fb.u, fb.v);
82    for _ in 0..ITERATIONS {
83        let (sa, sb) = (a.derivatives(ua, va, 1).ok()?, b.derivatives(ub, vb, 1).ok()?);
84        let residual = sa[0][0].sub(sb[0][0]);
85        if residual.length() <= tolerance {
86            let point = sa[0][0].add(sb[0][0]).scale(0.5);
87            return (point.sub(seed).length() <= reach).then_some((point, (ua, va), (ub, vb)));
88        }
89        // J = [Sa_u, Sa_v, -Sb_u, -Sb_v] (3x4); step = -J^T (J J^T)^-1 r.
90        let columns = [sa[1][0], sa[0][1], sb[1][0].scale(-1.), sb[0][1].scale(-1.)];
91        let mut m = [[0.0f64; 3]; 3];
92        for c in &columns {
93            let v = [c.x, c.y, c.z];
94            for i in 0..3 {
95                for j in 0..3 {
96                    m[i][j] += v[i] * v[j];
97                }
98            }
99        }
100        let lambda = solve3(m, [-residual.x, -residual.y, -residual.z])?;
101        let lambda = Vec3::new(lambda[0], lambda[1], lambda[2]);
102        let step = columns.map(|c| c.dot(lambda));
103        ua = (ua + step[0]).clamp(da_u[0], da_u[1]);
104        va = (va + step[1]).clamp(da_v[0], da_v[1]);
105        ub = (ub + step[2]).clamp(db_u[0], db_u[1]);
106        vb = (vb + step[3]).clamp(db_v[0], db_v[1]);
107    }
108    None
109}
110
111/// Partial-pivot solve of a 3x3 system; `None` when it is singular.
112fn solve3(m: [[f64; 3]; 3], r: [f64; 3]) -> Option<[f64; 3]> {
113    let out = crate::fit::solve_small(m, r, 3).ok()?;
114    out.iter().all(|value| value.is_finite()).then_some(out)
115}
116
117/// Does `face` own its own parameter `(u, v)`? `None` when the trim test fails.
118fn owns(face: &FaceRecord, (u, v): (f64, f64)) -> Option<PolygonClass> {
119    parameter_point_in_face(face, Vec2 { x: u, y: v }, TRIM_SAMPLE_TOLERANCE).ok()
120}
121
122/// Straddle of `face` across `other`'s carrier at its own parameter `at`,
123/// stepping `h` (world) each way across the common curve: the smaller of the
124/// two one-sided distances when they have opposite signs and both points are
125/// the face's own material, else `None`.
126fn straddle_across(face: &FaceRecord, at: (f64, f64), across: Vec3, other: &NurbsSurface, h: f64) -> Option<f64> {
127    let d = face.surface.derivatives(at.0, at.1, 1).ok()?;
128    let (su, sv) = (d[1][0], d[0][1]);
129    // Least squares (du, dv) with su du + sv dv = across.
130    let (a, b, c) = (su.dot(su), su.dot(sv), sv.dot(sv));
131    let det = a * c - b * b;
132    if !(det > 0.) {
133        return None;
134    }
135    let (p, q) = (su.dot(across), sv.dot(across));
136    let (du, dv) = ((c * p - b * q) / det, (a * q - b * p) / det);
137    let scale = h / su.scale(du).add(sv.scale(dv)).length();
138    if !scale.is_finite() {
139        return None;
140    }
141    let mut sides = [0.; 2];
142    for (slot, sign) in sides.iter_mut().zip([1., -1.]) {
143        let (u, v) = (at.0 + sign * scale * du, at.1 + sign * scale * dv);
144        if !matches!(owns(face, (u, v))?, PolygonClass::Inside) {
145            return None;
146        }
147        *slot = signed_distance(other, face.surface.evaluate(u, v).ok()?)?;
148    }
149    (sides[0] * sides[1] < 0.).then(|| sides[0].abs().min(sides[1].abs()))
150}
151
152/// Resolve one candidate: `segment` is the mesh crossing, `shared` the curves
153/// of the edges both faces use, `corners` the vertices both faces use.
154pub(super) fn resolve(
155    face_a: &FaceRecord,
156    face_b: &FaceRecord,
157    shared: &[&NurbsCurve],
158    corners: &[Vec3],
159    segment: (Vec3, Vec3),
160    options: SelfIntersectionOptions,
161) -> Resolution {
162    let band = options.straddle_band;
163    let reach = 4. * options.chord_tolerance + segment.1.sub(segment.0).length();
164    let mut all_clear = true;
165    for i in 0..SEEDS {
166        let t = i as f64 / (SEEDS - 1) as f64;
167        let seed = segment.0.add(segment.1.sub(segment.0).scale(t));
168        // Converged to the body's weld scale, or to what the coordinates'
169        // own precision can resolve where they are large (far from the origin
170        // a weld-scale residual is below one ulp).
171        let magnitude = seed.x.abs().max(seed.y.abs()).max(seed.z.abs());
172        let tolerance = (options.weld * 1e-3).max(64. * f64::EPSILON * magnitude);
173        let Some((point, pa, pb)) = common_point(&face_a.surface, &face_b.surface, seed, tolerance, reach) else {
174            all_clear = false;
175            continue;
176        };
177        // On an edge both faces use: the faces meet there by construction. An
178        // edge is the carriers' intersection only to its own accuracy, so the
179        // carriers' true common curve can sit up to that deviation (over the
180        // angle between them) off the edge, in a sliver both trims own.
181        let on_shared = shared.iter().any(|curve| {
182            project_point_to_curve(curve, point).is_ok_and(|foot| {
183                let off = |surface: &NurbsSurface| project_point_to_surface(surface, foot.point).map_or(f64::INFINITY, |f| f.distance);
184                let deviation = off(&face_a.surface) + off(&face_b.surface);
185                let sine = match (face_a.surface.normal(pa.0, pa.1), face_b.surface.normal(pb.0, pb.1)) {
186                    (Ok(na), Ok(nb)) => match (na.normalized(), nb.normalized()) {
187                        (Ok(na), Ok(nb)) => na.cross(nb).length(),
188                        _ => 0.,
189                    },
190                    _ => 0.,
191                };
192                foot.distance <= band || (deviation.is_finite() && sine > 0. && foot.distance <= band + 4. * deviation / sine)
193            })
194        });
195        // At a vertex both faces use: they touch there by construction.
196        let on_corner = corners.iter().any(|corner| corner.sub(point).length() <= band.max(tolerance));
197        if on_shared || on_corner {
198            continue;
199        }
200        let (Some(in_a), Some(in_b)) = (owns(face_a, pa), owns(face_b, pb)) else {
201            all_clear = false;
202            continue;
203        };
204        if matches!(in_a, PolygonClass::Outside) || matches!(in_b, PolygonClass::Outside) {
205            continue;
206        }
207        all_clear = false;
208        if !(matches!(in_a, PolygonClass::Inside) && matches!(in_b, PolygonClass::Inside)) {
209            continue;
210        }
211        let (Ok(na), Ok(nb)) = (face_a.surface.normal(pa.0, pa.1), face_b.surface.normal(pb.0, pb.1)) else { continue };
212        let (Ok(na), Ok(nb)) = (na.normalized(), nb.normalized()) else { continue };
213        let along = na.cross(nb);
214        let sine = along.length();
215        if !(sine >= MIN_SINE) {
216            continue;
217        }
218        let along = along.scale(1. / sine);
219        // Step far enough that a transversal crossing clears the band twice.
220        let h = 4. * band / sine;
221        let (Some(forward), Some(backward)) = (
222            straddle_across(face_a, pa, nb.sub(along.scale(nb.dot(along))), &face_b.surface, h),
223            straddle_across(face_b, pb, na.sub(along.scale(na.dot(along))), &face_a.surface, h),
224        ) else {
225            continue;
226        };
227        if forward > band && backward > band {
228            return Resolution::Crossing { point, straddle: forward.min(backward) };
229        }
230    }
231    if all_clear { Resolution::Clear } else { Resolution::Undecided }
232}
233