diff --git a/solidcore/crates/solidcore/src/error/surface.rs b/solidcore/crates/solidcore/src/error/surface.rs index 6b0b9e9d35d..fed0e317c60 100644 --- a/solidcore/crates/solidcore/src/error/surface.rs +++ b/solidcore/crates/solidcore/src/error/surface.rs @@ -42,13 +42,13 @@ //! the failure's `operation` path says which routine. A failure names an entity only where the //! site it replaces named one (a blend face whose net fails its re-certification). A check of a //! caller's argument that reports no status stays [`crate::SolidError::InvalidInput`]; one that -//! reports a status is a named cause of class `invalid_input`, keeping that status. Only part of -//! `crate::surface` uses these yet; the files that still build bare statuses are listed in this -//! module's ratchet test. +//! reports a status is a named cause of the class the paragraph above gives, keeping that +//! status. Only part of `crate::surface` uses these yet; the files that still build bare +//! statuses are listed in this module's ratchet test. use super::{ ErrorKind, Failure, Reason, SM_ERR, SM_ERR_INVALID_INPUT, SM_ERR_NOT_WITHIN_TOLERANCE, - SM_ERR_NULL_POINTER, SM_ERR_OUTSIDE_OF_DOMAIN, + SM_ERR_NULL_POINTER, SM_ERR_OUTSIDE_OF_DOMAIN, SM_ERR_WARNING, }; /// Why a surface routine fails. @@ -473,6 +473,52 @@ pub enum SurfaceFailure { /// not finite), though the bracket's upper end was made (whether an extension can be made /// is not monotone in the ask). Class `failed`. ExtensionNotMadeInBracket, + /// The solve operation asked for is not one the routine takes (a plane's fast drop + /// takes minimize, normalize and intersect). [`ErrorKind::InvalidInput`]. + OperationNotTaken, + /// The line given is not parallel to the plane within the angle test, but the + /// determinant of the crossing's linear solve is below the kernel's zero (a line + /// direction or plane scale too small to solve with). [`ErrorKind::Degenerate`]. + LineCrossingSingular, + /// The line where two planes meet is too nearly singular to solve for (a pivot below + /// the kernel's zero), so it is not built. Upstream's warning: status + /// `SM_ERR_WARNING`, class `failed`. + PlanesLineNearlySingular, + /// The trim domain given is not inside the surface's natural domain. + /// [`ErrorKind::OutsideDomain`]. + TrimDomainOutside, + /// The NURB tested as a plane has parallel u and v directions at its origin, so it has + /// no plane frame (the unitize's error is the cause). [`ErrorKind::Degenerate`]. + NurbAxesParallel, + /// The transformed plane's tangents cannot be measured: its NURB's evaluation cannot + /// make them non-zero (they are below the surface's derivative limit; its error is the + /// cause), or the squared length of a tangent or of their cross product is not above the + /// kernel's zero squared, or not finite. A uniform scale so small or so large takes the + /// plane outside what the kernel resolves. [`ErrorKind::Degenerate`]. + PlaneTangentUnmeasurable, + /// The evaluation of the surface's NURB form failed (its error is the cause). Class + /// `failed`; whether it is a defect or a refusal is its cause's. + NurbEvaluationFailed, + /// The domain given reaches past the cone's apex, where its radius would be negative. + /// [`ErrorKind::OutsideDomain`]. + DomainPastApex, + /// The iso curve asked for has zero length (its parameter range on the surface is + /// degenerate). [`ErrorKind::InvalidInput`]. + DegenerateIsoCurve, + /// The surface of revolution has no polar converter circle (its NURB form was never + /// made or read, or both sweep iso curves were degenerate when it was, which the make + /// does not report). Class `failed`. + NoPolarConverter, + /// The surface is not a cylinder with a radius above the kernel's zero, which the + /// routine takes. [`ErrorKind::Unsupported`]. + NotACylinder, + /// The cone the routine would build passes its apex within the surface's span: its + /// radius at a control point of the net is not above the kernel's zero. + /// [`ErrorKind::Degenerate`]. + ConeClosesWithinSpan, + /// The lean's slope or neutral height is NaN or infinite, or the radius law they give + /// overflows at a control point of the net. [`ErrorKind::InvalidInput`]. + LeanNotFinite, } /// An input of a surface routine that its caller did not give @@ -528,6 +574,24 @@ pub enum AnalyticCheck { MeridianOnAxis, /// Its generator circle, built from its first iso curve, is degenerate. GeneratorDegenerate, + /// Its iso curves at the two ends are not circular arcs. + EndsNotCircular, + /// Its end arcs' start or end angles differ by more than the tolerance. + EndArcsTwisted, + /// The distance between its end arcs' centres is degenerate. + HeightDegenerate, + /// The plane of its bottom arc is not perpendicular to the axis. + BottomNotSquareToAxis, + /// The plane of its top arc is not perpendicular to the axis. + TopNotSquareToAxis, + /// It is a cylinder's, and its end radii differ by more than the cylinder's tolerance. + RadiiDiffer, + /// Moved onto the mean-radius cylinder, its net would have a radius not above zero at + /// a control point. + NetRadiusNotPositive, + /// Moved onto the mean-radius cylinder, its net is not on that cylinder (its end + /// circles are turned against each other or off the axis). + NetOffCylinder, } impl core::fmt::Display for AnalyticCheck { @@ -539,6 +603,18 @@ impl core::fmt::Display for AnalyticCheck { "a meridian at an end of its sweep has no control point off the axis on its side" } Self::GeneratorDegenerate => "its generator circle is degenerate", + Self::EndsNotCircular => "its end iso curves are not circular", + Self::EndArcsTwisted => "its end arcs' angles differ by more than the tolerance", + Self::HeightDegenerate => "its height is degenerate", + Self::BottomNotSquareToAxis => { + "its bottom arc's plane is not perpendicular to the axis" + } + Self::TopNotSquareToAxis => "its top arc's plane is not perpendicular to the axis", + Self::RadiiDiffer => "its top and bottom radii differ", + Self::NetRadiusNotPositive => { + "its net has no positive radius at a control point on the mean-radius cylinder" + } + Self::NetOffCylinder => "its moved net is not on the mean-radius cylinder", }) } } @@ -586,13 +662,17 @@ impl SurfaceFailure { | Self::SurfaceWithoutGenerator | Self::GeneratorNotMade | Self::NoInputStream - | Self::SurfaceNotBSplineKind => SM_ERR_NULL_POINTER, + | Self::SurfaceNotBSplineKind + | Self::NoPolarConverter => SM_ERR_NULL_POINTER, Self::InvalidValue(_) | Self::LineDirectionZero | Self::NormalsCancel - | Self::RecordDoesNotRebuild => SM_ERR_INVALID_INPUT, + | Self::RecordDoesNotRebuild + | Self::DomainPastApex + | Self::DegenerateIsoCurve => SM_ERR_INVALID_INPUT, Self::OutsideDomain(_) => SM_ERR_OUTSIDE_OF_DOMAIN, Self::OffSurface(_) => SM_ERR_NOT_WITHIN_TOLERANCE, + Self::PlanesLineNearlySingular => SM_ERR_WARNING, _ => SM_ERR, } } @@ -637,13 +717,18 @@ impl SurfaceFailure { | Self::CurveDimensionTooLarge | Self::RecordDoesNotRebuild | Self::DoesNotContinueAsItself - | Self::OffsetNestedTooDeep => ErrorKind::InvalidInput, + | Self::OffsetNestedTooDeep + | Self::OperationNotTaken + | Self::DegenerateIsoCurve + | Self::LeanNotFinite => ErrorKind::InvalidInput, Self::BoxOutsideBendHalfSpace { .. } | Self::BoxOutsideZeroPeriod { .. } | Self::PointOutsideVolumeDomain { .. } | Self::PointOutsideGivenDomain { .. } | Self::BoxOutsideParamDomain - | Self::PseudoBoxOutsideDomain => ErrorKind::OutsideDomain, + | Self::PseudoBoxOutsideDomain + | Self::TrimDomainOutside + | Self::DomainPastApex => ErrorKind::OutsideDomain, Self::IsoCurveKindNotLiftable | Self::DerivativeCombinationUnsupported { .. } | Self::PlainVolume @@ -653,7 +738,8 @@ impl SurfaceFailure { | Self::AtPole | Self::NurbNotAnalytic { .. } | Self::SurfaceNotBSplineKind - | Self::NoBSplineForm => ErrorKind::Unsupported, + | Self::NoBSplineForm + | Self::NotACylinder => ErrorKind::Unsupported, Self::PointInBendSingularity | Self::ZeroVolumeTangent { .. } | Self::ZeroLengthTangent @@ -662,7 +748,11 @@ impl SurfaceFailure { | Self::NormalsCancel | Self::TangentAlongNormal | Self::TooFewUniqueKnots - | Self::ReferencePointOnBoundary => ErrorKind::Degenerate, + | Self::ReferencePointOnBoundary + | Self::LineCrossingSingular + | Self::NurbAxesParallel + | Self::PlaneTangentUnmeasurable + | Self::ConeClosesWithinSpan => ErrorKind::Degenerate, Self::SolveCacheNotMade | Self::BlendSurfaceNotMade | Self::MergedRangeReversed { .. } @@ -685,7 +775,9 @@ impl SurfaceFailure { | Self::NoTangentTowardDirection | Self::NurbNotMade | Self::GeneratorNotMade - | Self::CentreHasNoParameters => ErrorKind::Failed, + | Self::CentreHasNoParameters + | Self::NurbEvaluationFailed + | Self::NoPolarConverter => ErrorKind::Failed, _ => ErrorKind::of_status(self.comparison_status()), } } @@ -914,6 +1006,41 @@ impl core::fmt::Display for SurfaceFailure { Self::ExtensionNotMadeInBracket => f.write_str( "an extension asked inside the solve's bracket could not be made, though its upper end was made", ), + Self::OperationNotTaken => { + f.write_str("the solve operation is not one the routine takes") + } + Self::LineCrossingSingular => { + f.write_str("the line's crossing with the plane is singular to solve for") + } + Self::PlanesLineNearlySingular => { + f.write_str("the planes' line is nearly singular to solve for") + } + Self::TrimDomainOutside => { + f.write_str("the trim domain is not inside the surface's natural domain") + } + Self::NurbAxesParallel => { + f.write_str("the NURB's u and v directions are parallel at its origin") + } + Self::PlaneTangentUnmeasurable => { + f.write_str("the transformed plane's tangents are outside what the kernel resolves") + } + Self::NurbEvaluationFailed => { + f.write_str("the evaluation of the surface's NURB form failed") + } + Self::DomainPastApex => f.write_str("the domain reaches past the apex"), + Self::DegenerateIsoCurve => f.write_str("the iso curve has zero length"), + Self::NoPolarConverter => { + f.write_str("the surface of revolution has no polar converter circle") + } + Self::NotACylinder => { + f.write_str("the surface is not a cylinder with a positive radius") + } + Self::ConeClosesWithinSpan => { + f.write_str("the cone would pass its apex within the surface's span") + } + Self::LeanNotFinite => { + f.write_str("the lean's slope, neutral height or radius is not finite") + } } } } @@ -1458,6 +1585,137 @@ mod tests { } } + /// The named causes keep the status of the phrase each replaced, so `upstream_status` + /// (which most goldens units read) is unchanged; their class says whose the failure is, + /// and a cause chained under one decides whether it is a defect. + #[test] + fn the_analytic_and_swept_causes_keep_their_status_and_say_their_class() { + let op = "surface::op"; + let cases = [ + ( + SurfaceFailure::OperationNotTaken, + SM_ERR, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::LineCrossingSingular, + SM_ERR, + ErrorKind::Degenerate, + ), + ( + SurfaceFailure::PlanesLineNearlySingular, + SM_ERR_WARNING, + ErrorKind::Failed, + ), + ( + SurfaceFailure::ScaleNotUniform, + SM_ERR, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::TrimDomainOutside, + SM_ERR, + ErrorKind::OutsideDomain, + ), + ( + SurfaceFailure::NurbAxesParallel, + SM_ERR, + ErrorKind::Degenerate, + ), + ( + SurfaceFailure::PlaneTangentUnmeasurable, + SM_ERR, + ErrorKind::Degenerate, + ), + (SurfaceFailure::NurbNotMade, SM_ERR, ErrorKind::Failed), + ( + SurfaceFailure::NurbEvaluationFailed, + SM_ERR, + ErrorKind::Failed, + ), + ( + SurfaceFailure::RadiusNotPositive, + SM_ERR, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::SurfaceWithoutGenerator, + SM_ERR_NULL_POINTER, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::DomainPastApex, + SM_ERR_INVALID_INPUT, + ErrorKind::OutsideDomain, + ), + ( + SurfaceFailure::DerivativeOrderTooHigh { max: 3 }, + SM_ERR, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::DegenerateIsoCurve, + SM_ERR_INVALID_INPUT, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::NoPolarConverter, + SM_ERR_NULL_POINTER, + ErrorKind::Failed, + ), + (SurfaceFailure::NotACylinder, SM_ERR, ErrorKind::Unsupported), + ( + SurfaceFailure::ConeClosesWithinSpan, + SM_ERR, + ErrorKind::Degenerate, + ), + ( + SurfaceFailure::LeanNotFinite, + SM_ERR, + ErrorKind::InvalidInput, + ), + ( + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::EndArcsTwisted, + }, + SM_ERR, + ErrorKind::Unsupported, + ), + ]; + for (failure, status, kind) in cases { + let e = SolidError::surface(op, failure); + assert_eq!(e.sm_status(), Some(status), "{failure:?}"); + assert_eq!( + super::super::upstream_status(&e), + Some(status), + "{failure:?}" + ); + assert_eq!(e.kind(), kind, "{failure:?}"); + assert_eq!(e.operation(), op, "{failure:?}"); + assert_eq!(e.surface_failure(), Some(&failure)); + assert!(!e.is_defect() && !e.is_refusal(), "{failure:?}"); + } + assert_eq!( + SolidError::surface( + op, + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::HeightDegenerate + } + ) + .to_string(), + "surface::op: the NURB is not of the analytic kind: its height is degenerate" + ); + // a NURB not made keeps the site's status, and its make's defect decides the class + let made = Err(SolidError::surface(op, SurfaceFailure::Defect { why: "x" })); + let e = SolidError::surface_nurb_not_made(op, SM_ERR_NULL_POINTER, made); + assert_eq!(e.sm_status(), Some(SM_ERR_NULL_POINTER)); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::NurbNotMade)); + assert!(e.is_defect()); + let e = SolidError::surface_nurb_not_made(op, SM_ERR, Ok(())); + assert_eq!(e.sm_status(), Some(SM_ERR)); + assert!(e.cause().is_none() && !e.is_defect()); + } + /// The named causes of the surface extensions and the ball patch keep the status of the /// phrase causes they replaced (a site whose status differs from the cause's own keeps /// it through `with_status`), with the kind their condition is: the caller's input, or a @@ -1669,11 +1927,7 @@ mod tests { }; #[rustfmt::skip] // one file per line, so conversions in parallel merge cleanly const PINNED: &[(&str, usize)] = &[ - ("solidcore/src/surface/cone/p1.rs", 12), - ("solidcore/src/surface/cone/p2.rs", 14), ("solidcore/src/surface/cone/p3.rs", 3), - ("solidcore/src/surface/plane/p1.rs", 3), - ("solidcore/src/surface/plane/p2.rs", 9), ("solidcore/src/surface/surf_of_extrusion/p1.rs", 16), ("solidcore/src/surface/surf_of_extrusion/p2.rs", 13), ("solidcore/src/surface/surf_of_revolution/p1.rs", 10), diff --git a/solidcore/crates/solidcore/src/surface/cone/p1.rs b/solidcore/crates/solidcore/src/surface/cone/p1.rs index 98990cb23bd..2f6a7f340f1 100644 --- a/solidcore/crates/solidcore/src/surface/cone/p1.rs +++ b/solidcore/crates/solidcore/src/surface/cone/p1.rs @@ -135,7 +135,9 @@ use crate::curve::curve::p2::{CIRCLE_TYPE, LINE_TYPE}; use crate::curve::curve::{Curve, CurveKind}; use crate::curve::ellipse::{Ellipse, EllipseOptions}; use crate::curve::line::{BoundedLineOptions, Line}; -use crate::error::{ignore_status, ignored, Result, SolidError}; +use crate::error::{ + ignore_status, ignored, Failure, Result, SolidError, SM_ERR, SM_ERR_NULL_POINTER, +}; use crate::geom::axis2_placement::Axis2Placement; use crate::geom::extent1d::Extent1d; use crate::geom::extent2d::Extent2d; @@ -298,9 +300,9 @@ pub(crate) fn cone_convert_uv_from_nurbs_to_step_exact( }; // convert sweep coordinate - let circle = rev.polar_curve().ok_or_else(|| { - SolidError::surface_missing(OP_TO_STEP, "the polar curve of the surface of revolution") - })?; + let circle = rev + .polar_curve() + .ok_or_else(|| SolidError::surface(OP_TO_STEP, SurfaceFailure::NoPolarConverter))?; let (x, exact) = rev.polar.convert_to_polar_parameter(k, circle, nurb_uv.x)?; // convert linear coordinate @@ -472,7 +474,7 @@ pub(crate) fn cone_iso_curve( if length < scaled_zero { return Err(SolidError::surface( OP_ISO, - SurfaceFailure::InvalidValue("the iso line has zero length"), + SurfaceFailure::DegenerateIsoCurve, )); } let scale = length / line_vec.dot(cone_z_axis); @@ -765,10 +767,15 @@ impl Cone { /// (whose query makes the cone's NURB when missing). fn adjust_gen_line_with_owner(&mut self, k: &Kernel, ivl: &Extent1d) -> Result<()> { let Some(CurveKind::Line(line)) = self.rev.gen_curve.as_mut().map(Curve::kind_mut) else { - return Err(SolidError::surface_missing( + return Err(Failure::new( OP_GEN, - "the cone's generator line", - )); + SurfaceFailure::Defect { + why: "the cone's generator is not a line, though its one caller, the cone's \ + construction, set it to a line just before", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error()); }; let dom = line.step_interval(); if ivl.is_contained_by(&dom, EFF_ZERO) && dom.is_contained_by(ivl, EFF_ZERO) { @@ -938,18 +945,16 @@ impl Cone { // Build NURB; fail cleanly if degenerate (single zero-radius apex is valid). match self.make_nurb(k) { Err(e) if e.is_unported_or_cancelled() => return Err(e), - Err(_) => { - return Err(SolidError::surface_failed( - operation, - "the cone's NURB could not be made", - )) - } + Err(e) => return Err(SolidError::surface_nurb_not_made(operation, SM_ERR, Err(e))), Ok(()) => {} } if self.rev.base.gw_nurb().is_none() { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( operation, - "the cone has no NURB", + SurfaceFailure::Defect { + why: "the cone's make_nurb returned success yet left no NURB, though on \ + success it sets the NURB of the revolution it builds", + }, )); } Ok(self) @@ -1077,9 +1082,9 @@ impl Cone { ) -> Result { // Reject non-positive radius (ctor assert is a no-op in release). if radius.partial_cmp(&EFF_ZERO) != Some(core::cmp::Ordering::Greater) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_CYL_CANONICAL, - "the cylinder's radius is not positive", + SurfaceFailure::RadiusNotPositive, )); } let cylinder = Self::new_cylinder_unbounded( @@ -1239,7 +1244,7 @@ impl Cone { self.rev .gen_curve .as_ref() - .ok_or_else(|| SolidError::surface_missing(OP_GEN, "the cone's generator curve")) + .ok_or_else(|| SolidError::surface(OP_GEN, SurfaceFailure::SurfaceWithoutGenerator)) } // ---- equality ------------------------------------------------------------------- @@ -1281,16 +1286,10 @@ impl Cone { // Method: just call the parent's version, // unless the new domain would result in going past the apex. let v_domain = new_step_uv_domain.v_interval(); - if self.radius(v_domain.min()) < -EFF_ZERO { + if self.radius(v_domain.min()) < -EFF_ZERO || self.radius(v_domain.max()) < -EFF_ZERO { return Err(SolidError::surface( OP_ADJUST, - SurfaceFailure::InvalidValue("the domain reaches past the apex"), - )); - } - if self.radius(v_domain.max()) < -EFF_ZERO { - return Err(SolidError::surface( - OP_ADJUST, - SurfaceFailure::InvalidValue("the domain reaches past the apex"), + SurfaceFailure::DomainPastApex, )); } @@ -1619,11 +1618,10 @@ impl Cone { rows } Err(e) if e.is_unported_or_cancelled() => return Err(e), - Err(_) => { - return Err(SolidError::surface_failed( - OP_EVAL, - "the cone's NURB evaluation failed", - )) + Err(e) => { + return Err(Failure::new(OP_EVAL, SurfaceFailure::NurbEvaluationFailed) + .caused_by(e) + .into_error()) } } } else { @@ -1692,9 +1690,9 @@ impl Cone { ) -> Result<()> { // check input if hu > 3 || hv > 3 { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_EVAL_STEP, - "the STEP form evaluates derivatives up to order 3 only", + SurfaceFailure::DerivativeOrderTooHigh { max: 3 }, )); // Not implemented } @@ -1974,9 +1972,9 @@ impl Cone { if let Some(s) = opt_scale { if !are_same(s.x, s.y) || !are_same(s.x, s.z) || s.x < EFF_ZERO { // Unable to scale analytical surfaces non-uniformly - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_TRANSFORM, - "an analytic surface cannot be scaled non-uniformly", + SurfaceFailure::ScaleNotUniform, )); } scale = s.x; @@ -2419,10 +2417,9 @@ mod tests { assert_eq!(e.upstream_status(), Some(SM_ERR)); assert_eq!( e.surface_failure(), - Some(&SurfaceFailure::Failed( - "the cylinder's radius is not positive" - )) + Some(&SurfaceFailure::RadiusNotPositive) ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); let c = Cone::create_canonical_cylinder(&k(), &std_placement(), 2.0).unwrap(); assert!(c.is_cylinder() && c.is_cylinder_class()); assert_eq!(c.type_code(), CYLINDER_TYPE); @@ -2488,9 +2485,11 @@ mod tests { let e = c .convert_uv_from_nurbs_to_step(&k(), Point2::new(0.5, 0.5)) .unwrap_err(); - assert_eq!(e.upstream_status(), Some(crate::error::SM_ERR_NULL_POINTER)); + assert_eq!(e.upstream_status(), Some(SM_ERR_NULL_POINTER)); assert_eq!(e.operation(), OP_TO_STEP); - assert_eq!(e.kind(), crate::error::ErrorKind::Missing); + // the degenerate sweep iso curve left no polar converter after a successful make + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::NoPolarConverter)); + assert_eq!(e.kind(), crate::error::ErrorKind::Failed); } #[test] @@ -2522,12 +2521,7 @@ mod tests { Some(crate::error::SM_ERR_INVALID_INPUT) ); assert_eq!(e.operation(), OP_ADJUST); - assert_eq!( - e.surface_failure(), - Some(&SurfaceFailure::InvalidValue( - "the domain reaches past the apex" - )) - ); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::DomainPastApex)); // the parent's AdjustSTEPUVDomain is ported (surf_of_revolution_p2) assert!(c .adjust_step_uv_domain(&k(), &Extent2d::from_bounds(0.0, 0.0, 360.0, 1.0)) @@ -2542,7 +2536,8 @@ mod tests { .unwrap_err(); assert_eq!(e.upstream_status(), Some(SM_ERR)); assert_eq!(e.operation(), OP_TRANSFORM); - assert_eq!(e.kind(), crate::error::ErrorKind::Failed); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::ScaleNotUniform)); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); assert!(c .transform( &k(), @@ -2983,29 +2978,61 @@ mod tests { } } - /// The cone's failures keep the operation, status, kind and entity of the bare - /// `Upstream` statuses they replace (a sample). + /// A cone without generator (an empty one, whose data was never read) is the caller's, + /// with upstream's `SM_ERR_NULL_POINTER`. + #[test] + fn a_cone_without_generator_is_the_callers() { + let e = Cone::empty(true).max_analytic_domain(&k()).unwrap_err(); + assert_eq!(e.sm_status(), Some(SM_ERR_NULL_POINTER)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::SurfaceWithoutGenerator) + ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + } + + /// A STEP evaluation past order 3 is the caller's argument, refused by name with + /// upstream's `SM_ERR`. + #[test] + fn a_derivative_past_order_3_is_the_callers() { + let e = cone123() + .evaluate_step(Point2::new(10.0, 1.0), 4, 0) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(SM_ERR)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::DerivativeOrderTooHigh { max: 3 }) + ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + } + + /// The cone's failures keep the operation, status and entity of the bare `Upstream` + /// statuses they replace (a sample); their class is the cause's. #[test] fn typed_surface_failures_keep_their_upstream_answers() { use crate::error::surface::SurfaceFailure; - let samples: [(&'static str, SurfaceFailure, i32); 3] = [ + use crate::error::ErrorKind; + let samples: [(&'static str, SurfaceFailure, i32, ErrorKind); 3] = [ ( OP_GEN, - SurfaceFailure::Missing("the cone's generator curve"), - crate::error::SM_ERR_NULL_POINTER, + SurfaceFailure::SurfaceWithoutGenerator, + SM_ERR_NULL_POINTER, + ErrorKind::InvalidInput, ), ( OP_ISO, - SurfaceFailure::InvalidValue("the iso line has zero length"), + SurfaceFailure::DegenerateIsoCurve, crate::error::SM_ERR_INVALID_INPUT, + ErrorKind::InvalidInput, ), ( OP_EVAL_STEP, - SurfaceFailure::Failed("the STEP form evaluates derivatives up to order 3 only"), + SurfaceFailure::DerivativeOrderTooHigh { max: 3 }, SM_ERR, + ErrorKind::InvalidInput, ), ]; - for (operation, failure, code) in samples { + for (operation, failure, code, kind) in samples { let typed = SolidError::surface(operation, failure); let before = SolidError::Upstream { operation, @@ -3014,7 +3041,7 @@ mod tests { }; assert_eq!(typed.sm_status(), before.sm_status(), "{typed:?}"); assert_eq!(typed.upstream_status(), Some(code), "{typed:?}"); - assert_eq!(typed.kind(), before.kind(), "{typed:?}"); + assert_eq!(typed.kind(), kind, "{typed:?}"); assert_eq!(typed.operation(), before.operation(), "{typed:?}"); assert_eq!(typed.entity(), None, "{typed:?}"); assert_eq!(typed.is_port_failure(), before.is_port_failure()); diff --git a/solidcore/crates/solidcore/src/surface/cone/p2.rs b/solidcore/crates/solidcore/src/surface/cone/p2.rs index 8ebd2bfd61f..c6be5b6a6a0 100644 --- a/solidcore/crates/solidcore/src/surface/cone/p2.rs +++ b/solidcore/crates/solidcore/src/surface/cone/p2.rs @@ -96,7 +96,8 @@ use super::Cone; use crate::curve::curve::Curve; use crate::curve::ellipse::{Ellipse, EllipseOptions}; use crate::curve::line::{BoundedLineOptions, Line}; -use crate::error::{ignore_status, ignored, Result, SolidError}; +use crate::error::surface::{AnalyticCheck, SurfaceFailure}; +use crate::error::{ignore_status, ignored, Failure, Result, SolidError, SM_ERR_NULL_POINTER}; use crate::geom::axis2_placement::Axis2Placement; use crate::geom::extent1d::Extent1d; use crate::geom::extent2d::Extent2d; @@ -576,20 +577,20 @@ impl Cone { /// /// # Errors /// - /// `SM_ERR` unless this is a cylinder with a NURB whose radius stays positive; those of - /// the control point edits and of the rebuild. + /// `SM_ERR` unless this is a cylinder with a NURB whose radius stays positive and finite + /// under a finite `slope` and `neutral_height`; those of the control point edits and of + /// the rebuild. pub fn lean_cylinder(&self, k: &Kernel, slope: f64, neutral_height: f64) -> Result { - let err = || { - SolidError::surface_failed( - "surface::cone::p2::Cone::lean_cylinder", - "the surface is not a cylinder with a NURB whose radius stays positive", - ) - }; + const OP_LEAN: &str = "surface::cone::p2::Cone::lean_cylinder"; let canonical = self.canonical(); if !self.is_cylinder() || canonical.radius.partial_cmp(&EFF_ZERO) != Some(core::cmp::Ordering::Greater) { - return Err(err()); + return Err(SolidError::surface(OP_LEAN, SurfaceFailure::NotACylinder)); + } + // a NaN or infinite radius law is the caller's, not a cone that crosses its axis + if !(slope.is_finite() && neutral_height.is_finite()) { + return Err(SolidError::surface(OP_LEAN, SurfaceFailure::LeanNotFinite)); } let origin = canonical.origin.origin(); let axis = canonical.origin.x_axis().cross(canonical.origin.y_axis()); @@ -613,8 +614,15 @@ impl Cone { let d = p - origin; let height = d.dot(axis); let radius = canonical.radius + slope * (height - neutral_height); + // finite factors whose product overflows + if !radius.is_finite() { + return Err(SolidError::surface(OP_LEAN, SurfaceFailure::LeanNotFinite)); + } if radius.partial_cmp(&EFF_ZERO) != Some(core::cmp::Ordering::Greater) { - return Err(err()); + return Err(SolidError::surface( + OP_LEAN, + SurfaceFailure::ConeClosesWithinSpan, + )); } let moved = origin + axis * height + (d - axis * height) * (radius / canonical.radius); @@ -649,11 +657,26 @@ impl Cone { /// [`crate::surface::surf_of_revolution::SurfOfRevolution::reparameterize`]. pub fn reparameterize(&mut self, k: &Kernel, trim_domain: &Extent2d) -> Result<()> { // GetOrCreateGwNurbPointer (the virtual MakeNurb with the cone's iso curves) + let mut made = Ok(()); if self.rev.base.gw_nurb().is_none() { - ignore_status(self.make_nurb(k))?; + made = self.make_nurb(k); + ignore_status(made.clone())?; } if self.rev.base.gw_nurb().is_none() { - return Err(SolidError::surface_missing(OP_REPARAM, "the cone's NURB")); + return Err(match made { + Err(e) => { + SolidError::surface_nurb_not_made(OP_REPARAM, SM_ERR_NULL_POINTER, Err(e)) + } + Ok(()) => Failure::new( + OP_REPARAM, + SurfaceFailure::Defect { + why: "the NURB is missing after make_nurb returned success, which on \ + success sets the NURB", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error(), + }); } let inside_out = self.inside_out; self.rev @@ -860,7 +883,15 @@ impl Cone { tgt_nurb_domain.v_interval() }; let gen = off_cone.rev.gen_curve.as_mut().ok_or_else(|| { - SolidError::surface_missing(OP_OFFSET, "the offset cone's generator curve") + Failure::new( + OP_OFFSET, + SurfaceFailure::Defect { + why: "the offset cone has no generator, though create_canonical \ + built it above with its generator line", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error() })?; ignore_status(gen.edit_parameterization(k, &tgt_gen_nurb_ivl))?; @@ -958,8 +989,9 @@ impl Cone { // translate the NewCone->GenCurve from current center line (status ignored) let mut mv = Axis2Placement::IDENTITY; mv.translate(off_vec); + // (the offset cone is a copy of this one: its generator is this cone's) let gen = off_cone.rev.gen_curve.as_mut().ok_or_else(|| { - SolidError::surface_missing(OP_OFFSET, "the offset cone's generator curve") + SolidError::surface(OP_OFFSET, SurfaceFailure::SurfaceWithoutGenerator) })?; ignore_status(gen.transform(k, &mv, None))?; @@ -1210,8 +1242,8 @@ impl Cone { /// # Errors /// /// Upstream's `SER` statuses (returned as a `TRUE` result without cylinder): those - /// of the iso curves; those of the degeneracy and arc tests; - /// `SM_ERR_NULL_POINTER` for a surface without NURB (upstream copies the null NURB). + /// of the iso curves; those of the degeneracy and arc tests. A surface without NURB + /// is not a cylinder (`Ok(None)`). pub fn is_nurb_surface_cylinder( k: &Kernel, test_surface: &BSplineSurface, @@ -1449,7 +1481,15 @@ impl Cone { // the cylinder's NURB is a copy of the tested one let nurb = test_surface.gw_nurb().ok_or_else(|| { - SolidError::surface_missing(OP_NURB_CYLINDER, "the tested surface's NURB") + Failure::new( + OP_NURB_CYLINDER, + SurfaceFailure::Defect { + why: "the tested surface has no NURB, though its degrees summed to 3 \ + above, which a surface without NURB cannot", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error() })?; cylinder.rev.base.nurb = Some(copy_nurb_surface(nurb)).into(); cylinder.rev.base.nurb_is_borrowed = false; @@ -1505,9 +1545,11 @@ impl Cone { let h = d.dot(z); let here = bot_radius + (top_radius - bot_radius) * (h / height); if !(here > 0.0 && here.is_finite()) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the cylinder's net has no positive radius at a control point", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::NetRadiusNotPositive, + }, )); } moved.push((i, j, centre + z * h + (d - z * h) * (radius / here), w)); @@ -1548,10 +1590,11 @@ impl Cone { tan_angle: 0.0, }; if !implicit::lies_on(&base, &cylinder)? { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the cylinder's moved net is not on the mean-radius cylinder (its end \ - circles are turned against each other or off the axis)", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::NetOffCylinder, + }, )); } Ok(base) @@ -1594,9 +1637,11 @@ impl Cone { || linear_iso_param == SurfParamType::Neither { // Modified Nurb SmCone: no longer has degree 1 and 2 basis functions - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the NURB is no longer of degree 1 by 2 and rational", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::DegreeAndRationality, + }, )); } @@ -1643,18 +1688,22 @@ impl Cone { )? else { // Modified Nurb SmCone: no longer has circular top and bottom IsoParamCurves - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the NURB's top and bottom iso curves are not circular", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::EndsNotCircular, + }, )); }; // not a cone - top/bot start angles or top/bot end angles vary by more than // tolerance if twisted(&top, &bot, ang_tol)? { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the top and bottom arcs' angles differ by more than the tolerance", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::EndArcsTwisted, + }, )); } @@ -1667,18 +1716,22 @@ impl Cone { // not a cone - height of cone is degenerate (cone is a disk) if height < Self::MIN_HEIGHT { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the cone's height is degenerate", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::HeightDegenerate, + }, )); } nurb_z_axis = nurb_z_axis.unitize_or_z(); // not a cone - bottom arc's plane is not perpendicular to cone axis if !nurb_z_axis.is_parallel_to(bot.frame.z_axis(), ang_tol) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the bottom arc's plane is not perpendicular to the axis", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::BottomNotSquareToAxis, + }, )); } // Not upstream (#16982 review): nor the top arc's. `twisted` compares only the @@ -1688,9 +1741,11 @@ impl Cone { // circle's tilt from the centre line is below `ang_tol` degrees (the far circle's // from the recorded axis, below `2 ang_tol`) if !nurb_z_axis.is_parallel_to(top.frame.z_axis(), ang_tol) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the top arc's plane is not perpendicular to the axis", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::TopNotSquareToAxis, + }, )); } @@ -1719,9 +1774,11 @@ impl Cone { bot.radius = mean; top.radius = mean; } else { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_REBUILD, - "the cylinder's top and bottom radii differ", + SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::RadiiDiffer, + }, )); } } @@ -2773,7 +2830,13 @@ mod tests { let top = radius + sign * EFF_ZERO_SQRT * (1.0 + radius); let mut c = edited_cylinder(&k, radius, top, swap, inside); let before = c.clone(); - assert!(c.rebuild_step_from_nurb_parameters(&k).is_err()); + let e = c.rebuild_step_from_nurb_parameters(&k).unwrap_err(); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::RadiiDiffer + }) + ); assert_eq!(c.base_radius(), before.base_radius()); assert_eq!(c.semi_angle_deg(), before.semi_angle_deg()); assert_eq!(c.rev().position(), before.rev().position()); @@ -2814,6 +2877,21 @@ mod tests { let before = c.clone(); let result = c.rebuild_step_from_nurb_parameters(&k); assert_eq!(result.is_err(), refused, "{tilt_deg} {swap} {inside}"); + // the tilted row is the NURB's last; with swap and inside the rebuild + // reads it as its bottom or its top arc, so one of the two + // square-to-axis checks refuses it + if let Err(e) = &result { + assert!( + matches!( + e.surface_failure(), + Some(&SurfaceFailure::NurbNotAnalytic { + check: AnalyticCheck::BottomNotSquareToAxis + | AnalyticCheck::TopNotSquareToAxis + }) + ), + "{swap} {inside}: {e}" + ); + } if refused { assert_eq!(c.base_radius(), before.base_radius()); assert_eq!(c.semi_angle_deg(), before.semi_angle_deg()); @@ -3353,8 +3431,37 @@ mod tests { assert!(d_old.cross(d_new).length() < 1e-9 * 25.0, "{uv:?}"); } } - // a radius that would go through the axis is refused - assert!(cylinder.lean_cylinder(&k, 2.0, 4.0).is_err()); + // a radius that would go through the axis is refused, and so is a surface that is + // not a cylinder + let e = cylinder.lean_cylinder(&k, 2.0, 4.0).unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::ConeClosesWithinSpan) + ); + assert_eq!(e.kind(), crate::error::ErrorKind::Degenerate); + // a NaN or infinite slope or neutral height, or a finite pair whose radius law + // overflows, is the caller's: invalid input, not a cone through the axis + for (s, h) in [ + (f64::NAN, 4.0), + (slope, f64::NAN), + (f64::INFINITY, 4.0), + (slope, f64::NEG_INFINITY), + (1e308, -1e308), + ] { + let e = cylinder.lean_cylinder(&k, s, h).unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR), "{s} {h}"); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::LeanNotFinite), + "{s} {h}" + ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput, "{s} {h}"); + } + let e = cone.lean_cylinder(&k, slope, 4.0).unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::NotACylinder)); + assert_eq!(e.kind(), crate::error::ErrorKind::Unsupported); } /// Two end arcs of a short cylinder differ by two ulps at one control point. Their diff --git a/solidcore/crates/solidcore/src/surface/plane/p1.rs b/solidcore/crates/solidcore/src/surface/plane/p1.rs index d6479b3c4ea..cd27bd961d9 100644 --- a/solidcore/crates/solidcore/src/surface/plane/p1.rs +++ b/solidcore/crates/solidcore/src/surface/plane/p1.rs @@ -1034,9 +1034,9 @@ impl Plane { && operation != SolverOperation::Normalize && operation != SolverOperation::Intersect { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_DROP, - "the operation is neither minimize, normalize nor intersect", + SurfaceFailure::OperationNotTaken, )); } @@ -1193,7 +1193,7 @@ impl Plane { if line_vector.length_squared() < EFF_ZERO_SQ { return Err(SolidError::surface( OP_LINE, - SurfaceFailure::InvalidValue("the line direction is the zero vector"), + SurfaceFailure::LineDirectionZero, )); } @@ -1337,10 +1337,11 @@ impl Plane { let det = pu.cross(pv).dot(lt); if det.abs() < EFF_ZERO { - // should never happen, we're in the non-parallel case here. - return Err(SolidError::surface_failed( + // the angle test above passed, so a direction or a scale too small to solve + // with makes the determinant this small + return Err(SolidError::surface( OP_LINE, - "the line is parallel to the plane", + SurfaceFailure::LineCrossingSingular, )); } @@ -2630,10 +2631,63 @@ mod tests { false, 1e-6, ); + let e = r.err().unwrap(); + assert_eq!(e.sm_status(), Some(SM_ERR_INVALID_INPUT)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::LineDirectionZero) + ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + } + + /// A line square to a plane whose u and v scales are 1e-7 crosses it at a determinant + /// of 1e-14, below the kernel's zero: the crossing is singular to solve for, with + /// upstream's `SM_ERR`; the fast drop refuses an operation it does not take. + #[test] + fn a_crossing_too_small_to_solve_and_an_operation_not_taken_are_named() { + use crate::geom::global_solver::SolverOperation; + use crate::surface::surface::p4::NoObject; + let tiny = Plane::new( + Point3::new(0.0, 0.0, 0.0), + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(0.0, 1.0, 0.0), + Vec2::new(1e-7, 1e-7), + &Extent2d::from_bounds(0.0, 0.0, 1.0, 1.0), + ); + let e = tiny + .global_line_intersect::( + &Kernel::default(), + NoObject, + &tiny.step_uv_domain(), + Point3::new(0.0, 0.0, 1.0), + Vec3::new(0.0, 0.0, 1.0), + None, + false, + 1e-6, + ) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::LineCrossingSingular) + ); + let p = unit_plane(); + let e = p + .drop_point_fast::( + &p.step_uv_domain(), + SolverOperation::Maximize, + Point3::new(1.0, 2.0, 4.0), + 1e-6, + None, + None, + ) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); assert_eq!( - r.err().and_then(|e| e.sm_status()), - Some(SM_ERR_INVALID_INPUT) + e.surface_failure(), + Some(&SurfaceFailure::OperationNotTaken) ); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); } #[test] diff --git a/solidcore/crates/solidcore/src/surface/plane/p2.rs b/solidcore/crates/solidcore/src/surface/plane/p2.rs index e3cd5912275..b47f7977611 100644 --- a/solidcore/crates/solidcore/src/surface/plane/p2.rs +++ b/solidcore/crates/solidcore/src/surface/plane/p2.rs @@ -81,7 +81,7 @@ use crate::curve::curve::{Curve, CurveKind}; use crate::curve::ellipse::{Ellipse, EllipseOptions}; use crate::curve::line::{BoundedLineOptions, Line}; use crate::error::surface::SurfaceFailure; -use crate::error::{ignore_status, ignored, Failure, Result, SolidError, SM_ERR_WARNING}; +use crate::error::{ignore_status, ignored, Failure, Result, SolidError, SM_ERR_NULL_POINTER}; use crate::geom::axis2_placement::Axis2Placement; use crate::geom::certified::{self, next_up}; use crate::geom::extent1d::Extent1d; @@ -98,7 +98,7 @@ use crate::geom::tol::{are_same, is_zero, is_zero_to_tol, within_contact_tol, ZO use crate::geom::vector2d::{Point2, Vec2}; use crate::geom::vector3d::{sqrt, Point3, Vec3}; use crate::kernel::Kernel; -use crate::math::{max2, min2, EFF_ZERO, EFF_ZERO_PARAM, EFF_ZERO_SQRT, PI}; +use crate::math::{max2, min2, EFF_ZERO, EFF_ZERO_PARAM, EFF_ZERO_SQ, EFF_ZERO_SQRT, PI}; use crate::nurbs::b_spline_curve::BSplineCurve; use crate::nurbs::b_spline_curve_n_lib::TrimMode; use crate::nurbs::b_spline_surface::p2::EditNotify; @@ -138,12 +138,9 @@ impl PlaneIntersectWarning { #[must_use] pub fn into_error(self) -> SolidError { match self { - Self::NearlySingular => Failure::new( - OP_PP, - SurfaceFailure::Failed("the planes' line is nearly singular to solve for"), - ) - .with_status(SM_ERR_WARNING) - .into_error(), + Self::NearlySingular => { + SolidError::surface(OP_PP, SurfaceFailure::PlanesLineNearlySingular) + } } } } @@ -315,19 +312,34 @@ impl Plane { if !(s.x == 1.0 && s.y == 1.0 && s.z == 1.0) { // scaling must be isotropic if !are_same(s.x, s.y) || !are_same(s.x, s.z) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_XFORM, - "a plane cannot be scaled non-uniformly", + SurfaceFailure::ScaleNotUniform, + )); + } + // a zero scale collapses the plane to a point, a non-finite one leaves no + // net: the caller's scale, not a plane the transform lost + if s.x == 0.0 || !s.x.is_finite() { + return Err(SolidError::surface( + OP_XFORM, + SurfaceFailure::ScaleNotUniform, )); } } } // check transformed m_pNurb for planarity and gen transformed Plane parameters - let nurb = self - .base - .gw_nurb() - .ok_or_else(|| SolidError::surface_missing(OP_XFORM, "the plane's NURB"))?; + let Some(nurb) = self.base.gw_nurb() else { + return Err(Failure::new( + OP_XFORM, + SurfaceFailure::Defect { + why: "the plane's NURB is missing after the B-spline transform above \ + succeeded, which fails without a NURB", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error()); + }; let bss = BSplineSurface::from_nurb(nurb.clone(), true); let mut plane = None; for tol_scale in [1.0, 10.0, 100.0, 1000.0] { @@ -336,9 +348,40 @@ impl Plane { break; } } + // The test evaluates the tangents (the evaluation refuses them below the surface's + // derivative limit), measures them and their cross product (the normal) only above + // the kernel's zero squared, and a square that overflows has no angle: a scale that + // takes them there leaves a plane the test cannot see, which is the scale's, not the + // kernel's. + if plane.is_none() { + let at = bss.natural_uv_domain().evaluate(0.0, 0.0); + let unmeasurable = Failure::new(OP_XFORM, SurfaceFailure::PlaneTangentUnmeasurable); + match evaluate_1st_derivatives(k, &bss, at, Side::Left, Side::Left) { + Ok((_, du, dv)) => { + if [du, dv, du.cross(dv)].iter().any(|d| { + let length_squared = d.length_squared(); + !(length_squared > EFF_ZERO_SQ && length_squared.is_finite()) + }) { + return Err(unmeasurable.into_error()); + } + } + Err(e) if e.is_status_answer() => { + return Err(unmeasurable.caused_by(e).into_error()); + } + Err(e) => return Err(e), + } + } // Something wrong here if scaling a plane does not produce a plane. let plane = plane.ok_or_else(|| { - SolidError::surface_failed(OP_XFORM, "the transformed NURB is not a plane") + SolidError::surface( + OP_XFORM, + SurfaceFailure::Defect { + why: "the plane's bilinear NURB, moved rigidly and scaled uniformly by a \ + finite, non-zero factor, with tangents the test measures (all \ + checked above), no longer tests as a plane at 1000 times the \ + tolerance, though such a transform keeps every net planar", + }, + ) })?; // save the transformed plane parameters @@ -365,9 +408,9 @@ impl Plane { // Make sure trim domain in inside of natural domain if !trim_domain.is_contained_by(&natural_domain, EFF_ZERO_PARAM) { - return Err(SolidError::surface_failed( + return Err(SolidError::surface( OP_TRIM, - "the trim domain is not inside the natural domain", + SurfaceFailure::TrimDomainOutside, )); } @@ -603,8 +646,10 @@ impl Plane { // Force XAxis and YAxis to be nicely perpendicular if x_axis.dot(y_axis).abs() > EFF_ZERO { y_axis = x_axis.cross(y_axis).cross(x_axis); - y_axis = y_axis.unitize().map_err(|_| { - SolidError::surface_failed(OP_NURB, "the y axis is parallel to the x axis") + y_axis = y_axis.unitize().map_err(|e| { + Failure::new(OP_NURB, SurfaceFailure::NurbAxesParallel) + .caused_by(e) + .into_error() })?; } @@ -668,12 +713,18 @@ impl Plane { let b = self .base_with_nurb()? .calculate_bounding_box(k, uv_domain, &req)?; - let mut bbox = b - .normal - .ok_or_else(|| SolidError::surface_missing(OP_PP, "the plane's bounding box"))?; - let mut pbox = b - .pseudo - .ok_or_else(|| SolidError::surface_missing(OP_PP, "the plane's pseudo box"))?; + let (Some(mut bbox), Some(mut pbox)) = (b.normal, b.pseudo) else { + return Err(Failure::new( + OP_PP, + SurfaceFailure::Defect { + why: "the B-spline bounding box routine, asked for the normal and pseudo \ + boxes, returned without one, though it returns every box it is asked \ + for", + }, + ) + .with_status(SM_ERR_NULL_POINTER) + .into_error()); + }; // When asked, expand the normal and pseudo boxes by the zone tolerance bbox.expand_absolute(zone_tolerance(owner)?); pbox.expand_absolute(zone_tolerance(owner)?); @@ -794,9 +845,9 @@ impl Plane { // Arrive here when planes are not parallel. // unitize lineDir and set OriginCross = avg(midPoint1, midPoint2) - let line_dir = line_dir.unitize().map_err(|_| { - SolidError::surface_failed(OP_PP, "the planes' line direction is the zero vector") - })?; + // (its squared length is at least 1e-16 past the parallel test above, so the unit + // vector exists) + let line_dir = line_dir.unitize_or_z(); let origin_cross = if this_bounded && !other_bounded { origin_this } else if !this_bounded && other_bounded { @@ -1774,6 +1825,7 @@ pub(crate) fn global_surface_intersect_into BSplineSurface { let dx = 40.0 * shear; @@ -1816,8 +1868,51 @@ mod tests { fn transform_rejects_anisotropic_scale() { let k = &Kernel::default(); let mut p = rect(); - let r = p.transform(k, &Axis2Placement::IDENTITY, Some(Vec3::new(2.0, 1.0, 1.0))); - assert!(r.is_err()); + let e = p + .transform(k, &Axis2Placement::IDENTITY, Some(Vec3::new(2.0, 1.0, 1.0))) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::ScaleNotUniform)); + assert_eq!(e.kind(), crate::error::ErrorKind::InvalidInput); + // a uniform zero scale collapses the plane: the caller's scale too, not a defect + let e = rect() + .transform(k, &Axis2Placement::IDENTITY, Some(Vec3::ZERO)) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!(e.surface_failure(), Some(&SurfaceFailure::ScaleNotUniform)); + assert!(!e.is_defect()); + // a uniform scale that takes the tangents below the surface's derivative limit (the + // evaluation's error is the cause) or past the largest square leaves a plane the + // planarity test cannot measure: degenerate, not a defect + for factor in [1e-13, 1e-9, 1e-200, 1e200] { + let e = rect() + .transform( + k, + &Axis2Placement::IDENTITY, + Some(Vec3::new(factor, factor, factor)), + ) + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR), "{factor:e}"); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::PlaneTangentUnmeasurable), + "{factor:e}: {e:?}" + ); + // the evaluation's refusal of tangents below the derivative limit is the cause; + // tangents of 1e-9 evaluate but their normal's square is below the kernel's zero + // squared, and huge ones evaluate with squares that overflow + assert_eq!(e.cause().is_some(), factor < 1e-10, "{factor:e}: {e:?}"); + assert_eq!(e.kind(), crate::error::ErrorKind::Degenerate, "{factor:e}"); + assert!(!e.is_defect(), "{factor:e}"); + } + // tangents of 1e-5, whose normal's square is 1e-20, still scale + let mut q = rect(); + q.transform( + k, + &Axis2Placement::IDENTITY, + Some(Vec3::new(1e-5, 1e-5, 1e-5)), + ) + .unwrap(); let mut q = rect(); q.transform(k, &Axis2Placement::IDENTITY, Some(Vec3::new(2.0, 2.0, 2.0))) .unwrap(); @@ -1828,9 +1923,14 @@ mod tests { #[test] fn trim_with_domain_checks_containment() { let mut p = rect(); - assert!(p + let e = p .trim_with_domain(&Extent2d::from_bounds(-6.0, 0.0, 1.0, 1.0)) - .is_err()); + .unwrap_err(); + assert_eq!(e.sm_status(), Some(crate::error::SM_ERR)); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::TrimDomainOutside) + ); p.trim_with_domain(&Extent2d::from_bounds(-1.0, 0.0, 1.0, 1.0)) .unwrap(); assert_eq!( @@ -1979,7 +2079,10 @@ mod tests { assert_eq!(e.operation(), OP_PP); assert_eq!(e.entity(), None); assert_eq!(e.kind(), crate::error::ErrorKind::Failed); - assert!(e.surface_failure().is_some()); + assert_eq!( + e.surface_failure(), + Some(&SurfaceFailure::PlanesLineNearlySingular) + ); assert!(e.is_status_answer()); assert!(ignored(Err::<(), _>(e)).unwrap().is_none()); @@ -2340,29 +2443,33 @@ mod tests { assert!(Plane::read_from_db(&mut db, 30).is_err()); } - /// The plane's failures keep the operation, status, kind and entity of the bare - /// `Upstream` statuses they replace (a sample). + /// The plane's failures keep the operation, status and entity of the bare `Upstream` + /// statuses they replace (a sample); their class is the cause's. #[test] fn typed_surface_failures_keep_their_upstream_answers() { use crate::error::surface::SurfaceFailure; - let samples: [(&'static str, SurfaceFailure, i32); 3] = [ + use crate::error::ErrorKind; + let samples: [(&'static str, SurfaceFailure, i32, ErrorKind); 3] = [ ( OP_XFORM, - SurfaceFailure::Failed("a plane cannot be scaled non-uniformly"), + SurfaceFailure::ScaleNotUniform, crate::error::SM_ERR, + ErrorKind::InvalidInput, ), ( OP_PP, - SurfaceFailure::Missing("the plane's bounding box"), - crate::error::SM_ERR_NULL_POINTER, + SurfaceFailure::PlanesLineNearlySingular, + SM_ERR_WARNING, + ErrorKind::Failed, ), ( OP_TRIM, - SurfaceFailure::Failed("the trim domain is not inside the natural domain"), + SurfaceFailure::TrimDomainOutside, crate::error::SM_ERR, + ErrorKind::OutsideDomain, ), ]; - for (operation, failure, code) in samples { + for (operation, failure, code, kind) in samples { let typed = SolidError::surface(operation, failure); let before = SolidError::Upstream { operation, @@ -2371,7 +2478,7 @@ mod tests { }; assert_eq!(typed.sm_status(), before.sm_status(), "{typed:?}"); assert_eq!(typed.upstream_status(), Some(code), "{typed:?}"); - assert_eq!(typed.kind(), before.kind(), "{typed:?}"); + assert_eq!(typed.kind(), kind, "{typed:?}"); assert_eq!(typed.operation(), before.operation(), "{typed:?}"); assert_eq!(typed.entity(), None, "{typed:?}"); assert_eq!(typed.is_port_failure(), before.is_port_failure());