Exact, evidence-carrying planar curves, paths, contours, and regions for CAD topology.
Hypercurve is the two-dimensional curve kernel in the Hyper geometry stack. It
models lines, circular arcs, Bézier curves, B-splines, and NURBS with
hyperreal::Real coordinates, then builds
intersection, classification, regularized Boolean, offset, reconstruction, and
finite-projection operations on those carriers.
The crate owns planar curve geometry and topology. It deliberately does not own solid modeling or mesh topology: CSG grammar and operations such as extrusion, revolve, sweep, and loft belong in CSGRS, while triangle-mesh Boolean work belongs in Hypermesh.
This README describes crate version 0.3.1.
| Type | Role |
|---|---|
Point2, Aabb2, Similarity2 |
Exact planar coordinates, bounds, and similarity transforms |
CurvePoint2 |
Exact curve point retaining coordinates or selected geometric evidence |
LineSeg2, CircularArc2, Segment2 |
Native line/arc primitives and their common enum |
QuadraticBezier2, CubicBezier2, RationalQuadraticBezier2, RationalBezier2 |
Polynomial and rational Bézier carriers |
PolynomialSplineCurve2, NurbsCurve2 |
Validated B-spline and NURBS curves |
Curve2 |
Shared exact curve carrier with borrowed operations |
CurveString2, CurvePath2, Contour2 |
Connected open strings, general paths, and closed line/arc contours |
CurveRegion2 |
Native mixed-family filled planar region |
provisional, evaluate_under, Provisional<T>, CurvePreviewOptions, Classification<T> |
Explicitly qualified approximate evaluation, its certainty-carrying result, lossy preview adapter, and decided/uncertain result |
CurveError, ExactCurveError |
Construction and exact-topology failure information |
CurveRegion2 is the sole public filled-region carrier. Native line/arc
specializations remain private fast paths inside the unified kernel.
Region and closed-path point queries accept CurvePoint2, preserving selected
roots and generated contact evidence. Convert authored coordinates with
Point2::into(); coordinates() is an optional stored-coordinate view. Region
batches accept &[CurvePoint2] and share query preparation across scalar and
generated points. Closed paths retain their trace and even-odd interior; filled
regions classify their regularized boundary, including holes and nested islands.
CurveRegion2::try_from_boundary_paths(paths, fill_rule) applies one
fill rule to the total signed winding of all closed paths, then publishes the
regularized set. NonZero preserves equally oriented overlaps and cancels
opposite winding; EvenOdd selects odd winding. SVG compound fills use this
same admission path. Explicit material/hole constructors instead combine each
loop’s filled membership by its supplied role. Interior sides are certified by the
arrangement from winding; authoring does not require orientation hints.
[dependencies]
hypercurve = "0.3.1"
Hyperreal, Hypersolve, and Hyperlimit are mandatory parts of the exact kernel; feature flags select only optional adapters and instrumentation.
This builds a quadratic Bézier, constructs a square region from exact line segments, and classifies an interior point.
use hypercurve::{
BezierDegree, Contour2, CurveRegion2, LineSeg2, Point2, QuadraticBezier2, RegionPointLocation,
Segment2,
};
use hyperreal::Real;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let p = |x, y| Point2::new(Real::from(x), Real::from(y));
let bezier = QuadraticBezier2::new(p(0, 0), p(1, 2), p(2, 0));
assert_eq!(bezier.structural_facts().degree, BezierDegree::Quadratic);
let boundary = [
((0, 0), (2, 0)),
((2, 0), (2, 2)),
((2, 2), (0, 2)),
((0, 2), (0, 0)),
]
.into_iter()
.map(|(start, end)| LineSeg2::try_new(p(start.0, start.1), p(end.0, end.1)).map(Segment2::Line))
.collect::<hypercurve::CurveResult<Vec<_>>>()?;
let contour = Contour2::try_new(boundary)?;
let region = CurveRegion2::try_from_native_material_contours(vec![contour])?;
assert_eq!(
region.classify_point(&p(1, 1).into())?,
RegionPointLocation::Inside
);
Ok(())
}
Run the checked copy:
cargo run --example basic
Point2
├─ LineSeg2 / CircularArc2 ── Segment2 ── CurveString2 / Contour2
└─ Bézier / B-spline / NURBS ── Curve2 ── CurvePath2
│
arrange / classify / regularize
│
CurveRegion2
│
Boolean / offset / project / triangulate
A Contour2 is a closed, connected line/arc boundary with a fill rule.
CurvePath2 generalizes connected paths to every supported curve family.
CurveRegion2 stores filled topology as oriented exact boundary curves and
is the main input to mixed-family region operations. Curve operations emit
boundary provenance for inspection; authored input supplies geometry and fill
semantics.
The following list covers the useful public front doors. Result and evidence types have accessors for inspecting counts, sources, blockers, and retained topology; consult docs.rs for those fields and exact signatures.
Point2::{new, from_values, x, y, delta_from, distance_squared, lerp,
translated, structural_facts} creates and inspects exact points.CurvePoint2::{from, coordinates, coincides_with, compare_coordinate, bounds}
handles exact curve contacts through one opaque value. coordinates() is an
optional view of stored Real coordinates; selected points retain their
exact meaning and support geometric queries without that view. Undecided
predicates are reported as blockers.LineSeg2::{try_new, point_at, reversed, classify_point, contains_point,
structural_facts} covers checked segments and point predicates.CircularArc2::{try_from_center, from_bulge, contains_point,
contains_sweep_point, point_at_sweep_fraction, reversed, structural_facts}
covers directed circular arcs.Segment2::{from_bulge, kind, point_at, contains_point, reversed,
structural_facts} dispatches over lines and arcs.Similarity2::{try_from_real_affine, try_from_f64_affine, transform_point,
scale, reverses_orientation} validates exact translation, rotation, reflection,
and uniform scale transforms. Curve and region types expose
transform_similarity; CurveRegion2 also exposes transform_affine.QuadraticBezier2::{new, from_line_segment,
interpolate_point_at_parameter, interpolate_midpoint, point_at,
control_hull_box, endpoint_tangent, structural_facts}.CubicBezier2::{new, interpolate_hermite, point_at, control_hull_box,
endpoint_tangent, structural_facts}.RationalQuadraticBezier2 and RationalBezier2 provide checked rational
construction, evaluation, derivatives, splitting, reversal, transforms, and
topology/intersection evidence.RationalBezier2::from_homogeneous_controls retains exact Bernstein
(X, Y, W) coefficients, including zero-weight intermediate controls.
try_new accepts affine authoring points and weights; affine_control_points
returns an optional finite view. Splitting and degree elevation preserve the
homogeneous representation without forcing every control into affine space.
Domain finiteness and local convex-hull certificates are separate proofs. Retained
bounds and rational region point queries use the active finite interval,
including exterior charts and finite restrictions excluding source poles.BezierParameter2, BezierParameterRange2, and
BezierRootIsolationResult2 retain exact algebraic parameter information.Curve2::split_at.parallel_left, parallel_right, and
approximate_parallel_blend2d_certified. Their result types retain error and
singularity evidence; exact topology-producing offsets are owned by the
unified CurveRegion2 engine below.BezierParallel2::{from_source, source, distance, point_at, derivative_at,
reversed, split_at_exact, subcurve_between_exact, conservative_bounds,
transform_similarity} is the compact exact procedural parallel carrier.
Incidence and intersection go through Curve2::try_analytic_parallel,
Curve2::point_locations, and Curve2::intersect_curve. General parallel pairs use
complete polynomial projections, exact common-component saturation,
selected normal and tangent-degeneracy predicates, refined tensor-Bernstein
rejection, and preconditioned Poincare-Miranda box replay. Exact source
overlap transport handles partial and reversed reparameterizations;
materializable and structural overlap lanes remain cheaper. Its
BezierParallelSource2 plus signed distance is the lossless structural
export boundary. Curve2::try_analytic_parallel restricts a parallel to an
exact source-parameter range as a general Curve2, without fitting.PolynomialSplineCurve2::{try_new, try_new_periodic, point_at,
derivative_at, insert_knot, split_at, subcurve, clamped_subcurve, reversed,
transform_similarity}.NurbsCurve2::{try_new, try_new_periodic, from_homogeneous_controls,
point_at, derivative_at, insert_knot, insert_knots, remove_knot,
elevated_to_degree, split_at, subcurve, clamped_subcurve, reversed,
transform_similarity, native_subcurves}.Curve2::from(spline).native_bezier_fragments() returns each span as
CurveGeometry2, the same authored-family vocabulary used by Curve2::new,
with its exact source parameter interval.HomogeneousControl2 coefficients.
Extraction, knot insertion/removal, and degree recomposition preserve zero
and mixed control weights without affine projection. homogeneous_controls
is authoritative; affine_control_points is an optional finite view.
Homogeneous NURBS construction takes an expanded knot vector and explicit
SplinePeriodicity2; span evaluators retain their exact source knot intervals.
Conic and polynomial specializations are optional, and linear rational spans
retain degree one. Bounds and monotonicity use the actual curve denominator.*_wrapped and *_side method families.Curve2::{new, try_line, try_analytic_parallel, try_from_bezier_range,
point_locations,
try_polynomial_bspline, try_nurbs,
try_periodic_polynomial_bspline, try_periodic_nurbs, family, point_at,
derivative_at, bounds, split_at, subcurve, reversed,
transform_similarity, native_bezier_fragments, trim_inside_region,
trim_inside_region_with_parameters} is the common owned carrier.
try_line joins two general exact points, which may be selected algebraic
intersection or corner locations, without rounding either endpoint.
point_locations reports every exact parameter visit of a represented
point as CurveLocation2 values, one per visit and one per continuous
spline seam, or EntireCurve for a constant curve. Authored spans reuse
their cached rational evaluators; generated parallels, chords, and selected
circles use their own incidence authorities on their retained ranges.
point_at and derivative_at take general CurveParameter2 values.
Derivatives are CurveVector2: represented coordinates when the parameter
is a plain real, otherwise a selected-field vector with an exact chart
factor whose coordinate signs are decided without rounding. Selected
parameters are supported on authored spans, retained rational pieces and,
to first order, analytic parallels: the source velocity scaled by the
exact speed ratio 1 - d cross(v, a) / |v|^3, whose sign (including the
exact zero at a parallel cusp) is decided in the selected field. Other
generated carriers and orders report an explicit unsupported blocker. Exact
region trimming returns reusable Curve2 pieces from authored and generated
supports. The parameter-retaining form reports their oriented source
locations as CurveLocation2, exact parameter ranges and boundary contacts.
Positive-length boundary overlaps are retained; isolated tangencies add no
curve. Path trimming keeps disconnected spline spans in separate chunks.
These operations borrow &Curve2 directly and reuse its retained calculations.
Borrow paths as &CurvePath2; iterate their curves with path.curves().iter().
Curve2 also retains generated analytic parallels, selected circles, chords,
and algebraic cuts. start and end return CurvePoint2; parameter_domain
returns CurveParameterRange2, preserving selected endpoint evidence.
geometry() is an optional native definition, and coordinates() is an
optional scalar view of a point. Neither view is required for lossless
CurveRegion2::boundary_paths export or subsequent region construction.
point_at and point_at_side accept CurveParameter2 and return CurvePoint2,
retaining selected roots and local fibers without requiring coordinate images.
A Real or BezierParameter2 converts directly into the common parameter.
parameter.scalar() and range.scalar_endpoints() expose stored Real
views. Selected parameters remain exact when these views are absent.
Intersections return CurveLocation2 contacts and CurveParameterRange2
overlap ranges. A location retains its support parameter and span chart;
location.parameter() maps it into the authored curve domain on
demand, preserving selected roots for evaluation and subdivision.
CurveParameter2::compare compares parameters in a shared support chart
without requiring scalar payloads and reports predicate certainty.
Curve and open-path intersections consume retained rational-source cuts
and exact chords directly, clipping contacts and overlaps to both active domains.
Overlap boundaries retain their certified correspondence, including a shared
endpoint when clipping leaves no positive-length span. Chord pairs and
chord/rational-source pairs share the region intersection kernels while
retaining endpoint contacts for open paths. Overlap ranges pair corresponding
endpoints in the first curve’s traversal order, including reversed overlaps.
Selected overlap cuts reuse their source-interval certificates, and evaluation
reuses finite-chord parameter certificates without reconstructing incidence.
Self-crossings of projectively corresponding supports retain their
off-diagonal contacts.
Curve and path intersection_topology results expose reusable Curve2 pieces
in traversal order. They preserve selected source parameters and one-sided
spline endpoints without requiring native Bézier materialization. A path’s
CurvePathSplit2::curves() groups pieces by authored curve. Arrangement
graphs are internal: regions are admitted from CurvePath2 boundaries.
Retraced components, exterior source domains, and generated circle
and parallel pair kernels still report explicit blockers where their
common dispatch is unfinished.
Generated curves keep their source chart when traversal is reversed.
Subdivision accepts the same common parameters. Selected ranges retain their
source chart and endpoint evidence, share one authored source through repeated
cuts, and cover every intersected arc or spline span. Splitting returns pieces
in traversal order and preserves both one-sided endpoints at spline jumps.
Reversal, similarity transforms, bounds, and path corner edits consume these
retained carriers. General differential and pair-intersection APIs are still
being unified; operations report an explicit blocker for carriers they cannot
yet consume.CurveString2::{try_new, from_bulge_vertices, link_connected_endpoints,
connect_endpoints_with_line, merge_adjacent_collinear_lines,
remove_adjacent_reversed_duplicates, trim_between_parameters,
trim_between_points} edits connected line/arc strings without owning corner
construction semantics.CurvePath2::{try_new, reversed, transform_similarity,
chamfer_vertex_by_setbacks, fillet_vertex, bounds, classify_point,
native_bezier_fragments, bezier_boundary_loop} is the sole connected-curve
corner-edit authority and handles general connected curves. Chamfers
enumerate exact solutions from design setbacks. Fillets take CurveFillet2
with an exact radius and optional center or contact constraints. Contact
parameters use the incident input curve’s chart; contact points retain every
matching source location. Both edits return finite CurveCornerSolutions2.
A continuous fillet family requires an additional exact constraint and returns
CurveError::FilletConstraintRequired; it never publishes an arbitrary sample.Contour2::{try_new, try_new_with_fill_rule, from_bulge_vertices,
signed_area, winding_number, classify_point, point_on_boundary,
intersect_contour, intersect_self, split_at_intersections,
split_at_self_intersections} handles closed line/arc boundaries.CurveRegion2::{empty, arrange_unordered_segments,
try_from_native_contours,
try_from_native_material_contours, try_from_native_boundary_contours,
try_from_boundary_paths, classify_point, classify_points, signed_area,
filled_area, boundary_profiles, boundary_paths,
segment_certified, offset} is the mixed-family region API. offset is the
sole region offset operation and takes an explicit OffsetCornerStyle2;
unsupported exact carriers remain explicit blockers. segment_certified
is a separate lossy output adapter and never participates in offset
topology. Point queries return membership of the regularized set; authored
winding multiplicity is resolved during construction.
Boundary-path and native-boundary constructors take one explicit global fill
rule and return a regularized region directly. Native contours may cross,
overlap, or touch; their individual contour fill rules do not override the
chosen compound fill. Explicit material/hole constructors retain per-loop
fill semantics.
Unordered segment admission returns the region through the same exact-result
contract. Unresolved endpoint assembly or topology remains an exact blocker;
native views and structural counts are computed when requested.CurveRegion2::{intersect_region, boolean_region, boolean_regions} returns
intersection topology between regularized boundaries, or regularized union,
intersection, difference, and xor results. Authored winding and canceled
seams are resolved first. BooleanOp selects an operation; batched
CurveRegionBooleanResults2 exposes all four from one evaluation.CurveRegion2::straight_skeleton and the
straight_skeleton_*_events methods expose staged skeleton construction and
blockers. translation_obstacle_convex constructs the exact translational
configuration-space obstacle for supported convex contours.CurveString2::{from_real_line_string, from_finite_line_string,
reconstruct_from_polyline} and
Contour2::{from_real_ring, from_finite_ring,
reconstruct_from_closed_polyline} import or reconstruct line/arc geometry.CurveRegion2::recover_from_finite_profiles reconstructs and regularizes a
region from finite material/hole profiles. PolylineReconstructionOptions controls reconstruction
tolerance; the import remains lossy relative to the original source curves.project_to_finite_polyline, project_to_finite_curve_paths,
project_to_finite_profiles, and project_to_finite_region provide explicit
finite approximations. FiniteProjectionOptions makes the curve chord-error
budget visible at the boundary.triangulation, FiniteRegionProfile2::triangulate and
triangulate_finite_rings produce finite triangles through Hypertri.svg, SvgGeometry2::{from_svg, from_svg_with_options, to_svg,
to_svg_with_options}, parse_svg_path_data, import_svg_document, and
export_svg_document provide SVG exchange. Native L, A, Q, and C
commands are used where possible; a versioned data-hypercurve-path
attribute preserves curve families and exact values for Hypercurve
round-trips.Hypercurve separates exact values from decisions about them:
Real values, not an implicit f64 tolerance model.ExactCurveResult<T>. A decision that exact predicates cannot settle
is reported as an ExactCurveError::Blocked with its operation and reason,
never guessed. Optional results are Options: the empty region has no
bounds, and a region without a line/arc boundary has no native view.hypercurve::provisional(|| ...) evaluates those operations under the
APPROXIMATE_512 policy, which may consume Hyperlimit’s terminal 512-bit
interpretation. Its Provisional<T> result yields the value through
certified() only when no such terminal was consumed, and otherwise only
through the explicitly unverified accessors.hypercurve::evaluate_under(policy, || ...) takes a Hyperlimit
PredicatePolicy for callers whose policy is configuration: STRICT
evaluates exactly (certified), and APPROXIMATE_512 behaves as
provisional.CurvePreviewOptions owns finite display tolerances separately. Operations
called inside evaluate use its edge-preview context; its scoped preview
results are never exact topology or construction provenance.Classification::Decided(value) is a supported conclusion.
Classification::Uncertain(reason) preserves an undecidable or unsupported
predicate instead of silently choosing a side.CurveResult<T> reports ordinary construction/operation failures.
ExactCurveResult<T> can additionally report the precise exact-topology
blocker.f64, polyline segmentation, SVG rendering, and triangulation
are explicit conversion boundaries with caller-visible options or evidence.Support is deliberately operation-specific. A curve family being representable does not imply that every topology operation is decidable for every symbolic input. Inspect returned status and blocker evidence instead of treating uncertainty as empty geometry.
| Feature | Default | Purpose |
|---|---|---|
dispatch-trace |
no | Hyperreal/Hyperlimit dispatch instrumentation |
triangulation |
no | Finite-region triangulation through Hypertri |
svg |
no | SVG import/export and exact round-trip extension |
hershey |
no | Compiled Hershey stroke fonts and native curve-string text |
comparative-benchmarks |
no | Third-party benchmark adapters only |
Common configurations:
cargo check
cargo test --all-features
cargo run --example arrangement
cargo check --features svg
The browser demo lives in examples/hypercurve_ui and is built separately with
Trunk. It is not part of the library API.
The quick start is compiled as examples/basic.rs and checked byte-for-byte
against this README. The test suite also covers adversarial exact predicates,
mixed-family region Booleans, regression corpora, and finite adapters.
The rank-independent public-Boolean matrix, recursive radial/projective regressions (including fourth-generation offsets), and release-scale PCB corpora run in the normal suite. Longer selected-fiber and source-cusp stroke corpora can also be run explicitly:
cargo test --release --locked --all-features --lib selected_fiber_genuinely_analytic_contacts_complete_region_booleans -- --ignored
cargo test --release --locked --all-features --test hypercurve_curve_region_stroke -- --ignored
Detailed benchmark definitions and interpretation live in PERFORMANCE.md and COMPARATIVE_BENCHMARKS.md. Fuzz target ownership and replay instructions live in fuzz/README.md. These are maintainer validation resources, not API guarantees.
These sources describe algorithms or numerical principles used by the crate; they are not claims of source-code derivation.
Hypercurve builds on Hyperreal, Hyperlimit, and Hypersolve, with optional Hypertri integration. The wider Hyper ecosystem provides the three-dimensional and engineering layers.
The bibliography above acknowledges the research traditions that inform the implementation. Optional comparison dependencies are benchmark or validation peers and do not provide Hypercurve’s native topology.
The optional compiled single-stroke font catalog was created by Dr. A. V.
Hershey at the U.S. National Bureau of Standards. Its source distribution
format was created by James Hurt of Cognition, Inc.; the integrated Rust
representation is not the U.S. NTIS distribution format. The complete
required acknowledgement is available as
hypercurve::hershey::FONT_DATA_NOTICE.
Licensed under the Apache License 2.0.
Bug reports should include the smallest exact input, selected features, policy,
operation, and returned blocker or uncertainty evidence. Before proposing a
change, run cargo fmt --all -- --check, the relevant focused test, and
cargo test --all-features.