diff --git a/crates/engine/src/cmd/canvas_sketch.rs b/crates/engine/src/cmd/canvas_sketch.rs index 47411a4d684..63f2eea791f 100644 --- a/crates/engine/src/cmd/canvas_sketch.rs +++ b/crates/engine/src/cmd/canvas_sketch.rs @@ -74,12 +74,15 @@ fn to_sketch(s: &mut Session, p: &Value) -> Result { cur = seg.end(); } } + // A cubic whose handle has no length (a vertex with no tangent, a span too short) has an end + // with no direction, which a sketch spline can't have: it comes in as curves that follow it. + let (geom, _, _) = super::sketch_import::split_nurbs(geom, super::sketch_import::DEFAULT_FIT_TOLERANCE / 2.0, 1.0).map_err(|e| bad(cmd, e))?; let name = str_(p, "name").map(str::to_string).unwrap_or_else(|| format!("{} sketch", canvas.name)); let r = super::sketch::create_sketch_with_plane(s, &json!({ "name": name }), canvas.plane.clone(), None)?; let id = r.get("sketch").and_then(Value::as_u64); let tol = (sc * 0.01).max(1e-6); let made = super::sketch::edit(s, &json!({}), cmd, false, |sk, _| { - let (cs, _) = super::sketch_import::add_geometry(sk, &geom, &|q| q, 1.0, tol)?; + let (cs, _, _) = super::sketch_import::add_geometry(sk, &geom, &|q| q, 1.0, tol)?; Ok(cs.len()) }); let finish = super::find_command("sketch.finish").ok_or_else(|| bad(cmd, "sketch.finish"))?.run; diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs index 1ef7b05057e..cb3cf83c35e 100644 --- a/crates/engine/src/cmd/sketch_import.rs +++ b/crates/engine/src/cmd/sketch_import.rs @@ -4,9 +4,10 @@ use solidcraft_geom::prelude::*; use std::collections::HashMap; use serde_json::{Value, json}; -use solidcore_record::Vec2; +use solidcore_record::{MAX_BEZIER_DEGREE, Vec2, Vec3}; +use solidcraft_geom::bspline::{self, Fit, HPoint, NurbsCurve}; use solidcraft_io::{Geom2, MAX_DRAWING_BYTES}; -use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch}; +use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, MAX_SPLINE_POINTS, Sketch}; use super::CommandSpec; use super::sketch::{edit, ids_of}; @@ -18,11 +19,11 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.insert_dxf", "Insert DXF", insert_dxf) .at("SKETCH", "INSERT") .icon("sketch_dxf") - .params(concat!("path | text: ASCII DXF (blocks expanded); at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())), + .params(concat!("path | text: ASCII DXF (blocks expanded); at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); fit_tolerance?: mm a spline may be from the file's curve in the sketch, 0.0001 to 10 (default 0.001; half for following it, half for joining its ends; a piece that can't be followed that close comes in within a tolerance 4, 16, … times looser, and the reply's warnings give its proven distance; a spline within 1e-9 mm of a point in the sketch is left out, and the warnings count it); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())), CommandSpec::new("sketch.insert_svg", "Insert SVG", insert_svg) .at("SKETCH", "INSERT") .icon("svg") - .params(concat!("path | text: SVG; at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())), + .params(concat!("path | text: SVG; at?: [x,y] offset, scale? | width? | height?: mm, the drawing's size before rotation, aspect kept (win over scale); angle?: degrees, about the drawing's origin (or its centre); align?: \"origin\" (default: `at` is where the file's origin goes) | \"center\" (`at` is where the drawing's middle goes and it turns and scales about it); tolerance?: mm within which ends join (default 0.0001); fit_tolerance?: mm a curve may be from the file's curve in the sketch, 0.0001 to 10 (default 0.001; half for following it, half for joining its ends; a piece that can't be followed that close comes in within a tolerance 4, 16, … times looser, and the reply's warnings give its proven distance; a curve within 1e-9 mm of a point in the sketch is left out, and the warnings count it); plane?: (when no sketch is active, a new sketch on it; default XY)", created_doc!())), CommandSpec::new("sketch.drawing_bounds", "Drawing Size", drawing_bounds) .icon("svg") .noundo() @@ -71,8 +72,9 @@ fn drawing_error(p: &Value, svg: bool, msg: String) -> EngineError { /// Add imported geometry to a sketch, sharing end points that meet. /// Adds the geometry; end points closer than `q` (mm) become one point, so drawings whose -/// ends almost meet still make closed profiles. -pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> Vec2, k: f64, q: f64) -> Result<(Vec, Vec)> { +/// ends almost meet still make closed profiles. Also returns how far that moved the end of a +/// spline or conic, which otherwise keeps the shape it was given (mm). +pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> Vec2, k: f64, q: f64) -> Result<(Vec, Vec, f64)> { let mut map: HashMap<(i64, i64), Vec<(Vec2, usize)>> = HashMap::new(); let mut pt = |sk: &mut Sketch, p: Vec2| -> Result { let p = f(p); @@ -90,6 +92,9 @@ pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> map.entry(key).or_default().push((p, i)); Ok(i) }; + // How far the point an end joined is from where the end was. + let shift = |sk: &Sketch, p: Vec2, i: usize| sk.point(i).map_or(0.0, |o| o.dist(f(p))); + let mut moved = 0.0f64; let mut curves = Vec::new(); let mut texts = Vec::new(); for g in geom { @@ -109,18 +114,41 @@ pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> } Geom2::Ellipse { c, major, minor } => Some(CurveKind::Ellipse { c: pt(sk, *c)?, m: pt(sk, *major)?, r: minor * k }), Geom2::Spline { pts, control, degree } => { - let mut idx = Vec::new(); - for p in pts.iter().take(solidcraft_sketch::MAX_SPLINE_POINTS) { - let i = pt(sk, *p)?; - if idx.last() != Some(&i) { - idx.push(i); + // Only the ends join other curves: an inner point moved would reshape the curve. A + // through-point spline keeps one of two equal points in a row; a control-point one + // repeating a point never comes here (every caller passes its geometry through + // [`split_nurbs`], which follows it with curves that don't), so its points are kept + // as they are. + let mut pts: Vec = pts.iter().take(MAX_SPLINE_POINTS).copied().collect(); + if !*control { + pts.dedup(); + } + match (pts.first(), pts.last()) { + (Some(&first), Some(&last)) if pts.iter().any(|q| *q != first) => { + let (a, b) = (pt(sk, first)?, pt(sk, last)?); + moved = moved.max(shift(sk, first, a)).max(shift(sk, last, b)); + let inner = pts.get(1..pts.len() - 1).unwrap_or_default(); + if inner.is_empty() && a == b { + None + } else { + let mut idx = vec![a]; + for q in inner { + idx.push(sk.add_point(f(*q), None)?); + } + idx.push(b); + Some(CurveKind::Spline { pts: idx, control: *control, degree: *degree, periodic: false, nurbs: None }) + } } + _ => None, } - (idx.len() >= 2).then_some(CurveKind::Spline { pts: idx, control: *control, degree: *degree, periodic: false, nurbs: None }) } + Geom2::Nurbs(_) => return Err(EngineError::Other("a B-spline must be brought in as sketch curves first (split_nurbs)".into())), Geom2::Conic { a, apex, b, rho } => { - let (a, x, b) = (pt(sk, *a)?, pt(sk, *apex)?, pt(sk, *b)?); - (a != b && x != a && x != b).then_some(CurveKind::Conic { a, b, apex: x, rho: *rho }) + // The apex shapes the curve: it joins nothing. + let (a0, b0) = (*a, *b); + let (a, b) = (pt(sk, a0)?, pt(sk, b0)?); + moved = moved.max(shift(sk, a0, a)).max(shift(sk, b0, b)); + if a == b { None } else { Some(CurveKind::Conic { a, b, apex: sk.add_point(f(*apex), None)?, rho: *rho }) } } Geom2::Text { text, at, height, angle } => { texts.push(Geom2::Text { text: text.clone(), at: f(*at), height: height * k, angle: *angle }); @@ -133,7 +161,7 @@ pub(super) fn add_geometry(sk: &mut Sketch, geom: &[Geom2], f: &dyn Fn(Vec2) -> curves.push(c); } } - Ok((curves, texts)) + Ok((curves, texts, moved)) } /// The box around a drawing's geometry (arcs, circles and curves by their extent). @@ -167,6 +195,8 @@ fn bounds_of(geom: &[Geom2]) -> Option<(Vec2, Vec2)> { pts.extend([*c + Vec2::new(r, r), *c - Vec2::new(r, r)]); } Geom2::Spline { pts: sp, .. } => pts.extend(sp.iter().copied()), + // A B-spline lies within its control points' hull. + Geom2::Nurbs(curve) => pts.extend(curve.ctrl().filter_map(|h| h.project()).map(|q| Vec2::new(q.x, q.y))), // Points along the curve, not its apex, which can lie well outside it (an elliptical // arc of a DXF comes in as conics, #8155). Geom2::Conic { a, apex, b, rho } if *rho > 0.0 && *rho < 1.0 => { @@ -194,6 +224,246 @@ fn read_drawing(p: &Value, cmd: &str, svg: bool) -> Result<(Vec, (Vec2, V Ok((geom, bounds)) } +/// How far (mm, in the sketch) a B-spline may come in from the file's curve unless `fit_tolerance` +/// says otherwise: half of it for the curves that follow it, half for joining their ends to other +/// curves. An end moved further to join another (a join tolerance above that) is reported. +pub(super) const DEFAULT_FIT_TOLERANCE: f64 = 1e-3; +/// Most sketch curves one Bézier piece of a B-spline may become. +const MAX_PIECE_CURVES: usize = 4096; +/// Most sketch curves a drawing's B-splines may become together: a bound on the work and memory +/// a hostile file can ask for. +const MAX_SPLINE_CURVES: usize = 200_000; +/// How much a tolerance a piece can't be followed within is loosened each time, and how many +/// times at most: from 0.0005 mm, past a kilometre. +const LOOSEN: f64 = 4.0; +const MAX_LOOSENINGS: usize = 32; + +/// The `fit_tolerance` asked for (mm), within the bounds an equation curve's tolerance has. +fn fit_tolerance(p: &Value, cmd: &str) -> Result { + use solidcraft_doc::sketch_equation::{MAX_TOLERANCE, MIN_TOLERANCE}; + match p.get("fit_tolerance") { + None | Some(Value::Null) => Ok(DEFAULT_FIT_TOLERANCE), + Some(v) => v + .as_f64() + .filter(|t| t.is_finite() && (MIN_TOLERANCE..=MAX_TOLERANCE).contains(t)) + .ok_or_else(|| bad(cmd, format!("`fit_tolerance` must be a number of mm from {MIN_TOLERANCE} to {MAX_TOLERANCE}"))), + } +} + +/// Whether two neighbouring points of a control-point spline are nearer than `gap` (in the +/// drawing: [`bspline::MIN_CONTROL_GAP`] in the sketch), which the sketch's own splines don't +/// allow: at an end it leaves the curve no direction there. +fn repeats(pts: &[Vec2], gap: f64) -> bool { + pts.windows(2).any(|w| w[0].dist(w[1]) < gap) +} + +/// Whether every one of `pts` lies nearer than `gap` to the first: a curve that small is a point. +fn is_point(pts: &[Vec2], gap: f64) -> bool { + pts.first().is_none_or(|&o| pts.iter().all(|p| p.dist(o) < gap)) +} + +/// Whether every control point of `fit` lies nearer than `gap` to its first ([`is_point`]). +fn fit_is_point(fit: &Fit, gap: f64) -> bool { + let conic; + let pts: &[Vec3] = match fit { + Fit::Bezier(p) => p, + Fit::Conic { a, apex, b, .. } => { + conic = [*a, *apex, *b]; + &conic + } + }; + pts.first().is_none_or(|&o| pts.iter().all(|p| p.dist(o) < gap)) +} + +/// [`bspline::follow`] within `tolerance`, no two neighbouring points nearer than `gap`, or, when +/// the piece can't be followed that close in `room` curves, within the first of the tolerances +/// [`LOOSEN`] times looser, up to [`MAX_LOOSENINGS`] times, that it can be: not the closest fit +/// there is, but one with its bound proven. With whether it was loosened. A piece still not +/// followed then, or that can't be at all (its points don't project, its weights lose their +/// precision), is refused with the last reason. +fn follow_loosened( + piece: &bspline::CurvePiece, + tolerance: f64, + gap: f64, + room: usize, +) -> bspline::SplineResult<(Vec>, bool)> { + let (mut at, mut loosenings) = (tolerance, 0); + loop { + match bspline::follow(piece, at, gap, MAX_BEZIER_DEGREE, room) { + Ok(fits) => return Ok((fits, at > tolerance)), + Err(bspline::SplineError::TooLarge(_) | bspline::SplineError::Unsupported(_)) if loosenings < MAX_LOOSENINGS => { + loosenings += 1; + at *= LOOSEN; + } + Err(e) => return Err(e), + } + } +} + +/// A drawing's B-splines as the curves a sketch holds. One that is the sketch's own spline +/// ([`sketch_own`]) comes in as that one editable spline. Any other is split into Bézier pieces, +/// each followed within `tolerance` (mm, in the drawing) of the file's curve with the bound proven +/// ([`bspline::follow`]): a polynomial piece of degree at most 9 as a control-point spline (a line +/// at degree 1), a rational quadratic one as a conic, any other as cubic control-point splines. +/// That is every [`Geom2::Nurbs`], every control-point spline with more points than a sketch +/// spline holds, which would otherwise lose the rest, and every one that repeats a control point, +/// which a sketch spline doesn't (a zero-length handle leaves its end no direction, and the solid +/// kernel refuses to build on it). Points repeat when they are nearer than +/// [`bspline::MIN_CONTROL_GAP`] in the sketch, which is that over `k` in the drawing. A spline +/// whose control points all lie that near one another is a point, not a curve: it is left out, as +/// is a fit of a piece that small (the curves either side of it meet across it). A piece that +/// can't be followed within the tolerance comes in within a looser one, its bound proven +/// ([`follow_loosened`]). Also what the import should say about them, its distances in the +/// sketch's millimetres (`k` per drawing millimetre), and how many curves they became. A spline +/// that isn't a curve, can't be followed even loosened, or makes more curves than a drawing may, +/// refuses the drawing with the reason. +pub(super) fn split_nurbs(geom: Vec, tolerance: f64, k: f64) -> std::result::Result<(Vec, Vec, usize), String> { + let bad = |e: &dyn std::fmt::Display| format!("a spline can't be brought in: {e}"); + let gap = bspline::MIN_CONTROL_GAP / k; + let mut out = Vec::with_capacity(geom.len()); + let (mut fitted, mut worst, mut made, mut repeated) = (0usize, 0.0f64, 0usize, 0usize); + let (mut loosened, mut loosest, mut dropped) = (0usize, 0.0f64, 0usize); + for g in geom { + let curve = match g { + Geom2::Nurbs(curve) => curve, + Geom2::Spline { pts, control: true, .. } if is_point(&pts, gap) => { + dropped += 1; + continue; + } + Geom2::Spline { pts, control: true, degree } if pts.len() > MAX_SPLINE_POINTS || repeats(&pts, gap) => { + sketch_spline(&pts, degree).map_err(|e| bad(&e))? + } + g => { + out.push(g); + continue; + } + }; + let ctrl = flat_ctrl(&curve); + if is_point(&ctrl, gap) { + dropped += 1; + continue; + } + if let Some(own) = sketch_own(&curve, gap) { + made += 1; + out.push(own); + continue; + } + repeated += usize::from(repeats(&ctrl, gap)); + for piece in curve.pieces().map_err(|e| bad(&e))? { + if made >= MAX_SPLINE_CURVES { + return Err(format!("the drawing's splines make more than {MAX_SPLINE_CURVES} curves")); + } + let (fits, wider) = follow_loosened(&piece, tolerance, gap, MAX_PIECE_CURVES.min(MAX_SPLINE_CURVES - made)).map_err(|e| bad(&e))?; + let fits: Vec> = fits.into_iter().filter(|c| !fit_is_point(c.value(), gap)).collect(); + if wider { + loosened += 1; + loosest = fits.iter().fold(loosest, |w, c| w.max(c.bound())); + } + // The piece itself: over its own control points, or a conic; or nothing, a point. + let own_points: Vec = piece.ctrl().filter_map(|h| h.project()).collect(); + let own = match &fits[..] { + [] => true, + [c] => matches!(c.value(), Fit::Conic { .. }) || *c.value() == Fit::Bezier(own_points), + _ => false, + }; + if !own { + fitted += 1; + worst = fits.iter().fold(worst, |w, c| w.max(c.bound())); + } + made += fits.len(); + out.extend(fits.into_iter().map(|c| sketch_curve(c.into_value()))); + } + } + // A fit's bound is how closely it follows the file's curve; joining its ends to other curves + // can move them further, up to the join tolerance (reported by itself past the fit tolerance). + let join = "an end joined to another curve can move further, up to the join tolerance"; + let mut warnings = Vec::new(); + if dropped > 0 { + warnings.push(format!( + "{dropped} spline(s) left out: each lies within {:.0e} mm in the sketch, the least gap between a sketch spline's points, so it is a point, not a curve", + bspline::MIN_CONTROL_GAP + )); + } + if repeated > 0 { + warnings.push(format!( + "{repeated} spline(s) repeat a control point, which a sketch spline can't (a zero-length handle leaves its end no direction): each comes in as curves that follow it" + )); + } + if fitted > 0 { + warnings.push(format!( + "{fitted} spline piece(s) have no exact sketch curve: each comes in as cubic splines followed within {:.1e} mm of the file's curve ({join})", + worst * k + )); + } + if loosened > 0 { + warnings.push(format!( + "{loosened} spline piece(s) couldn't be followed within the fit tolerance of {:.1e} mm: they come in followed within {:.1e} mm of the file's curve ({join})", + 2.0 * tolerance * k, + loosest * k + )); + } + Ok((out, warnings, made)) +} + +/// The knots of the sketch's spline of degree `p` over `n > p` points on `[lo, hi]`: each end +/// `p + 1` times, the inner ones evenly spaced. +fn sketch_knots(p: usize, n: usize, lo: f64, hi: f64) -> Vec { + let spans = n.saturating_sub(p).max(1); + (0..n + p + 1).map(|i| lo + (hi - lo) * (i.saturating_sub(p).min(spans) as f64 / spans as f64)).collect() +} + +/// The sketch's own spline of `degree` over `pts` (clamped, its inner knots evenly spaced, at the +/// degree its points allow), as a B-spline. +fn sketch_spline(pts: &[Vec2], degree: u8) -> bspline::SplineResult { + let n = pts.len(); + let p = usize::from(degree).clamp(1, MAX_BEZIER_DEGREE).min(n.saturating_sub(1)).max(1); + let ctrl: Vec = pts.iter().map(|q| HPoint::weighted(Vec3::new(q.x, q.y, 0.0), 1.0)).collect(); + NurbsCurve::from_homogeneous(p, sketch_knots(p, n, 0.0, 1.0), &ctrl) +} + +/// `curve` as one sketch spline when it is the sketch's own: degree at most 9, at most 500 +/// points, no two neighbours nearer than `gap` ([`repeats`]), its weights all alike (which is no +/// weighting), its knots clamped and evenly spaced up to the rounding of a number (4ε of the +/// domain). Knots written to fewer digits than that are a different curve, which comes in as its +/// exact pieces. +fn sketch_own(curve: &NurbsCurve, gap: f64) -> Option { + let p = curve.degree(); + let degree = u8::try_from(p).ok().filter(|_| p <= MAX_BEZIER_DEGREE)?; + let ctrl: Vec = curve.ctrl().collect(); + let n = ctrl.len(); + if n > MAX_SPLINE_POINTS || ctrl.windows(2).any(|w| w[0].w != w[1].w) { + return None; + } + let k = curve.knots(); + let (lo, hi) = (*k.get(p)?, *k.get(n)?); + if !sketch_knots(p, n, lo, hi).iter().zip(k).all(|(a, b)| (a - b).abs() <= 4.0 * f64::EPSILON * (hi - lo)) { + return None; + } + let pts = ctrl.iter().map(|h| h.project().map(|q| Vec2::new(q.x, q.y))).collect::>>()?; + (!repeats(&pts, gap)).then_some(Geom2::Spline { pts, control: true, degree }) +} + +/// The control points of `curve` in the drawing's plane. +fn flat_ctrl(curve: &NurbsCurve) -> Vec { + curve.ctrl().filter_map(|h| h.project()).map(|q| Vec2::new(q.x, q.y)).collect() +} + +/// A curve a sketch holds for a fit (z dropped: the file's curves have z = 0). +fn sketch_curve(fit: Fit) -> Geom2 { + let flat = |q: Vec3| Vec2::new(q.x, q.y); + match fit { + Fit::Bezier(p) => match &p[..] { + [a, b] => Geom2::Line(flat(*a), flat(*b)), + _ => Geom2::Spline { + degree: u8::try_from(p.len().saturating_sub(1)).unwrap_or(u8::MAX), + control: true, + pts: p.into_iter().map(flat).collect(), + }, + }, + Fit::Conic { a, apex, b, rho } => Geom2::Conic { a: flat(a), apex: flat(apex), b: flat(b), rho }, + } +} + /// How big a drawing is in its own file, to size it before it is inserted. fn drawing_bounds(_s: &mut Session, p: &Value) -> Result { let cmd = "sketch.drawing_bounds"; @@ -221,6 +491,9 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { None => sized("height", |n| n.1)?, }; let k = from_size.or_else(|| num(p, "scale")).filter(|k| *k > 1e-9 && *k < 1e6).unwrap_or(1.0); + // The sketch's curves are the drawing's scaled by `k`: half of the fit tolerance there. + let fit = fit_tolerance(p, cmd)?; + let (geom, mut warnings, from_bsplines) = split_nurbs(geom, fit / 2.0 / k, k).map_err(|e| drawing_error(p, svg, e))?; let angle = match p.get("angle") { Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad(cmd, "`angle` must be a number (degrees)"))?.to_radians(), None => 0.0, @@ -251,10 +524,15 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { if geom.len() > solidcraft_sketch::MAX_POINTS { return Err(solidcraft_sketch::SketchError::TooLarge.into()); } - let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| { - let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?; - Ok((ids_of(sk, &cs), texts)) + let ((curves, texts, moved), info) = edit(s, p, cmd, false, |sk, _| { + let (cs, texts, moved) = add_geometry(sk, &geom, &f, k, tol)?; + Ok((ids_of(sk, &cs), texts, moved)) })?; + if from_bsplines > 0 && moved > fit / 2.0 { + warnings.push(format!( + "curve ends moved up to {moved:.1e} mm to join others (the join tolerance is {tol} mm), so a spline from the file can be that far from it at an end" + )); + } // Text becomes sketch text. let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch"))?; let mut n_text = 0; @@ -279,7 +557,7 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { } } } - Ok(json!({"sketch": id, "created_sketch": created, "curves": curves.len(), "texts": n_text, "info": info})) + Ok(json!({"sketch": id, "created_sketch": created, "curves": curves.len(), "texts": n_text, "warnings": warnings, "info": info})) } fn insert_dxf(s: &mut Session, p: &Value) -> Result { @@ -323,6 +601,9 @@ fn export_dxf(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { use serde_json::json; + use solidcore_record::Vec2; + use solidcraft_geom::prelude::*; + use solidcraft_sketch::{CurveKind, Sketch}; use crate::Session; @@ -446,6 +727,429 @@ mod tests { assert!(worst < 1e-9, "{worst}"); } + /// A degree-`p` SPLINE over `ctrl` with `knots` and, when given, `weights`. + fn spline_dxf(p: usize, ctrl: &[[f64; 2]], knots: &[f64], weights: &[f64]) -> String { + let mut body = format!("0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n{p}\n"); + body.extend(knots.iter().map(|k| format!("40\n{k}\n"))); + body.extend(weights.iter().map(|w| format!("41\n{w}\n"))); + body.extend(ctrl.iter().map(|[x, y]| format!("10\n{x}\n20\n{y}\n"))); + body + "0\nENDSEC\n0\nEOF\n" + } + + /// De Boor's evaluation, in homogeneous coordinates when there are weights, both factors of + /// each step from knot differences: the B-spline at `u`, independent of the importer. + fn de_boor(ctrl: &[[f64; 2]], weights: &[f64], knots: &[f64], p: usize, u: f64) -> Vec2 { + let k = (p..ctrl.len()).rev().find(|&k| knots[k] <= u && knots[k] < knots[k + 1]).unwrap(); + let w = |i: usize| if weights.is_empty() { 1.0 } else { weights[i] }; + let mut d: Vec<[f64; 3]> = (0..=p).map(|j| j + k - p).map(|i| [ctrl[i][0] * w(i), ctrl[i][1] * w(i), w(i)]).collect(); + for r in 1..=p { + for j in (r..=p).rev() { + let i = j + k - p; + let (lo, hi) = (knots[i], knots[i + p + 1 - r]); + let (f, g) = ((hi - u) / (hi - lo), (u - lo) / (hi - lo)); + d[j] = [0, 1, 2].map(|c| d[j - 1][c] * f + d[j][c] * g); + } + } + Vec2::new(d[p][0] / d[p][2], d[p][1] / d[p][2]) + } + + fn insert_scaled(dxf: &str, scale: f64) -> Result<(serde_json::Value, Sketch, usize), String> { + insert_with(json!({"text": dxf, "scale": scale})) + } + + fn insert_with(params: serde_json::Value) -> Result<(serde_json::Value, Sketch, usize), String> { + let mut s = Session::default(); + let r = s.execute("sketch.insert_dxf", ¶ms).map_err(|e| e.to_string())?; + let ss = s.model.state().sketch(r["sketch"].as_u64().unwrap()).unwrap().clone(); + Ok((r, ss.sketch, ss.profiles.len())) + } + + fn insert_one(dxf: &str) -> (serde_json::Value, Sketch, usize) { + insert_scaled(dxf, 1.0).unwrap() + } + + /// Sketch curve `i` at `t ∈ [0, 1]`. + fn curve_point(sk: &Sketch, i: usize, t: f64) -> Vec2 { + let at = |j: usize| sk.point(j).unwrap(); + match &sk.curves[i].kind { + CurveKind::Line { a, b } => at(*a) + (at(*b) - at(*a)) * t, + CurveKind::Spline { pts, control, degree, .. } => { + solidcraft_sketch::spline_point(&pts.iter().map(|j| at(*j)).collect::>(), *control, *degree, t) + } + CurveKind::Conic { a, b, apex, rho } => solidcraft_sketch::conic_point(at(*a), at(*apex), at(*b), *rho, t), + k => panic!("{k:?}"), + } + } + + /// The distance from `x` to the curve `f` over `[lo, hi]`: samples spread along the curve, not + /// its parameter (a rational curve can run much of its length in a sliver of it), and closer + /// together the nearer they come to `x` (a curve can loop tighter than the spacing), each one + /// closer than its neighbours refined by golden-section search. Never less than the true + /// distance (each is to a point on the curve), so a check against it can't pass wrongly. + fn closest(f: &dyn Fn(f64) -> Vec2, lo: f64, hi: f64, x: Vec2) -> f64 { + let mut s: Vec = (0..=64).map(|i| lo + (hi - lo) * f64::from(i) / 64.0).collect(); + let mut p: Vec = s.iter().map(|&t| f(t)).collect(); + let length: f64 = p.windows(2).map(|w| w[0].dist(w[1])).sum(); + for _ in 0..60 { + let (mut ns, mut np) = (vec![s[0]], vec![p[0]]); + for i in 1..s.len() { + let near = 0.5 * p[i - 1].dist(x).min(p[i].dist(x)); + if p[i - 1].dist(p[i]) > near.min(length / 512.0) && s[i] - s[i - 1] > 1e-13 * (hi - lo) && ns.len() < 20_000 { + let mid = 0.5 * (s[i - 1] + s[i]); + ns.push(mid); + np.push(f(mid)); + } + ns.push(s[i]); + np.push(p[i]); + } + if ns.len() == s.len() { + break; + } + (s, p) = (ns, np); + } + let d: Vec = p.iter().map(|q| q.dist(x)).collect(); + let last = d.len() - 1; + let mut found = d.iter().copied().fold(f64::INFINITY, f64::min); + for i in (0..=last).filter(|&i| d[i] <= d[i.saturating_sub(1)] && d[i] <= d[(i + 1).min(last)]) { + let (mut a, mut b) = (s[i.saturating_sub(1)], s[(i + 1).min(last)]); + for _ in 0..80 { + let (m1, m2) = (a + (b - a) * 0.381_966, b - (b - a) * 0.381_966); + let (d1, d2) = (f(m1).dist(x), f(m2).dist(x)); + found = found.min(d1).min(d2); + if d1 < d2 { b = m2 } else { a = m1 } + } + } + found + } + + /// Every point of the file's curve (scaled by `k`) within `allowed` of the sketch's curves from + /// `from` on, and the points of the first, middle and last of those within it of the file's + /// curve. + fn assert_within(sk: &Sketch, from: usize, ctrl: &[[f64; 2]], weights: &[f64], knots: &[f64], p: usize, k: f64, allowed: f64) { + let (lo, hi) = (knots[p], knots[ctrl.len()]); + let file = |u: f64| de_boor(ctrl, weights, knots, p, u) * k; + for j in 0..=40 { + let x = file(lo + (hi - lo) * f64::from(j) / 40.0); + let off = (from..sk.curves.len()).map(|i| closest(&|t| curve_point(sk, i, t), 0.0, 1.0, x)).fold(f64::INFINITY, f64::min); + assert!(off <= allowed, "file point {j}/40 is {off:e} from the sketch's curves"); + } + let last = sk.curves.len() - 1; + for i in [from, (from + last) / 2, last] { + for j in 0..=4 { + let y = curve_point(sk, i, f64::from(j) / 4.0); + let off = closest(&file, lo, hi, y); + assert!(off <= allowed, "curve {i} at {j}/4 is {off:e} from the file's curve"); + } + } + } + + /// #9355: a SPLINE with uneven knots, a double knot or unclamped closed knots comes in as the + /// curve its own knots describe: one control-point spline per span of its domain, each on the + /// file's curve (by de Boor) all along, not one spline over the points with even knots. + #[test] + fn a_spline_comes_in_as_its_own_knots_describe() { + let open = [[0.0, 0.0], [10.0, 25.0], [30.0, 30.0], [45.0, 5.0], [60.0, 20.0], [80.0, 0.0]]; + let (a, b, c) = ([0.0, 0.0], [20.0, 0.0], [10.0, 20.0]); + let closed = [a, b, c, a, b, c]; + for (ctrl, knots, closes) in [ + (&open[..], vec![0.0, 0.0, 0.0, 0.0, 0.1, 0.15, 1.0, 1.0, 1.0, 1.0], false), + (&open, vec![0.0, 0.0, 0.0, 0.0, 0.4, 0.4, 1.0, 1.0, 1.0, 1.0], false), + (&closed, (0..10).map(f64::from).collect(), true), + ] { + let (r, sk, profiles) = insert_one(&spline_dxf(3, ctrl, &knots, &[])); + assert_eq!(r["warnings"], json!([]), "{r}"); + let spans: Vec<(f64, f64)> = knots[3..=ctrl.len()].windows(2).map(|w| (w[0], w[1])).filter(|(a, b)| a < b).collect(); + assert_eq!(sk.curves.len(), spans.len(), "{knots:?}"); + for (i, (lo, hi)) in spans.into_iter().enumerate() { + let CurveKind::Spline { pts, control: true, degree: 3, .. } = &sk.curves[i].kind else { panic!("{:?}", sk.curves[i].kind) }; + // A cubic's piece: four control points, repeated ones included. + assert_eq!(pts.len(), 4, "{knots:?}: {pts:?}"); + for j in 0..=16 { + let t = f64::from(j) / 16.0; + let (got, want) = (curve_point(&sk, i, t), de_boor(ctrl, &[], &knots, 3, lo + (hi - lo) * t)); + assert!(got.dist(want) < 1e-9, "{knots:?} at {t} of [{lo}, {hi}]: {got:?} vs {want:?}"); + } + } + assert_eq!(profiles, usize::from(closes), "{knots:?}"); + } + } + + /// Whether sketch spline `i` repeats a control point, which the sketch's own spline tool + /// refuses. + fn repeats_a_point(sk: &Sketch, i: usize) -> bool { + let CurveKind::Spline { pts, .. } = &sk.curves[i].kind else { return false }; + pts.windows(2).any(|w| sk.point(w[0]).unwrap().dist(sk.point(w[1]).unwrap()) < solidcraft_geom::bspline::MIN_CONTROL_GAP) + } + + /// A spline repeating a control point (a Bézier [A, A, B, C], one with the zero-length handle + /// at its end, an exact piece starting so) has an end with no direction, which a sketch spline + /// can't have and the solid kernel won't build on: it comes in as curves that repeat no point, + /// within 0.001 mm of the file's curve, and the import says so. An SVG path's zero-length handle + /// (`C4,31 8,20 8,20`) alike, and a handle that only repeats a point once the drawing is + /// scaled down (3·10⁻⁸ in the file, 3·10⁻¹⁰ mm in the sketch at a hundredth), with or without + /// a zero-length handle at the other end: the gap is kept in the sketch. + #[test] + fn a_repeated_control_point_comes_in_as_curves_that_dont_repeat_it() { + let (a, b, c) = ([0.0, 0.0], [20.0, 0.0], [10.0, 20.0]); + let cubic = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + for (ctrl, knots) in [ + (vec![a, a, b, c], cubic.clone()), + (vec![a, b, c, c], cubic), + (vec![a, a, b, c, [30.0, 5.0]], vec![0.0, 0.0, 0.0, 0.0, 0.3, 1.0, 1.0, 1.0, 1.0]), + ] { + let (r, sk, _) = insert_one(&spline_dxf(3, &ctrl, &knots, &[])); + let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with("1 spline(s) repeat a control point")); + assert!(warned, "{r}"); + assert!((0..sk.curves.len()).all(|i| !repeats_a_point(&sk, i)), "{ctrl:?}: {:?}", sk.curves); + assert_within(&sk, 0, &ctrl, &[], &knots, 3, 1.0, 1e-3); + } + for (path, scale) in [("M5,35 C4,31 8,20 8,20", 1.0), ("M5,35 C5.00000003,35 8,20 8,20", 0.01), ("M5,35 C5.00000003,35 8,21 8,20", 0.01)] { + let svg = format!(r#""#); + let mut s = Session::default(); + let r = s.execute("sketch.insert_svg", &json!({"text": svg, "scale": scale})).unwrap(); + let sk = s.model.state().sketch(r["sketch"].as_u64().unwrap()).unwrap().sketch.clone(); + let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().starts_with("1 spline(s) repeat a control point")); + assert!( + warned && !sk.curves.is_empty() && (0..sk.curves.len()).all(|i| !repeats_a_point(&sk, i)), + "{path} at {scale}: {r} {:?}", + sk.curves + ); + } + } + + /// A spline whose control points all lie within the sketch's gap of one another is a point, + /// not a curve: it is left out, and the import says so, rather than coming in as a closed + /// spline smaller than the gap. The gap is in the sketch: a spline its own at full size is left + /// out of a drawing scaled to a hundredth. + #[test] + fn a_spline_smaller_than_the_gap_is_left_out() { + let knots = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + let tiny = spline_dxf(2, &[[0.0, 0.0], [1e-10, 0.0], [2e-10, 0.0]], &knots, &[]); + let small = spline_dxf(2, &[[0.0, 0.0], [1e-8, 0.0], [2e-8, 0.0]], &knots, &[]); + for (dxf, scale) in [(&tiny, 1.0), (&small, 0.01)] { + let (r, sk, _) = insert_scaled(dxf, scale).unwrap(); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(sk.curves.is_empty() && warnings.len() == 1 && warnings[0].starts_with("1 spline(s) left out"), "{r}"); + } + let (r, sk, _) = insert_one(&small); + assert_eq!((sk.curves.len(), &r["warnings"]), (1, &json!([])), "{r}"); + } + + /// `fit_tolerance` sets how close a spline with no exact sketch curve comes in, apart from the + /// join `tolerance`: looser takes fewer curves. Outside 0.0001 to 10 mm it is refused. + #[test] + fn the_fit_tolerance_sets_how_close_a_spline_comes_in() { + let (ctrl, weights, knots) = + ([[0.0, 0.0], [5.0, 30.0], [40.0, 30.0], [50.0, 0.0]], [1.0, 3.0, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + let dxf = spline_dxf(3, &ctrl, &knots, &weights); + let curves = |fit: f64| { + let (r, sk, _) = insert_with(json!({"text": dxf, "fit_tolerance": fit})).unwrap(); + assert_within(&sk, 0, &ctrl, &weights, &knots, 3, 1.0, fit); + assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("couldn't be followed")), "{r}"); + sk.curves.len() + }; + let (loose, default, tight) = (curves(0.1), curves(0.001), curves(0.0001)); + assert!(loose < default && default < tight, "{loose} {default} {tight}"); + for bad in [json!(0.0), json!(-1.0), json!(1e-5), json!(11.0), json!("0.01")] { + let e = insert_with(json!({"text": dxf, "fit_tolerance": bad})).unwrap_err(); + assert!(e.contains("`fit_tolerance` must be a number of mm from 0.0001 to 10"), "{bad}: {e}"); + } + } + + /// A spline that can't be followed within the fit tolerance in the curves a piece may take (a + /// 1000 km curve with weights 10⁸ apart) comes in within a looser tolerance, and the import + /// gives the proven distance; it is not refused. + #[test] + fn a_spline_that_cant_be_followed_closely_comes_in_and_says_how_close() { + let (ctrl, weights, knots) = + ([[0.0, 0.0], [0.0, 1e9], [1e9, 3e8], [2e8, 0.0]], [1.0, 1e4, 1e-4, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + let (r, sk, _) = insert_one(&spline_dxf(3, &ctrl, &knots, &weights)); + let warning = r["warnings"] + .as_array() + .unwrap() + .iter() + .filter_map(|w| w.as_str()) + .find(|w| w.contains("couldn't be followed")) + .unwrap_or_else(|| panic!("{r}")); + let close: f64 = warning + .split("come in followed within ") + .nth(1) + .and_then(|w| w.split(' ').next()) + .and_then(|x| x.parse().ok()) + .unwrap_or_else(|| panic!("{warning}")); + assert!(close > 5e-4, "{warning}"); + assert_within(&sk, 0, &ctrl, &weights, &knots, 3, 1.0, close * 1.1); + } + + /// A SPLINE that is the sketch's own (clamped, evenly spaced knots, no weights or all alike) + /// comes in as one editable spline over its points, as it did before; knots written to six + /// digits are a different curve and come in as its exact pieces. + #[test] + fn the_sketchs_own_spline_comes_in_as_one_spline() { + let five = [[0.0, 0.0], [10.0, 20.0], [30.0, 20.0], [40.0, 0.0], [60.0, 10.0]]; + let even = [0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0]; + for weights in [&[][..], &[2.0; 5]] { + let (r, sk, _) = insert_one(&spline_dxf(3, &five, &even, weights)); + let [curve] = &sk.curves[..] else { panic!("{r}") }; + let CurveKind::Spline { pts, control: true, degree: 3, .. } = &curve.kind else { panic!("{:?}", curve.kind) }; + let pts: Vec = pts.iter().map(|i| sk.point(*i).unwrap()).collect(); + assert!(pts.iter().zip(&five).all(|(p, q)| p.dist(Vec2::new(q[0], q[1])) < 1e-12), "{pts:?}"); + } + let six = [[0.0, 0.0], [10.0, 20.0], [30.0, 20.0], [40.0, 0.0], [60.0, 10.0], [70.0, 5.0]]; + let thirds = [0.0, 0.0, 0.0, 0.0, 0.333333, 0.666667, 1.0, 1.0, 1.0, 1.0]; + let (_, sk, _) = insert_one(&spline_dxf(3, &six, &thirds, &[])); + assert_eq!(sk.curves.len(), 3); + assert_within(&sk, 0, &six, &[], &thirds, 3, 1.0, 1e-3); + } + + /// #9355: a SPLINE with more control points than a sketch spline holds (500) comes in whole, + /// as exact pieces on the file's curve from its first point to its last: with uneven knots, + /// with even ones, and with none given (the sketch's even knots). + #[test] + fn a_spline_past_five_hundred_control_points_comes_in_whole() { + let n = 520; + let ctrl: Vec<[f64; 2]> = (0..n).map(|i| [i as f64, 10.0 * (i as f64 / 7.0).sin()]).collect(); + let even: Vec = (0..n + 4).map(|i| (i.clamp(3, n) - 3) as f64 / (n - 3) as f64).collect(); + let uneven: Vec = (0..n + 4).map(|i| ((i.clamp(3, n) - 3) as f64 / (n - 3) as f64).powi(2)).collect(); + for (given, knots) in [(&uneven[..], &uneven), (&even, &even), (&[][..], &even)] { + let (r, sk, _) = insert_one(&spline_dxf(3, &ctrl, given, &[])); + assert_eq!((r["curves"].as_u64(), &r["warnings"]), (Some(n as u64 - 3), &json!([])), "{} knots given", given.len()); + for i in 0..sk.curves.len() { + assert!(matches!(sk.curves[i].kind, CurveKind::Spline { control: true, degree: 3, .. }), "{:?}", sk.curves[i].kind); + let (lo, hi) = (knots[i + 3], knots[i + 4]); + for j in 0..=4 { + let t = f64::from(j) / 4.0; + let (got, want) = (curve_point(&sk, i, t), de_boor(&ctrl, &[], knots, 3, lo + (hi - lo) * t)); + assert!(got.dist(want) < 1e-9, "{} knots given, piece {i} at {t}: {got:?} vs {want:?}", given.len()); + } + } + } + } + + /// #9355: weighted quadratics (how CAD programs write arcs and circles) come in as conics on + /// the circle all along: a quarter, and a whole circle of four, closed. + #[test] + fn a_weighted_quadratic_spline_comes_in_as_conics_on_its_circle() { + let h = std::f64::consts::FRAC_1_SQRT_2; + let quarter = spline_dxf(2, &[[20.0, 0.0], [20.0, 20.0], [0.0, 20.0]], &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &[1.0, h, 1.0]); + let ctrl = [[20.0, 0.0], [20.0, 20.0], [0.0, 20.0], [-20.0, 20.0], [-20.0, 0.0], [-20.0, -20.0], [0.0, -20.0], [20.0, -20.0], [20.0, 0.0]]; + let knots = [0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0]; + let circle = spline_dxf(2, &ctrl, &knots, &[1.0, h, 1.0, h, 1.0, h, 1.0, h, 1.0]); + for (dxf, conics, profiles) in [(quarter, 1, 0), (circle, 4, 1)] { + let (r, sk, found) = insert_one(&dxf); + assert_eq!((r["curves"].as_u64(), found, &r["warnings"]), (Some(conics), profiles, &json!([])), "{r}"); + for i in 0..sk.curves.len() { + assert!(matches!(sk.curves[i].kind, CurveKind::Conic { .. }), "{:?}", sk.curves[i].kind); + let worst = (0..=64).map(|j| (curve_point(&sk, i, f64::from(j) / 64.0).len() - 20.0).abs()).fold(0.0, f64::max); + assert!(worst < 1e-9, "{worst}"); + } + } + } + + /// #9355: a weighted cubic has no exact sketch curve: it comes in as cubic splines within + /// 0.001 mm of it in the sketch, scaled up or not, and the import says how close. + #[test] + fn a_weighted_cubic_spline_comes_in_within_its_tolerance_and_the_import_says_so() { + let (ctrl, weights, knots) = + ([[0.0, 0.0], [5.0, 30.0], [40.0, 30.0], [50.0, 0.0]], [1.0, 3.0, 0.5, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + for scale in [1.0, 40.0] { + let (r, sk, _) = insert_scaled(&spline_dxf(3, &ctrl, &knots, &weights), scale).unwrap(); + assert!(sk.curves.iter().all(|c| matches!(c.kind, CurveKind::Spline { control: true, degree: 3, .. })), "{r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().starts_with("1 spline piece(s) have no exact sketch curve"), "{r}"); + assert_within(&sk, 0, &ctrl, &weights, &knots, 3, scale, 1e-3); + } + } + + /// A weighted quadratic so sharp (middle weight 2·10⁹, so 1 − rho below 10⁻⁹) that the sketch + /// would hold its conic at another weight comes in as cubics within 0.001 mm, not as that conic. + #[test] + fn a_quadratic_sharper_than_a_sketch_conic_comes_in_as_cubics() { + let (ctrl, weights, knots) = ([[0.0, 0.0], [1000.0, 0.0], [1000.0, 1000.0]], [1.0, 2e9, 1.0], [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]); + let (r, sk, _) = insert_one(&spline_dxf(2, &ctrl, &knots, &weights)); + assert!(sk.curves.iter().all(|c| matches!(c.kind, CurveKind::Spline { control: true, degree: 3, .. })), "{r}"); + assert_within(&sk, 0, &ctrl, &weights, &knots, 2, 1.0, 1e-3); + } + + /// A spline's end joining a line's end 0.01 mm away, with a join tolerance of 0.05 mm, moves + /// that far: the import says so, for a weighted cubic split into pieces and for the sketch's + /// own spline alike. With the default tolerance it doesn't join, and the spline keeps within + /// 0.001 mm. + #[test] + fn a_spline_end_moved_further_than_the_tolerance_to_join_is_reported() { + let (ctrl, knots) = ([[0.0, 0.0], [5.0, 30.0], [40.0, 30.0], [50.0, 0.0]], [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + let line = "0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n-20\n20\n0\n11\n0.01\n21\n0\n"; + for weights in [&[1.0, 3.0, 0.5, 1.0][..], &[]] { + let dxf = line.to_string() + spline_dxf(3, &ctrl, &knots, weights).trim_start_matches("0\nSECTION\n2\nENTITIES\n"); + let (r, sk, _) = insert_with(json!({"text": dxf, "tolerance": 0.05})).unwrap(); + let warned = |r: &serde_json::Value, start: &str| { + r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().starts_with(start)).count() + }; + assert_eq!(warned(&r, "curve ends moved up to 1.0e-2 mm"), 1, "{weights:?}: {r}"); + let (r, sk2, _) = insert_with(json!({"text": dxf})).unwrap(); + assert_eq!(warned(&r, "curve ends moved"), 0, "{weights:?}: {r}"); + assert_within(&sk2, 1, &ctrl, weights, &knots, 3, 1.0, 1e-3); + assert!(sk.curves.len() == sk2.curves.len()); + } + } + + /// An inner control point of a spline joins no other curve, even one ending right on it: it + /// shapes the curve, and moving it would move the curve. The ends still join. + #[test] + fn an_inner_spline_point_joins_no_other_curve() { + let dxf = "0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n100\n20\n100\n11\n10\n21\n25\n0\nLINE\n10\n45\n20\n5\n11\n90\n21\n5\n\ + 0\nSPLINE\n71\n3\n10\n0\n20\n0\n10\n10\n20\n25\n10\n30\n20\n30\n10\n45\n20\n5\n0\nENDSEC\n0\nEOF\n"; + let (_, sk, _) = insert_one(dxf); + let (CurveKind::Line { b: inner_end, .. }, CurveKind::Line { a: end, .. }, CurveKind::Spline { pts, .. }) = + (&sk.curves[0].kind, &sk.curves[1].kind, &sk.curves[2].kind) + else { + panic!("{:?}", sk.curves) + }; + assert!(pts[1] != *inner_end && pts[3] == *end, "{pts:?}"); + } + + /// Random SPLINEs of degree 1 to 9 (now and then 11), clamped or not, inner knots repeated up + /// to and past the degree, weights up to 100 apart, inserted at three scales: each comes in + /// within 0.001 mm of the file's curve in the sketch, both ways, or is refused with the reason. + #[test] + fn random_splines_come_in_within_the_tolerance_or_are_refused() { + let mut rng = 0x9355_u64; + let mut unit = move || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + (rng >> 11) as f64 / (1u64 << 53) as f64 + }; + let (mut came, mut refused) = (0, 0); + for _ in 0..150 { + let p = if unit() < 0.1 { 11 } else { 1 + (unit() * 9.0) as usize }; + let n = p + 1 + (unit() * 8.0) as usize; + let clamped = unit() < 0.6; + let mut knots = Vec::with_capacity(n + p + 1); + let mut u = 0.0; + for i in 0..n + p + 1 { + if i > 0 && !(clamped && (i <= p || i > n)) && !(i > p && i < n && unit() < 0.25) { + u += 0.05 + unit(); + } + knots.push(u); + } + let ctrl: Vec<[f64; 2]> = (0..n).map(|_| [100.0 * unit() - 50.0, 100.0 * unit() - 50.0]).collect(); + let weights: Vec = if unit() < 0.5 { Vec::new() } else { (0..n).map(|_| 10f64.powf(2.0 * unit() - 1.0)).collect() }; + let scale = [1.0, 7.5, 0.02][(unit() * 3.0) as usize]; + match insert_scaled(&spline_dxf(p, &ctrl, &knots, &weights), scale) { + Ok((_, sk, _)) => { + assert_within(&sk, 0, &ctrl, &weights, &knots, p, scale, 1e-3 * (1.0 + 1e-6) + 1e-12 * 100.0 * scale); + came += 1; + } + Err(e) => { + assert!(e.contains("spline") || e.contains("SPLINE"), "{e}"); + refused += 1; + } + } + } + assert!(came > 100 && refused > 5, "came in {came}, refused {refused}"); + } + const PLATE: &str = r#""#; diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index b38f93fcf3d..d8fbc852c7a 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -3780,7 +3780,9 @@ fn freeform_offsets_trim_folds_and_round_chain_corners_into_an_extrudable_wall() let mut s = new_sketch(); run(&mut s, "sketch.insert_svg", json!({"text": svg})); let sources = sketch(&s).curves.iter().map(|c| c.id.clone()).collect::>(); - assert_eq!(sources.len(), 5); + // Five curves as written; the one with the zero-length handle comes in as several that + // have a direction at that end, which a sketch spline needs (Insert SVG), so more than five. + assert!(sources.len() > 5, "{sources:?}"); // Picking every curve of the chain makes one offset, not one per curve. let out = run(&mut s, "sketch.offset", json!({"curves": sources, "distance": distance})); let curves = ids(&out["curves"]); @@ -3789,8 +3791,8 @@ fn freeform_offsets_trim_folds_and_round_chain_corners_into_an_extrudable_wall() curves.iter().any(|c| matches!(sk.curves[sk.curve_index(c).unwrap()].kind, CurveKind::Arc { .. })), "an outer corner is rounded: {out}" ); - assert_eq!(sk.curves.len(), 5 + curves.len()); - let source: Vec<_> = (0..5).flat_map(|i| sk.exact_pieces(i)).collect(); + assert_eq!(sk.curves.len(), sources.len() + curves.len()); + let source: Vec<_> = (0..sources.len()).flat_map(|i| sk.exact_pieces(i)).collect(); for c in &curves { for seg in sk.exact_pieces(sk.curve_index(c).unwrap()) { for k in 0..=8 { diff --git a/crates/geom/src/bspline.rs b/crates/geom/src/bspline.rs index 8e1dba073bd..f3fd6720d6b 100644 --- a/crates/geom/src/bspline.rs +++ b/crates/geom/src/bspline.rs @@ -15,9 +15,15 @@ use std::ops::{Add, AddAssign, Mul, Sub}; use solidcore_record::Vec3; +mod curve; +mod interval; + +pub use curve::{Certified, CurvePiece, Fit, MIN_CONIC_RHO_GAP, MIN_CONTROL_GAP, NurbsCurve, follow}; + /// Highest polynomial degree accepted in either direction: the B-rep record's own bound /// (`Brep::validate`), so every spline a record may hold can be evaluated. A G4 blend is of -/// degree 9 (five conditions at each end). +/// degree 9 (five conditions at each end). A [`NurbsCurve`] has the same bound, which bounds +/// the work a hostile curve can ask for. pub const MAX_SPLINE_DEGREE: usize = solidcore_record::brep::MAX_SPLINE_DEGREE; /// Most knots accepted in one knot vector. pub const MAX_KNOTS: usize = 1 << 14; @@ -95,6 +101,33 @@ impl AddAssign for HPoint { } } +/// A homogeneous control point as knot insertion and de Casteljau combine it: in floating point +/// ([`HPoint`]), or enclosed in intervals that hold the exact result ([`interval::HInterval`]). +/// One implementation of each of those steps serves both. +pub(crate) trait Blend: Copy { + /// What a point is weighted by: a number, or an interval holding one. + type Factor: Copy; + const ZERO: Self; + /// The factors of the later and the earlier point for `u` between `lo < hi`: + /// `((u − lo)/(hi − lo), (hi − u)/(hi − lo))`, both from knot differences (`1 − α` loses α's + /// digits when α is near 1, and a weight of 10¹² beside one of 1 shows it). + fn factors(lo: f64, u: f64, hi: f64) -> (Self::Factor, Self::Factor); + /// `self·a + other·b`. + fn blend(self, a: Self::Factor, other: Self, b: Self::Factor) -> Self; +} + +impl Blend for HPoint { + type Factor = f64; + const ZERO: HPoint = HPoint::ZERO; + fn factors(lo: f64, u: f64, hi: f64) -> (f64, f64) { + let den = hi - lo; + ((u - lo) / den, (hi - u) / den) + } + fn blend(self, a: f64, other: HPoint, b: f64) -> HPoint { + self * a + other * b + } +} + /// A parameter direction: along s (u, the first) or along t (v, the second). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Dir { @@ -341,6 +374,11 @@ pub fn find_span(knots: &[f64], p: usize, n: usize, u: f64) -> Option { /// points (Boehm; NURBS Book eq. 5.10 / A5.1). `u` must lie in the domain `[knots[p], /// knots[n]]`; the curve is unchanged. pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineResult<(Vec, Vec)> { + insert_row(p, knots, ctrl, u) +} + +/// [`insert_knot`] for either kind of point ([`Blend`]). +pub(crate) fn insert_row(p: usize, knots: &[f64], ctrl: &[P], u: f64) -> SplineResult<(Vec, Vec

)> { let n = ctrl.len(); if n <= p || knots.len() != n + p + 1 { return invalid("knot and control point counts do not match the degree"); @@ -351,17 +389,18 @@ pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineRe check_knots(knots)?; let k = find_span(knots, p, n, u).ok_or_else(|| SplineError::Invalid(format!("knot {u} is outside the domain")))?; let kn = |i: usize| knots.get(i).copied().unwrap_or(0.0); - let pt = |i: usize| ctrl.get(i).copied().unwrap_or(HPoint::ZERO); + let pt = |i: usize| ctrl.get(i).copied().unwrap_or(P::ZERO); let mut q = Vec::with_capacity(n + 1); for i in 0..=n { q.push(if i + p <= k { pt(i) } else if i > k { pt(i - 1) + } else if kn(i + p) > kn(i) { + let (alpha, beta) = P::factors(kn(i), u, kn(i + p)); + pt(i).blend(alpha, pt(i - 1), beta) } else { - let den = kn(i + p) - kn(i); - let alpha = if den > 0.0 { (u - kn(i)) / den } else { 1.0 }; - pt(i) * alpha + pt(i - 1) * (1.0 - alpha) + pt(i) }); } let mut nk = knots.to_vec(); @@ -430,7 +469,7 @@ pub fn bernstein(p: usize, i: usize, x: f64) -> f64 { /// basis functions that vanish on the domain dropped (a basis function's last span does not /// depend on its first knot, so that knot moves to the domain end). The curve on the domain is /// unchanged. -pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult<(Vec, Vec)> { +pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[P]) -> SplineResult<(Vec, Vec

)> { let n = row.len(); let (Some(&a), Some(&b)) = (knots.get(p), knots.get(n)) else { return invalid("too few knots") }; let (mut knots, mut row) = (knots.to_vec(), row.to_vec()); @@ -439,10 +478,10 @@ pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult let mut guard = 0; while mult(&knots) < p { guard += 1; - if guard > MAX_SPLINE_DEGREE + 1 { + if guard > p + 1 { return invalid("clamping did not converge"); } - (knots, row) = insert_knot(p, &knots, &row, x)?; + (knots, row) = insert_row(p, &knots, &row, x)?; } let n = row.len(); let (first, last) = if at_end { @@ -461,7 +500,7 @@ pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult } else { nk.first_mut().into_iter().for_each(|y| *y = x); } - row = row.get(first..last).map(<[HPoint]>::to_vec).unwrap_or_default(); + row = row.get(first..last).map(<[P]>::to_vec).unwrap_or_default(); knots = nk; } Ok((knots, row)) @@ -469,7 +508,7 @@ pub(crate) fn clamp_row(p: usize, knots: &[f64], row: &[HPoint]) -> SplineResult /// A Bézier curve's point at `x ∈ [0, 1]` (de Casteljau, NURBS Book §1.4). pub fn bezier_point(ctrl: &[HPoint], x: f64) -> HPoint { - subdivide(ctrl, x).0.last().copied().unwrap_or(HPoint::ZERO) + subdivide(ctrl, x, 1.0 - x).0.last().copied().unwrap_or(HPoint::ZERO) } /// The control points of the piece of a Bézier curve over `[a, b] ⊂ [0, 1]` (two de Casteljau @@ -479,19 +518,21 @@ pub fn bezier_segment(ctrl: &[HPoint], a: f64, b: f64) -> SplineResult (Vec, Vec) { +/// Split a Bézier curve where its parameter is `t` (and `1 − t` is `s`), by de Casteljau: control +/// points of `[0, t]` and `[t, 1]`. +pub(crate) fn subdivide(ctrl: &[P], t: P::Factor, s: P::Factor) -> (Vec

, Vec

) { let mut left = Vec::with_capacity(ctrl.len()); let mut right = Vec::with_capacity(ctrl.len()); let mut pts = ctrl.to_vec(); while let (Some(&f), Some(&l)) = (pts.first(), pts.last()) { left.push(f); right.push(l); - pts = pts.windows(2).map(|w| if let [a, b] = w { *a * (1.0 - x) + *b * x } else { HPoint::ZERO }).collect(); + pts = pts.windows(2).map(|w| if let [a, b] = w { a.blend(s, *b, t) } else { P::ZERO }).collect(); } right.reverse(); (left, right) @@ -896,6 +937,20 @@ pub(crate) mod tests { assert!(worst < 1e-13, "deviation {worst}"); assert!(insert_knot(p, &KNOTS, &ctrl, 1.5).is_err()); assert!(insert_knot(p, &KNOTS, &ctrl, f64::NAN).is_err()); + // Beside a weight of 10¹², α = (1.5 − 2⁻⁵²)/1.5 is so near 1 that `1 − α` keeps a + // quarter of the other factor wrong; from knot differences it stays on the curve. + let ub = 1.5 - 2f64.powi(-52); + let heavy = [ + HPoint::weighted(Vec3::new(0.0, 0.0, 0.0), 1.0), + HPoint::weighted(Vec3::new(10.0, 20.0, 0.0), 1e12), + HPoint::weighted(Vec3::new(20.0, 0.0, 0.0), 1.0), + ]; + let open = [0.0, 0.0, 0.0, 1.5, 1.5, 1.5]; + let (kn, pts) = insert_knot(2, &open, &heavy, ub).unwrap(); + for u in [0.75, 1.4, ub, 1.5] { + let off = curve(2, &open, &heavy, u).dist(curve(2, &kn, &pts, u)); + assert!(off < 1e-9, "{off:e} off the curve at {u}"); + } } pub(crate) fn random_surface(seed: u64, ku: Vec, kv: Vec, degree: [usize; 2]) -> NurbsSurface { diff --git a/crates/geom/src/bspline/curve.rs b/crates/geom/src/bspline/curve.rs new file mode 100644 index 00000000000..dbf62fd9724 --- /dev/null +++ b/crates/geom/src/bspline/curve.rs @@ -0,0 +1,1071 @@ +//! Rational B-spline curves that are valid by construction, their exact Bézier pieces, and the +//! curves that follow a piece within a tolerance with a proven bound (#9355). 2D curves are curves +//! with z = 0. +//! +//! A [`NurbsCurve`] is only made by [`NurbsCurve::from_homogeneous`], which checks everything that +//! ties its parts together: the degree, `n + degree + 1` knots for `n` control points, knots that +//! never decrease, room to clamp them, no inner knot repeated more than the degree, a non-empty +//! domain, finite points no further than [`MAX_COORDINATE`] from the origin, positive weights that +//! can be divided by. Arithmetic on a valid curve can still overflow or run out of +//! precision, so its operations return [`SplineResult`]. +//! +//! Every piece carries intervals that hold its exact control points ([`super::interval`]): the +//! curve's own, then every knot insertion done in intervals, each factor from knot differences. +//! So what the pieces stand for is exactly the curve as given, whatever rounding happened on the +//! way; their `f64` control points are numbers inside those intervals. +//! +//! The bound of [`follow`]: a piece is `N(t) / W(t)`, homogeneous numerator over weight, and a +//! fit, written as a rational Bézier, `C(t) / V(t)`, so their difference at the same `t` is +//! `(C·W − N·V)(t) / (V·W)(t)`. In the Bernstein basis of degree `n + m` that numerator has vector +//! coefficients `dₖ` and the denominator positive ones `Wₖ`, both combinations with the same +//! non-negative basis, so the distance is at most `maxₖ ‖dₖ‖ / Wₖ`. Computed in intervals from the +//! enclosed piece and the fit, with `‖dₖ‖` taken as the sum of its components' sizes and `Wₖ` at +//! its smallest, the bound holds for the exact curve. A polynomial Bézier is the same point set +//! with weights `1, c, c², …` for any `c > 0` (and a conic with weights `1, ω·c, c²`), so `c` is +//! chosen to match the piece's own parametrisation; the bound then holds for the point sets. + +use super::interval::{HInterval, Interval}; +use super::{Blend, HPoint, MAX_KNOTS, MAX_SPLINE_DEGREE, SplineError, SplineResult, binomial, check_knots, clamp_row, invalid, subdivide}; +use crate::prelude::*; +use solidcore_record::Vec3; + +/// Least `1 − rho` a conic [`Fit`] has: past it the sketch holds a conic's middle weight at +/// `rho / MIN_CONIC_RHO_GAP` rather than `rho / (1 − rho)`, a different curve. +pub const MIN_CONIC_RHO_GAP: f64 = 1e-9; +/// Furthest a control point may be from the origin along any axis (mm). +const MAX_COORDINATE: f64 = 1e12; +/// Least distance between neighbouring control points of a sketch spline, as the sketch's own +/// spline tool asks of the points it is given: nearer, a point repeats, which at an end leaves the +/// curve no direction there (a zero-length handle), and the solid kernel refuses to build on it. +/// The gap [`follow`] keeps for curves at the sketch's size; one drawn at another is scaled to it. +pub const MIN_CONTROL_GAP: f64 = 1e-9; + +/// A rational B-spline curve of `degree` with `knots` and homogeneous control points, checked when +/// it is made (module documentation). +#[derive(Clone, Debug, PartialEq)] +pub struct NurbsCurve { + degree: usize, + knots: Vec, + exact: Vec, +} + +impl NurbsCurve { + /// The curve over homogeneous control points `(x·w, y·w, z·w, w)`. + pub fn from_homogeneous(degree: usize, knots: Vec, ctrl: &[HPoint]) -> SplineResult { + let (n, p) = (ctrl.len(), degree); + if !(1..=MAX_SPLINE_DEGREE).contains(&p) { + return Err(SplineError::Unsupported(format!("degree {p} (1 to {MAX_SPLINE_DEGREE})"))); + } + if n <= p || knots.len() != n + p + 1 { + return invalid(format!("{n} control points of degree {p} need {} knots, not {}", n + p + 1, knots.len())); + } + check_knots(&knots)?; + // Clamping inserts each end of the domain up to `p` times more. + if knots.len() + 2 * p > MAX_KNOTS { + return Err(SplineError::TooLarge(format!("{} knots of degree {p} (at most {})", knots.len(), MAX_KNOTS - 2 * p))); + } + let (Some(&lo), Some(&hi)) = (knots.get(p), knots.get(n)) else { return invalid("too few knots") }; + if hi <= lo { + return invalid("the curve's domain is empty"); + } + for run in knots.get(p + 1..n).unwrap_or_default().chunk_by(|a, b| a == b) { + if let Some(&u) = run.first() + && run.len() > p + && lo < u + && u < hi + { + return invalid(format!("the inner knot {u} repeats more than the degree")); + } + } + for h in ctrl { + if !(h.w.is_finite() && h.w > 0.0) { + return invalid("weights must be positive numbers"); + } + if h.w < f64::MIN_POSITIVE { + return invalid(format!("a weight of {:e} is too small to divide by", h.w)); + } + let q = h.project().ok_or_else(|| SplineError::Invalid("a control point is not finite".into()))?; + if q.x.abs().max(q.y.abs()).max(q.z.abs()) > MAX_COORDINATE { + return Err(SplineError::TooLarge(format!("a control point more than {MAX_COORDINATE} mm from the origin"))); + } + } + let exact = ctrl.iter().map(|h| HInterval::point(*h)).collect(); + Ok(NurbsCurve { degree: p, knots, exact }) + } + + pub fn degree(&self) -> usize { + self.degree + } + pub fn knots(&self) -> &[f64] { + &self.knots + } + /// The homogeneous control points, as the curve was made with them. + pub fn ctrl(&self) -> impl Iterator + '_ { + self.exact.iter().map(|h| h.mid()) + } + + /// The curve's Bézier pieces: one per span of non-zero length of its domain, in order. The + /// curve is clamped on its domain, then split in one pass (NURBS Book A5.6), in work linear in + /// its length, all in intervals. An inner knot repeated more than the degree (a curve broken + /// there) is refused when the curve is made; this refuses it too. + pub fn pieces(&self) -> SplineResult> { + let p = self.degree; + let (u, pw) = clamp_row(p, &self.knots, &self.exact)?; + let bad = || SplineError::Invalid("Bézier decomposition".into()); + let kn = |i: usize| u.get(i).copied().ok_or_else(bad); + let m = u.len().checked_sub(1).ok_or_else(bad)?; + let mut piece = pw.get(..=p).ok_or_else(bad)?.to_vec(); + let mut factors = vec![(Interval::ZERO, Interval::ZERO); p]; + let mut out = Vec::new(); + // `a` is the last index of the knot that starts the piece, `b` walks to the one that ends it. + let (mut a, mut b) = (p, p + 1); + while b < m { + let first = b; + while b < m && kn(b + 1)? == kn(b)? { + b += 1; + } + let mult = b - first + 1; + let end = b >= m; + if !end && mult > p { + return invalid(format!("the inner knot {} repeats more than the degree", kn(b)?)); + } + let (ua, ub) = (kn(a)?, kn(b)?); + let mut next = vec![HInterval::ZERO; p + 1]; + if mult < p { + // Insert `ub` until it repeats `p` times; the piece's points become Bézier points, + // and the next piece's first ones fall out on the way. + for j in (mult + 1..=p).rev() { + *factors.get_mut(j - mult - 1).ok_or_else(bad)? = HInterval::factors(ua, ub, kn(a + j)?); + } + let r = p - mult; + for j in 1..=r { + let s = mult + j; + for k in (s..=p).rev() { + let (alpha, beta) = *factors.get(k - s).ok_or_else(bad)?; + let prev = *piece.get(k - 1).ok_or_else(bad)?; + let cur = piece.get_mut(k).ok_or_else(bad)?; + *cur = cur.blend(alpha, prev, beta); + } + if !end { + *next.get_mut(r - j).ok_or_else(bad)? = *piece.get(p).ok_or_else(bad)?; + } + } + } + if !piece.iter().all(|h| h.is_sound()) { + return invalid("the curve's points overflow, or its weights lose their precision"); + } + if !end { + for i in p - mult..=p { + *next.get_mut(i).ok_or_else(bad)? = *pw.get(b - p + i).ok_or_else(bad)?; + } + a = b; + b += 1; + } + out.push(CurvePiece { span: [ua, ub], exact: std::mem::replace(&mut piece, next) }); + } + Ok(out) + } +} + +/// One Bézier piece of a [`NurbsCurve`] over `span` of its parameter: `degree + 1` intervals that +/// hold its exact homogeneous control points. +#[derive(Clone, Debug, PartialEq)] +pub struct CurvePiece { + span: [f64; 2], + exact: Vec, +} + +impl CurvePiece { + /// The part of the curve's parameter the piece covers. + pub fn span(&self) -> [f64; 2] { + self.span + } + /// The homogeneous control points: each a point inside the interval that holds the exact one. + pub fn ctrl(&self) -> impl Iterator + '_ { + self.exact.iter().map(|h| h.mid()) + } +} + +/// A curve that follows (part of) a curve piece, as a sketch holds curves. +#[derive(Clone, Debug, PartialEq)] +pub enum Fit { + /// The polynomial Bézier curve over these control points; two make a line. + Bezier(Vec), + /// The conic from `a` to `b` with control point `apex` and shape `rho ∈ (0, 1)`: the rational + /// quadratic with end weights 1 and middle weight `rho / (1 − rho)`. + Conic { a: Vec3, apex: Vec3, b: Vec3, rho: f64 }, +} + +/// A value with a bound, proven when it was made, on how far it is from the part of a curve piece +/// it stands for: every point of either lies within `bound` of the other. Only this module makes +/// one. +#[derive(Clone, Debug, PartialEq)] +pub struct Certified { + value: T, + bound: f64, + along: [f64; 2], +} + +impl Certified { + pub fn value(&self) -> &T { + &self.value + } + pub fn bound(&self) -> f64 { + self.bound + } + /// The fractions of the piece's parameter between which the part it stands for lies. + pub fn along(&self) -> [f64; 2] { + self.along + } + pub fn into_value(self) -> T { + self.value + } +} + +/// Curves that follow `piece` end to end, in order, each within `tolerance` of it with the bound +/// proven ([`Certified`]): the piece itself as a polynomial Bézier when it is one (up to its +/// parametrisation) and its degree is at most `max_degree`; a quadratic one as a conic; otherwise +/// cubics matching the ends of parts of it and their tangents, a part halved until its bound is +/// within the tolerance. No fit repeats a control point, two neighbours nearer than `gap` (the +/// piece's units: [`MIN_CONTROL_GAP`] divided by the scale the curves are drawn at): a piece that +/// does (an end with no direction, as a zero-length handle leaves) is followed by cubics whose +/// handles point the way the piece leaves that end. Refused, with how close it came, when that +/// would take more than `max_fits` curves, or the intervals can't prove it (a tolerance below the +/// piece's rounding). +pub fn follow(piece: &CurvePiece, tolerance: f64, gap: f64, max_degree: usize, max_fits: usize) -> SplineResult>> { + if !(tolerance.is_finite() && tolerance > 0.0) { + return invalid("the tolerance must be a positive number"); + } + if !(gap.is_finite() && gap > 0.0) { + return invalid("the gap between control points must be a positive number"); + } + // Every piece takes at least one curve; past this, curves made plus parts pending never + // exceed the room (a split is checked before it adds one). + if max_fits == 0 { + return Err(SplineError::TooLarge("no room for a curve: a curve piece takes at least one".into())); + } + let mids: Vec = piece.ctrl().collect(); + let pts: Vec = + mids.iter().map(|h| h.project()).collect::>().ok_or_else(|| SplineError::Invalid("a curve piece's points don't project".into()))?; + let whole = |value: Fit, bound: f64| vec![Certified { value, bound, along: [0.0, 1.0] }]; + let (Some(first), Some(last)) = (mids.first(), mids.last()) else { return invalid("a curve piece has no points") }; + let n = mids.len() - 1; + if (1..=max_degree).contains(&n) && !repeats(&pts, gap) { + // Weights 1, c, c², … with c from the end weights' ratio, so the parametrisations meet. + let c = (last.w / first.w).powf(1.0 / n as f64); + let c = Interval::point(if c.is_finite() && c > 0.0 { c } else { 1.0 }); + let weights: Vec = std::iter::successors(Some(Interval::point(1.0)), |w| Some(w.mul(c))).take(n + 1).collect(); + if let Ok(bound) = error_bound(&piece.exact, &weighted(&pts, &weights)) + && bound <= tolerance + { + return Ok(whole(Fit::Bezier(pts), bound)); + } + } + if let ([a, apex, b], [h0, h1, h2]) = (&pts[..], &mids[..]) { + // A conic whose apex lies on its chord is a line traced unevenly: no conic for a sketch. + let side = (*apex - *a).cross(*b - *a).len(); + let w = h1.w / (h0.w * h2.w).sqrt(); + let rho = w / (1.0 + w); + // Weights 1, ω·c, c² with c from the end weights' ratio, so the parametrisations meet. + let c = (h2.w / h0.w).sqrt(); + // 1 − rho is exact for rho ≥ ½ (and far above the gap below it): the sketch's own test. + if side > 1e-12 * a.dist(*apex) * a.dist(*b) && rho > 0.0 && 1.0 - rho >= MIN_CONIC_RHO_GAP && c.is_finite() && c > 0.0 { + let rho_i = Interval::point(rho); + let omega = rho_i.div(Interval::point(1.0).sub(rho_i)); + let c = Interval::point(c); + if let Ok(bound) = error_bound(&piece.exact, &weighted(&pts, &[Interval::point(1.0), omega.mul(c), c.mul(c)])) + && bound <= tolerance + { + return Ok(whole(Fit::Conic { a: *a, apex: *apex, b: *b, rho }, bound)); + } + } + } + cubics(&piece.exact, tolerance, gap, max_fits) +} + +/// Points `pts` with the weights `w`, as homogeneous intervals. +fn weighted(pts: &[Vec3], w: &[Interval]) -> Vec { + pts.iter() + .zip(w) + .map(|(p, &w)| HInterval { x: Interval::point(p.x).mul(w), y: Interval::point(p.y).mul(w), z: Interval::point(p.z).mul(w), w }) + .collect() +} + +/// Whether two neighbouring points of `pts` are closer than `gap`, and not all of them are (a +/// curve smaller than that is a point, whatever its points: it is kept as it is). +fn repeats(pts: &[Vec3], gap: f64) -> bool { + pts.windows(2).any(|w| w[0].dist(w[1]) < gap) && !pts.iter().all(|p| p.dist(pts[0]) < gap) +} + +/// Cubic Hermite curves that follow the enclosed Bézier `exact`, halving a part until its bound is +/// within `tolerance`, no two neighbouring points nearer than `gap` ([`follow`]). +fn cubics(exact: &[HInterval], tolerance: f64, gap: f64, max_fits: usize) -> SplineResult>> { + let half = Interval::point(0.5); + let ones = [Interval::point(1.0); 4]; + let mut out = Vec::new(); + let mut parts = vec![(exact.to_vec(), [0.0, 1.0])]; + let mut mids = Vec::with_capacity(exact.len()); + while let Some((part, along)) = parts.pop() { + mids.clear(); + mids.extend(part.iter().map(|h| h.mid())); + let (ctrl, run) = hermite(&mids, gap)?; + // Traced as `run` goes, the cubic is still every one of its points, so a bound between the + // part and it bounds the distance from each point of either to the other. + let traced = match run { + Run::Even => weighted(&ctrl, &ones), + Run::Stops(psi) => composed(&ctrl, psi), + }; + let bound = error_bound(&part, &traced)?; + // A cubic with a repeated point (a part too small for its handles) is split, as one too far. + if bound <= tolerance && !repeats(&ctrl, gap) { + out.push(Certified { value: Fit::Bezier(ctrl.to_vec()), bound, along }); + continue; + } + if out.len() + parts.len() + 2 > max_fits { + return Err(SplineError::TooLarge(format!( + "more than {max_fits} curves to come within {tolerance} of a curve piece (one is {bound:.1e} off)" + ))); + } + let mid = f64::midpoint(along[0], along[1]); + if !(along[0] < mid && mid < along[1]) { + return Err(SplineError::Unsupported(format!("no cubic comes within {tolerance} of a curve piece: {bound:.1e} at the finest part"))); + } + let (left, right) = subdivide(&part, half, half); + if !left.iter().chain(&right).all(|h| h.is_sound()) { + return invalid("the piece's points overflow, or its weights lose their precision"); + } + parts.push((right, [mid, along[1]])); + parts.push((left, [along[0], mid])); + } + Ok(out) +} + +/// How a cubic is traced when it is compared with the part it follows: as its own parameter runs, +/// or as `ψ` (Bernstein coefficients, rising from 0 to 1) runs, which stops at an end, as a part +/// that arrives at an end with no speed does. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Run { + Even, + Stops(&'static [f64]), +} + +/// `ψ(s) = s²`: stops at the start. +const STOPS_AT_START: &[f64] = &[0.0, 0.0, 1.0]; +/// `ψ(s) = 1 − (1 − s)²`: stops at the end. +const STOPS_AT_END: &[f64] = &[0.0, 1.0, 1.0]; +/// `ψ(s) = 3s² − 2s³`: stops at both. +const STOPS_AT_BOTH: &[f64] = &[0.0, 0.0, 1.0, 1.0]; + +/// The cubic with the ends of the Bézier `q` and its tangents there (cubic Hermite): a rational +/// Bézier's derivative at its start is `n·(w₁/w₀)·(p₁ − p₀)`, and alike at its end; traced evenly. +/// +/// Where the derivative leaves a handle shorter than `gap` (the end has no +/// direction: `p₁` on `p₀`, as a zero-length handle in a drawing leaves it), the curve arrives +/// there with no speed and turns ever more sharply into it. A cubic that follows it as closely in +/// the same parameter would have to turn as sharply. Instead the cubic is traced as a `ψ` that +/// stops there too ([`Run::Stops`]), and its handle matches the part's second derivative there, +/// `n(n−1)·(w₂/w₀)·(p₂ − p₀)`, through `ψ`: it points the way the curve leaves that end and is +/// long, so the cubic bends gently where the part bends sharply, within its bound of it. The other +/// end's handle matches its derivative through `ψ` likewise. Any cubic would do: the bound is +/// computed for the one made. +fn hermite(q: &[HPoint], gap: f64) -> SplineResult<([Vec3; 4], Run)> { + let n = q.len().saturating_sub(1); + let at = |i: usize| q.get(i).and_then(|h| h.project().map(|p| (p, h.w))); + let (Some((p0, w0)), Some((p1, w1)), Some((pm, wm)), Some((pn, wn))) = (at(0), at(1), at(n.saturating_sub(1)), at(n)) else { + return invalid("a curve piece's points don't project"); + }; + let nf = u32::try_from(n).map(f64::from).or_else(|_| invalid("a curve piece's degree is too high"))?; + let chord = p0.dist(pn); + // The derivatives at the ends, into the curve. + let (d0, d1) = ((p1 - p0) * (nf * w1 / w0), (pm - pn) * (nf * wm / wn)); + // An end stops where its handle would have no length and the part is long enough for one. + let stops = |d: Vec3| n >= 2 && d.len() / 3.0 < gap && chord / 3.0 >= gap; + // A stopped end's handle, for `ψ` with `bend = ψ''` there: the second derivative into the curve + // over three times `bend`; where that has no length either, a third of the chord along the + // first of the points that leaves the end. + let stopped = |from: Vec3, w: f64, next: usize, others: &mut dyn Iterator, bend: f64| -> Vec3 { + let second = at(next).map_or(Vec3::ZERO, |(p, wn2)| (p - from) * (nf * (nf - 1.0) * wn2 / w)); + if second.len() / (3.0 * bend) >= gap { + return second / (3.0 * bend); + } + let away = others.filter_map(|i| at(i).map(|(p, _)| p - from)).find(|v| v.len() >= gap); + away.and_then(Vec3::normalized).map_or(Vec3::ZERO, |u| u * (chord / 3.0)) + }; + let (h0, h1, run) = match (stops(d0), stops(d1)) { + (false, false) => (d0 / 3.0, d1 / 3.0, Run::Even), + // ψ = 1 − (1 − s)²: ψ'(0) = 2, ψ''(1) = −2. + (false, true) => (d0 / 6.0, stopped(pn, wn, n.saturating_sub(2), &mut (0..n.saturating_sub(2)).rev(), 2.0), Run::Stops(STOPS_AT_END)), + // ψ = s²: ψ''(0) = 2, ψ'(1) = 2. + (true, false) => (stopped(p0, w0, 2, &mut (3..=n), 2.0), d1 / 6.0, Run::Stops(STOPS_AT_START)), + // ψ = 3s² − 2s³: ψ''(0) = 6, ψ''(1) = −6. + (true, true) => ( + stopped(p0, w0, 2, &mut (3..=n), 6.0), + stopped(pn, wn, n.saturating_sub(2), &mut (0..n.saturating_sub(2)).rev(), 6.0), + Run::Stops(STOPS_AT_BOTH), + ), + }; + let ctrl = [p0, p0 + h0, pn + h1, pn]; + if !ctrl.iter().all(|p| p.is_finite()) { + return invalid("a curve piece's tangents overflow"); + } + Ok((ctrl, run)) +} + +/// The polynomial Bézier `q` traced as `psi` runs (Bernstein coefficients of `ψ`): `q(ψ(s))`, of +/// degree 3·deg ψ, as homogeneous intervals of weight 1 that hold its exact control points. +fn composed(q: &[Vec3; 4], psi: &[f64]) -> Vec { + let one = Interval::point(1.0); + let psi: Vec = psi.iter().map(|&x| Interval::point(x)).collect(); + let rest: Vec = psi.iter().map(|&x| one.sub(x)).collect(); + let power = |f: &[Interval], k: usize| (0..k).fold(vec![one], |acc, _| bernstein_mul(&acc, f)); + let mut out: Vec<[Interval; 3]> = Vec::new(); + for (i, qi) in q.iter().enumerate() { + // C(3, i) ψⁱ (1 − ψ)³⁻ⁱ, the Bernstein basis function through ψ. + let basis = bernstein_mul(&power(&psi, i), &power(&rest, 3 - i)); + out.resize(basis.len(), [Interval::ZERO; 3]); + let c = Interval::point(binomial(3, i)); + for (o, b) in out.iter_mut().zip(&basis) { + let b = c.mul(*b); + for (oc, qc) in o.iter_mut().zip([qi.x, qi.y, qi.z]) { + *oc = oc.add(b.mul(Interval::point(qc))); + } + } + } + out.into_iter().map(|[x, y, z]| HInterval { x, y, z, w: one }).collect() +} + +/// The Bernstein coefficients of the product of two polynomials given by theirs (of degrees +/// `f.len() − 1` and `g.len() − 1`). +fn bernstein_mul(f: &[Interval], g: &[Interval]) -> Vec { + let (a, b) = (f.len().saturating_sub(1), g.len().saturating_sub(1)); + let mut out = vec![Interval::ZERO; a + b + 1]; + for (i, fi) in f.iter().enumerate() { + for (j, gj) in g.iter().enumerate() { + let c = Interval::point(binomial(a, i) * binomial(b, j)).div(Interval::point(binomial(a + b, i + j))); + if let Some(o) = out.get_mut(i + j) { + *o = o.add(c.mul(fi.mul(*gj))); + } + } + } + out +} + +/// A bound, proven in intervals, on the distance at each `t` from the rational Bézier `c` to the +/// one `q` stands for (module documentation). +fn error_bound(q: &[HInterval], c: &[HInterval]) -> SplineResult { + let (Some(n), Some(m)) = (q.len().checked_sub(1), c.len().checked_sub(1)) else { return invalid("a Bézier has no points") }; + let mut worst = 0.0f64; + for k in 0..=n + m { + let (mut d, mut weight) = ([Interval::ZERO; 3], Interval::ZERO); + // Binomials up to (32 k) are integers below 2⁵³, and so are the products here: exact. + let all = Interval::point(binomial(n + m, k)); + for j in k.saturating_sub(n)..=k.min(m) { + // A term left out would make the bound a guess, so a missing point is an error. + let (Some(h), Some(cj)) = (q.get(k - j), c.get(j)) else { return invalid("a Bézier's points are missing") }; + let coef = Interval::point(binomial(m, j) * binomial(n, k - j)).div(all); + for (dc, (hc, cc)) in d.iter_mut().zip([(h.x, cj.x), (h.y, cj.y), (h.z, cj.z)]) { + *dc = dc.add(coef.mul(cc.mul(h.w).sub(hc.mul(cj.w)))); + } + weight = weight.add(coef.mul(h.w.mul(cj.w))); + } + if !(weight.lo > 0.0) { + return Err(SplineError::Unsupported("a curve piece's weights have lost their precision".into())); + } + // ‖dₖ‖ ≤ |dx| + |dy| + |dz|, rounded up. + let length = d.iter().fold(Interval::ZERO, |acc, c| acc.add(Interval::point(c.mag()))); + worst = worst.max(Interval::point(length.hi).div(Interval::point(weight.lo)).hi); + } + if worst.is_finite() { Ok(worst) } else { invalid("a curve piece's bound overflows") } +} + +#[cfg(test)] +mod tests { + use super::super::tests::Lcg; + use super::*; + use solidcore_record::Vec3; + + /// A double-double number: `hi + lo` with `|lo|` at most half an ulp of `hi`, about 106 bits. + /// The reference the curves are checked against, independent of this module's intervals. + #[derive(Clone, Copy, Debug)] + struct Dd(f64, f64); + + fn two_sum(a: f64, b: f64) -> (f64, f64) { + let s = a + b; + let v = s - a; + (s, (a - (s - v)) + (b - v)) + } + fn fast(a: f64, b: f64) -> Dd { + let s = a + b; + Dd(s, b - (s - a)) + } + + impl Dd { + fn of(x: f64) -> Dd { + Dd(x, 0.0) + } + fn add(self, o: Dd) -> Dd { + let (s, e) = two_sum(self.0, o.0); + let (t, f) = two_sum(self.1, o.1); + let Dd(s, e) = fast(s, e + t); + fast(s, e + f) + } + fn neg(self) -> Dd { + Dd(-self.0, -self.1) + } + fn sub(self, o: Dd) -> Dd { + self.add(o.neg()) + } + fn mul(self, o: Dd) -> Dd { + let p = self.0 * o.0; + let e = self.0.mul_add(o.0, -p); + fast(p, e + (self.0 * o.1 + self.1 * o.0)) + } + fn div(self, o: Dd) -> Dd { + let q1 = self.0 / o.0; + let r = self.sub(o.mul(Dd::of(q1))); + let q2 = r.0 / o.0; + let r = r.sub(o.mul(Dd::of(q2))); + fast(q1, q2).add(Dd::of(r.0 / o.0)) + } + fn val(self) -> f64 { + self.0 + self.1 + } + } + + /// A curve as given: degree, knots and exact homogeneous control points in double-double. + struct Def { + p: usize, + knots: Vec, + h: Vec<[Dd; 4]>, + } + + /// The homogeneous points over Cartesian `pts` and, when given, their weights. + fn weighted(pts: &[Vec3], w: Option<&[f64]>) -> Vec { + pts.iter().enumerate().map(|(i, &q)| HPoint::weighted(q, w.map_or(1.0, |w| w[i]))).collect() + } + + /// A curve over Cartesian points and its definition. + fn cartesian(p: usize, knots: &[f64], pts: &[Vec3], w: Option<&[f64]>) -> (NurbsCurve, Def) { + let (curve, def) = homogeneous(p, knots, &weighted(pts, w)); + (curve.unwrap(), def) + } + + /// A curve over homogeneous points (made or not) and its definition. + fn homogeneous(p: usize, knots: &[f64], ctrl: &[HPoint]) -> (SplineResult, Def) { + let h = ctrl.iter().map(|q| [q.x, q.y, q.z, q.w].map(Dd::of)).collect(); + (NurbsCurve::from_homogeneous(p, knots.to_vec(), ctrl), Def { p, knots: knots.to_vec(), h }) + } + + /// A piece's point at `t ∈ [0, 1]`, from its `f64` control points. + fn point(piece: &CurvePiece, t: f64) -> Vec3 { + super::super::bezier_point(&piece.ctrl().collect::>(), t).project().unwrap() + } + + /// The exact curve's point at fraction `s` of `span`, by de Boor on its own knot interval in + /// double-double (knots taken relative to the first, which double-double does exactly), both + /// factors of each step from knot differences. + fn truth(def: &Def, span: [f64; 2], s: Dd) -> [Dd; 3] { + let (p, kn) = (def.p, &def.knots); + let n = def.h.len(); + let at = (p..n).rev().find(|&j| kn[j] <= span[0] && kn[j] < kn[j + 1]).unwrap(); + let k = |i: usize| Dd::of(kn[i]).sub(Dd::of(kn[0])); + let (a, b) = (Dd::of(span[0]).sub(Dd::of(kn[0])), Dd::of(span[1]).sub(Dd::of(kn[0]))); + let u = a.add(s.mul(b.sub(a))); + let mut d: Vec<[Dd; 4]> = (0..=p).map(|j| def.h[j + at - p]).collect(); + for r in 1..=p { + for j in (r..=p).rev() { + let i = j + at - p; + let (lo, hi) = (k(i), k(i + p + 1 - r)); + let den = hi.sub(lo); + let (f, g) = (hi.sub(u).div(den), u.sub(lo).div(den)); + d[j] = [0, 1, 2, 3].map(|c| d[j - 1][c].mul(f).add(d[j][c].mul(g))); + } + } + let w = d[p][3]; + [0, 1, 2].map(|c| d[p][c].div(w)) + } + + /// Whether the exact curve's point at fraction `t` of the piece lies in the piece's enclosure + /// there, evaluated in intervals. + fn encloses(def: &Def, piece: &CurvePiece, t: f64) -> bool { + let (tt, s) = (Interval::point(t), Interval::point(1.0).sub(Interval::point(t))); + let mut pts = piece.exact.clone(); + while pts.len() > 1 { + pts = pts.windows(2).map(|w| w[0].blend(s, w[1], tt)).collect(); + } + let h = pts[0]; + let want = truth(def, piece.span(), Dd::of(t)); + [h.x, h.y, h.z].iter().zip(want).all(|(c, v)| { + let held = c.div(h.w); + held.lo.next_down() <= v.val() && v.val() <= held.hi.next_up() + }) + } + + /// The pieces' spans are the domain's in order, each piece holds the curve, and its control + /// points are close to the exact ones. + fn assert_pieces_trace(curve: &NurbsCurve, def: &Def, want: usize) -> Vec { + let (p, kn) = (def.p, &def.knots); + let pieces = curve.pieces().unwrap(); + let mut spans: Vec<[f64; 2]> = (p..def.h.len()).map(|i| [kn[i], kn[i + 1]]).filter(|s| s[0] < s[1]).collect(); + spans.dedup(); + assert_eq!((pieces.len(), pieces.iter().map(|b| b.span()).collect::>()), (want, spans)); + for b in &pieces { + assert_eq!(b.ctrl().count(), p + 1); + for t in [0.0, 0.17, 0.5, 0.83, 1.0] { + assert!(encloses(def, b, t), "span {:?} at {t}", b.span()); + let got = point(b, t); + let want = truth(def, b.span(), Dd::of(t)).map(Dd::val); + assert!(got.dist(Vec3::new(want[0], want[1], want[2])) < 1e-9, "span {:?} at {t}: {got:?}", b.span()); + } + } + pieces + } + + fn plain(xy: &[(f64, f64)]) -> Vec { + xy.iter().map(|&(x, y)| Vec3::new(x, y, 0.0)).collect() + } + + #[test] + fn a_curve_splits_into_the_bezier_pieces_of_its_own_knots() { + let ctrl = plain(&[(0.0, 0.0), (10.0, 6.0), (18.0, -4.0), (30.0, 9.0), (36.0, 1.0), (48.0, 5.0), (52.0, -2.0)]); + // Uneven gaps, as a DXF from another program has them; a double inner knot; an inner knot + // repeated `degree` times, where the points are already Bézier points. + for (knots, pieces) in [ + ([0.0, 0.0, 0.0, 0.0, 0.1, 0.15, 0.6, 1.0, 1.0, 1.0, 1.0], 4), + ([0.0, 0.0, 0.0, 0.0, 0.3, 0.3, 0.7, 1.0, 1.0, 1.0, 1.0], 3), + ([0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0], 2), + ] { + let (curve, def) = cartesian(3, &knots, &ctrl, None); + assert_pieces_trace(&curve, &def, pieces); + } + // Rational, in space, at random. + let mut rng = Lcg(9355); + let rational: Vec = + (0..8).map(|_| HPoint::weighted(Vec3::new(rng.unit(), rng.unit(), rng.unit()) * 10.0, 0.5 + rng.unit())).collect(); + let (curve, def) = homogeneous(3, &[0.0, 0.0, 0.0, 0.0, 0.3, 0.3, 0.5, 0.9, 1.0, 1.0, 1.0, 1.0], &rational); + assert_pieces_trace(&curve.unwrap(), &def, 4); + // A long one: 5000 points, uneven knots, one piece per span. + let long = plain(&(0..5000).map(|i| (i as f64, (i as f64 / 7.0).sin())).collect::>()); + let knots: Vec = (0..5004).map(|i| ((i.clamp(3, 5000) - 3) as f64).powf(1.3)).collect(); + assert_eq!(cartesian(3, &knots, &long, None).0.pieces().unwrap().len(), 4997); + } + + #[test] + fn weighted_quadratics_trace_circles_exactly() { + let h = std::f64::consts::FRAC_1_SQRT_2; + let c = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0), (-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (1.0, 0.0)]; + let pts = plain(&c.map(|(x, y)| (10.0 * x, 10.0 * y))); + let knots = [0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0]; + let (curve, def) = cartesian(2, &knots, &pts, Some(&[1.0, h, 1.0, h, 1.0, h, 1.0, h, 1.0])); + for b in assert_pieces_trace(&curve, &def, 4) { + for t in [0.0, 0.3, 0.6, 1.0] { + assert!((point(&b, t).len() - 10.0).abs() < 1e-12); + } + } + } + + #[test] + fn an_unclamped_curve_is_cut_to_its_domain() { + // A closed (periodic) cubic as DXF writes one: unclamped even knots; it doesn't start or + // end on a control point, and ends where it starts. + let ctrl = plain(&[(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0), (0.0, 0.0), (20.0, 0.0), (20.0, 20.0)]); + let knots: Vec = (0..=10).map(f64::from).collect(); + let (curve, def) = cartesian(3, &knots, &ctrl, None); + let pieces = assert_pieces_trace(&curve, &def, 4); + let (first, last) = (point(&pieces[0], 0.0), point(&pieces[3], 1.0)); + assert!(first.dist(last) < 1e-9 && ctrl.iter().all(|q| q.dist(first) > 1.0), "{first:?} {last:?}"); + // Degree 9 (a G4 blend's) unclamped: eight insertions at each end. + let mut rng = Lcg(9); + let nine: Vec = (0..12).map(|_| Vec3::new(rng.unit(), rng.unit(), 0.0) * 10.0).collect(); + let knots: Vec = (0..22).map(f64::from).collect(); + let (curve, def) = cartesian(9, &knots, &nine, None); + assert_pieces_trace(&curve, &def, 3); + } + + #[test] + fn a_curve_that_isnt_one_is_not_made() { + let three = plain(&[(0.0, 0.0), (1.0, 1.0), (2.0, 0.0)]); + let clamped = vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + let made = |p: usize, knots: &[f64], pts: &[Vec3], w: Option<&[f64]>| NurbsCurve::from_homogeneous(p, knots.to_vec(), &weighted(pts, w)); + assert!(made(2, &clamped, &three, None).is_ok()); + for (p, knots) in [ + (2, &[0.0, 0.0, 0.0, 1.0, 1.0][..]), + (2, &[0.0, 0.0, 1.0, 0.5, 1.0, 1.0]), + (2, &[0.0, 0.0, 0.0, f64::NAN, 1.0, 1.0]), + (2, &[0.0; 6]), + (0, &clamped[..4]), + (3, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]), + (MAX_SPLINE_DEGREE + 1, &[0.0; 21]), + ] { + assert!(made(p, knots, &three, None).is_err(), "{p} {knots:?}"); + } + for w in [[1.0, 0.0, 1.0], [1.0, -1.0, 1.0], [1.0, f64::INFINITY, 1.0], [1.0, 1e-310, 1.0]] { + assert!(made(2, &clamped, &three, Some(&w)).is_err(), "{w:?}"); + } + assert!(made(2, &clamped, &plain(&[(f64::NAN, 0.0), (1.0, 1.0), (2.0, 0.0)]), None).is_err()); + assert!(made(2, &clamped, &plain(&[(2e12, 0.0), (1.0, 1.0), (2.0, 0.0)]), None).is_err()); + // A point times its weight past the largest number. + assert!(made(2, &clamped, &plain(&[(1e12, 0.0), (1.0, 1.0), (2.0, 0.0)]), Some(&[1e300, 1.0, 1.0])).is_err()); + // Weights all scaled alike are the same curve. + let small = made(2, &clamped, &three, Some(&[1e-200, 3e-200, 1e-200])).unwrap(); + let same = made(2, &clamped, &three, Some(&[1.0, 3.0, 1.0])).unwrap(); + let (a, b) = (&small.pieces().unwrap()[0], &same.pieces().unwrap()[0]); + assert!(point(a, 0.3).dist(point(b, 0.3)) < 1e-15); + // A line through three points breaks at an inner knot repeated twice (past degree 1), + // which is refused when the curve is made, not first when it is split. + let four = plain(&[(0.0, 0.0), (1.0, 1.0), (2.0, 0.0), (3.0, 1.0)]); + assert!(made(1, &[0.0, 0.0, 0.5, 1.0, 1.0], &four[..3], None).unwrap().pieces().is_ok()); + assert!(made(1, &[0.0, 0.0, 0.5, 0.5, 1.0, 1.0], &four, None).is_err()); + // A curve made has room to be clamped and split: knots just under the limit, unclamped. + let p = 3; + for len in [MAX_KNOTS - 2 * p, MAX_KNOTS - 2 * p + 1] { + let knots: Vec = (0..len).map(|i| i as f64).collect(); + let pts = plain(&vec![(0.0, 0.0); len - p - 1]); + match made(p, &knots, &pts, None) { + Ok(c) => assert!(len == MAX_KNOTS - 2 * p && c.pieces().is_ok(), "{len} knots"), + Err(e) => assert!(len > MAX_KNOTS - 2 * p, "{len} knots refused: {e}"), + } + } + } + + /// A knot inserted just short of the next, beside a weight of 10¹² and one of 1: `1 − α`, + /// α = (1.5 − 2⁻⁵²)/1.5, rounds 2⁻⁵²/1.5 to 2⁻⁵³, 25 % off, which moved the piece's end by + /// 8·10⁻⁴ mm. Both factors from knot differences, in intervals, keep it on the curve. + #[test] + fn a_knot_inserted_beside_a_heavy_weight_keeps_the_piece_on_the_curve() { + let ub = 1.5 - 2f64.powi(-52); + let pts = plain(&[(0.0, 0.0), (10.0, 20.0), (20.0, 0.0), (30.0, 10.0)]); + let (curve, def) = cartesian(2, &[0.0, 0.0, 0.0, ub, 1.5, 1.5, 1.5], &pts, Some(&[1.0, 1e12, 1.0, 1.0])); + let first = &curve.pieces().unwrap()[0]; + assert_eq!(first.span(), [0.0, ub]); + for t in [0.5, 0.9, 1.0] { + assert!(encloses(&def, first, t), "at {t}"); + let want = truth(&def, first.span(), Dd::of(t)).map(Dd::val); + let off = point(first, t).dist(Vec3::new(want[0], want[1], want[2])); + assert!(off < 1e-9, "{off:e} off the curve at {t}"); + } + } + + /// A random curve, valid or not: degree 1 to 9 (now and then 16), clamped or not, inner knots + /// repeated up to and past the degree, knots offset far from zero with tiny spans, weights up + /// to 10⁸ apart, sizes from a micrometre to 100 km. + fn random_curve(rng: &mut Lcg) -> (usize, Vec, Vec, f64) { + let p = if rng.unit() < 0.05 { 16 } else { 1 + (rng.unit() * 9.0) as usize }; + let n = p + 1 + (rng.unit() * 12.0) as usize; + let scale = 10f64.powf(-3.0 + rng.unit() * 11.0); + let spread = 10f64.powf(rng.unit() * 8.0); + let offset = if rng.unit() < 0.2 { 1e9 } else { 0.0 }; + let gap = if rng.unit() < 0.2 { 1e-6 } else { 1.0 }; + let mut knots = Vec::with_capacity(n + p + 1); + let mut u = offset; + let clamped = rng.unit() < 0.6; + for i in 0..n + p + 1 { + let inner = i > p && i < n; + let repeat = inner && rng.unit() < 0.25; + if !(clamped && (i <= p || i > n)) && !repeat && i > 0 { + u += gap * (0.05 + rng.unit()); + } + knots.push(u); + } + let ctrl = (0..n) + .map(|_| { + let w = spread.powf(rng.unit() - 0.5); + HPoint::weighted(Vec3::new(rng.unit() - 0.5, rng.unit() - 0.5, if rng.unit() < 0.3 { rng.unit() } else { 0.0 }) * scale, w) + }) + .collect(); + (p, knots, ctrl, scale) + } + + /// Thousands of random curves, valid and not: never a panic; a curve is either refused with a + /// reason or split into pieces that hold it, checked in double-double; a piece's fits either + /// come within the tolerance, the bound checked both ways in double-double, or are refused + /// with the reason. Enough of each happens for the test to mean something. + #[test] + fn random_curves_are_split_and_followed_with_proof_or_refused() { + let mut rng = Lcg(0x9355); + let (mut made, mut refused, mut certified, mut declined) = (0, 0, 0, 0); + for i in 0..3000 { + let (p, knots, ctrl, scale) = random_curve(&mut rng); + let (curve, def) = homogeneous(p, &knots, &ctrl); + let pieces = match curve.and_then(|c| c.pieces()) { + Ok(pieces) => pieces, + Err(e) => { + assert!(!e.to_string().is_empty()); + refused += 1; + continue; + } + }; + made += 1; + for piece in &pieces { + for t in [0.0, 0.5, 1.0] { + assert!(encloses(&def, piece, t), "degree {p}, span {:?}, knots {knots:?}, at {t}", piece.span()); + } + } + // A tolerance a millionth of the size, then one near rounding with little room; the + // bound checked both ways on a tenth of the curves (it is slow in double-double). + let Some(piece) = pieces.first() else { continue }; + for (tolerance, room) in [(1e-6 * scale, 4096), (1e-13 * scale, 64)] { + match follow(piece, tolerance, MIN_CONTROL_GAP, solidcore_record::MAX_BEZIER_DEGREE, room) { + Ok(fits) => { + assert_follows(&def, piece, &fits, tolerance, if i % 10 == 0 { 3 } else { 0 }); + certified += 1; + } + Err(e) => { + assert!(!e.to_string().is_empty()); + declined += 1; + } + } + } + } + assert!( + made > 1000 && refused > 100 && certified > 1000 && declined > 100, + "made {made}, refused {refused}, certified {certified}, declined {declined}" + ); + } + + /// A fit's point at `s` of its own parameter, in double-double. + fn fit_point(fit: &Fit, s: Dd) -> [Dd; 3] { + let one = Dd::of(1.0); + let (pts, w): (Vec, Vec

) = match fit { + Fit::Bezier(p) => (p.clone(), vec![one; p.len()]), + Fit::Conic { a, apex, b, rho } => (vec![*a, *apex, *b], vec![one, Dd::of(*rho).div(one.sub(Dd::of(*rho))), one]), + }; + let r = one.sub(s); + let mut h: Vec<[Dd; 4]> = pts.iter().zip(&w).map(|(p, &w)| [Dd::of(p.x).mul(w), Dd::of(p.y).mul(w), Dd::of(p.z).mul(w), w]).collect(); + while h.len() > 1 { + h = h.windows(2).map(|q| [0, 1, 2, 3].map(|c| q[0][c].mul(r).add(q[1][c].mul(s)))).collect(); + } + [0, 1, 2].map(|c| h[0][c].div(h[0][3])) + } + + fn dist(a: [Dd; 3], b: [Dd; 3]) -> f64 { + (0..3).fold(Dd::of(0.0), |acc, c| acc.add(a[c].sub(b[c]).mul(a[c].sub(b[c])))).val().sqrt() + } + + /// The distance from `x` to the curve `f` over `[0, 1]`: samples spread along the curve, not + /// its parameter (a rational curve can run most of its length in a sliver of it), and closer + /// together the nearer they come to `x` (a curve can loop tighter than the spacing), each one + /// closer than its neighbours refined by golden-section search in double-double. Never less + /// than the true distance (each is to a point on the curve), so a check against it can't pass + /// wrongly. + fn closest(f: &dyn Fn(Dd) -> [Dd; 3], x: [Dd; 3]) -> f64 { + let mut s: Vec
= (0..=64).map(|i| Dd::of(f64::from(i) / 64.0)).collect(); + let mut p: Vec<[Dd; 3]> = s.iter().map(|&t| f(t)).collect(); + let length: f64 = p.windows(2).map(|w| dist(w[0], w[1])).sum(); + for _ in 0..60 { + let (mut ns, mut np) = (vec![s[0]], vec![p[0]]); + for i in 1..s.len() { + let near = 0.5 * dist(p[i - 1], x).min(dist(p[i], x)); + if dist(p[i - 1], p[i]) > near.min(length / 256.0) && s[i].sub(s[i - 1]).val() > 1e-28 && ns.len() < 20_000 { + let mid = s[i - 1].add(s[i].sub(s[i - 1]).mul(Dd::of(0.5))); + ns.push(mid); + np.push(f(mid)); + } + ns.push(s[i]); + np.push(p[i]); + } + if ns.len() == s.len() { + break; + } + (s, p) = (ns, np); + } + let d: Vec = p.iter().map(|q| dist(*q, x)).collect(); + let last = d.len() - 1; + let mut found = d.iter().copied().fold(f64::INFINITY, f64::min); + let g = Dd::of(0.381_966_011_250_105_1); + for i in (0..=last).filter(|&i| d[i] <= d[i.saturating_sub(1)] && d[i] <= d[(i + 1).min(last)]) { + let (mut lo, mut hi) = (s[i.saturating_sub(1)], s[(i + 1).min(last)]); + for _ in 0..100 { + let (m1, m2) = (lo.add(hi.sub(lo).mul(g)), hi.sub(hi.sub(lo).mul(g))); + let (d1, d2) = (dist(f(m1), x), dist(f(m2), x)); + found = found.min(d1).min(d2); + if d1 < d2 { hi = m2 } else { lo = m1 } + } + } + found + } + + /// The fits end to end over the piece, each bound within the tolerance; and on `check` fits + /// (the first, last and middle ones), every point of each within its bound of the part of the + /// piece it follows, both ways, at seven fractions, in double-double. + fn assert_follows(def: &Def, piece: &CurvePiece, fits: &[Certified], tolerance: f64, check: usize) { + assert_eq!(fits.first().map(|c| c.along()[0]), Some(0.0)); + assert_eq!(fits.last().map(|c| c.along()[1]), Some(1.0)); + assert!(fits.windows(2).all(|w| w[0].along()[1] == w[1].along()[0])); + assert!(fits.iter().all(|c| c.bound() <= tolerance)); + let mut picks = vec![0, fits.len() / 2, fits.len() - 1]; + picks.dedup(); + for c in picks.into_iter().take(check).map(|i| &fits[i]) { + let [a, b] = c.along(); + let part = |s: Dd| truth(def, piece.span(), Dd::of(a).add(s.mul(Dd::of(b).sub(Dd::of(a))))); + let fit = |s: Dd| fit_point(c.value(), s); + // The rounding of the check's own square root. + let allowed = c.bound() * (1.0 + 1e-9); + for i in 0..=6 { + let s = Dd::of(f64::from(i) / 6.0); + let (to_fit, to_part) = (closest(&fit, part(s)), closest(&part, fit(s))); + assert!(to_fit <= allowed && to_part <= allowed, "{to_fit:e}, {to_part:e} past the bound {:e} of {:?}", c.bound(), c.value()); + } + } + } + + /// A piece that is a polynomial Bézier, up to how its parameter runs, is followed by itself: + /// a cubic, the same with weights 1, 2, 4, 8 (the same curve, traced unevenly), a line with + /// weights 1 and 7. Above the degree allowed it is followed by cubics. + #[test] + fn a_piece_that_is_a_polynomial_bezier_is_followed_by_itself() { + let pts = plain(&[(0.0, 0.0), (5.0, 30.0), (40.0, 30.0), (50.0, 0.0)]); + let cubic = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + for (knots, pts, w) in + [(&cubic[..], &pts[..], None), (&cubic, &pts, Some(&[1.0, 2.0, 4.0, 8.0][..])), (&[0.0, 0.0, 1.0, 1.0], &pts[..2], Some(&[1.0, 7.0]))] + { + let (curve, def) = cartesian(knots.len() - pts.len() - 1, knots, pts, w); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 1e-9, MIN_CONTROL_GAP, 9, 100).unwrap(); + assert!(matches!(&fits[..], [c] if *c.value() == Fit::Bezier(pts.to_vec()) && c.bound() < 1e-12), "{w:?}: {fits:?}"); + assert_follows(&def, piece, &fits, 1e-9, 1); + } + let five = plain(&[(0.0, 0.0), (5.0, 30.0), (20.0, -10.0), (30.0, 40.0), (40.0, 30.0), (50.0, 0.0)]); + let (curve, def) = cartesian(5, &[0.0; 6].into_iter().chain([1.0; 6]).collect::>(), &five, None); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 1e-6, MIN_CONTROL_GAP, 3, 1000).unwrap(); + assert!(fits.len() > 1 && fits.iter().all(|c| matches!(c.value(), Fit::Bezier(p) if p.len() == 4)), "{fits:?}"); + assert_follows(&def, piece, &fits, 1e-6, 3); + } + + /// Weighted quadratics (how CAD programs write arcs) are followed by conics on their circle; one + /// sharper than a sketch conic holds, or whose points lie on a line, is not a conic. + #[test] + fn weighted_quadratics_are_followed_by_conics() { + let h = std::f64::consts::FRAC_1_SQRT_2; + let pts = plain(&[(10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let knots = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]; + // Written with end weights other than 1, as some programs do. + for w in [[1.0, h, 1.0], [2.0, 3.0 * h, 4.5]] { + let (curve, def) = cartesian(2, &knots, &pts, Some(&w)); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 1e-9, MIN_CONTROL_GAP, 9, 100).unwrap(); + let [c] = &fits[..] else { panic!("{fits:?}") }; + assert!(matches!(c.value(), Fit::Conic { .. }) && c.bound() < 1e-12, "{w:?}: {c:?}"); + assert_follows(&def, piece, &fits, 1e-9, 1); + } + // Middle weight 2·10⁹: 1 − rho is below the sketch's least, so no conic, though its bound + // would pass. + let (curve, def) = cartesian(2, &knots, &pts, Some(&[1.0, 2e9, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 1e-3, MIN_CONTROL_GAP, 9, 1000).unwrap(); + assert!(fits.iter().all(|c| !matches!(c.value(), Fit::Conic { .. })), "{fits:?}"); + assert_follows(&def, piece, &fits, 1e-3, 3); + let (curve, def) = cartesian(2, &knots, &plain(&[(0.0, 0.0), (30.0, 0.0), (10.0, 0.0)]), Some(&[1.0, 3.0, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 1e-6, MIN_CONTROL_GAP, 9, 1000).unwrap(); + assert!(fits.iter().all(|c| !matches!(c.value(), Fit::Conic { .. })), "{fits:?}"); + assert_follows(&def, piece, &fits, 1e-6, 3); + } + + #[test] + fn a_weighted_cubic_is_followed_within_its_tolerance_with_proof() { + let pts = plain(&[(0.0, 0.0), (5.0, 30.0), (40.0, 30.0), (50.0, 0.0)]); + let knots = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + let (curve, def) = cartesian(3, &knots, &pts, Some(&[1.0, 3.0, 0.5, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + for tolerance in [1e-1, 1e-3, 1e-6] { + let fits = follow(piece, tolerance, MIN_CONTROL_GAP, 9, 10_000).unwrap(); + assert_follows(&def, piece, &fits, tolerance, 3); + // Each halving gains about 16x, so a tolerance a thousand times tighter takes about + // six times the cubics, not a thousand. + assert!(fits.len() < 200, "{tolerance}: {} cubics", fits.len()); + } + // Room for one curve is enough for a piece one curve follows; none is refused. + let (plain, _) = cartesian(3, &knots, &pts, None); + let piece = &plain.pieces().unwrap()[0]; + assert_eq!(follow(piece, 1e-9, MIN_CONTROL_GAP, 9, 1).unwrap().len(), 1); + assert!(matches!(follow(piece, 1e-9, MIN_CONTROL_GAP, 9, 0), Err(SplineError::TooLarge(_)))); + } + + #[test] + fn a_follow_past_its_limits_says_so() { + let pts = plain(&[(0.0, 0.0), (0.0, 1e5), (1e5, 3e4), (2e4, 0.0)]); + let (curve, def) = cartesian(3, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], &pts, Some(&[1.0, 1e4, 1e-4, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + // Too few curves allowed; a tolerance below rounding; no tolerance or gap at all. + assert!(matches!(follow(piece, 1e-3, MIN_CONTROL_GAP, 9, 8), Err(SplineError::TooLarge(_)))); + assert!(follow(piece, 1e-30, MIN_CONTROL_GAP, 9, usize::MAX).is_err()); + for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(follow(piece, bad, MIN_CONTROL_GAP, 9, 100).is_err(), "{bad}"); + assert!(follow(piece, 1e-3, bad, 9, 100).is_err(), "{bad}"); + } + // Given room, the same 100 m curve with weights 10⁸ apart does come within 0.001 mm, proven. + let fits = follow(piece, 1e-3, MIN_CONTROL_GAP, 9, 100_000).unwrap(); + assert_follows(&def, piece, &fits, 1e-3, 3); + } + + /// A curve about 10⁻²⁰⁰ across: its bounds stay above zero and hold, where lengths taken as the + /// root of the squares, which underflow there, made every bound 0. + #[test] + fn a_tiny_curve_is_bounded_and_held() { + let s = 2f64.powi(-664); + let pts: Vec = plain(&[(0.0, 0.0), (5.0, 30.0), (40.0, 30.0), (50.0, 0.0)]).into_iter().map(|p| p * s).collect(); + let (curve, def) = cartesian(3, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], &pts, Some(&[1.0, 3.0, 0.5, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + assert!(follow(piece, 1e-250, MIN_CONTROL_GAP, 9, 1000).is_err()); + let fits = follow(piece, 1e-3 * s, MIN_CONTROL_GAP, 9, 10_000).unwrap(); + assert!(fits.iter().all(|c| c.bound() > 0.0)); + assert_follows(&def, piece, &fits, 1e-3 * s, 3); + } + + /// A piece over two adjacent numbers of the parameter (near 10⁹): its fits, tied to fractions + /// of the piece rather than to its parameter, still follow it. + #[test] + fn a_piece_with_no_room_in_its_parameter_is_followed() { + let (a, b) = (1e9, f64::from_bits(1e9f64.to_bits() + 1)); + let pts = plain(&[(0.0, 0.0), (5.0, 30.0), (40.0, 30.0), (50.0, 0.0)]); + let (curve, def) = cartesian(3, &[a, a, a, a, b, b, b, b], &pts, Some(&[1.0, 3.0, 0.5, 1.0])); + let piece = &curve.pieces().unwrap()[0]; + assert_eq!(piece.span(), [a, b]); + let fits = follow(piece, 1e-3, MIN_CONTROL_GAP, 9, 1000).unwrap(); + assert_follows(&def, piece, &fits, 1e-3, 3); + } + + /// A cubic whose handle at an end has no length (`C4,31 8,20 8,20` in an SVG path, both ends, + /// or a rational one) is followed by cubics with no repeated point, within the tolerance, + /// proven; so is each handle shortened towards none, and one longer than the sketch's gap but + /// shorter than a larger gap asked for (a drawing scaled down to the sketch). At a stalled end + /// the cubic leaves the way the curve does. + #[test] + fn an_end_with_no_direction_is_followed_by_curves_that_have_one() { + let cubic = [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]; + let svg = plain(&[(5.0, -35.0), (4.0, -31.0), (8.0, -20.0), (8.0, -20.0)]); + let both = plain(&[(0.0, 0.0), (0.0, 0.0), (30.0, 10.0), (30.0, 10.0)]); + let start = plain(&[(0.0, 0.0), (0.0, 0.0), (10.0, 20.0), (30.0, 0.0)]); + for (pts, w, tolerance) in [(&svg, None, 5e-4), (&svg, None, 1e-6), (&both, None, 5e-4), (&start, Some(&[1.0, 2.0, 0.5, 1.0][..]), 5e-4)] { + let (curve, def) = cartesian(3, &cubic, pts, w); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, tolerance, MIN_CONTROL_GAP, 9, 4096).unwrap(); + assert!(fits.iter().all(|c| matches!(c.value(), Fit::Bezier(p) if !repeats(p, MIN_CONTROL_GAP))), "{pts:?}: {fits:?}"); + assert!(fits.len() < 100, "{pts:?} at {tolerance}: {} cubics", fits.len()); + assert_follows(&def, piece, &fits, tolerance, 3); + let leaves = |f: &Certified, end: bool| match f.value() { + Fit::Bezier(p) if end => p[2] - p[3], + Fit::Bezier(p) => p[1] - p[0], + Fit::Conic { .. } => Vec3::ZERO, + }; + for (stalled, end, along) in [(pts[0] == pts[1], false, pts[2] - pts[0]), (pts[3] == pts[2], true, pts[1] - pts[3])] { + let fit = if end { fits.last() } else { fits.first() }; + let way = fit.map_or(Vec3::ZERO, |f| leaves(f, end)); + // Parallel up to the rounding of the halved parts' points near the end (their + // offsets from it are 10⁻⁷ of their size there). + assert!(!stalled || (way.cross(along).len() <= 1e-6 * way.len() * along.len() && way.dot(along) > 0.0), "{pts:?}: {way:?}"); + } + } + for (gap, keep) in [(1e-3, MIN_CONTROL_GAP), (1e-8, MIN_CONTROL_GAP), (1e-10, MIN_CONTROL_GAP), (3e-8, 1e-7)] { + let pts = plain(&[(5.0, -35.0), (4.0, -31.0), (8.0, -20.0 - gap), (8.0, -20.0)]); + let (curve, def) = cartesian(3, &cubic, &pts, None); + let piece = &curve.pieces().unwrap()[0]; + let fits = follow(piece, 5e-4, keep, 9, 4096).unwrap(); + let apart = |p: &[Vec3]| p.windows(2).all(|w| w[0].dist(w[1]) >= keep); + assert!(fits.iter().all(|c| matches!(c.value(), Fit::Bezier(p) if apart(p))), "{gap}: {fits:?}"); + assert_follows(&def, piece, &fits, 5e-4, 3); + } + } +} diff --git a/crates/geom/src/bspline/interval.rs b/crates/geom/src/bspline/interval.rs new file mode 100644 index 00000000000..b0895d1bbcd --- /dev/null +++ b/crates/geom/src/bspline/interval.rs @@ -0,0 +1,127 @@ +//! Intervals that hold the exact result of every operation on what they hold: each bound is the +//! nearest number to its exact value, moved one step outward, and a nearest number is never more +//! than half a step from the exact one (normal, subnormal or underflowed to zero alike). This is +//! what the bounds of [`super::curve`] are computed in, so they are proven, not estimated. + +use super::{Blend, HPoint}; + +/// The numbers from `lo` to `hi`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Interval { + pub(crate) lo: f64, + pub(crate) hi: f64, +} + +impl Interval { + pub(crate) const ZERO: Interval = Interval { lo: 0.0, hi: 0.0 }; + const ENTIRE: Interval = Interval { lo: f64::NEG_INFINITY, hi: f64::INFINITY }; + + /// Exactly `x`. + pub(crate) const fn point(x: f64) -> Interval { + Interval { lo: x, hi: x } + } + /// The rounded `lo` and `hi` moved one step outward. + fn out(lo: f64, hi: f64) -> Interval { + if lo.is_nan() || hi.is_nan() { Interval::ENTIRE } else { Interval { lo: lo.next_down(), hi: hi.next_up() } } + } + /// The four rounded products or quotients of the bounds, moved outward. + fn hull(c: [f64; 4]) -> Interval { + if c.iter().any(|x| x.is_nan()) { + return Interval::ENTIRE; + } + Interval::out(c.iter().copied().fold(f64::INFINITY, f64::min), c.iter().copied().fold(f64::NEG_INFINITY, f64::max)) + } + pub(crate) fn add(self, o: Interval) -> Interval { + Interval::out(self.lo + o.lo, self.hi + o.hi) + } + pub(crate) fn sub(self, o: Interval) -> Interval { + Interval::out(self.lo - o.hi, self.hi - o.lo) + } + pub(crate) fn mul(self, o: Interval) -> Interval { + Interval::hull([self.lo * o.lo, self.lo * o.hi, self.hi * o.lo, self.hi * o.hi]) + } + /// Anything, when `o` holds zero. + pub(crate) fn div(self, o: Interval) -> Interval { + if !(o.lo > 0.0 || o.hi < 0.0) { + return Interval::ENTIRE; + } + Interval::hull([self.lo / o.lo, self.lo / o.hi, self.hi / o.lo, self.hi / o.hi]) + } + pub(crate) fn is_finite(self) -> bool { + self.lo.is_finite() && self.hi.is_finite() + } + /// The largest absolute value held. + pub(crate) fn mag(self) -> f64 { + self.lo.abs().max(self.hi.abs()) + } + /// A number held: the midpoint, correctly rounded, so between the bounds even in the + /// subnormal range. + pub(crate) fn mid(self) -> f64 { + f64::midpoint(self.lo, self.hi) + } +} + +/// A homogeneous point each of whose coordinates is held by an interval. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct HInterval { + pub(crate) x: Interval, + pub(crate) y: Interval, + pub(crate) z: Interval, + pub(crate) w: Interval, +} + +impl HInterval { + /// Exactly `h`. + pub(crate) fn point(h: HPoint) -> HInterval { + HInterval { x: Interval::point(h.x), y: Interval::point(h.y), z: Interval::point(h.z), w: Interval::point(h.w) } + } + /// Finite, with a weight that is surely positive. + pub(crate) fn is_sound(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite() && self.w.lo > 0.0 + } + /// A point held by it. + pub(crate) fn mid(self) -> HPoint { + HPoint { x: self.x.mid(), y: self.y.mid(), z: self.z.mid(), w: self.w.mid() } + } +} + +impl Blend for HInterval { + type Factor = Interval; + const ZERO: HInterval = HInterval { x: Interval::ZERO, y: Interval::ZERO, z: Interval::ZERO, w: Interval::ZERO }; + fn factors(lo: f64, u: f64, hi: f64) -> (Interval, Interval) { + let (lo, u, hi) = (Interval::point(lo), Interval::point(u), Interval::point(hi)); + let den = hi.sub(lo); + (u.sub(lo).div(den), hi.sub(u).div(den)) + } + fn blend(self, a: Interval, other: HInterval, b: Interval) -> HInterval { + let f = |p: Interval, q: Interval| p.mul(a).add(q.mul(b)); + HInterval { x: f(self.x, other.x), y: f(self.y, other.y), z: f(self.z, other.z), w: f(self.w, other.w) } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Each operation holds its exact result (checked with a fused multiply-add, which rounds + /// once, so its sign is the exact one's), including where it rounds below the normal range or + /// to zero, and where `1 − α` loses most of α's digits; and a midpoint is held even there. + #[test] + fn every_operation_holds_its_exact_result() { + let holds = |x: Interval, k: f64, target: f64| x.lo.mul_add(k, -target) <= 0.0 && x.hi.mul_add(k, -target) >= 0.0; + let third = Interval::point(1.0).div(Interval::point(3.0)); + assert!(holds(third, 3.0, 1.0), "{third:?}"); + let tiny = Interval::point(f64::from_bits(1)).mul(Interval::point(0.5)); + assert!(tiny.lo < 0.0 && tiny.hi > 0.0, "{tiny:?}"); + // α = (1.5 − 2⁻⁵²)/1.5; the exact 1 − α is 2⁻⁵²/1.5. + let rest = Interval::point(1.0).sub(Interval::point(1.5 - 2f64.powi(-52)).div(Interval::point(1.5))); + assert!(holds(rest, 1.5, 2f64.powi(-52)), "{rest:?}"); + assert_eq!(Interval::point(1.0).div(Interval::ZERO), Interval::ENTIRE); + assert!(!Interval::point(f64::MAX).add(Interval::point(f64::MAX)).is_finite()); + assert!(!Interval::point(0.0).mul(Interval::point(f64::INFINITY)).is_finite()); + // `lo/2 + hi/2` rounds the smallest subnormal to 0, outside [η, η]. + for x in [f64::from_bits(1), f64::from_bits(3)] { + assert_eq!(Interval::point(x).mid(), x); + } + } +} diff --git a/crates/geom/src/hlr/curve.rs b/crates/geom/src/hlr/curve.rs index 1b1b74d51aa..046d5a7dd96 100644 --- a/crates/geom/src/hlr/curve.rs +++ b/crates/geom/src/hlr/curve.rs @@ -214,7 +214,7 @@ impl C3 { fn spline(knots: &[f64], points: Vec<[f64; 4]>) -> Result { let degree = knots.len().checked_sub(points.len() + 1).ok_or(HlrError::Unsupported("spline knot count"))?; - if degree == 0 || degree > 16 || points.is_empty() { + if degree == 0 || degree > crate::bspline::MAX_SPLINE_DEGREE || points.is_empty() { return Err(HlrError::Unsupported("spline degree")); } let pieces = bezier_pieces(degree, knots, &points); @@ -272,34 +272,13 @@ fn part(knots: &[f64], points: Vec<[f64; 4]>, t: [f64; 2]) -> Result Vec<([f64; 2], Vec<[f64; 4]>)> { - use crate::bspline::{HPoint, clamp_row, insert_knot}; + use crate::bspline::{HPoint, NurbsCurve}; let row: Vec = points.iter().map(|h| HPoint { x: h[0], y: h[1], z: h[2], w: h[3] }).collect(); - let Ok((mut k, mut c)) = clamp_row(p, knots, &row) else { return Vec::new() }; - let (Some(&lo), Some(&hi)) = (k.get(p), k.get(c.len())) else { return Vec::new() }; - let mut inner: Vec = k.iter().copied().filter(|x| *x > lo && *x < hi).collect(); - inner.dedup(); - for u in &inner { - let mut guard = 0; - while k.iter().filter(|x| *x == u).count() < p { - guard += 1; - let Ok((nk, nc)) = insert_knot(p, &k, &c, *u) else { return Vec::new() }; - if guard > p + 1 { - return Vec::new(); - } - (k, c) = (nk, nc); - } - } - let breaks: Vec = std::iter::once(lo).chain(inner).chain(std::iter::once(hi)).collect(); - let mut out = Vec::with_capacity(breaks.len()); - for (j, w) in breaks.windows(2).enumerate() { - let (Some(&s0), Some(&s1)) = (w.first(), w.get(1)) else { return Vec::new() }; - let Some(ctrl) = c.get(j * p..=j * p + p) else { return Vec::new() }; - out.push(([s0, s1], ctrl.iter().map(|h| [h.x, h.y, h.z, h.w]).collect())); - } - out + let Ok(pieces) = NurbsCurve::from_homogeneous(p, knots.to_vec(), &row).and_then(|c| c.pieces()) else { return Vec::new() }; + pieces.iter().map(|b| (b.span(), b.ctrl().map(|h| [h.x, h.y, h.z, h.w]).collect())).collect() } /// The Bernstein coefficients of the product of two polynomials given by theirs. diff --git a/crates/io/src/dxf.rs b/crates/io/src/dxf.rs index d046035296a..df4c1582682 100644 --- a/crates/io/src/dxf.rs +++ b/crates/io/src/dxf.rs @@ -8,7 +8,8 @@ use solidcraft_geom::prelude::*; use std::collections::HashMap; -use solidcore_record::{MAX_BEZIER_DEGREE, Vec2}; +use solidcore_record::{MAX_BEZIER_DEGREE, Vec2, Vec3}; +use solidcraft_geom::bspline::{HPoint, MAX_SPLINE_DEGREE, NurbsCurve}; use crate::sketch2d::{Geom2, MAX_DRAWING_BYTES, MAX_ENTITIES, bulge_arc}; use crate::{IoError, Result}; @@ -170,7 +171,7 @@ fn convert(ents: &[Ent], k: f64, blocks: &HashMap)>, dep let off = Vec2::from_angle(rot) * (dc * c as f64) + Vec2::from_angle(rot).perp() * (dr * r as f64); let t = Affine::insert(ins + off, *base, sx, sy, rot); for g in &inner { - t.apply(g, out); + t.apply(g, out)?; } } } @@ -273,14 +274,21 @@ fn convert(ents: &[Ent], k: f64, blocks: &HashMap)>, dep } } "SPLINE" => { - // The degrees a sketch spline takes (a G4 blend's Bézier is degree 9). - let degree = e.get(71).unwrap_or(3.0).clamp(1.0, MAX_BEZIER_DEGREE as f64) as u8; let (fx, fy) = (e.all(11), e.all(21)); let (cx, cy) = (e.all(10), e.all(20)); if fx.len() >= 2 && fx.len() == fy.len() { out.push(Geom2::Spline { pts: fx.iter().zip(&fy).map(|(x, y)| pt(*x, *y)).collect(), control: false, degree: 3 }); } else if cx.len() >= 2 && cx.len() == cy.len() { - out.push(Geom2::Spline { pts: cx.iter().zip(&cy).map(|(x, y)| pt(*x, *y)).collect(), control: true, degree }); + let ctrl: Vec = cx.iter().zip(&cy).map(|(x, y)| pt(*x, *y)).collect(); + let (knots, weights) = (e.all(40), e.all(41)); + if knots.is_empty() && weights.is_empty() { + // The sketch's spline over the points, at the degrees a sketch spline takes + // (a G4 blend's Bézier is degree 9). + let degree = e.get(71).unwrap_or(3.0).clamp(1.0, MAX_BEZIER_DEGREE as f64) as u8; + out.push(Geom2::Spline { pts: ctrl, control: true, degree }); + } else { + out.push(spline(e.get(71).unwrap_or(3.0), &ctrl, knots, &weights)?); + } } } "TEXT" | "MTEXT" => { @@ -325,7 +333,7 @@ impl Affine { let (a, b) = (self.v(Vec2::new(1.0, 0.0)), self.v(Vec2::new(0.0, 1.0))); ((a.len() - b.len()).abs() <= 1e-9 * a.len().max(b.len()) && a.dot(b).abs() <= 1e-9 * a.len() * b.len()).then_some(a.len()) } - fn apply(&self, g: &Geom2, out: &mut Vec) { + fn apply(&self, g: &Geom2, out: &mut Vec) -> Result<()> { let flip = self.det() < 0.0; let sampled = |f: &dyn Fn(f64) -> Vec2, closed: bool| { let n = 32; @@ -374,13 +382,46 @@ impl Affine { Geom2::Spline { pts: pts.iter().map(|p| self.p(*p)).collect(), control: *control, degree: *degree } } Geom2::Conic { a, apex, b, rho } => Geom2::Conic { a: self.p(*a), apex: self.p(*apex), b: self.p(*b), rho: *rho }, + // An affine map moves a B-spline, rational or not, by its control points. + Geom2::Nurbs(curve) => { + let ctrl: Vec = curve + .ctrl() + .map(|h| { + let q = self.p(Vec2::new(h.x / h.w, h.y / h.w)); + HPoint::weighted(Vec3::new(q.x, q.y, 0.0), h.w) + }) + .collect(); + let placed = NurbsCurve::from_homogeneous(curve.degree(), curve.knots().to_vec(), &ctrl); + Geom2::Nurbs(placed.map_err(|e| IoError::Invalid(format!("a SPLINE in a block can't be placed: {e}")))?) + } Geom2::Text { text, at, height, angle } => { let dir = self.v(Vec2::from_angle(*angle)); let up = self.v(Vec2::from_angle(*angle).perp()); Geom2::Text { text: text.clone(), at: self.p(*at), height: height * up.len(), angle: dir.angle() } } }); + Ok(()) + } +} + +/// A SPLINE with its own knots (40) and, when rational, a weight per control point (41), its +/// points in millimetres: the curve they describe, checked ([`NurbsCurve`]). Refused, with the +/// reason, when they don't describe one; weights need knots. +fn spline(degree: f64, ctrl: &[Vec2], knots: Vec, weights: &[f64]) -> Result { + let refuse = |why: String| IoError::Invalid(format!("a SPLINE can't be read: {why}")); + let p = Some(degree) + .filter(|d| d.fract() == 0.0 && (1.0..=MAX_SPLINE_DEGREE as f64).contains(d)) + .map(|d| d as usize) + .ok_or_else(|| refuse(format!("its degree {degree} is not one of 1 to {MAX_SPLINE_DEGREE}")))?; + if knots.is_empty() { + return Err(refuse("it has weights but no knots".into())); } + if !weights.is_empty() && weights.len() != ctrl.len() { + return Err(refuse(format!("{} weights for {} control points", weights.len(), ctrl.len()))); + } + let h: Vec = + ctrl.iter().enumerate().map(|(i, q)| HPoint::weighted(Vec3::new(q.x, q.y, 0.0), weights.get(i).copied().unwrap_or(1.0))).collect(); + NurbsCurve::from_homogeneous(p, knots, &h).map(Geom2::Nurbs).map_err(|e| refuse(e.to_string())) } fn polyline(verts: &[(Vec2, f64)], closed: bool, out: &mut Vec) { @@ -453,7 +494,7 @@ pub fn write_dxf(geom: &[Geom2]) -> String { w(1, &text.replace('\n', " ")); } // Free-form curves are written by the caller as polylines (lines). - Geom2::Ellipse { .. } | Geom2::Spline { .. } | Geom2::Conic { .. } => {} + Geom2::Ellipse { .. } | Geom2::Spline { .. } | Geom2::Nurbs(_) | Geom2::Conic { .. } => {} } } w(0, "ENDSEC"); @@ -576,6 +617,70 @@ mod tests { } } + /// A SPLINE keeps its own knots (40) and weights (41) (solidcraft#9355): the curve as written + /// (its points in millimetres), whatever its knots, placed by a block like any other entity. + /// Without knots or weights it is the sketch's spline over its points, as before. Knots or + /// weights that don't describe a curve refuse the drawing, saying why. + #[test] + fn a_spline_keeps_its_own_knots_and_weights() { + let entities = |body: &str| { + read_dxf(&format!("0\nSECTION\n2\nHEADER\n9\n$INSUNITS\n70\n1\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{body}0\nENDSEC\n0\nEOF\n")) + }; + let spline = |degree: u32, points: &[(f64, f64)], knots: &[f64], weights: &[f64]| { + let mut body = format!("0\nSPLINE\n71\n{degree}\n"); + body.extend(knots.iter().map(|k| format!("40\n{k}\n"))); + body.extend(weights.iter().map(|w| format!("41\n{w}\n"))); + body.extend(points.iter().map(|(x, y)| format!("10\n{x}\n20\n{y}\n"))); + body + }; + let five = [(0.0, 0.0), (1.0, 2.0), (3.0, 2.0), (4.0, 0.0), (6.0, 1.0)]; + let inches: Vec = five.iter().map(|(x, y)| Vec2::new(x * 25.4, y * 25.4)).collect(); + let ctrl = |c: &NurbsCurve| c.ctrl().map(|h| Vec2::new(h.x / h.w, h.y / h.w)).collect::>(); + // Clamped and even, uneven, not clamped, degree 12, unweighted or weighted alike: the knots + // and points as written. + let twelve: Vec<(f64, f64)> = (0..14).map(|i| (f64::from(i), f64::from(i % 3))).collect(); + for (degree, points, knots, weights) in [ + (3, &five[..], vec![0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0], &[][..]), + (3, &five, vec![0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0], &[2.0; 5]), + (3, &five, vec![0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 1.0, 1.0, 1.0], &[]), + (3, &five, (0..9).map(f64::from).collect(), &[]), + (12, &twelve, [0.0; 13].into_iter().chain([0.5]).chain([1.0; 13]).collect(), &[]), + ] { + let back = entities(&spline(degree, points, &knots, weights)).unwrap(); + let [Geom2::Nurbs(c)] = &back[..] else { panic!("{back:?}") }; + assert!(c.knots() == knots && c.degree() == degree as usize, "{c:?}"); + if degree == 3 { + assert!(ctrl(c).iter().zip(&inches).all(|(a, b)| a.dist(*b) < 1e-12), "{:?}", ctrl(c)); + } + } + // A quarter circle as a weighted quadratic: its weights. + let w = std::f64::consts::FRAC_1_SQRT_2; + let back = entities(&spline(2, &[(1.0, 0.0), (1.0, 1.0), (0.0, 1.0)], &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &[1.0, w, 1.0])).unwrap(); + assert!(matches!(&back[..], [Geom2::Nurbs(c)] if c.ctrl().map(|h| h.w).collect::>() == [1.0, w, 1.0]), "{back:?}"); + // In a block placed at (10, 0) mm and turned a quarter: its control points move with it. + let block = format!( + "0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nB\n10\n0\n20\n0\n{}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n0\nINSERT\n2\nB\n10\n10\n20\n0\n50\n90\n0\nENDSEC\n0\nEOF\n", + spline(3, &five, &[0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 1.0, 1.0, 1.0], &[]) + ); + let back = read_dxf(&block).unwrap(); + let [Geom2::Nurbs(c)] = &back[..] else { panic!("{back:?}") }; + let want: Vec = five.iter().map(|(x, y)| Vec2::new(10.0 - y, *x)).collect(); + assert!(ctrl(c).iter().zip(&want).all(|(a, b)| a.dist(*b) < 1e-12), "{:?}", ctrl(c)); + // Knots one short or decreasing, weights one short or not positive, weights without knots, + // a degree past 16: refused. + for (degree, knots, weights) in [ + (3, &[0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 1.0, 1.0][..], &[][..]), + (3, &[0.0, 0.0, 0.0, 0.0, 0.7, 0.2, 1.0, 1.0, 1.0], &[]), + (3, &[0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 1.0, 1.0, 1.0], &[1.0; 4]), + (3, &[0.0, 0.0, 0.0, 0.0, 0.2, 1.0, 1.0, 1.0, 1.0], &[1.0, 1.0, -1.0, 1.0, 1.0]), + (3, &[], &[1.0, 2.0, 1.0, 1.0, 1.0]), + (17, &[], &[1.0; 5]), + ] { + let err = entities(&spline(degree, &five, knots, weights)).unwrap_err().to_string(); + assert!(err.contains("a SPLINE can't be read"), "{knots:?} {weights:?}: {err}"); + } + } + #[test] fn round_trip_and_polyline_bulges() { let g = vec![ diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs index 56d12dbcd48..61d542d5190 100644 --- a/crates/io/src/dxf_out.rs +++ b/crates/io/src/dxf_out.rs @@ -872,9 +872,11 @@ mod tests { let Geom2::Conic { a, apex, b, rho } = &back[4] else { panic!("{:?}", back[4]) }; assert!(a.dist(Vec2::new(75.0, 40.0)) < 1e-9 && apex.dist(Vec2::new(75.0, 52.0)) < 1e-9 && b.dist(Vec2::new(50.0, 52.0)) < 1e-9); assert!((rho - FRAC_1_SQRT_2 / (1.0 + FRAC_1_SQRT_2)).abs() < 1e-12, "{rho}"); - // The cubic: degree and control points. - let Geom2::Spline { pts, control: true, degree: 3 } = &back[5] else { panic!("{:?}", back[5]) }; - assert!(pts.iter().zip(&cubic).all(|(a, b)| a.dist(*b) < 1e-9) && pts.len() == 4); + // The cubic: degree, knots and control points, as the B-spline written. + let points = |c: &solidcraft_geom::bspline::NurbsCurve| c.ctrl().map(|h| Vec2::new(h.x / h.w, h.y / h.w)).collect::>(); + let Geom2::Nurbs(c) = &back[5] else { panic!("{:?}", back[5]) }; + assert_eq!((c.degree(), c.knots()), (3, &[0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0][..])); + assert!(points(c).iter().zip(&cubic).all(|(a, b)| a.dist(*b) < 1e-9) && points(c).len() == 4); // A degree-9 Bézier (a G4 blend) comes back at its own degree over all ten points. let mut q = [Vec2::ZERO; solidcore_record::MAX_BEZIER_CTRL]; for (i, s) in q.iter_mut().enumerate() { @@ -883,7 +885,7 @@ mod tests { let nine = write_dxf_drawing(&[], &[DxfEntity { layer: "0".into(), shape: seg_shape(&Seg2::Bezier { n: 9, p: q }) }]).unwrap(); let back_nine = read_dxf(&nine).unwrap(); assert!( - matches!(&back_nine[..], [Geom2::Spline { pts, control: true, degree: 9 }] if pts.len() == 10 && pts.iter().zip(&q).all(|(a, b)| a.dist(*b) < 1e-9)), + matches!(&back_nine[..], [Geom2::Nurbs(c)] if c.degree() == 9 && points(c).len() == 10 && points(c).iter().zip(&q).all(|(a, b)| a.dist(*b) < 1e-9)), "{back_nine:?}" ); diff --git a/crates/io/src/sketch2d.rs b/crates/io/src/sketch2d.rs index 9792e6f3688..d3b6ecb5457 100644 --- a/crates/io/src/sketch2d.rs +++ b/crates/io/src/sketch2d.rs @@ -2,6 +2,7 @@ //! plain 2D geometry in millimetres; the engine turns it into sketch curves. use solidcore_record::Vec2; +use solidcraft_geom::bspline::NurbsCurve; use solidcraft_geom::prelude::*; /// One imported 2D entity (millimetres, y up). @@ -28,6 +29,10 @@ pub enum Geom2 { control: bool, degree: u8, }, + /// A B-spline with its own knots and, when rational, weights, as a file gives it (z = 0). The + /// importer brings it in as the curves a sketch holds: one sketch spline when it is the + /// sketch's own, else its exact pieces. + Nurbs(NurbsCurve), /// Quadratic Bézier / conic. Conic { a: Vec2, diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 9e474e7c03e..8893f1d55cf 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -57,6 +57,8 @@ fn geom_is_finite(g: &Geom2) -> bool { Geom2::Arc { c, a, b } => c.is_finite() && a.is_finite() && b.is_finite(), Geom2::Ellipse { c, major, minor } => c.is_finite() && major.is_finite() && minor.is_finite(), Geom2::Spline { pts, .. } => pts.iter().all(|p| p.is_finite()), + // Finite by construction. + Geom2::Nurbs(_) => true, Geom2::Conic { a, apex, b, rho } => a.is_finite() && apex.is_finite() && b.is_finite() && rho.is_finite(), Geom2::Text { at, height, angle, .. } => at.is_finite() && height.is_finite() && angle.is_finite(), } diff --git a/crates/sketch/src/curves.rs b/crates/sketch/src/curves.rs index 0ef36d7f560..c38510e88db 100644 --- a/crates/sketch/src/curves.rs +++ b/crates/sketch/src/curves.rs @@ -28,7 +28,7 @@ pub fn ellipse_polyline(c: Vec2, m: Vec2, r: f64) -> Vec { /// Rational quadratic Bézier from `a` to `b` with control `apex` and shape `rho` in (0, 1) /// (0.5 = parabola, below = ellipse, above = hyperbola). pub fn conic_point(a: Vec2, apex: Vec2, b: Vec2, rho: f64, t: f64) -> Vec2 { - let w = rho / (1.0 - rho).max(1e-9); + let w = rho / (1.0 - rho).max(solidcraft_geom::bspline::MIN_CONIC_RHO_GAP); let (b0, b1, b2) = ((1.0 - t) * (1.0 - t), 2.0 * t * (1.0 - t) * w, t * t); let den = b0 + b1 + b2; (a * b0 + apex * b1 + b * b2) / den.max(1e-12) diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 18a238df14f..292152a232a 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1539,7 +1539,12 @@ impl Sketch { .collect(), ) } - CurveKind::Conic { a, b, apex, rho } => Some(vec![Seg2::Conic { a: pt(a)?, apex: pt(apex)?, b: pt(b)?, w: rho / (1.0 - rho).max(1e-9) }]), + CurveKind::Conic { a, b, apex, rho } => Some(vec![Seg2::Conic { + a: pt(a)?, + apex: pt(apex)?, + b: pt(b)?, + w: rho / (1.0 - rho).max(solidcraft_geom::bspline::MIN_CONIC_RHO_GAP), + }]), CurveKind::Spline { pts, control: false, periodic, .. } => { let p: Vec = pts.iter().map(pt).collect::>()?; Some( diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index a6e2de8c2c4..4ae34c57bba 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -328,7 +328,12 @@ impl State<'_> { } } Some(CurveKind::Conic { a, b, apex, rho }) => { - vec![Seg2::Conic { a: self.p(*a), b: self.p(*b), apex: self.p(*apex), w: rho / (1.0 - rho).max(1e-9) }] + vec![Seg2::Conic { + a: self.p(*a), + b: self.p(*b), + apex: self.p(*apex), + w: rho / (1.0 - rho).max(solidcraft_geom::bspline::MIN_CONIC_RHO_GAP), + }] } _ => Vec::new(), };