From b4f8067f26b1ae5df2fa900fa08532792fa95bad Mon Sep 17 00:00:00 2001 From: NiJingzhe <1448976235@qq.com> Date: Thu, 29 Oct 2026 16:58:17 +0800 Subject: [PATCH] refactor: name the tolerances (scad::tol) instead of repeating their numbers include/scad/core/tolerance.hpp holds 38 constants, each named for what it is a tolerance for, with a how-to-choose comment and a table. 116 sites in 56 files use them; every constant has exactly the value of the literal it replaces, so nothing computes differently (ctest and the golden parity tests unchanged). About 110 literals stay where they are on purpose: OCCT mirror bindings, solver constants that already have local names, relative-times-floor combinations, raster/render epsilons. Six ambiguous sites are listed in the CHANGELOG-free note of the commit for the owner: extrude_until.cpp:68 (1e-8 sine test), :193 (extent below 1e-12 uses kDegenerateNorm), probes.cpp:207,228, bind_surface.cpp:75 (interpolation default 1e-5 vs kSplineInterpolation 1e-6), tracking.hpp:148 (tracked_shell tol), BuildCurves3d at 1e-6 (kernel/curves.cpp:177) and 1e-7 (tracking_lofts.cpp:254). Co-Authored-By: Claude Sonnet 5.5 --- src/cpp/bindings/python/bind_core.cpp | 5 +- src/cpp/bindings/python/bind_io.cpp | 3 +- src/cpp/bindings/python/bind_ops_features.cpp | 4 +- src/cpp/bindings/python/bind_ops_geometry.cpp | 8 +- .../bindings/python/bind_reactive_math.cpp | 8 +- src/cpp/bindings/python/bind_sdk_compat.cpp | 3 +- src/cpp/bindings/python/bind_sketch.cpp | 12 ++- src/cpp/bindings/python/bind_surface.cpp | 21 ++-- src/cpp/include/scad/core/tolerance.hpp | 96 +++++++++++++++++++ src/cpp/include/scad/io/exchange.hpp | 5 +- src/cpp/include/scad/kernel/curves.hpp | 3 +- src/cpp/include/scad/ops/features/blends.hpp | 3 +- src/cpp/include/scad/ops/geometry/splines.hpp | 6 +- src/cpp/include/scad/reactive/bspline_fit.hpp | 11 ++- src/cpp/include/scad/semantic/tracking.hpp | 4 +- src/cpp/include/scad/sketch/sketch.hpp | 3 +- src/cpp/include/scad/sketch/solver.hpp | 3 +- src/cpp/include/scad/surface/fitter.hpp | 3 +- src/cpp/include/scad/surface/operators.hpp | 15 +-- src/cpp/include/scad/surface/types.hpp | 5 +- src/cpp/src/core/coordinate_system.cpp | 3 +- src/cpp/src/kernel/convert.cpp | 3 +- src/cpp/src/kernel/properties.cpp | 7 +- src/cpp/src/ops/features/affine.cpp | 5 +- src/cpp/src/ops/features/blends.cpp | 3 +- .../src/ops/features/boolean_diagnosis.cpp | 3 +- src/cpp/src/ops/features/booleans.cpp | 11 ++- src/cpp/src/ops/features/extrude_until.cpp | 14 +-- src/cpp/src/ops/features/extrusion.cpp | 3 +- src/cpp/src/ops/features/loft_diagnosis.cpp | 5 +- src/cpp/src/ops/features/multisection.cpp | 3 +- src/cpp/src/ops/features/offsets.cpp | 3 +- src/cpp/src/ops/features/patterns.cpp | 3 +- src/cpp/src/ops/features/probes.cpp | 7 +- src/cpp/src/ops/features/sweeps.cpp | 3 +- src/cpp/src/ops/features/taper.cpp | 3 +- src/cpp/src/ops/features/transforms.cpp | 3 +- src/cpp/src/ops/geometry/bspline_args.cpp | 3 +- src/cpp/src/ops/geometry/faces.cpp | 3 +- src/cpp/src/ops/geometry/plane.cpp | 5 +- src/cpp/src/ops/geometry/rectangles.cpp | 3 +- src/cpp/src/product/connector.cpp | 3 +- src/cpp/src/product/placement.cpp | 3 +- src/cpp/src/ql/diagnostics.cpp | 14 +-- src/cpp/src/reactive/bspline_fit.cpp | 3 +- src/cpp/src/render/camera.cpp | 5 +- src/cpp/src/semantic/tracking_lofts.cpp | 3 +- src/cpp/src/semantic/tracking_sweeps.cpp | 3 +- src/cpp/src/sketch/bspline_params.cpp | 3 +- src/cpp/src/sketch/convert.cpp | 7 +- src/cpp/src/sketch/sketch.cpp | 7 +- src/cpp/src/std/bolt.cpp | 5 +- src/cpp/src/std/fastener_tables.cpp | 3 +- src/cpp/src/std/gear_geometry.cpp | 3 +- src/cpp/src/std/gear_profiles.cpp | 3 +- src/cpp/src/std/nut.cpp | 3 +- src/cpp/src/surface/faces_from_data.cpp | 5 +- 57 files changed, 275 insertions(+), 115 deletions(-) create mode 100644 src/cpp/include/scad/core/tolerance.hpp diff --git a/src/cpp/bindings/python/bind_core.cpp b/src/cpp/bindings/python/bind_core.cpp index 92392af2..7f5dbc87 100644 --- a/src/cpp/bindings/python/bind_core.cpp +++ b/src/cpp/bindings/python/bind_core.cpp @@ -1,5 +1,6 @@ #include "bindings.hpp" +#include "scad/core/tolerance.hpp" #include "scad/core/coordinate_system.hpp" #include #include @@ -36,14 +37,14 @@ void bind_core(py::module_& m) { .def("norm", [](const PyVec3& p) { return p.v.norm(); }) .def("normalized", [](const PyVec3& p) { - if (p.v.norm() <= 1e-15) + if (p.v.norm() <= scad::tol::kZeroDirectionNorm) throw scad::ValueError("Cannot normalize a zero-length vector"); return PyVec3{p.v.normalized()}; }) .def("getAngle", [](const PyVec3& p, const scad::Vec3& o) { const double sn = p.v.norm(), on = o.norm(); - if (sn <= 1e-15 || on <= 1e-15) + if (sn <= scad::tol::kZeroDirectionNorm || on <= scad::tol::kZeroDirectionNorm) throw scad::ValueError("Cannot compute angle with a zero-length vector"); return std::acos(std::max(-1.0, std::min(1.0, p.v.dot(o) / (sn * on)))); }) diff --git a/src/cpp/bindings/python/bind_io.cpp b/src/cpp/bindings/python/bind_io.cpp index ca1f12e9..d5bf27a7 100644 --- a/src/cpp/bindings/python/bind_io.cpp +++ b/src/cpp/bindings/python/bind_io.cpp @@ -13,6 +13,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/io/brep.hpp" #include "scad/io/brep_region.hpp" @@ -549,7 +550,7 @@ void bind_files(py::module_& m) { [](const std::filesystem::path& path, double sewing_tolerance) { return cast_shape(io::import_stl_shape(path, sewing_tolerance)); }, - py::arg("path"), py::arg("sewing_tolerance") = 1e-6, + py::arg("path"), py::arg("sewing_tolerance") = tol::kSewing, "Read an STL as a faceted BREP (a Solid when the triangles close up)."); m.def( "export_obj", diff --git a/src/cpp/bindings/python/bind_ops_features.cpp b/src/cpp/bindings/python/bind_ops_features.cpp index d1beb9ae..e474394a 100644 --- a/src/cpp/bindings/python/bind_ops_features.cpp +++ b/src/cpp/bindings/python/bind_ops_features.cpp @@ -10,6 +10,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/ops/features/features.hpp" #include "scad/ql/ql.hpp" @@ -288,7 +289,8 @@ void bind_derived(py::module_& m) { [&] { return offset_rsolid(solid, amount, selection, {tolerance, kind}); }); }, py::arg("solid"), py::arg("amount"), py::arg("openings") = py::tuple(), py::kw_only(), - py::arg("tolerance") = 1e-4, py::arg("kind") = "ARC", "Offset a solid outward (positive) or inward (negative)."); + py::arg("tolerance") = tol::kOffsetTolerance, py::arg("kind") = "ARC", + "Offset a solid outward (positive) or inward (negative)."); m.def( "draft_rsolid", diff --git a/src/cpp/bindings/python/bind_ops_geometry.cpp b/src/cpp/bindings/python/bind_ops_geometry.cpp index 989acec4..aaab1cf4 100644 --- a/src/cpp/bindings/python/bind_ops_geometry.cpp +++ b/src/cpp/bindings/python/bind_ops_geometry.cpp @@ -3,6 +3,7 @@ // defaults (keyword-only where Python is keyword-only), plus the create_* aliases. #include "bindings.hpp" +#include "scad/core/tolerance.hpp" #include "scad/io/brep_region.hpp" #include @@ -154,13 +155,14 @@ void bind_splines(py::module_& m) { }; }; m.def("make_interpolated_spline_redge", interpolated(&make_interpolated_spline_redge), py::kw_only(), - py::arg("points"), py::arg("periodic") = false, py::arg("tolerance") = 1.0e-6, + py::arg("points"), py::arg("periodic") = false, py::arg("tolerance") = tol::kSplineInterpolation, "Interpolate an exact B-spline edge through the supplied points."); m.def("make_interpolated_spline_rwire", interpolated(&make_interpolated_spline_rwire), py::kw_only(), - py::arg("points"), py::arg("periodic") = false, py::arg("tolerance") = 1.0e-6, + py::arg("points"), py::arg("periodic") = false, py::arg("tolerance") = tol::kSplineInterpolation, "Create a one-edge wire that interpolates the supplied points."); m.def("make_periodic_spline_rwire", &make_periodic_spline_rwire, py::kw_only(), py::arg("points"), - py::arg("tolerance") = 1.0e-6, "Create a closed periodic spline wire interpolating the supplied points."); + py::arg("tolerance") = tol::kSplineInterpolation, + "Create a closed periodic spline wire interpolating the supplied points."); } void bind_helix(py::module_& m) { diff --git a/src/cpp/bindings/python/bind_reactive_math.cpp b/src/cpp/bindings/python/bind_reactive_math.cpp index 5828b2ff..657c361d 100644 --- a/src/cpp/bindings/python/bind_reactive_math.cpp +++ b/src/cpp/bindings/python/bind_reactive_math.cpp @@ -1,6 +1,7 @@ // simplecadapi.math: fit_cubic_bspline_control_points and BSplineFitResult. #include "bind_reactive_common.hpp" +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include @@ -104,9 +105,10 @@ void bind_reactive_math(py::module_& m) { } return sr::fit_cubic_bspline_control_points(samples, options); }, - py::arg("sample_points"), py::kw_only(), py::arg("tolerance") = 1e-3, - py::arg("max_control_points") = py::none(), py::arg("fairing") = 1e-6, py::arg("duplicate_tolerance") = 1e-12, - py::arg("knot_tolerance") = 1e-9, py::arg("raise_on_failure") = true, + py::arg("sample_points"), py::kw_only(), py::arg("tolerance") = tol::kFitError, + py::arg("max_control_points") = py::none(), py::arg("fairing") = 1e-6, + py::arg("duplicate_tolerance") = tol::kDuplicateParameter, + py::arg("knot_tolerance") = tol::kInteriorKnotSpacing, py::arg("raise_on_failure") = true, "Fit a minimal cubic B-spline control polygon to sampled curve points."); }; bind_into(math); diff --git a/src/cpp/bindings/python/bind_sdk_compat.cpp b/src/cpp/bindings/python/bind_sdk_compat.cpp index 7a14d86f..3a631524 100644 --- a/src/cpp/bindings/python/bind_sdk_compat.cpp +++ b/src/cpp/bindings/python/bind_sdk_compat.cpp @@ -6,6 +6,7 @@ #include "bind_product_args.hpp" #include "bind_reactive_common.hpp" #include "py_lifetime.hpp" +#include "scad/core/tolerance.hpp" #include "scad/topo/diagnostic_image.hpp" #include @@ -586,7 +587,7 @@ void bind_sdk_compat(py::module_& m) { pts.push_back(Vec3{p[0], p[1], p[2]}); return Edge(kernel::make_interpolated_bspline_edge(pts, periodic, tolerance)); }, - py::arg("points"), py::kw_only(), py::arg("periodic") = false, py::arg("tolerance") = 1e-6, + py::arg("points"), py::kw_only(), py::arg("periodic") = false, py::arg("tolerance") = tol::kSplineInterpolation, "An interpolating B-spline edge through the points (GeomAPI_Interpolate)."); m.def( "_bspline_curve_of", diff --git a/src/cpp/bindings/python/bind_sketch.cpp b/src/cpp/bindings/python/bind_sketch.cpp index 79c25dd0..04a447f8 100644 --- a/src/cpp/bindings/python/bind_sketch.cpp +++ b/src/cpp/bindings/python/bind_sketch.cpp @@ -6,6 +6,7 @@ #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/sketch/native_solver.hpp" #include "scad/sketch/operators.hpp" @@ -239,7 +240,7 @@ void bind_data_classes(py::module_& m) { py::class_(m, "SketchSolverOptions") .def( py::init([](double tolerance, int max_iterations) { return SketchSolverOptions{tolerance, max_iterations}; }), - py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80) + py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80) .def_readonly("tolerance", &SketchSolverOptions::tolerance) .def_readonly("max_iterations", &SketchSolverOptions::max_iterations); @@ -489,7 +490,8 @@ void bind_sketch_class(py::module_& m) { return s.solve(request); }, py::kw_only(), py::arg("require_fully_constrained") = false, py::arg("strict") = true, - py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80, py::arg("backend") = py::none()) + py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80, + py::arg("backend") = py::none()) .def("solved_result", [](Sketch& s) { return s.solved_result(); }) .def( "make_wire", @@ -625,7 +627,7 @@ void bind_solve_operators(py::module_& m) { return inspect_sketch_rsketchresult(sketch, request_of(fully, strict, tolerance, max_iterations)); }, py::arg("sketch"), py::kw_only(), py::arg("require_fully_constrained") = false, py::arg("strict") = true, - py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80); + py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80); m.def( "make_wire_from_sketch_rwire", [](const Sketch& sketch, const SketchProfileId& profile, bool fully, bool strict, double tolerance, @@ -633,7 +635,7 @@ void bind_solve_operators(py::module_& m) { return make_wire_from_sketch_rwire(sketch, profile, request_of(fully, strict, tolerance, max_iterations)); }, py::arg("sketch"), py::arg("profile") = 0, py::kw_only(), py::arg("require_fully_constrained") = false, - py::arg("strict") = true, py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80); + py::arg("strict") = true, py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80); m.def( "make_face_from_sketch_rface", [](const Sketch& sketch, const SketchProfileId& profile, const std::vector& inner, bool fully, @@ -643,7 +645,7 @@ void bind_solve_operators(py::module_& m) { }, py::arg("sketch"), py::arg("profile") = 0, py::kw_only(), py::arg("inner_profiles") = std::vector{}, py::arg("require_fully_constrained") = false, - py::arg("strict") = true, py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80); + py::arg("strict") = true, py::arg("tolerance") = tol::kSketchSolveResidual, py::arg("max_iterations") = 80); } } // namespace diff --git a/src/cpp/bindings/python/bind_surface.cpp b/src/cpp/bindings/python/bind_surface.cpp index 82bff889..6b52ce2d 100644 --- a/src/cpp/bindings/python/bind_surface.cpp +++ b/src/cpp/bindings/python/bind_surface.cpp @@ -26,6 +26,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/reactive/expr.hpp" #include "scad/reactive/units.hpp" #include "scad/surface/hooks.hpp" @@ -146,9 +147,9 @@ void bind_surface(py::module_& m) { return settings; }), py::arg("degree") = 3, py::arg("points_per_curve") = 15, py::arg("iterations") = 2, - py::arg("anisotropic") = false, py::arg("tolerance_2d") = 1e-5, py::arg("tolerance_3d") = 1e-4, - py::arg("angular_tolerance") = 0.01, py::arg("curvature_tolerance") = 0.1, py::arg("max_degree") = 8, - py::arg("max_segments") = 9) + py::arg("anisotropic") = false, py::arg("tolerance_2d") = tol::kFillingTolerance2d, + py::arg("tolerance_3d") = tol::kFillingTolerance3d, py::arg("angular_tolerance") = 0.01, + py::arg("curvature_tolerance") = 0.1, py::arg("max_degree") = 8, py::arg("max_segments") = 9) .def_readonly("degree", &SurfaceFillingSettings::degree) .def_readonly("points_per_curve", &SurfaceFillingSettings::points_per_curve) .def_readonly("iterations", &SurfaceFillingSettings::iterations) @@ -185,7 +186,7 @@ void bind_surface(py::module_& m) { }, py::arg("radius"), py::arg("u_range"), py::arg("v_range"), py::arg("origin") = ScalarVec3{0.0, 0.0, 0.0}, py::arg("axis") = ScalarVec3{0.0, 0.0, 1.0}, py::arg("x_direction") = py::none(), py::kw_only(), - py::arg("tolerance") = Scalar(1e-7), py::arg("tag_prefix") = py::none(), + py::arg("tolerance") = Scalar(tol::kSurfaceTrim), py::arg("tag_prefix") = py::none(), "Create a finite cylindrical carrier Face over explicit U/V ranges (U in raw radians, at most one turn)."); m.def( @@ -198,7 +199,7 @@ void bind_surface(py::module_& m) { .smoothing = smoothing, .tag_prefix = tag_prefix}); }, - py::arg("points"), py::kw_only(), py::arg("tolerance") = 1e-3, py::arg("degree_min") = 3, + py::arg("points"), py::kw_only(), py::arg("tolerance") = tol::kFitError, py::arg("degree_min") = 3, py::arg("degree_max") = 8, py::arg("smoothing") = py::none(), py::arg("tag_prefix") = py::none(), "Fit a B-spline Face through a rectangular 3D point grid."); @@ -214,7 +215,7 @@ void bind_surface(py::module_& m) { "make_gordon_surface_rface", [](const std::vector& profiles, const std::vector& guides, double tolerance, const TagPrefix& tag_prefix) { return make_gordon_surface_rface(profiles, guides, tolerance, tag_prefix); }, - py::arg("profiles"), py::arg("guides"), py::kw_only(), py::arg("tolerance") = 1e-3, + py::arg("profiles"), py::arg("guides"), py::kw_only(), py::arg("tolerance") = tol::kFitError, py::arg("tag_prefix") = py::none(), "Create a Gordon Face from intersecting profile and guide edge networks."); m.def( @@ -236,7 +237,7 @@ void bind_surface(py::module_& m) { return trim_surface_rface(carrier, outer, {.holes = holes, .tolerance = tolerance, .tag_prefix = tag_prefix}); }, py::arg("carrier"), py::arg("outer"), py::arg("holes") = std::vector{}, py::kw_only(), - py::arg("tolerance") = 1e-7, py::arg("tag_prefix") = py::none(), + py::arg("tolerance") = tol::kSurfaceTrim, py::arg("tag_prefix") = py::none(), "Trim a carrier Face to exactly one connected Face."); m.def( @@ -270,7 +271,7 @@ void bind_surface(py::module_& m) { [](const std::vector& faces, double tolerance, const TagPrefix& tag_prefix) { return sew_faces_rshell(faces, tolerance, tag_prefix); }, - py::arg("faces"), py::kw_only(), py::arg("tolerance") = 1e-6, py::arg("tag_prefix") = py::none(), + py::arg("faces"), py::kw_only(), py::arg("tolerance") = tol::kSewing, py::arg("tag_prefix") = py::none(), "Sew faces into exactly one connected Shell."); m.def( @@ -282,7 +283,7 @@ void bind_surface(py::module_& m) { m.def( "free_boundaries_rwirelist", [](const Shell& shell, double tolerance) { return free_boundaries_rwirelist(shell, tolerance); }, - py::arg("shell"), py::kw_only(), py::arg("tolerance") = 1e-6, + py::arg("shell"), py::kw_only(), py::arg("tolerance") = tol::kSewing, "Return unique closed and open free boundary wires of a Shell."); m.def( @@ -293,7 +294,7 @@ void bind_surface(py::module_& m) { shell, {.hole_indices = hole_indices, .tolerance = tolerance, .settings = settings, .tag_prefix = tag_prefix}); }, - py::arg("shell"), py::arg("hole_indices") = py::none(), py::kw_only(), py::arg("tolerance") = 1e-6, + py::arg("shell"), py::arg("hole_indices") = py::none(), py::kw_only(), py::arg("tolerance") = tol::kSewing, py::arg("settings") = py::none(), py::arg("tag_prefix") = py::none(), "Fill selected closed free boundaries and return a sewn Shell."); diff --git a/src/cpp/include/scad/core/tolerance.hpp b/src/cpp/include/scad/core/tolerance.hpp new file mode 100644 index 00000000..3571720a --- /dev/null +++ b/src/cpp/include/scad/core/tolerance.hpp @@ -0,0 +1,96 @@ +// Named numeric tolerances. +// +// Every threshold in the C++ tree that decides "is this zero / equal / parallel / small enough" and +// would otherwise be a bare `1e-9` lives here, named by what it is a tolerance FOR. The same number +// can appear under several names on purpose: two meanings that share a value today may need to +// diverge later, and a reviewer should be able to see that they are different decisions. +// +// How to choose a tolerance +// * Reuse a constant only when the new site asks the same question (a vector length below which +// the direction is undefined, two sketch points that coincide, ...). Same value is not enough. +// * Add a new constant when the question is new, even if its value equals an existing one. Give +// it a one-line comment that says what it is a tolerance for and, when the site ports old +// Python, the SimpleCADAPI module the number comes from. +// * Leave algorithm-local numbers (sample counts, scale factors, iteration limits, a solver's own +// pivoting thresholds) where they are, next to the code that explains them. +// * OCCT's own tolerances (`Precision::Confusion()` and friends) are not copied here: write them +// where the call into OCCT happens. +// * Changing a value here changes behaviour everywhere it is used, and several of these are +// defaults visible in the Python signatures (`help(...)`) and in the goldens. Run the tests. +// +// Table of meanings (value, group) +// kDegenerateNorm 1e-12 vector / bounds diagonal with no usable direction or extent +// kZeroDirectionNorm 1e-15 direction vector that is exactly zero for practical purposes +// kUndefinedNormal 1e-14 plane / surface normal or extrusion direction that is undefined +// kSingularDeterminant 1e-14 3x3 matrix determinant of a non-invertible transform +// kAffineBottomRow 1e-12 4x4 matrix bottom row must be (0, 0, 0, 1) within this +// kMirrorNormalNorm 1e-10 mirror plane normal of zero length +// kParallelCrossNorm 1e-10 |x cross n| below this: x_dir is parallel to the normal +// kParallelCosineGap 1e-12 1 - |cos| below this: two axes are parallel +// kNegligibleLength 1e-9 model-space vector / axis length treated as zero +// kCoincidentPoints 1e-9 two points (sketch plane, section centroids) coincide +// kEmptyVolume 1e-12 a solid / overlap volume below this is empty +// kCatalogDiameter 1e-9 a diameter equals a catalog nominal (math.isclose abs_tol) +// kArcSweepZero 1e-12 arc sweep (radians) below this is zero +// kArcRadiusRelative 1e-7 arc endpoints may differ in radius by this fraction +// kBaseCircleClearance 1e-8 root / tip circle compared with the involute base circle +// kCutterOverrunFloor 1e-5 floor of the overshoot that makes a cutter pass through a face +// kCutterOverrunRelative 1e-4 the same overshoot as a fraction of the feature size +// kVolumeIntegration 1e-9 Gauss-Kronrod error target for exact volume / centroid +// kVolumeEstimate 1e-5 Gauss-Kronrod error target for the quick volume estimate +// kFuzzyUnionRelative 1e-7 fuzzy value of a union as a fraction of the operands' span +// kFuzzyUnionMin / Max 1e-7 / 1e-5 clamp of that fuzzy value (model units); Min is also +// the default fuzzy value of tracked_union +// kSurfaceCoincidentDistance 1e-6 two analytic surfaces coincide: offset of planes / axes / centres +// kSurfaceRadiusMatch 1e-7 two analytic surfaces coincide: radii agree +// kParallelAxisCosine 0.999 two analytic surfaces coincide: |cos| of axis angle at least this +// kSketchSolveResidual 1e-7 default residual target of the sketch constraint solver +// kSurfaceTrim 1e-7 default tolerance of a carrier surface / trimmed face +// kFitError 1e-3 default maximum error of a fitted B-spline / network surface +// kSewing 1e-6 default tolerance for sewing faces / joining free boundaries +// kSplineInterpolation 1e-6 default tolerance of an interpolating spline +// kOffsetTolerance 1e-4 default tolerance of a solid offset +// kFillingTolerance2d / 3d 1e-5 / 1e-4 default tolerances of the surface filling algorithm +// kDuplicateParameter 1e-12 consecutive knots / samples closer than this are the same +// kInteriorKnotSpacing 1e-9 spacing threshold for interior knots of a fitted B-spline +#pragma once + +namespace scad::tol { + +inline constexpr double kDegenerateNorm = 1e-12; // vector length / bounds diagonal that has no direction or extent +inline constexpr double kZeroDirectionNorm = 1e-15; // direction vector that is zero for practical purposes +inline constexpr double kUndefinedNormal = 1e-14; // plane/surface normal or direction magnitude: undefined below +inline constexpr double kSingularDeterminant = 1e-14; // |det| of a 3x3 transform basis: non-invertible below +inline constexpr double kAffineBottomRow = 1e-12; // 4x4 matrix bottom row must equal (0, 0, 0, 1) within this +inline constexpr double kMirrorNormalNorm = 1e-10; // mirror plane normal length treated as zero +inline constexpr double kParallelCrossNorm = 1e-10; // |x cross normal| below this: x_dir parallel to normal +inline constexpr double kParallelCosineGap = 1e-12; // 1 - |cos| below this: two axes are parallel +inline constexpr double kNegligibleLength = 1e-9; // model-space vector / axis length treated as zero +inline constexpr double kCoincidentPoints = 1e-9; // two points coincide +inline constexpr double kEmptyVolume = 1e-12; // solid / overlap volume below this is empty +inline constexpr double kCatalogDiameter = 1e-9; // a diameter equals a catalog nominal (abs_tol) +inline constexpr double kArcSweepZero = 1e-12; // arc sweep in radians below this is zero +inline constexpr double kArcRadiusRelative = 1.0e-7; // arc endpoint radius mismatch, fraction of the radius +inline constexpr double kBaseCircleClearance = 1e-8; // root / tip circle against the involute base circle +inline constexpr double kCutterOverrunFloor = 1e-5; // minimum cutter overshoot past a face +inline constexpr double kCutterOverrunRelative = 1e-4; // cutter overshoot as a fraction of the feature size +inline constexpr double kVolumeIntegration = 1e-9; // Gauss-Kronrod error target, exact volume / centroid +inline constexpr double kVolumeEstimate = 1e-5; // Gauss-Kronrod error target, quick volume estimate +inline constexpr double kFuzzyUnionRelative = 1e-7; // fuzzy value of a union, fraction of the operands' span +inline constexpr double kFuzzyUnionMin = 1e-7; // lower clamp of that fuzzy value (also tracked_union default) +inline constexpr double kFuzzyUnionMax = 1e-5; // upper clamp of that fuzzy value +inline constexpr double kSurfaceCoincidentDistance = 1e-6; // analytic surfaces coincide: plane/axis/centre offset +inline constexpr double kSurfaceRadiusMatch = 1e-7; // analytic surfaces coincide: radii agree +inline constexpr double kParallelAxisCosine = 0.999; // analytic surfaces coincide: min |cos| between axes +inline constexpr double kSketchSolveResidual = 1e-7; // default residual target of the sketch solver +inline constexpr double kSurfaceTrim = 1e-7; // default tolerance of a carrier surface / trimmed face +inline constexpr double kFitError = 1e-3; // default maximum error of a fitted curve / surface +inline constexpr double kSewing = 1e-6; // default sewing / free-boundary joining tolerance +inline constexpr double kSplineInterpolation = 1e-6; // default tolerance of an interpolating spline +inline constexpr double kOffsetTolerance = 1e-4; // default tolerance of a solid offset +inline constexpr double kFillingTolerance2d = 1e-5; // default 2D tolerance of the surface filling algorithm +inline constexpr double kFillingTolerance3d = 1e-4; // default 3D tolerance of the surface filling algorithm +inline constexpr double kDuplicateParameter = 1e-12; // consecutive knots / samples closer than this are the same +inline constexpr double kInteriorKnotSpacing = 1e-9; // minimum spacing of interior knots of a fitted B-spline + +} // namespace scad::tol diff --git a/src/cpp/include/scad/io/exchange.hpp b/src/cpp/include/scad/io/exchange.hpp index 79d0114c..8bf28a59 100644 --- a/src/cpp/include/scad/io/exchange.hpp +++ b/src/cpp/include/scad/io/exchange.hpp @@ -20,6 +20,7 @@ #include +#include "scad/core/tolerance.hpp" #include "scad/io/brep.hpp" #include "scad/io/files.hpp" #include "scad/io/mesh.hpp" @@ -100,8 +101,8 @@ Mesh read_stl(const std::filesystem::path& path); // Faceted BREP of an STL: one planar face per triangle, sewn at `sewing_tolerance`. // A closed result is returned as a Solid, otherwise as a Shell (or a Compound of // shells). Degenerate triangles are skipped. -TopoDS_Shape stl_to_shape(const Mesh& mesh, double sewing_tolerance = 1e-6); -Shape import_stl_shape(const std::filesystem::path& path, double sewing_tolerance = 1e-6); +TopoDS_Shape stl_to_shape(const Mesh& mesh, double sewing_tolerance = tol::kSewing); +Shape import_stl_shape(const std::filesystem::path& path, double sewing_tolerance = tol::kSewing); // --------------------------------------------------------------------------- // OBJ and GLB diff --git a/src/cpp/include/scad/kernel/curves.hpp b/src/cpp/include/scad/kernel/curves.hpp index 6e09764a..379ce77e 100644 --- a/src/cpp/include/scad/kernel/curves.hpp +++ b/src/cpp/include/scad/kernel/curves.hpp @@ -12,6 +12,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/vec.hpp" namespace scad::kernel { @@ -45,7 +46,7 @@ TopoDS_Edge make_bspline_edge(const BSplineSpec& spec); // Interpolates `points` (GeomAPI_Interpolate); ValueError when the fit fails. TopoDS_Edge make_interpolated_bspline_edge(const std::vector& points, bool periodic = false, - double tolerance = 1.0e-6); + double tolerance = tol::kSplineInterpolation); // The edges must chain end to start; a gap is a KernelError (StdFail_NotDone). TopoDS_Wire make_wire_from_edges(const std::vector& edges); diff --git a/src/cpp/include/scad/ops/features/blends.hpp b/src/cpp/include/scad/ops/features/blends.hpp index eb47359d..6208595c 100644 --- a/src/cpp/include/scad/ops/features/blends.hpp +++ b/src/cpp/include/scad/ops/features/blends.hpp @@ -4,6 +4,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/ops/features/support.hpp" #include "scad/ops/features/tags.hpp" #include "scad/ops/geometry/types.hpp" @@ -37,7 +38,7 @@ Solid shell_rsolid(const Solid& solid, const FaceSelection& faces_to_remove, con const ShellTags& tags = {}); struct OffsetOptions { - double tolerance = 1e-4; + double tolerance = tol::kOffsetTolerance; std::string kind = "ARC"; // join type: "ARC" or "INTERSECTION" }; diff --git a/src/cpp/include/scad/ops/geometry/splines.hpp b/src/cpp/include/scad/ops/geometry/splines.hpp index d299a7b7..0839c0b1 100644 --- a/src/cpp/include/scad/ops/geometry/splines.hpp +++ b/src/cpp/include/scad/ops/geometry/splines.hpp @@ -4,6 +4,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/ops/geometry/types.hpp" #include "scad/topo/shape.hpp" @@ -28,13 +29,14 @@ Wire make_spline_rwire(const SplineSpec& spec); struct SplineInterpolation { std::vector points; bool periodic = false; // closed: the first point need not be repeated at the end - Scalar tolerance = Scalar(1.0e-6); + Scalar tolerance = Scalar(tol::kSplineInterpolation); }; // Error "make_interpolated_spline_redge" / "_rwire": too few or coincident points. Edge make_interpolated_spline_redge(const SplineInterpolation& spec); Wire make_interpolated_spline_rwire(const SplineInterpolation& spec); // make_interpolated_spline_rwire with periodic = true. -Wire make_periodic_spline_rwire(const std::vector& points, const Scalar& tolerance = Scalar(1.0e-6)); +Wire make_periodic_spline_rwire(const std::vector& points, + const Scalar& tolerance = Scalar(tol::kSplineInterpolation)); } // namespace scad diff --git a/src/cpp/include/scad/reactive/bspline_fit.hpp b/src/cpp/include/scad/reactive/bspline_fit.hpp index c6de6258..a6bf3660 100644 --- a/src/cpp/include/scad/reactive/bspline_fit.hpp +++ b/src/cpp/include/scad/reactive/bspline_fit.hpp @@ -8,16 +8,17 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/value.hpp" namespace scad::reactive { struct BSplineFitOptions { - double tolerance = 1e-3; // maximum Euclidean error at the samples - std::optional max_control_points; // default: the cleaned sample count (at least 4) - double fairing = 1e-6; // second-difference regularization weight - double duplicate_tolerance = 1e-12; // consecutive samples closer than this are merged - double knot_tolerance = 1e-9; // spacing threshold for interior knots + double tolerance = tol::kFitError; // maximum Euclidean error at the samples + std::optional max_control_points; // default: the cleaned sample count (at least 4) + double fairing = 1e-6; // second-difference regularization weight + double duplicate_tolerance = tol::kDuplicateParameter; // consecutive samples closer than this are merged + double knot_tolerance = tol::kInteriorKnotSpacing; // spacing threshold for interior knots bool raise_on_failure = true; }; diff --git a/src/cpp/include/scad/semantic/tracking.hpp b/src/cpp/include/scad/semantic/tracking.hpp index 490f5bb7..503399c2 100644 --- a/src/cpp/include/scad/semantic/tracking.hpp +++ b/src/cpp/include/scad/semantic/tracking.hpp @@ -41,6 +41,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/vec.hpp" #include "scad/kernel/builders.hpp" // kernel::Axes3 #include "scad/semantic/tracked_result.hpp" @@ -159,7 +160,8 @@ TrackedBooleanResult tracked_cut(const Solid& body, const Solid& tool); // tracked_union: a two-solid fuse with `track_union_history` on top. ValueError // unless the fuse yields exactly one solid. Glue is opt-in (see kernel::fuse_shapes_with_history). -TrackedBooleanResult tracked_union(const Solid& body, const Solid& tool, bool glue = false, double tol = 1e-7); +TrackedBooleanResult tracked_union(const Solid& body, const Solid& tool, bool glue = false, + double tol = tol::kFuzzyUnionMin); // track_union_history: the delta of an N-ary union already performed with // kernel::fuse_shapes_with_history(solids, ..., clean). Input i has origin diff --git a/src/cpp/include/scad/sketch/sketch.hpp b/src/cpp/include/scad/sketch/sketch.hpp index 8b3d3f01..25567300 100644 --- a/src/cpp/include/scad/sketch/sketch.hpp +++ b/src/cpp/include/scad/sketch/sketch.hpp @@ -15,6 +15,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/scalar.hpp" #include "scad/core/value.hpp" #include "scad/core/vec.hpp" @@ -41,7 +42,7 @@ struct SketchControlPoint { struct SketchSolveRequest { bool require_fully_constrained = false; bool strict = true; - double tolerance = 1e-7; + double tolerance = tol::kSketchSolveResidual; int max_iterations = 80; // Null: the process default backend. std::shared_ptr backend; diff --git a/src/cpp/include/scad/sketch/solver.hpp b/src/cpp/include/scad/sketch/solver.hpp index d8831ea5..1f79c59c 100644 --- a/src/cpp/include/scad/sketch/solver.hpp +++ b/src/cpp/include/scad/sketch/solver.hpp @@ -11,6 +11,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/sketch/types.hpp" namespace scad { @@ -18,7 +19,7 @@ namespace scad { class Sketch; struct SketchSolverOptions { - double tolerance = 1e-7; + double tolerance = tol::kSketchSolveResidual; int max_iterations = 80; }; diff --git a/src/cpp/include/scad/surface/fitter.hpp b/src/cpp/include/scad/surface/fitter.hpp index 71bdef17..5990a8a7 100644 --- a/src/cpp/include/scad/surface/fitter.hpp +++ b/src/cpp/include/scad/surface/fitter.hpp @@ -20,13 +20,14 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/vec.hpp" #include "scad/surface/types.hpp" namespace scad::surface { struct GridFit { - double tolerance = 1e-3; + double tolerance = tol::kFitError; int degree_min = 3; int degree_max = 8; // Weights of the three smoothing terms; nullopt = plain tolerance-driven fit. diff --git a/src/cpp/include/scad/surface/operators.hpp b/src/cpp/include/scad/surface/operators.hpp index 17e0bf78..66670a94 100644 --- a/src/cpp/include/scad/surface/operators.hpp +++ b/src/cpp/include/scad/surface/operators.hpp @@ -10,6 +10,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/surface/types.hpp" #include "scad/topo/shape.hpp" @@ -26,7 +27,7 @@ struct CylindricalSurfaceOptions { ScalarVec3 origin{0, 0, 0}; ScalarVec3 axis{0, 0, 1}; std::optional x_direction; // default: the canonical in-plane X for `axis` - Scalar tolerance = 1e-7; + Scalar tolerance = tol::kSurfaceTrim; TagPrefix tag_prefix; }; @@ -36,7 +37,7 @@ Face make_cylindrical_surface_rface(const Scalar& radius, const ScalarRange& u_r const CylindricalSurfaceOptions& options = {}); struct FitPointGridOptions { - double tolerance = 1e-3; + double tolerance = tol::kFitError; int degree_min = 3; int degree_max = 8; std::optional> smoothing; // three non-negative smoothing weights @@ -53,7 +54,7 @@ Face make_ruled_surface_rface(const Edge& edge_a, const Edge& edge_b, const TagP // A Gordon Face interpolating a network of intersecting profile and guide edges. Face make_gordon_surface_rface(const std::vector& profiles, const std::vector& guides, - double tolerance = 1e-3, const TagPrefix& tag_prefix = std::nullopt); + double tolerance = tol::kFitError, const TagPrefix& tag_prefix = std::nullopt); struct SurfacePatchOptions { std::vector points; // extra points to pass through (current coordinate system) @@ -69,7 +70,7 @@ Face make_surface_patch_rface(const std::vector& boundaries, co struct TrimSurfaceOptions { std::vector holes; - double tolerance = 1e-7; + double tolerance = tol::kSurfaceTrim; TagPrefix tag_prefix; }; @@ -91,18 +92,18 @@ struct LoftShellTags { Shell loft_rshell(const std::vector& sections, bool ruled = false, const LoftShellTags& tags = {}); // Sew faces into exactly one connected Shell. -Shell sew_faces_rshell(const std::vector& faces, double tolerance = 1e-6, +Shell sew_faces_rshell(const std::vector& faces, double tolerance = tol::kSewing, const TagPrefix& tag_prefix = std::nullopt); // One oriented Solid from one valid closed Shell. Solid make_solid_from_shell_rsolid(const Shell& shell, const TagPrefix& tag_prefix = std::nullopt); // The unique closed and open free boundary wires of a Shell (closed ones first). -std::vector free_boundaries_rwirelist(const Shell& shell, double tolerance = 1e-6); +std::vector free_boundaries_rwirelist(const Shell& shell, double tolerance = tol::kSewing); struct FillHolesOptions { std::optional> hole_indices; // indices into free_boundaries_rwirelist; default: all - double tolerance = 1e-6; + double tolerance = tol::kSewing; std::optional settings; TagPrefix tag_prefix; }; diff --git a/src/cpp/include/scad/surface/types.hpp b/src/cpp/include/scad/surface/types.hpp index 60a3df19..5be4ebf0 100644 --- a/src/cpp/include/scad/surface/types.hpp +++ b/src/cpp/include/scad/surface/types.hpp @@ -10,6 +10,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/scalar.hpp" #include "scad/core/value.hpp" #include "scad/core/vec.hpp" @@ -48,8 +49,8 @@ struct SurfaceFillingSettings { int points_per_curve = 15; int iterations = 2; bool anisotropic = false; - double tolerance_2d = 1e-5; - double tolerance_3d = 1e-4; + double tolerance_2d = tol::kFillingTolerance2d; + double tolerance_3d = tol::kFillingTolerance3d; double angular_tolerance = 0.01; double curvature_tolerance = 0.1; int max_degree = 8; diff --git a/src/cpp/src/core/coordinate_system.cpp b/src/cpp/src/core/coordinate_system.cpp index 67db9459..5c4b6492 100644 --- a/src/cpp/src/core/coordinate_system.cpp +++ b/src/cpp/src/core/coordinate_system.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/core/coordinate_system.hpp" #include @@ -145,7 +146,7 @@ CoordinateSystem workplane_frame(const Vec3& origin, const Vec3& normal, const V Vec3 global_y = global_normal.cross(global_x); const double y_norm = global_y.norm(); - if (y_norm < 1e-10) { + if (y_norm < tol::kParallelCrossNorm) { // x_dir is parallel to the normal: pick any perpendicular. const Vec3 temp_x = std::abs(global_normal.x) < 0.9 ? Vec3{1, 0, 0} : Vec3{0, 1, 0}; global_y = global_normal.cross(temp_x); diff --git a/src/cpp/src/kernel/convert.cpp b/src/cpp/src/kernel/convert.cpp index 575765d4..2824748c 100644 --- a/src/cpp/src/kernel/convert.cpp +++ b/src/cpp/src/kernel/convert.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include @@ -7,7 +8,7 @@ namespace scad::kernel { gp_Dir to_dir(const Vec3& v, const char* what) { - if (!v.is_finite() || v.norm() <= 1e-15) { + if (!v.is_finite() || v.norm() <= tol::kZeroDirectionNorm) { throw ValueError(std::string(what) + " must be a finite, non-zero vector, got " + scad::to_string(v)); } return gp_Dir(v.x, v.y, v.z); diff --git a/src/cpp/src/kernel/properties.cpp b/src/cpp/src/kernel/properties.cpp index 402ae0ee..bbddf74b 100644 --- a/src/cpp/src/kernel/properties.cpp +++ b/src/cpp/src/kernel/properties.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/kernel/properties.hpp" #include @@ -55,7 +56,7 @@ double volume(const TopoDS_Shape& shape) { GProp_GProps props; // Knot-span integration: the fixed-order routine loses precision on // rational curves and can crash on affine-transformed trims. - BRepGProp::VolumePropertiesGK(shape, props, 1e-9, true, true); + BRepGProp::VolumePropertiesGK(shape, props, tol::kVolumeIntegration, true, true); return props.Mass(); }); } @@ -63,7 +64,7 @@ double volume(const TopoDS_Shape& shape) { double volume_estimate(const TopoDS_Shape& shape) { return occt_guard([&] { GProp_GProps props; - BRepGProp::VolumePropertiesGK(shape, props, 1e-5, true, true); + BRepGProp::VolumePropertiesGK(shape, props, tol::kVolumeEstimate, true, true); return props.Mass(); }); } @@ -92,7 +93,7 @@ Vec3 center_of_mass(const TopoDS_Shape& shape) { case TopAbs_COMPSOLID: case TopAbs_COMPOUND: try { - BRepGProp::VolumePropertiesGK(shape, props, 1e-9, true, true); + BRepGProp::VolumePropertiesGK(shape, props, tol::kVolumeIntegration, true, true); if (mass_point(props, point)) return point; } catch (...) { diff --git a/src/cpp/src/ops/features/affine.cpp b/src/cpp/src/ops/features/affine.cpp index c656ff3d..fcb4e66d 100644 --- a/src/cpp/src/ops/features/affine.cpp +++ b/src/cpp/src/ops/features/affine.cpp @@ -10,6 +10,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include "scad/ops/features/transforms.hpp" @@ -127,14 +128,14 @@ Solid transform_rsolid(const Solid& solid, const std::vector } const std::array last{0, 0, 0, 1}; for (std::size_t j = 0; j < 4; ++j) { - if (std::abs(values[3][j] - last[j]) > 1e-12) + if (std::abs(values[3][j] - last[j]) > tol::kAffineBottomRow) throw ValueError("perspective transforms cannot define an affine solid"); } Mat3 affine{}; for (std::size_t i = 0; i < 3; ++i) for (std::size_t j = 0; j < 3; ++j) affine[i][j] = values[i][j]; - if (std::abs(determinant(affine)) < 1e-14) + if (std::abs(determinant(affine)) < tol::kSingularDeterminant) throw ValueError("matrix must be nonsingular"); const Mat3 basis = current_basis(); diff --git a/src/cpp/src/ops/features/blends.cpp b/src/cpp/src/ops/features/blends.cpp index 2e568649..59555b2d 100644 --- a/src/cpp/src/ops/features/blends.cpp +++ b/src/cpp/src/ops/features/blends.cpp @@ -1,4 +1,5 @@ // fillet_rsolid, chamfer_rsolid (operators/features.py). +#include "scad/core/tolerance.hpp" #include "scad/ops/features/blends.hpp" #include @@ -154,7 +155,7 @@ namespace { std::vector> chamfer_reference_face_pairs(const std::vector& edges, const Vec3& reference_direction) { const double norm = reference_direction.norm(); - if (norm <= 1e-12) + if (norm <= tol::kDegenerateNorm) throw ValueError("chamfer reference_direction must be non-zero"); const Vec3 direction = reference_direction / norm; std::vector> pairs; diff --git a/src/cpp/src/ops/features/boolean_diagnosis.cpp b/src/cpp/src/ops/features/boolean_diagnosis.cpp index 92208874..58e3e5ee 100644 --- a/src/cpp/src/ops/features/boolean_diagnosis.cpp +++ b/src/cpp/src/ops/features/boolean_diagnosis.cpp @@ -4,6 +4,7 @@ #include #include "probes.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/booleans.hpp" #include "scad/kernel/properties.hpp" #include "scad/kernel/topology.hpp" @@ -176,7 +177,7 @@ std::optional diagnose_boolean_failure(const std::vector @@ -23,9 +24,9 @@ constexpr const char* kCutOp = "make_cut_rsolid"; constexpr const char* kCutListOp = "make_cut_rsolid_list"; constexpr const char* kIntersectOp = "make_intersect_rsolid"; -constexpr double kUnionTolFactor = 1e-7; -constexpr double kUnionTolMin = 1e-7; -constexpr double kUnionTolMax = 1e-5; +constexpr double kUnionTolFactor = tol::kFuzzyUnionRelative; +constexpr double kUnionTolMin = tol::kFuzzyUnionMin; +constexpr double kUnionTolMax = tol::kFuzzyUnionMax; const ErrorSpec& union_spec() { static const ErrorSpec spec{ @@ -312,7 +313,7 @@ CutRun run_cuts(const std::vector& solids, const CutOptions& options, Tra next.push_back(piece); continue; } - if (kernel::volume(overlap.front()) < 1e-12) { + if (kernel::volume(overlap.front()) < tol::kEmptyVolume) { too_small = true; next.push_back(piece); continue; @@ -471,7 +472,7 @@ Solid intersect_rsolid(const std::vector& solids) { result_solid = *tracked.solid; deltas.push_back(std::move(tracked.delta)); merge_entries(merged_entries, std::move(tracked.delta_entries)); - if (kernel::volume(result_solid.wrapped()) < 1e-12) { + if (kernel::volume(result_solid.wrapped()) < tol::kEmptyVolume) { empty_result = true; throw ValueError("The intersection is empty or its volume is too small"); } diff --git a/src/cpp/src/ops/features/extrude_until.cpp b/src/cpp/src/ops/features/extrude_until.cpp index 4563f63d..6a884bad 100644 --- a/src/cpp/src/ops/features/extrude_until.cpp +++ b/src/cpp/src/ops/features/extrude_until.cpp @@ -26,6 +26,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include "scad/kernel/properties.hpp" #include "scad/kernel/topology.hpp" @@ -65,7 +66,8 @@ bool crosses_direction(const TopoDS_Face& face, const Vec3& axis) { gp_Vec normal; properties.Normal(u0 + u * (u1 - u0), v0 + v * (v1 - v0), point, normal); const double length = normal.Magnitude(); - if (length > 1e-14 && std::abs(normal.X() * axis.x + normal.Y() * axis.y + normal.Z() * axis.z) / length > 1e-8) + if (length > tol::kUndefinedNormal && + std::abs(normal.X() * axis.x + normal.Y() * axis.y + normal.Z() * axis.z) / length > 1e-8) return true; } } @@ -102,7 +104,7 @@ std::vector contact_surfaces(const TopoDS_Shape& target, const Top if (touched.empty()) throw ValueError("No target boundary surfaces found in extrusion intersection"); - BRepBuilderAPI_Sewing sewing(1e-6); + BRepBuilderAPI_Sewing sewing(tol::kSewing); for (const TopoDS_Face& face : touched) { if (crosses_direction(face, axis)) sewing.Add(face); @@ -138,7 +140,7 @@ std::vector split_on_surface(const TopoDS_Shape& prism, const Topo gp_Pnt point; gp_Vec normal; BRepGProp_Face(reference_face).Normal((u0 + u1) / 2, (v0 + v1) / 2, point, normal); - if (normal.Magnitude() <= 1e-14) + if (normal.Magnitude() <= tol::kUndefinedNormal) throw ValueError("Undefined normal on termination surface"); normal.Normalize(); const gp_Pnt reference = point.Translated(normal); @@ -176,7 +178,7 @@ Solid extrude_until_rsolid(const Face& profile, const std::vector& target const Vec3 values = finite_vector(direction, "direction"); const Vec3 global_direction = features_detail::place_vector(values); const double magnitude = global_direction.norm(); - if (!std::isfinite(magnitude) || magnitude <= 1e-14) + if (!std::isfinite(magnitude) || magnitude <= tol::kUndefinedNormal) throw ValueError("direction must be a finite nonzero vector"); Vec3 axis = global_direction / magnitude; if (mode == "PREVIOUS" || mode == "FIRST") @@ -190,7 +192,7 @@ Solid extrude_until_rsolid(const Face& profile, const std::vector& target const TopoDS_Compound bound_target = compound_of(target_shapes); const kernel::BoundingBox box = kernel::bounding_box(compound_of({profile.wrapped(), bound_target})); const double length = std::sqrt(box.xlen() * box.xlen() + box.ylen() * box.ylen() + box.zlen() * box.zlen()); - if (length <= 1e-12) + if (length <= tol::kDegenerateNorm) throw ValueError("Degenerate profile and target bounds"); const TopoDS_Shape prism = BRepPrimAPI_MakePrism(profile.wrapped(), kernel::to_vec(axis * length)).Shape(); @@ -219,7 +221,7 @@ Solid extrude_until_rsolid(const Face& profile, const std::vector& target if (std::abs(chosen_volume - prism_volume) <= std::max(1e-8, std::abs(prism_volume) * 1e-9)) { throw ValueError("Target termination surface does not completely cover the extrusion profile"); } - if (chosen_volume <= 1e-12 || !BRepCheck_Analyzer(*best).IsValid()) { + if (chosen_volume <= tol::kEmptyVolume || !BRepCheck_Analyzer(*best).IsValid()) { throw ValueError("Target surface did not completely cover a valid limited extrusion"); } return *best; diff --git a/src/cpp/src/ops/features/extrusion.cpp b/src/cpp/src/ops/features/extrusion.cpp index 47d8f8b1..40a643d5 100644 --- a/src/cpp/src/ops/features/extrusion.cpp +++ b/src/cpp/src/ops/features/extrusion.cpp @@ -1,4 +1,5 @@ // extrude_rsolid (operators/features.py). +#include "scad/core/tolerance.hpp" #include "scad/ops/features/extrusion.hpp" #include "internal.hpp" @@ -51,7 +52,7 @@ Solid extrude_rsolid(const Shape& profile, const Scalar3& direction, const Scala if (distance_value <= 0) throw ValueError("The extrusion distance must be greater than zero"); const Vec3 global_direction = features_detail::place_vector(rec.point("direction", direction)); - if (global_direction.norm() <= 1e-15) + if (global_direction.norm() <= tol::kZeroDirectionNorm) throw ValueError("The extrusion direction cannot be a zero vector"); const Face face = extrusion_face(profile); diff --git a/src/cpp/src/ops/features/loft_diagnosis.cpp b/src/cpp/src/ops/features/loft_diagnosis.cpp index 597a98ad..39213a88 100644 --- a/src/cpp/src/ops/features/loft_diagnosis.cpp +++ b/src/cpp/src/ops/features/loft_diagnosis.cpp @@ -8,6 +8,7 @@ #include #include "probes.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/topology.hpp" #include "scad/ops/features/diagnostics.hpp" #include "scad/ops/features/support.hpp" @@ -133,7 +134,7 @@ void raise_loft_failure_if_diagnosed(const std::vector& sections, std::st for (std::size_t i = 0; i + 1 < facts.size(); ++i) { const SectionFacts &a = facts[i], &b = facts[i + 1]; const double distance = a.centroid.distance(b.centroid); - if (distance > 1e-9) + if (distance > tol::kCoincidentPoints) continue; findings.push_back(b.id + " coincides with " + a.id + " (centroid distance " + g3(distance) + " mm)"); implicated.insert({a.id, b.id}); @@ -178,7 +179,7 @@ void raise_loft_failure_if_diagnosed(const std::vector& sections, std::st // Station order: project the centroids on the first-to-last axis; any backtrack is out of order. const Vec3 first = facts.front().centroid, last = facts.back().centroid; const double axis_norm = first.distance(last); - if (axis_norm > 1e-9 && facts.size() > 2) { + if (axis_norm > tol::kNegligibleLength && facts.size() > 2) { const Vec3 axis = last - first; std::vector projections; for (const SectionFacts& fact : facts) diff --git a/src/cpp/src/ops/features/multisection.cpp b/src/cpp/src/ops/features/multisection.cpp index 9dce7534..e21b0dec 100644 --- a/src/cpp/src/ops/features/multisection.cpp +++ b/src/cpp/src/ops/features/multisection.cpp @@ -4,6 +4,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include "scad/ops/features/sweeps.hpp" @@ -31,7 +32,7 @@ Solid sweep_multisection_rsolid(const std::vector& profiles, const Wire& } else if (direction) { const Vec3 values = finite_vector(*direction, "binormal"); const Vec3 placed = features_detail::place_vector(values); - if (placed.norm() < 1e-12) + if (placed.norm() < tol::kDegenerateNorm) throw ValueError("binormal direction must be nonzero"); builder.SetMode(kernel::to_dir(placed, "binormal")); rotate = true; diff --git a/src/cpp/src/ops/features/offsets.cpp b/src/cpp/src/ops/features/offsets.cpp index cf86e183..5c4bd6f8 100644 --- a/src/cpp/src/ops/features/offsets.cpp +++ b/src/cpp/src/ops/features/offsets.cpp @@ -12,6 +12,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include "scad/ops/features/blends.hpp" @@ -67,7 +68,7 @@ Solid draft_rsolid(const Solid& solid, const FaceSelection& faces_to_draft, cons const Vec3 global_origin = features_detail::place_point(origin); Vec3 global_normal = features_detail::place_vector(normal); const double magnitude = global_normal.norm(); - if (magnitude <= 1e-14) + if (magnitude <= tol::kUndefinedNormal) throw ValueError("plane_normal must be nonzero"); global_normal = global_normal / magnitude; diff --git a/src/cpp/src/ops/features/patterns.cpp b/src/cpp/src/ops/features/patterns.cpp index 74ddfafd..a46565c8 100644 --- a/src/cpp/src/ops/features/patterns.cpp +++ b/src/cpp/src/ops/features/patterns.cpp @@ -2,6 +2,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/ops/features/transforms.hpp" namespace scad { @@ -37,7 +38,7 @@ std::vector linear_pattern_rsolidlist(const Shape& shape, const Scalar3& throw ValueError("The pattern spacing must be greater than zero"); const Vec3 direction_value = evaluate_point(direction, "direction"); const double norm = direction_value.norm(); - if (norm <= 1e-15 || !std::isfinite(norm)) + if (norm <= tol::kZeroDirectionNorm || !std::isfinite(norm)) throw ValueError("The pattern direction cannot be a zero vector"); const Vec3 unit = direction_value / norm; diff --git a/src/cpp/src/ops/features/probes.cpp b/src/cpp/src/ops/features/probes.cpp index d29c5f21..98a5a3cb 100644 --- a/src/cpp/src/ops/features/probes.cpp +++ b/src/cpp/src/ops/features/probes.cpp @@ -18,6 +18,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/kernel/convert.hpp" #include "scad/kernel/topology.hpp" #include "scad/ops/features/support.hpp" @@ -76,7 +77,7 @@ EdgeEnd edge_end(const BRepAdaptor_Curve& curve, bool at_start) { if (toward == parameter) return end; const Vec3 along = vec_of(curve.Value(toward)) - vec_of(end.point); - if (along.norm() >= 1e-12) + if (along.norm() >= tol::kDegenerateNorm) end.inward = along.normalized(); return end; } @@ -204,7 +205,7 @@ std::optional edge_is_concave(const TopoDS_Solid& solid, const TopoDS_Face return std::nullopt; const Vec3 bisector = *na + *nb; const double length = bisector.norm(); - if (length < 1e-9) + if (length < tol::kNegligibleLength) return std::nullopt; return inside(solid, offset_point(middle, bisector, 1e-3 / length)); } catch (const std::exception&) { @@ -225,7 +226,7 @@ std::optional edge_is_concave_side_probe(const TopoDS_Solid& solid, const const Vec3 delta = *normals[static_cast(first)] - *normals[static_cast(second)]; const double length = delta.norm(); // Equal normals: tangent faces, left to the tangent-adjacency probe. - if (length < 1e-9) + if (length < tol::kNegligibleLength) continue; if (inside(solid, offset_point(middle, delta, 1e-3 / length))) return true; diff --git a/src/cpp/src/ops/features/sweeps.cpp b/src/cpp/src/ops/features/sweeps.cpp index a4157af0..524e8d94 100644 --- a/src/cpp/src/ops/features/sweeps.cpp +++ b/src/cpp/src/ops/features/sweeps.cpp @@ -1,4 +1,5 @@ // loft_rsolid, sweep_rsolid, twisted_sweep_rsolid (operators/features.py). +#include "scad/core/tolerance.hpp" #include "scad/ops/features/sweeps.hpp" #include @@ -149,7 +150,7 @@ Solid twisted_sweep_rsolid(const Shape& profile, const Scalar& distance, const S const Vec3 global_axis = features_detail::place_vector(rec.point("axis", axis)); const Vec3 global_origin = features_detail::place_point(rec.point("origin", origin)); const double axis_norm = global_axis.norm(); - if (!std::isfinite(axis_norm) || axis_norm <= 1.0e-15) + if (!std::isfinite(axis_norm) || axis_norm <= tol::kZeroDirectionNorm) throw ValueError("axis must be a finite non-zero vector"); const OutputTags output = features_detail::sweep_output_tags(options.tags, "twisted_sweep.start", diff --git a/src/cpp/src/ops/features/taper.cpp b/src/cpp/src/ops/features/taper.cpp index cf8362ee..2c17b513 100644 --- a/src/cpp/src/ops/features/taper.cpp +++ b/src/cpp/src/ops/features/taper.cpp @@ -14,6 +14,7 @@ #include #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/kernel/booleans.hpp" #include "scad/kernel/convert.hpp" #include "scad/kernel/topology.hpp" @@ -53,7 +54,7 @@ Solid extrude_taper_rsolid(const Face& profile, const Scalar3& vector, const Sca throw ValueError("taper must be finite and between -90 and 90 degrees"); const Vec3 displacement = features_detail::place_vector(values); const double length = displacement.norm(); - if (length <= 1e-12) + if (length <= tol::kDegenerateNorm) throw ValueError("extrusion vector must be nonzero"); const TopoDS_Face face = TopoDS::Face(profile.wrapped()); diff --git a/src/cpp/src/ops/features/transforms.cpp b/src/cpp/src/ops/features/transforms.cpp index 5ee92dba..cc7cbf26 100644 --- a/src/cpp/src/ops/features/transforms.cpp +++ b/src/cpp/src/ops/features/transforms.cpp @@ -1,4 +1,5 @@ // translate_shape, rotate_shape, mirror_shape (operators/transform.py). +#include "scad/core/tolerance.hpp" #include "scad/ops/features/transforms.hpp" #include "internal.hpp" @@ -96,7 +97,7 @@ Shape mirror_shape(const Shape& shape, const Scalar3& plane_origin, const Scalar FeatureRecord rec(kMirrorOp); const Vec3 global_origin = features_detail::place_point(rec.point("plane_origin", plane_origin)); const Vec3 global_normal = features_detail::place_vector(rec.point("plane_normal", plane_normal)); - if (global_normal.norm() < 1e-10) + if (global_normal.norm() < tol::kMirrorNormalNorm) throw ValueError("The mirror plane normal cannot be a zero vector"); if (shape.kind() == Kind::Solid) { diff --git a/src/cpp/src/ops/geometry/bspline_args.cpp b/src/cpp/src/ops/geometry/bspline_args.cpp index 0475d743..945b7dc2 100644 --- a/src/cpp/src/ops/geometry/bspline_args.cpp +++ b/src/cpp/src/ops/geometry/bspline_args.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/ops/geometry/bspline_args.hpp" #include @@ -40,7 +41,7 @@ Knots collapse_knot_vector(const ScalarList& knots) { } Knots out; for (const double value : values) { - if (!out.unique.empty() && std::abs(value - out.unique.back()) <= 1e-12) { + if (!out.unique.empty() && std::abs(value - out.unique.back()) <= tol::kDuplicateParameter) { ++out.multiplicities.back(); } else { out.unique.push_back(value); diff --git a/src/cpp/src/ops/geometry/faces.cpp b/src/cpp/src/ops/geometry/faces.cpp index 82ef585b..88f67ee2 100644 --- a/src/cpp/src/ops/geometry/faces.cpp +++ b/src/cpp/src/ops/geometry/faces.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/ops/geometry/faces.hpp" #include @@ -84,7 +85,7 @@ Face make_face_from_wires_rface(const Shape& outer_wire, const std::vector raw_inner; diff --git a/src/cpp/src/ops/geometry/plane.cpp b/src/cpp/src/ops/geometry/plane.cpp index 3c893143..fa943a98 100644 --- a/src/cpp/src/ops/geometry/plane.cpp +++ b/src/cpp/src/ops/geometry/plane.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/ops/geometry/plane.hpp" #include @@ -15,14 +16,14 @@ namespace scad { PlaneAxes orthonormal_plane_axes(const Vec3& normal) { const double norm = normal.norm(); - if (norm <= 1e-12) + if (norm <= tol::kDegenerateNorm) throw ValueError("The normal vector cannot be a zero vector"); const Vec3 z = normal / norm; const Vec3 reference = std::abs(z.z) > 0.9 ? Vec3{1.0, 0.0, 0.0} : Vec3{0.0, 0.0, 1.0}; // Gram-Schmidt: the reference stays away from z, so the projection never degenerates. Vec3 x = reference - z * reference.dot(z); const double x_norm = x.norm(); - if (x_norm <= 1e-12) + if (x_norm <= tol::kDegenerateNorm) throw ValueError("Cannot build a local coordinate system from the given normal vector"); x = x / x_norm; Vec3 y = z.cross(x); diff --git a/src/cpp/src/ops/geometry/rectangles.cpp b/src/cpp/src/ops/geometry/rectangles.cpp index a792b6d8..069a5151 100644 --- a/src/cpp/src/ops/geometry/rectangles.cpp +++ b/src/cpp/src/ops/geometry/rectangles.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/ops/geometry/rectangles.hpp" #include @@ -57,7 +58,7 @@ std::vector placed_corners(double width, double height, const Scalar3& cen const Vec3 center_global = cs.transform_point(evaluate_point(center, "center")); const Vec3 normal_value = evaluate_point(normal, "normal"); const double normal_norm = cs.transform_vector(normal_value).norm(); - if (normal_norm <= 1e-15 || !std::isfinite(normal_norm)) + if (normal_norm <= tol::kZeroDirectionNorm || !std::isfinite(normal_norm)) throw ValueError("The normal vector cannot be a zero vector"); const PlaneAxes axes = orthonormal_plane_axes(normal_value); diff --git a/src/cpp/src/product/connector.cpp b/src/cpp/src/product/connector.cpp index fe4b1f6c..045a7216 100644 --- a/src/cpp/src/product/connector.cpp +++ b/src/cpp/src/product/connector.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/product/connector.hpp" #include @@ -172,7 +173,7 @@ Vec3 selector_vec(const Value& selector, std::string_view key, const Vec3& fallb Vec3 normalized_or_throw(const Vec3& value, const char* field) { const Vec3 vec = finite_vec3(value, field); const double length = vec.norm(); - if (length <= 1e-9) + if (length <= tol::kNegligibleLength) throw ValueError(std::string(field) + " must be a non-zero vector"); return {vec.x / length, vec.y / length, vec.z / length}; } diff --git a/src/cpp/src/product/placement.cpp b/src/cpp/src/product/placement.cpp index 0217fc9f..ea6ae169 100644 --- a/src/cpp/src/product/placement.cpp +++ b/src/cpp/src/product/placement.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/product/placement.hpp" #include @@ -9,7 +10,7 @@ namespace scad::product { namespace { -constexpr double kAxisTolerance = 1e-9; +constexpr double kAxisTolerance = tol::kNegligibleLength; constexpr double kOrthogonalTolerance = 1e-7; constexpr double kExactTolerance = 2.0e-6; diff --git a/src/cpp/src/ql/diagnostics.cpp b/src/cpp/src/ql/diagnostics.cpp index 79714611..f20a5079 100644 --- a/src/cpp/src/ql/diagnostics.cpp +++ b/src/cpp/src/ql/diagnostics.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/ql/diagnostics.hpp" #include @@ -161,24 +162,25 @@ bool same_surface(const SurfaceKey& a, const SurfaceKey& b) { switch (a.type) { case GeomAbs_Plane: { const double parallel = std::abs(a.plane.Axis().Direction().Dot(b.plane.Axis().Direction())); - return parallel >= 0.999 && std::abs(a.plane.Distance(b.plane.Location())) < 1e-6; + return parallel >= tol::kParallelAxisCosine && + std::abs(a.plane.Distance(b.plane.Location())) < tol::kSurfaceCoincidentDistance; } case GeomAbs_Cylinder: { - if (std::abs(a.cylinder.Radius() - b.cylinder.Radius()) > 1e-7) + if (std::abs(a.cylinder.Radius() - b.cylinder.Radius()) > tol::kSurfaceRadiusMatch) return false; const gp_Dir da = a.cylinder.Axis().Direction(); - if (std::abs(da.Dot(b.cylinder.Axis().Direction())) < 0.999) + if (std::abs(da.Dot(b.cylinder.Axis().Direction())) < tol::kParallelAxisCosine) return false; const gp_Pnt oa = a.cylinder.Axis().Location(); const gp_Pnt ob = b.cylinder.Axis().Location(); const double delta[3] = {ob.X() - oa.X(), ob.Y() - oa.Y(), ob.Z() - oa.Z()}; const double along = delta[0] * da.X() + delta[1] * da.Y() + delta[2] * da.Z(); const double off[3] = {delta[0] - along * da.X(), delta[1] - along * da.Y(), delta[2] - along * da.Z()}; - return std::sqrt(off[0] * off[0] + off[1] * off[1] + off[2] * off[2]) < 1e-6; + return std::sqrt(off[0] * off[0] + off[1] * off[1] + off[2] * off[2]) < tol::kSurfaceCoincidentDistance; } case GeomAbs_Sphere: - return a.sphere.Location().Distance(b.sphere.Location()) < 1e-6 && - std::abs(a.sphere.Radius() - b.sphere.Radius()) < 1e-7; + return a.sphere.Location().Distance(b.sphere.Location()) < tol::kSurfaceCoincidentDistance && + std::abs(a.sphere.Radius() - b.sphere.Radius()) < tol::kSurfaceRadiusMatch; case GeomAbs_Cone: case GeomAbs_Torus: return !a.handle.IsNull() && a.handle.get() == b.handle.get(); diff --git a/src/cpp/src/reactive/bspline_fit.cpp b/src/cpp/src/reactive/bspline_fit.cpp index 096c9a04..edcfa930 100644 --- a/src/cpp/src/reactive/bspline_fit.cpp +++ b/src/cpp/src/reactive/bspline_fit.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/reactive/bspline_fit.hpp" #include @@ -12,7 +13,7 @@ namespace scad::reactive { namespace { constexpr int kDegree = 3; -constexpr double kKnotMergeTolerance = 1e-12; +constexpr double kKnotMergeTolerance = tol::kDuplicateParameter; // Dense row-major matrix. struct Matrix { diff --git a/src/cpp/src/render/camera.cpp b/src/cpp/src/render/camera.cpp index 41b57c14..70d5fac0 100644 --- a/src/cpp/src/render/camera.cpp +++ b/src/cpp/src/render/camera.cpp @@ -2,6 +2,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/render/render.hpp" @@ -78,9 +79,9 @@ Camera fit_camera(double elevation_deg, double azimuth_deg, const Bounds& bounds cam.target = center; cam.forward = -dir; Vec3 right = cam.forward.cross(up_hint); - if (right.norm() < 1e-12) + if (right.norm() < tol::kDegenerateNorm) right = cam.forward.cross(Vec3{0, 1, 0}); - if (right.norm() < 1e-12) + if (right.norm() < tol::kDegenerateNorm) right = cam.forward.cross(Vec3{1, 0, 0}); cam.right = right.normalized(); cam.up = cam.right.cross(cam.forward).normalized(); diff --git a/src/cpp/src/semantic/tracking_lofts.cpp b/src/cpp/src/semantic/tracking_lofts.cpp index 73318529..1c83e4b9 100644 --- a/src/cpp/src/semantic/tracking_lofts.cpp +++ b/src/cpp/src/semantic/tracking_lofts.cpp @@ -28,6 +28,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/kernel/cast.hpp" #include "scad/kernel/convert.hpp" @@ -287,7 +288,7 @@ TrackedResult tracked_twisted_sweep(const Face& profile, const Vec3& axis, const const TopoDS_Shape end_face = kernel::apply_transform(face, translation.Multiplied(rotation)); // The skins plus a cap at each end close into a shell. - BRepBuilderAPI_Sewing sewing(1.0e-6, true); + BRepBuilderAPI_Sewing sewing(tol::kSewing, true); for (const TopoDS_Shape& skinned : skins) sewing.Add(skinned); sewing.Add(face); diff --git a/src/cpp/src/semantic/tracking_sweeps.cpp b/src/cpp/src/semantic/tracking_sweeps.cpp index c50c0f2e..6118db02 100644 --- a/src/cpp/src/semantic/tracking_sweeps.cpp +++ b/src/cpp/src/semantic/tracking_sweeps.cpp @@ -7,6 +7,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/kernel/cast.hpp" #include "scad/kernel/convert.hpp" @@ -47,7 +48,7 @@ TrackedResult track_swept_profile(Sweep& sweep, const Face& profile, const Solid TrackedResult tracked_extrude(const Face& profile, const Vec3& direction, double distance) { const double norm = direction.norm(); - if (norm <= 1e-15) + if (norm <= tol::kZeroDirectionNorm) throw ValueError("Extrude direction cannot be zero-length"); const Vec3 offset = direction / norm * distance; diff --git a/src/cpp/src/sketch/bspline_params.cpp b/src/cpp/src/sketch/bspline_params.cpp index b7751110..e5bbdb1b 100644 --- a/src/cpp/src/sketch/bspline_params.cpp +++ b/src/cpp/src/sketch/bspline_params.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/sketch/bspline_params.hpp" #include @@ -23,7 +24,7 @@ BSplineKnots collapse_knot_vector(const std::vector& values) { } BSplineKnots out; for (const double value : values) { - if (!out.knots.empty() && std::abs(value - out.knots.back()) <= 1e-12) { + if (!out.knots.empty() && std::abs(value - out.knots.back()) <= tol::kDuplicateParameter) { ++out.multiplicities.back(); } else { out.knots.push_back(value); diff --git a/src/cpp/src/sketch/convert.cpp b/src/cpp/src/sketch/convert.cpp index 5e16c71f..b949eae1 100644 --- a/src/cpp/src/sketch/convert.cpp +++ b/src/cpp/src/sketch/convert.cpp @@ -6,6 +6,7 @@ #include #include +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/kernel/convert.hpp" #include "scad/kernel/curves.hpp" @@ -15,7 +16,7 @@ namespace scad::sketch_detail { namespace { -constexpr double kPointEps = 1e-9; +constexpr double kPointEps = tol::kCoincidentPoints; // OCCT's canonical in-plane X axis for a normal (what make_circle_redge uses). Vec3 default_plane_x_direction(const Vec3& normal) { @@ -39,7 +40,7 @@ TopoDS_Edge arc_edge(const Sketch& sketch, const SketchSolveResult& result, cons const SketchPoint2 cp = result.solved_points.at(entity.point_id("center")); const double start_radius = std::hypot(sp.first - cp.first, sp.second - cp.second); const double end_radius = std::hypot(ep.first - cp.first, ep.second - cp.second); - const double radius_tolerance = std::max(kPointEps, start_radius * 1.0e-7); + const double radius_tolerance = std::max(kPointEps, start_radius * tol::kArcRadiusRelative); if (start_radius <= kPointEps) throw ValueError("Sketch arc '" + eid + "' has zero radius"); if (std::abs(start_radius - end_radius) > radius_tolerance) { @@ -50,7 +51,7 @@ TopoDS_Edge arc_edge(const Sketch& sketch, const SketchSolveResult& result, cons double sweep = std::fmod(end_angle - start_angle, 2.0 * kPi); if (sweep < 0.0) sweep += 2.0 * kPi; // Python's `% (2 pi)` is non-negative - if (sweep <= 1.0e-12) + if (sweep <= tol::kArcSweepZero) throw ValueError("Sketch arc '" + eid + "' has a zero sweep"); const double middle_angle = start_angle + 0.5 * sweep; const Vec3 middle = sketch.point3( diff --git a/src/cpp/src/sketch/sketch.cpp b/src/cpp/src/sketch/sketch.cpp index 4f8f7cd2..00136dd6 100644 --- a/src/cpp/src/sketch/sketch.cpp +++ b/src/cpp/src/sketch/sketch.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/sketch/sketch.hpp" #include "scad/topo/recorder.hpp" @@ -17,7 +18,7 @@ namespace scad { namespace { -constexpr double kPointEps = 1e-9; +constexpr double kPointEps = tol::kCoincidentPoints; thread_local const SketchIdAllocatorScope::Allocator* g_id_allocator = nullptr; @@ -545,12 +546,12 @@ SketchPlaneFrame Sketch::plane_frame() const { throw ValueError("Sketch plane origin and axes must contain finite values"); } const double x_length = x_axis.norm(); - if (x_length <= 1.0e-15) + if (x_length <= tol::kZeroDirectionNorm) throw ValueError("Sketch plane x_axis must be non-zero"); x_axis = x_axis / x_length; y_axis = y_axis - x_axis * y_axis.dot(x_axis); const double y_length = y_axis.norm(); - if (y_length <= 1.0e-15) + if (y_length <= tol::kZeroDirectionNorm) throw ValueError("Sketch plane x_axis and y_axis must not be parallel"); y_axis = y_axis / y_length; Vec3 normal = x_axis.cross(y_axis); diff --git a/src/cpp/src/std/bolt.cpp b/src/cpp/src/std/bolt.cpp index e9e4f452..fc8d7b74 100644 --- a/src/cpp/src/std/bolt.cpp +++ b/src/cpp/src/std/bolt.cpp @@ -6,6 +6,7 @@ #include #include "metadata.hpp" +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/ops/features/features.hpp" #include "scad/ops/geometry/geometry.hpp" @@ -93,7 +94,7 @@ std::vector drive_cutters(const std::string& drive_style, double drive_si double head_height) { if (drive_style == "none") return {}; - const double epsilon = std::max(1e-5, head_height * 1e-4); + const double epsilon = std::max(tol::kCutterOverrunFloor, head_height * tol::kCutterOverrunRelative); const Scalar3 cutter_origin = scalar3(0.0, 0.0, -head_height - epsilon); const double cutter_height = drive_depth + epsilon; const double slot_width = std::max(drive_size * 0.22, epsilon * 10.0); @@ -204,7 +205,7 @@ Solid make_bolt_rsolid(double diameter, double length, const BoltOptions& option throw ValueError("underhead_fillet_radius is too large for the shank and head dimensions"); } - const double epsilon = std::max(1e-5, resolved_diameter * 1e-4); + const double epsilon = std::max(tol::kCutterOverrunFloor, resolved_diameter * tol::kCutterOverrunRelative); double thread_phase_degrees = 0.0; const Solid shank = make_cylinder_rsolid(major_radius, resolved_length + epsilon, scalar3(0.0, 0.0, -epsilon), scalar3(0.0, 0.0, 1.0)); diff --git a/src/cpp/src/std/fastener_tables.cpp b/src/cpp/src/std/fastener_tables.cpp index e456ee36..cef1d325 100644 --- a/src/cpp/src/std/fastener_tables.cpp +++ b/src/cpp/src/std/fastener_tables.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/std/fastener_tables.hpp" #include @@ -45,7 +46,7 @@ constexpr std::array kMetricHexHead{{ // math.isclose(candidate, nominal, rel_tol=0, abs_tol=1e-9) bool matches_catalog(double candidate, double diameter) { - return std::fabs(candidate - diameter) <= 1e-9; + return std::fabs(candidate - diameter) <= tol::kCatalogDiameter; } } // namespace diff --git a/src/cpp/src/std/gear_geometry.cpp b/src/cpp/src/std/gear_geometry.cpp index 5038fac0..2b4c092f 100644 --- a/src/cpp/src/std/gear_geometry.cpp +++ b/src/cpp/src/std/gear_geometry.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/std/gear_geometry.hpp" #include @@ -90,7 +91,7 @@ InternalToothGeometry compute_internal_tooth_geometry(int n_teeth, double module return base_half_angle + (t - std::atan(t)); }; g.flank_tip_radius = std::max(g.base_radius, g.tip_radius); - g.needs_tip_connectors = g.tip_radius < g.base_radius - 1e-8; + g.needs_tip_connectors = g.tip_radius < g.base_radius - tol::kBaseCircleClearance; const double tip_half_angle = half_angle_at(g.flank_tip_radius); const double root_half_angle = half_angle_at(g.root_radius); diff --git a/src/cpp/src/std/gear_profiles.cpp b/src/cpp/src/std/gear_profiles.cpp index 85b93211..53af35ec 100644 --- a/src/cpp/src/std/gear_profiles.cpp +++ b/src/cpp/src/std/gear_profiles.cpp @@ -1,3 +1,4 @@ +#include "scad/core/tolerance.hpp" #include "scad/std/gear_profiles.hpp" #include @@ -62,7 +63,7 @@ Sketch build_gear_profile_sketch(int n_teeth, double module, double pressure_ang const double tip_radius = geo.tip_radius; const double tooth_angle = geo.tooth_angle; const double flank_start_radius = std::max(base_radius, root_radius); - const bool needs_root_connectors = root_radius < base_radius - 1e-8; + const bool needs_root_connectors = root_radius < base_radius - tol::kBaseCircleClearance; const double t_flank_start = involute_t_for_radius(base_radius, flank_start_radius); const double flank_start_span = t_flank_start - std::atan(t_flank_start); const double left_flank_start_angle = geo.left_start + flank_start_span; diff --git a/src/cpp/src/std/nut.cpp b/src/cpp/src/std/nut.cpp index 2efde283..b6ae7234 100644 --- a/src/cpp/src/std/nut.cpp +++ b/src/cpp/src/std/nut.cpp @@ -4,6 +4,7 @@ #include #include "metadata.hpp" +#include "scad/core/tolerance.hpp" #include "scad/core/error.hpp" #include "scad/ops/features/features.hpp" #include "scad/ops/geometry/geometry.hpp" @@ -81,7 +82,7 @@ Solid make_nut_rsolid(double diameter, double width, double height, const NutOpt } const Solid body = make_nut_body(nut_style, resolved_width, resolved_height, options.knurl_count); - const double epsilon = std::max(1e-5, resolved_diameter * 1e-4); + const double epsilon = std::max(tol::kCutterOverrunFloor, resolved_diameter * tol::kCutterOverrunRelative); const bool through = hole_style == "through"; const double cut_start = through ? -epsilon : hole_start; const double cut_height = through ? hole_depth + 2.0 * epsilon : hole_depth + epsilon; diff --git a/src/cpp/src/surface/faces_from_data.cpp b/src/cpp/src/surface/faces_from_data.cpp index 8adaab34..be590c53 100644 --- a/src/cpp/src/surface/faces_from_data.cpp +++ b/src/cpp/src/surface/faces_from_data.cpp @@ -14,6 +14,7 @@ #include "finalize.hpp" #include "internal.hpp" +#include "scad/core/tolerance.hpp" #include "scad/core/coordinate_system.hpp" #include "scad/kernel/convert.hpp" #include "scad/surface/fitter.hpp" @@ -173,9 +174,9 @@ Face make_cylindrical_surface_rface(const Scalar& radius, const ScalarRange& u_r throw ValueError("origin, axis, and x_direction must be finite 3D values"); const double axis_norm = axis.norm(); const double x_norm = x_direction.norm(); - if (axis_norm <= 1e-12 || x_norm <= 1e-12) + if (axis_norm <= tol::kDegenerateNorm || x_norm <= tol::kDegenerateNorm) throw ValueError("axis and x_direction must be non-zero"); - if (std::abs(axis.dot(x_direction)) / (axis_norm * x_norm) >= 1.0 - 1e-12) + if (std::abs(axis.dot(x_direction)) / (axis_norm * x_norm) >= 1.0 - tol::kParallelCosineGap) throw ValueError("axis and x_direction must not be parallel"); const CoordinateSystem& cs = current_cs();