From 9634ad345b3aa7fad1af9a69a6ffc1ff72914a8b Mon Sep 17 00:00:00 2001 From: Markus Reichart <52602624+MarkusReichart@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:02:07 +0100 Subject: [PATCH 1/2] solidcore: claim the query typed-errors ticket (TE-O-13, #19846) Co-Authored-By: Claude Code From 1e180ac476535477068871f8687d9d95e7eb6eec Mon Sep 17 00:00:00 2001 From: Markus Reichart <52602624+MarkusReichart@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:21:41 +0100 Subject: [PATCH 2/2] solidcore: the deviation measures' and small queries' failures become named causes or reviewed defects (TE-O-13 part 1, #19846) The 35 query phrase-cause sites of curve/plane_of.rs, nurbs/crv_deviation.rs, nurbs/srf_deviation.rs, query/contact.rs, continuity.rs, curve.rs, deviation.rs, distance_bound.rs, face_surface.rs and normal.rs become QueryFailure causes (BoundOverflows, NoStationDropped, NoPatchInBox, FaceWithoutSurface, SurfaceWithoutNurbs) or Defect { why }, each with the status of the phrase it replaces; four unreachable sites are deleted by restructuring. Their lines leave the query pin list. Co-Authored-By: Claude Code --- .../crates/solidcore/src/curve/plane_of.rs | 13 +-- solidcore/crates/solidcore/src/error/query.rs | 90 +++++++++++++++---- .../solidcore/src/nurbs/crv_deviation.rs | 74 ++++++++------- .../solidcore/src/nurbs/srf_deviation.rs | 13 +-- .../crates/solidcore/src/query/contact.rs | 21 +---- .../crates/solidcore/src/query/continuity.rs | 41 ++++----- solidcore/crates/solidcore/src/query/curve.rs | 3 +- .../crates/solidcore/src/query/deviation.rs | 17 ++-- .../solidcore/src/query/distance_bound.rs | 77 +++++++++------- .../solidcore/src/query/face_surface.rs | 34 ++++++- .../crates/solidcore/src/query/normal.rs | 5 +- 11 files changed, 235 insertions(+), 153 deletions(-) diff --git a/solidcore/crates/solidcore/src/curve/plane_of.rs b/solidcore/crates/solidcore/src/curve/plane_of.rs index 29fb4d468a3..f3f325e0bb4 100644 --- a/solidcore/crates/solidcore/src/curve/plane_of.rs +++ b/solidcore/crates/solidcore/src/curve/plane_of.rs @@ -27,6 +27,7 @@ //! Deviations: none (no upstream counterpart). A line is read as its segment from `start` to //! `end`. No recursion. +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::eval::Curve; use crate::math::{Point3, Vec3}; @@ -54,7 +55,8 @@ pub struct PlaneOf { /// /// `InvalidInput` for no curves, a tolerance not finite and positive, numbers not finite, or /// a rational spline with a weight not positive; `Unsupported` for a traced intersection -/// curve; a query failure for curves so large their chords or normal overflow. +/// curve; [`QueryFailure::BoundOverflows`] for curves so large their chords or normal +/// overflow. pub fn plane_of(curves: &[Curve], tol: f64) -> Result> { if curves.is_empty() { return Err(SolidError::invalid_input(OP, "no curves")); @@ -108,7 +110,7 @@ pub fn plane_of(curves: &[Curve], tol: f64) -> Result> { }; // A size past the floating range (a chord or a cross product overflowing) leaves no // normal to bound with: refused, never read as a plane. `f64::max` would drop a NaN. - let overflow = || SolidError::query_failed(OP, "the curves' size overflows the bound"); + let overflow = || SolidError::query(OP, QueryFailure::BoundOverflows); if !(reach.is_finite() && normal.x.is_finite() && normal.y.is_finite() && normal.z.is_finite()) { return Err(overflow()); @@ -275,10 +277,9 @@ mod tests { let huge = Curve::Polyline { points: vec![[0.0; 3], [1e200, 0.0, 0.0], [0.0, 1e200, 0.0]], }; - assert!(matches!( - plane_of(&[huge], 1e-6), - Err(SolidError::Failed(_)) - )); + let e = plane_of(&[huge], 1e-6).unwrap_err(); + assert_eq!(e.query_failure(), Some(&QueryFailure::BoundOverflows)); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); } #[test] diff --git a/solidcore/crates/solidcore/src/error/query.rs b/solidcore/crates/solidcore/src/error/query.rs index 20a3420bb43..50bbbd34ee4 100644 --- a/solidcore/crates/solidcore/src/error/query.rs +++ b/solidcore/crates/solidcore/src/error/query.rs @@ -13,15 +13,20 @@ //! | [`QueryFailure::Missing`] | `SM_ERR_NULL_POINTER` | //! | [`QueryFailure::InvalidValue`] | `SM_ERR_INVALID_INPUT` | //! | [`QueryFailure::Defect`] | `SM_ERR` (or the site's, through `with_status`) | +//! | the named causes, from [`QueryFailure::BoundOverflows`] on | the status of the phrase each replaced (`comparison_status`), or the site's through `with_status` | //! //! [`QueryFailure::Defect`] is a failure reviewed at its site as the kernel's fault, with its //! reason: a defect ([`ErrorKind::StageFailed`], class 127). The phrase causes are sites //! not yet converted (the conversion guide: `docs/failure-codes-and-reproduction.md` §6). //! -//! Deviations: not upstream. A failure says in a phrase what went wrong; the failure's -//! `operation` path says which routine. A failure names an entity only where the site -//! it replaces did (the point classification's seam failure, at its face). The failures -//! that are checks of a caller's arguments stay [`crate::SolidError::InvalidInput`]. +//! Deviations: not upstream. A failure names what went wrong (a named cause, or a phrase +//! where a site is not yet converted); the failure's `operation` path says which routine. +//! A failure names an entity only where the site it replaces did (the point +//! classification's seam failure, at its face). A check of a caller's argument or body +//! that upstream answers with a status is a named cause of kind +//! [`ErrorKind::InvalidInput`] that keeps the status (for example +//! [`QueryFailure::FaceWithoutSurface`]); the checks that report no status stay +//! [`crate::SolidError::InvalidInput`]. use super::{ErrorKind, Failure, Reason, SM_ERR, SM_ERR_INVALID_INPUT, SM_ERR_NULL_POINTER}; @@ -48,26 +53,52 @@ pub enum QueryFailure { /// The step that failed, and why that is the kernel's fault. why: &'static str, }, + /// A bound or size the query computes overflows the floating range, though every number + /// given is finite: the inputs' size, or how far apart they are, reaches past it. Class + /// `failed`. + BoundOverflows, + /// No station of the first curve dropped onto the other curve or the surface, so no + /// deviation was measured. Class `failed`. + NoStationDropped, + /// No patch of the surface overlaps the UV box given: the box is within the rounding of + /// the patches' knot range, but past every patch. [`ErrorKind::InvalidInput`]. + NoPatchInBox, + /// A face of the caller's body has no surface. [`ErrorKind::InvalidInput`]. + FaceWithoutSurface, + /// The surface the query reads (a B-spline surface, or the B-spline base of an analytic + /// one) has no NURBS net: none was made for it, or it could not be made (a NURB that + /// cannot be made stays missing), so the query has no net to read. + /// [`ErrorKind::Unsupported`]. + SurfaceWithoutNurbs, } impl QueryFailure { /// The status the C++ reports for the failure (a comparison detail). pub(crate) const fn comparison_status(&self) -> i32 { match self { - Self::Failed(_) | Self::Defect { .. } => SM_ERR, - Self::Missing(_) => SM_ERR_NULL_POINTER, + Self::Failed(_) + | Self::Defect { .. } + | Self::BoundOverflows + | Self::NoStationDropped + | Self::NoPatchInBox + | Self::SurfaceWithoutNurbs => SM_ERR, + Self::Missing(_) | Self::FaceWithoutSurface => SM_ERR_NULL_POINTER, Self::InvalidValue(_) => SM_ERR_INVALID_INPUT, } } - /// The failure's stable [`ErrorKind`]: [`ErrorKind::Missing`] for - /// [`QueryFailure::Missing`], [`ErrorKind::InvalidInput`] for - /// [`QueryFailure::InvalidValue`], [`ErrorKind::Failed`] otherwise. + /// The failure's stable [`ErrorKind`]: [`ErrorKind::InvalidInput`] for + /// [`QueryFailure::InvalidValue`] and for a check of the caller's argument or body, + /// [`ErrorKind::Unsupported`] for a surface or object the routine does not take, + /// [`ErrorKind::Missing`] for [`QueryFailure::Missing`], otherwise the kind of the status + /// it replaced. /// [`QueryFailure::Defect`] is [`ErrorKind::StageFailed`], a defect. #[must_use] pub const fn kind(&self) -> ErrorKind { match self { Self::Defect { .. } => ErrorKind::StageFailed, + Self::SurfaceWithoutNurbs => ErrorKind::Unsupported, + Self::NoPatchInBox | Self::FaceWithoutSurface => ErrorKind::InvalidInput, _ => ErrorKind::of_status(self.comparison_status()), } } @@ -79,6 +110,11 @@ impl core::fmt::Display for QueryFailure { Self::Failed(what) | Self::InvalidValue(what) => f.write_str(what), Self::Missing(what) => write!(f, "{what} is missing"), Self::Defect { why } => write!(f, "{}: {why}", ErrorKind::StageFailed), + Self::BoundOverflows => f.write_str("the bound overflows the floating range"), + Self::NoStationDropped => f.write_str("no station dropped onto the other"), + Self::NoPatchInBox => f.write_str("no patch of the surface overlaps the UV box"), + Self::FaceWithoutSurface => f.write_str("the face has no surface"), + Self::SurfaceWithoutNurbs => f.write_str("the surface has no NURBS net"), } } } @@ -179,6 +215,32 @@ pub(super) mod tests { assert_eq!(SolidError::sm_err("query::op").query_failure(), None); } + /// Each named cause reports the status of the phrase it replaced, and its kind. + #[test] + fn the_named_query_causes_keep_the_status_they_replaced() { + use ErrorKind as K; + use QueryFailure as F; + let cases = [ + (F::BoundOverflows, SM_ERR, K::Failed), + (F::NoStationDropped, SM_ERR, K::Failed), + (F::NoPatchInBox, SM_ERR, K::InvalidInput), + (F::FaceWithoutSurface, SM_ERR_NULL_POINTER, K::InvalidInput), + (F::SurfaceWithoutNurbs, SM_ERR, K::Unsupported), + ]; + for (failure, code, kind) in cases { + let e = SolidError::query("query::op", failure); + assert_eq!(e.sm_status(), Some(code), "{failure:?}"); + assert_eq!(super::super::upstream_status(&e), Some(code), "{failure:?}"); + assert_eq!(e.kind(), kind, "{failure:?}"); + assert_eq!(e.query_failure(), Some(&failure)); + assert!(!e.is_defect(), "{failure:?}"); + } + assert_eq!( + SolidError::query("query::op", F::FaceWithoutSurface).to_string(), + "query::op: the face has no surface" + ); + } + /// The query routines describe their failures: their library code builds no bare /// `Upstream` status, except the files listed (with the bare sites each may still hold) /// whose conversion waits on other open work. @@ -242,25 +304,15 @@ pub(super) mod tests { }; #[rustfmt::skip] // one file per line, so conversions in parallel merge cleanly const PINNED: &[(&str, usize)] = &[ - ("solidcore/src/curve/plane_of.rs", 1), - ("solidcore/src/nurbs/crv_deviation.rs", 12), - ("solidcore/src/nurbs/srf_deviation.rs", 3), ("solidcore/src/query/api_queries.rs", 36), ("solidcore/src/query/brep.rs", 2), ("solidcore/src/query/brep/ray.rs", 2), ("solidcore/src/query/brep/ray/live.rs", 4), - ("solidcore/src/query/contact.rs", 3), - ("solidcore/src/query/continuity.rs", 5), - ("solidcore/src/query/curve.rs", 1), - ("solidcore/src/query/deviation.rs", 2), - ("solidcore/src/query/distance_bound.rs", 4), ("solidcore/src/query/edge.rs", 10), ("solidcore/src/query/face/p1.rs", 2), ("solidcore/src/query/face/p2.rs", 19), ("solidcore/src/query/face/p3.rs", 2), ("solidcore/src/query/face/p4.rs", 2), - ("solidcore/src/query/face_surface.rs", 2), - ("solidcore/src/query/normal.rs", 2), ("solidcore/src/query/poly.rs", 13), ("solidcore/src/query/poly/copy.rs", 11), ("solidcore/src/query/poly_properties.rs", 2), diff --git a/solidcore/crates/solidcore/src/nurbs/crv_deviation.rs b/solidcore/crates/solidcore/src/nurbs/crv_deviation.rs index c6aed6d3534..b664a3624fc 100644 --- a/solidcore/crates/solidcore/src/nurbs/crv_deviation.rs +++ b/solidcore/crates/solidcore/src/nurbs/crv_deviation.rs @@ -41,6 +41,7 @@ //! Deviations: none (no upstream counterpart). Non-rational 3D curves only, of degree 1 to //! [`MAX_DEGREE`]; their knot vectors clamped, on one domain for [`certified_distance`]. +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::math::Vec3; use crate::nurbs::crv_basic::Curve; @@ -59,8 +60,8 @@ const OP_FIT: &str = "nurbs::crv_deviation::interpolation_bound"; /// /// `InvalidInput` for a rational or 2D curve, a parameter count other than the points', or a /// number not finite; -/// a query failure when the bound is not finite; those of the evaluation (a parameter -/// outside the knots). +/// [`QueryFailure::BoundOverflows`] when the bound overflows the floating range; those of the +/// evaluation (a parameter outside the knots). pub fn interpolation_bound(c: &Curve, params: &[f64], points: &[Vec3]) -> Result { if c.cpts().iter().any(|p| p.w != NOW || p.z == NOZ) { return Err(SolidError::invalid_input(OP_FIT, "a rational or 2D curve")); @@ -95,15 +96,15 @@ pub fn interpolation_bound(c: &Curve, params: &[f64], points: &[Vec3]) -> Result .derivs(u, Side::Left, 0)? .first() .copied() - .ok_or_else(|| SolidError::query_failed(OP_FIT, "no point evaluated"))?; + .ok_or_else(|| SolidError::query(OP_FIT, QueryFailure::Defect { why: "the curve's evaluation of order 0 returned no point, though an evaluation that succeeds returns the point it is asked for" }))?; let d = norm_up(p.x - q.x, p.y - q.y, p.z - q.z) - .ok_or_else(|| SolidError::query_failed(OP_FIT, "the bound is not finite"))?; + .ok_or_else(|| SolidError::query(OP_FIT, QueryFailure::BoundOverflows))?; largest = largest.max(d); } let eval_err = gamma(c.degree().saturating_mul(12).saturating_add(4)) * size; let bound = (largest + 2.0 * eval_err) * (1.0 + gamma(2)); if !bound.is_finite() { - return Err(SolidError::query_failed(OP_FIT, "the bound is not finite")); + return Err(SolidError::query(OP_FIT, QueryFailure::BoundOverflows)); } Ok(bound) } @@ -117,8 +118,8 @@ pub fn interpolation_bound(c: &Curve, params: &[f64], points: &[Vec3]) -> Result /// # Errors /// /// `InvalidInput` for a rational or 2D curve, a number not finite, knots not clamped, or two -/// curves on different domains; a query failure when their pieces do not share their spans or the bound is not -/// finite; those of the refinement, the extraction and the elevation. +/// curves on different domains; [`QueryFailure::BoundOverflows`] when the bound overflows the +/// floating range; those of the refinement, the extraction and the elevation. pub fn certified_distance(a: &Curve, b: &Curve) -> Result { check(a, OP)?; check(b, OP)?; @@ -139,7 +140,7 @@ pub fn certified_distance(a: &Curve, b: &Curve) -> Result { let largest = largest_gap(&pa, &pb, OP)?; let bound = (largest + 2.0 * (ea + eb)) * (1.0 + gamma(2)); if !bound.is_finite() { - return Err(SolidError::query_failed(OP, "the bound is not finite")); + return Err(SolidError::query(OP, QueryFailure::BoundOverflows)); } Ok(bound) } @@ -209,10 +210,7 @@ pub fn certified_hausdorff(a: &Curve, ia: [f64; 2], b: &Curve, ib: [f64; 2]) -> }; let (ca, cb) = (over(&pa, c0, c1), over(&pb, c0, c1)); if ca.is_empty() { - return Err(SolidError::query_failed( - OP_HAUSDORFF, - "the curves' pieces do not share their spans", - )); + return Err(SolidError::query(OP_HAUSDORFF, QueryFailure::Defect { why: "every interval end is a breakpoint of both curves' pieces and the intervals overlap past a point, so a piece lies in their common interval" })); } let largest = largest_gap(&ca, &cb, OP_HAUSDORFF)?; // the largest distance of a piece past the common interval from the curve's point there, @@ -221,10 +219,7 @@ pub fn certified_hausdorff(a: &Curve, ia: [f64; 2], b: &Curve, ib: [f64; 2]) -> let first = common.first().and_then(|x| x.cpts().first()); let last = common.last().and_then(|x| x.cpts().last()); let (Some(&at_c0), Some(&at_c1)) = (first, last) else { - return Err(SolidError::query_failed( - OP_HAUSDORFF, - "a piece without points", - )); + return Err(SolidError::query(OP_HAUSDORFF, QueryFailure::Defect { why: "the common pieces were checked to pair up, and a Bézier piece of degree 1 or more has at least two control points" })); }; let mut s = None; for (lo, hi, end) in [(lo, c0, at_c0), (c1, hi, at_c1)] { @@ -232,9 +227,8 @@ pub fn certified_hausdorff(a: &Curve, ia: [f64; 2], b: &Curve, ib: [f64; 2]) -> continue; } for r in over(p, lo, hi).iter().flat_map(Curve::cpts) { - let d = norm_up(r.x - end.x, r.y - end.y, r.z - end.z).ok_or_else(|| { - SolidError::query_failed(OP_HAUSDORFF, "the bound is not finite") - })?; + let d = norm_up(r.x - end.x, r.y - end.y, r.z - end.z) + .ok_or_else(|| SolidError::query(OP_HAUSDORFF, QueryFailure::BoundOverflows))?; s = Some(s.map_or(d, |m: f64| m.max(d))); } } @@ -249,9 +243,9 @@ pub fn certified_hausdorff(a: &Curve, ia: [f64; 2], b: &Curve, ib: [f64; 2]) -> } }; if !bound.is_finite() { - return Err(SolidError::query_failed( + return Err(SolidError::query( OP_HAUSDORFF, - "the bound is not finite", + QueryFailure::BoundOverflows, )); } Ok(bound) @@ -279,28 +273,19 @@ fn in_own_frame(a: &Curve, b: &Curve, op: &'static str) -> Result<(Curve, Curve) /// degree on the same spans (computed, each rounded up by `γ_8`). fn largest_gap(pa: &[Curve], pb: &[Curve], op: &'static str) -> Result { if pa.len() != pb.len() { - return Err(SolidError::query_failed( - op, - "the curves' pieces do not share their spans", - )); + return Err(SolidError::query(op, QueryFailure::Defect { why: "both curves are cut into Bézier pieces at the union of their breakpoints, so their pieces pair up span by span" })); } let mut largest = 0.0_f64; for (x, y) in pa.iter().zip(pb) { if x.knots().first() != y.knots().first() || x.knots().last() != y.knots().last() { - return Err(SolidError::query_failed( - op, - "the curves' pieces do not share their spans", - )); + return Err(SolidError::query(op, QueryFailure::Defect { why: "both curves are cut into Bézier pieces at the union of their breakpoints, so their pieces pair up span by span" })); } if x.cpts().len() != y.cpts().len() { - return Err(SolidError::query_failed( - op, - "the curves' pieces are not of one degree", - )); + return Err(SolidError::query(op, QueryFailure::Defect { why: "both curves' pieces are raised to the higher of the two degrees, so paired pieces have as many control points" })); } for (p, r) in x.cpts().iter().zip(y.cpts()) { let d = norm_up(p.x - r.x, p.y - r.y, p.z - r.z) - .ok_or_else(|| SolidError::query_failed(op, "the bound is not finite"))?; + .ok_or_else(|| SolidError::query(op, QueryFailure::BoundOverflows))?; largest = largest.max(d); } } @@ -573,6 +558,27 @@ mod tests { )); } + /// Finite curves too far apart for the bound: each difference of control points is + /// finite, its length is not. + #[test] + fn curves_too_far_apart_for_the_bound_overflow_by_name() { + use crate::error::query::QueryFailure; + let a = spline(&[[8e307, 8e307, 0.0], [8e307, 8e307, 1.0]], 1); + let b = spline(&[[-8e307, -8e307, 0.0], [-8e307, -8e307, 1.0]], 1); + for e in [ + certified_distance(&a, &b).unwrap_err(), + certified_hausdorff(&a, [0.0, 1.0], &b, [0.0, 1.0]).unwrap_err(), + ] { + assert_eq!( + e.query_failure(), + Some(&QueryFailure::BoundOverflows), + "{e}" + ); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert!(!e.is_defect()); + } + } + #[test] fn an_extreme_degree_is_refused_not_overflowed() { let c = spline(&WAVE, 3); diff --git a/solidcore/crates/solidcore/src/nurbs/srf_deviation.rs b/solidcore/crates/solidcore/src/nurbs/srf_deviation.rs index 461172f3679..d0bac63a30b 100644 --- a/solidcore/crates/solidcore/src/nurbs/srf_deviation.rs +++ b/solidcore/crates/solidcore/src/nurbs/srf_deviation.rs @@ -26,6 +26,7 @@ //! Deviations: none (no upstream counterpart). Non-rational 3D surfaces only, of degrees 1 to //! [`MAX_DEGREE`], their knot vectors clamped on one domain. +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::nurbs::crv_deviation::norm_up; use crate::nurbs::knots::MAX_DEGREE; @@ -45,8 +46,8 @@ const OP: &str = "nurbs::srf_deviation::certified_distance"; /// /// `InvalidInput` for a rational or 2D surface, a number not finite, a degree outside /// `1..=MAX_DEGREE` or knots that do not fit the net, knots not clamped, or two surfaces on -/// different domains; a query failure when their patches do not match or the bound is not -/// finite; those of the refinement, the extraction and the elevation. +/// different domains; [`QueryFailure::BoundOverflows`] when the bound overflows the floating +/// range; those of the refinement, the extraction and the elevation. pub fn certified_distance(a: &Surface, b: &Surface) -> Result { check(a)?; check(b)?; @@ -83,7 +84,9 @@ pub fn certified_distance(a: &Surface, b: &Surface) -> Result { let moved = gamma(2) * size; let (pa, ea) = patches(a, b, degrees, size)?; let (pb, eb) = patches(b, a, degrees, size)?; - let mismatch = || SolidError::query_failed(OP, "the surfaces' patches do not match"); + let mismatch = || { + SolidError::query(OP, QueryFailure::Defect { why: "both surfaces are cut into Bézier patches at the union of their knots and raised to the same degrees, so their patches pair up span by span with nets of one size" }) + }; if pa.len() != pb.len() { return Err(mismatch()); } @@ -105,7 +108,7 @@ pub fn certified_distance(a: &Surface, b: &Surface) -> Result { } for (p, r) in row_x.iter().zip(row_y) { let d = norm_up(p.x - r.x, p.y - r.y, p.z - r.z) - .ok_or_else(|| SolidError::query_failed(OP, "the bound is not finite"))?; + .ok_or_else(|| SolidError::query(OP, QueryFailure::BoundOverflows))?; largest = largest.max(d); } } @@ -113,7 +116,7 @@ pub fn certified_distance(a: &Surface, b: &Surface) -> Result { } let bound = (largest + 2.0 * (ea + eb + 2.0 * moved)) * (1.0 + gamma(2)); if !bound.is_finite() { - return Err(SolidError::query_failed(OP, "the bound is not finite")); + return Err(SolidError::query(OP, QueryFailure::BoundOverflows)); } Ok(bound) } diff --git a/solidcore/crates/solidcore/src/query/contact.rs b/solidcore/crates/solidcore/src/query/contact.rs index 4f50f327412..1d0844957d9 100644 --- a/solidcore/crates/solidcore/src/query/contact.rs +++ b/solidcore/crates/solidcore/src/query/contact.rs @@ -36,6 +36,7 @@ use std::cmp::Ordering; use std::collections::BinaryHeap; +use crate::error::query::QueryFailure; use crate::geom::certified::{gamma, Verdict}; use crate::geom::extent1d::Extent1d; use crate::geom::tol::{brep_zone_tol_3d, SmallTopoType}; @@ -347,15 +348,7 @@ fn pair_lower(a: &Piece, b: &Piece, axis: Option<[f64; 3]>) -> Result { fn box_lower(a: &Piece, b: &Piece) -> Result { let ((al, ah), (bl, bh)) = (a.widened_box()?, b.widened_box()?); let mut sum = 0.0_f64; - for i in 0..3 { - let (Some(&x0), Some(&x1), Some(&y0), Some(&y1)) = - (al.get(i), ah.get(i), bl.get(i), bh.get(i)) - else { - return Err(SolidError::query_failed( - OP, - "a box has fewer than three axes", - )); - }; + for (((&x0, &x1), &y0), &y1) in al.iter().zip(&ah).zip(&bl).zip(&bh) { let gap = (y0 - x1).max(x0 - y1).max(0.0); // (the difference rounded up by at most gamma_1 of its terms) let gap = (gap - gamma(1) * (x0.abs() + x1.abs() + y0.abs() + y1.abs())).max(0.0); @@ -487,10 +480,7 @@ fn bracket( first.sort_by(|x, y| x.lower.total_cmp(&y.lower)); for pair in first { let (Some(fa), Some(fb)) = (pa.faces.get(pair.a.0), pb.faces.get(pair.b.0)) else { - return Err(SolidError::query_failed( - OP, - "a pair's face is not among its piece's faces", - )); + return Err(SolidError::query(OP, QueryFailure::Defect { why: "a pair's face indices are those of the prepared faces it was made from, enumerated, so each is among them" })); }; if pair.lower < upper { witness_from( @@ -521,10 +511,7 @@ fn bracket( let (ia, x) = &pair.a; let (ib, y) = &pair.b; let (Some(fa), Some(fb)) = (pa.faces.get(*ia), pb.faces.get(*ib)) else { - return Err(SolidError::query_failed( - OP, - "a pair's face is not among its piece's faces", - )); + return Err(SolidError::query(OP, QueryFailure::Defect { why: "a pair's face indices are those of the prepared faces it was made from, enumerated, so each is among them" })); }; // a witness from the pair's centres (none can be nearer than the pair's bound, so a // pair past the witness so far is skipped) diff --git a/solidcore/crates/solidcore/src/query/continuity.rs b/solidcore/crates/solidcore/src/query/continuity.rs index b1646fbdc14..4ea7568a0cc 100644 --- a/solidcore/crates/solidcore/src/query/continuity.rs +++ b/solidcore/crates/solidcore/src/query/continuity.rs @@ -31,6 +31,7 @@ #![allow(clippy::neg_cmp_op_on_partial_ord)] // NaN-refusing tests use crate::curve::curve::Curve; +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::eval::normal_section::normal_section; use crate::eval::{Partials, MAX_PARTIAL_ORDER}; @@ -116,10 +117,7 @@ fn partials(k: &Kernel, s: &Surface, uv: Point2) -> Result { for (j, x) in row.iter_mut().enumerate() { if i + j <= MAX_PARTIAL_ORDER { *x = d.get(i).and_then(|r| r.get(j)).copied().ok_or_else(|| { - SolidError::query_failed( - OP, - "the surface evaluation has fewer partials than asked", - ) + SolidError::query(OP, QueryFailure::Defect { why: "the surface evaluation, asked for the partials to the fourth order, returned fewer, though an evaluation that succeeds returns every order it is asked for" }) })?; } } @@ -404,19 +402,15 @@ pub fn continuity_on_surfaces( } let d = curve.evaluate(k, t, 1, true, false)?; let (Some(&point), Some(&d1)) = (d.first(), d.get(1)) else { - return Err(SolidError::query_failed( - OP, - "the curve evaluation has no first derivative", - )); + return Err(SolidError::query(OP, QueryFailure::Defect { why: "the curve evaluation, asked for the first derivative, returned fewer, though an evaluation that succeeds returns every order it is asked for" })); }; let speed = d1.length(); if !(speed > 0.0 && speed.is_finite() && finite(point)) { return Ok(None); } let tangent = d1 * (1.0 / speed); - let mut feet = Vec::with_capacity(2); - let mut jets = Vec::with_capacity(2); - for (&(s, sign), g) in sides.iter().zip(guess) { + // one face at the station, with its normal section across the edge; `None` as below + let one_side = |(s, sign): (&Surface, f64), g: Option| -> Result> { let Some(one) = side(k, s, sign, point, g)? else { return Ok(None); }; @@ -430,16 +424,14 @@ pub fn continuity_on_surfaces( let Some(jet) = normal_section(&d, one.normal, across * (1.0 / len)) else { return Ok(None); }; - feet.push(one); - jets.push(jet.values()); - } - let (Some(a), Some(bb), Some(ja), Some(jb)) = - (feet.first(), feet.get(1), jets.first(), jets.get(1)) - else { - return Err(SolidError::query_failed( - OP, - "the edge has fewer than two sides", - )); + Ok(Some((one, jet.values()))) + }; + let ([s0, s1], [g0, g1]) = (sides, guess); + let Some((a, ja)) = one_side(s0, g0)? else { + return Ok(None); + }; + let Some((bb, jb)) = one_side(s1, g1)? else { + return Ok(None); }; let opposed = a.normal.dot(bb.normal) < 0.0; let mut jumps = [0.0_f64; 3]; @@ -491,10 +483,7 @@ pub fn curvature_of(k: &Kernel, curve: &Curve, t: f64) -> Result 0.0) { @@ -527,7 +516,7 @@ pub fn iso_curvature( let d = s.evaluate(k, uv, 2, 2, flags)?; let at = |i: usize, j: usize| { d.get(i).and_then(|r| r.get(j)).copied().ok_or_else(|| { - SolidError::query_failed(OP, "the surface evaluation has fewer partials than asked") + SolidError::query(OP, QueryFailure::Defect { why: "the surface evaluation, asked for the partials to the second order, returned fewer, though an evaluation that succeeds returns every order it is asked for" }) }) }; let (point, su, sv) = (at(0, 0)?, at(1, 0)?, at(0, 1)?); diff --git a/solidcore/crates/solidcore/src/query/curve.rs b/solidcore/crates/solidcore/src/query/curve.rs index 0eb2b3251fc..87254953c7d 100644 --- a/solidcore/crates/solidcore/src/query/curve.rs +++ b/solidcore/crates/solidcore/src/query/curve.rs @@ -11,6 +11,7 @@ use super::edge::CurveHandle; use crate::curve::curve::p9::CurveSolveOptions; use crate::curve::curve::Curve; use crate::curve::line::Line; +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::geom::extent1d::Extent1d; use crate::geom::extent3d::Extent3d; @@ -81,7 +82,7 @@ pub fn closest_point_to_ray( let curve_box = curve .calculate_bounding_box(k, interval, req, true)? .normal - .ok_or_else(|| SolidError::query_failed(OP_CLOSEST_RAY, "the curve has no box"))?; + .ok_or_else(|| SolidError::query(OP_CLOSEST_RAY, QueryFailure::Defect { why: "the curve's bounding box was asked for with its normal box, which the box of every curve kind computes when asked" }))?; let reach = curve_box.max_distance(&Extent3d::from_points(origin, origin)) + 1.0; let ray = Curve::from(Line::create_line_segment( 3, diff --git a/solidcore/crates/solidcore/src/query/deviation.rs b/solidcore/crates/solidcore/src/query/deviation.rs index 65ae6b756b7..7f63d65b83d 100644 --- a/solidcore/crates/solidcore/src/query/deviation.rs +++ b/solidcore/crates/solidcore/src/query/deviation.rs @@ -20,6 +20,7 @@ //! Bounded: at most [`MAX_SAMPLES`] drops; no recursion. use crate::curve::curve::{Curve, CurveKind}; +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::geom::extent2d::Extent2d; use crate::geom::global_solver::SolverOperation; @@ -79,10 +80,7 @@ fn of(comb: Vec<(Point3, Point3)>, bound: Option) -> Result { } } let Some((max, at, to)) = worst else { - return Err(SolidError::query_failed( - OP, - "no station dropped onto the other", - )); + return Err(SolidError::query(OP, QueryFailure::NoStationDropped)); }; Ok(Deviation { max, @@ -97,8 +95,9 @@ fn of(comb: Vec<(Point3, Point3)>, bound: Option) -> Result { /// /// # Errors /// -/// `InvalidInput` for a station count outside [`MIN_SAMPLES`]..=[`MAX_SAMPLES`]; a query failure -/// when no station drops onto `b`; those of the evaluations and the drops. +/// `InvalidInput` for a station count outside [`MIN_SAMPLES`]..=[`MAX_SAMPLES`]; +/// [`QueryFailure::NoStationDropped`] when no station drops onto `b`; those of the evaluations +/// and the drops. pub fn curve_deviation(k: &Kernel, a: &Curve, b: &Curve, samples: usize) -> Result { of(curve_pairs(k, a, b, samples)?, certified(a, b)) } @@ -147,8 +146,8 @@ pub struct DistanceDeviation { /// # Errors /// /// `InvalidInput` for a distance not finite or negative, or a station count outside -/// [`MIN_SAMPLES`]..=[`MAX_SAMPLES`]; a query failure when no station drops onto `from`; those -/// of the evaluations and the drops. +/// [`MIN_SAMPLES`]..=[`MAX_SAMPLES`]; [`QueryFailure::NoStationDropped`] when no station drops +/// onto `from`; those of the evaluations and the drops. pub fn distance_deviation( k: &Kernel, c: &Curve, @@ -170,7 +169,7 @@ pub fn distance_deviation( }); } } - worst.ok_or_else(|| SolidError::query_failed(OP, "no station dropped onto the other")) + worst.ok_or_else(|| SolidError::query(OP, QueryFailure::NoStationDropped)) } /// How far curve `c` strays from `surface` over its parameter box `domain`, at `samples` diff --git a/solidcore/crates/solidcore/src/query/distance_bound.rs b/solidcore/crates/solidcore/src/query/distance_bound.rs index 5977ee9188f..f8b436803b0 100644 --- a/solidcore/crates/solidcore/src/query/distance_bound.rs +++ b/solidcore/crates/solidcore/src/query/distance_bound.rs @@ -24,6 +24,7 @@ use std::cmp::Ordering; use std::collections::BinaryHeap; use crate::blend::fillet_section::station::as_b_spline; +use crate::error::query::QueryFailure; use crate::geom::certified::above; use crate::geom::extent2d::Extent2d; use crate::kernel::Kernel; @@ -146,36 +147,19 @@ impl Piece { let (rl, rr) = r.split_v(0.5); [ll, lr, rl, rr] }; - let [x, y, z, w] = [ - split(&self.h[0]), - split(&self.h[1]), - split(&self.h[2]), - split(&self.h[3]), - ]; + let [x0, x1, x2, x3] = split(&self.h[0]); + let [y0, y1, y2, y3] = split(&self.h[1]); + let [z0, z1, z2, z3] = split(&self.h[2]); + let [w0, w1, w2, w3] = split(&self.h[3]); let [u0, u1, v0, v1] = self.uv; let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1)); - let rects = [ - [u0, um, v0, vm], - [u0, um, vm, v1], - [um, u1, v0, vm], - [um, u1, vm, v1], - ]; - let mut out = Vec::new(); - for (i, uv) in rects.into_iter().enumerate() { - let pick = |a: &[Bernstein2; 4]| { - a.get(i).cloned().ok_or_else(|| { - SolidError::query_failed(OP, "a split patch has fewer than four quarters") - }) - }; - out.push(Self::new( - [pick(&x)?, pick(&y)?, pick(&z)?, pick(&w)?], - err, - self.depth + 1, - uv, - )?); - } - out.try_into() - .map_err(|_| SolidError::query_failed(OP, "a split patch has fewer than four quarters")) + let depth = self.depth + 1; + Ok([ + Self::new([x0, y0, z0, w0], err, depth, [u0, um, v0, vm])?, + Self::new([x1, y1, z1, w1], err, depth, [u0, um, vm, v1])?, + Self::new([x2, y2, z2, w2], err, depth, [um, u1, v0, vm])?, + Self::new([x3, y3, z3, w3], err, depth, [um, u1, vm, v1])?, + ]) } } @@ -386,7 +370,8 @@ pub fn measurable(k: &Kernel, surf: &Surface) -> Result { /// # Errors /// /// `InvalidInput` for a point or `want` not finite, `want` negative, or a UV box not inside -/// the patches' knot range (to its rounding); `Unsupported` for a surface without a NURBS +/// the patches' knot range (to its rounding); [`QueryFailure::NoPatchInBox`] for a box inside +/// that rounding but past every patch; `Unsupported` for a surface without a NURBS /// form, a 2D form, or weights not proved positive; those of making the form and of its /// Bézier decomposition. pub fn surface_distance_lower_bound( @@ -411,10 +396,12 @@ pub fn surface_distance_lower_bound( let mut heap: BinaryHeap = pieces.into_iter().collect(); let off = |lower: f64| (lower - slack).max(0.0); loop { - // (the box is inside the patches' range, so some patch overlaps it) + // (empty only at the start, for a box within the range's rounding but past every + // patch, or a decomposition with no patch: each piece popped later is bounded or + // replaced by its quarters) let nearest = heap .pop() - .ok_or_else(|| SolidError::query_failed(OP, "no patch overlaps the UV box"))?; + .ok_or_else(|| SolidError::query(OP, QueryFailure::NoPatchInBox))?; if nearest.lower >= want_net || made >= MAX_PATCHES { return Ok(off(nearest.lower)); } @@ -563,7 +550,7 @@ pub(crate) fn pieces_about( let (Some(&u0), Some(&u1), Some(&v0), Some(&v1)) = (uk.first(), uk.last(), vk.first(), vk.last()) else { - return Err(SolidError::query_failed(OP, "a patch has no knots")); + return Err(SolidError::query(OP, QueryFailure::Defect { why: "a patch of the surface's Bézier decomposition has no knots, though the decomposition gives each patch the knots of its span" })); }; // the part of the patch inside the UV box, in the patch's [0, 1]^2 let (mut a0, mut a1, mut b0, mut b1) = (0.0, 1.0, 0.0, 1.0); @@ -1113,6 +1100,32 @@ mod tests { } } + /// A UV box inside the rounding of the patches' knot range but past every patch leaves + /// no piece to bound: the caller's box, named. + #[test] + fn a_box_past_every_patch_is_refused_by_name() { + use crate::error::query::QueryFailure; + let k = Kernel::default(); + let dom = Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0); + let plane = Plane::new( + Point3::new(0.0, 0.0, 0.0), + Vec3::X, + Vec3::Y, + Vec2::new(1.0, 1.0), + &dom, + ); + let s = Surface::from(plane); + let full = s.natural_uv_domain_with_nurb(&k).unwrap(); + let u1 = full.max().x; + let du = 4.0 * f64::EPSILON * u1.abs().max(1.0); + let past = Extent2d::from_bounds(u1, full.min().y, u1 + du, full.max().y); + let p = Point3::new(0.5, 0.5, 1.0); + let e = surface_distance_lower_bound(&k, &s, Some(&past), p, 0.0).unwrap_err(); + assert_eq!(e.query_failure(), Some(&QueryFailure::NoPatchInBox), "{e}"); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + } + /// A flat rational sheet far from the origin, the point just above it: `z = hz` exactly /// (hz and the weights have short mantissas, so every `Z W = hz W` is exact), and /// translating to the point rounds each `p.z W` on the size of `p`, far above the diff --git a/solidcore/crates/solidcore/src/query/face_surface.rs b/solidcore/crates/solidcore/src/query/face_surface.rs index ea137d13ea0..596fc684447 100644 --- a/solidcore/crates/solidcore/src/query/face_surface.rs +++ b/solidcore/crates/solidcore/src/query/face_surface.rs @@ -11,6 +11,7 @@ //! Deviations: this convenience entry point binds the arena face and its trimmed //! cache before delegating to the existing surface solver. No recursion. +use crate::error::query::QueryFailure; use crate::geom::extent2d::Extent2d; use crate::geom::global_solver::{SolutionRequested, SolverOperation}; use crate::nurbs::knots::Side; @@ -48,7 +49,10 @@ pub fn face_surface_intersect( ) -> Result { let surface = face::surface(brep, id)? .ok_or_else(|| { - SolidError::query_missing("query::face_surface_intersect", "the face's surface") + SolidError::query( + "query::face_surface_intersect", + QueryFailure::FaceWithoutSurface, + ) })? .clone_for_evaluation()?; let domain = face::uv_domain(brep, id)?; @@ -109,7 +113,9 @@ pub fn face_surface_feet( points: &[Point3], ) -> Result>> { let stored = face::surface(brep, id)? - .ok_or_else(|| SolidError::query_missing("query::face_surface_feet", "the face's surface"))? + .ok_or_else(|| { + SolidError::query("query::face_surface_feet", QueryFailure::FaceWithoutSurface) + })? .clone_for_evaluation()?; let surface = untrimmed(k, stored, points)?; let domain = surface.natural_uv_domain_with_nurb(k)?; @@ -190,3 +196,27 @@ fn surface_foot( let along = (p - foot.point).cross(normal).length(); Ok((along <= tolerance).then_some(foot)) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::error::query::QueryFailure; + + /// A face of the caller's body without a surface is the caller's input, named, with + /// upstream's null-pointer status. + #[test] + fn a_face_without_a_surface_is_refused_by_name() { + let k = Kernel::default(); + let mut b = Brep::new(); + let f = crate::query::face::p2::tests::square(&mut b); + b.face_mut(f).unwrap().surface = None; + let e = face_surface_feet(&k, &b, f, &[Point3::new(0.0, 0.0, 0.0)]).unwrap_err(); + assert_eq!( + e.query_failure(), + Some(&QueryFailure::FaceWithoutSurface), + "{e}" + ); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR_NULL_POINTER)); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + } +} diff --git a/solidcore/crates/solidcore/src/query/normal.rs b/solidcore/crates/solidcore/src/query/normal.rs index eae4ce470ed..62b6defcae7 100644 --- a/solidcore/crates/solidcore/src/query/normal.rs +++ b/solidcore/crates/solidcore/src/query/normal.rs @@ -63,6 +63,7 @@ use crate::blend::fillet_section::definition_box::{definition_partials_naive, gn_def_face_of}; use crate::blend::fillet_section::interval::{round_up, Ivl}; use crate::blend::fillet_section::station::{as_b_spline, Nurbs}; +use crate::error::query::QueryFailure; use crate::error::{Result, SolidError}; use crate::kernel::Kernel; use crate::math::{Point2, Vec3}; @@ -210,7 +211,7 @@ fn degenerate() -> SolidError { fn exact_of<'a>(k: &Kernel, surface: &'a Surface) -> Result> { let net = |b: &'a crate::nurbs::b_spline_surface::BSplineSurface| { b.gw_nurb() - .ok_or_else(|| SolidError::query_failed(OP, "the B-spline surface's NURBS net")) + .ok_or_else(|| SolidError::query(OP, QueryFailure::SurfaceWithoutNurbs)) }; let mut s = surface; for _ in 0..MAX_HOPS { @@ -341,7 +342,7 @@ fn definition_jet( } })?; let bs = as_b_spline(k, s)? - .ok_or_else(|| SolidError::query_failed(OP, "the surface's B-spline form"))?; + .ok_or_else(|| SolidError::query(OP, QueryFailure::Defect { why: "a blend's definition is read only for a procedural blend, whose net is the B-spline form as_b_spline returns for it" }))?; let net = Nurbs::of(&bs)?; let ku = span(&net.u, net.p, net.nu.saturating_sub(1), uv.x) .ok_or_else(|| unsupported("(u, v) outside the blend's net"))?;