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