From c49d45c8266308eb92273a40c8da8599a7940f0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:01:23 -0800 Subject: [PATCH 1/4] Path Precision Tools: Common Tangents measures each line near where it touches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each tangent measured every segment of both paths to find where it touches them, so two paths of thousands of segments with thousands of tangents took segments × tangents work. Each line now starts from the segment found for the nearest sampled direction and walks outward only as far as the stretch that lies along it. On two 2,000-sided polygons with 4,000 tangents, the segment measurements drop from about 33.5 million to 1.6 million. A turned or scaled ellipse is measured exactly however thin it is. A map is refused only when its determinant is within the rounding of its entries; before, an ellipse more than about 1e12 times longer than wide was refused as having no area. --- .../pathops/src/addons/pathtools/tangents.rs | 132 +++++++++++++++--- 1 file changed, 113 insertions(+), 19 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 2059932aa2..c01c80957e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -77,7 +77,9 @@ impl Outline { pub fn ellipse(unit: Affine) -> Result { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); - if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may + // belong to a map with no area. Any thinner ellipse is measured exactly. + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) @@ -270,11 +272,13 @@ impl Outline { } } - /// The points of the outline on the line `p · n = h`, its support value: the point where - /// `p · n` is largest, and the ends of any straight side along the line. Another point counts - /// when it lies within `tol` of the line plus `slope` times its distance from that largest - /// point, where `slope` is how far off the normal's angle may be. - fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + /// The points of the outline on the line `p · n = h`, its support value, which is reached on + /// segment `at`: the point where `p · n` is largest, and the ends of any straight side along + /// the line. Another point counts when it lies within `tol` of the line plus `slope` times its + /// distance from that largest point, where `slope` is how far off the normal's angle may be. + /// On a convex outline the points that count form one run around the largest one, so the + /// segments are measured from `at` outward both ways until a segment's end does not count. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64, at: usize) -> Vec { match self { Outline::Ellipse { center, m: [a, b, c, d] } => { let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); @@ -282,9 +286,25 @@ impl Outline { vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] } Outline::Convex { segments, .. } => { + let len = segments.len(); let mut all = vec![]; - for s in segments { - each_extreme(s, n, |p, v| all.push((p, v))); + let Some(first) = segments.get(at % len.max(1)) else { return vec![] }; + each_extreme(first, n, |p, v| all.push((p, v))); + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + let counts = |p: Point| h - p.to_vec2().dot(n) <= tol + slope * (p - peak).hypot(); + let mut ahead = 0; + for j in 1..len { + match segments.get((at + j) % len) { + Some(s) if counts(s.p0) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } + ahead = j; + } + for j in 1..len - ahead { + match segments.get((at + len - j) % len) { + Some(s) if counts(s.p3) => each_extreme(s, n, |p, v| all.push((p, v))), + _ => break, + } } let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() @@ -322,6 +342,8 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { } fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + #[cfg(test)] + tests::EXTREMES.with(|c| c.set(c.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -396,10 +418,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincid let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb }); let mut out = Vec::with_capacity(external.len() + internal.len()); for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { for root in list { - let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + let t = tangent_at(&a, &b, kind, root.angle, root.double, size); out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); } } @@ -414,21 +437,47 @@ struct Root { double: bool, } -/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, -/// and `b` on the same side (external) or the other side (internal). `double` when the outlines -/// touch there. -fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { +/// An outline with the segment it is touched on at each sampled normal angle. +struct Hinted<'a> { + o: &'a Outline, + at: &'a [f64], + hints: &'a [usize], +} + +impl Hinted<'_> { + /// The support value at the normal angle `angle` and the segment it is reached on, walking on + /// from the segment of the sample at or before `angle`. + fn support(&self, angle: f64) -> (f64, usize) { + let angle = angle.rem_euclid(TAU); + // Before the first sample, the last one (taken 2π back) comes before `angle`. + let k = self.at.partition_point(|t| *t <= angle).checked_sub(1).unwrap_or(self.at.len().saturating_sub(1)); + self.o.support_from(dir(angle), self.hints.get(k).copied().unwrap_or(0)) + } +} + +/// The tangent of `kind` whose normal is at `angle`: `a` lies where `p · n` is at most the line's +/// value, and `b` on the same side (external) or the other side (internal). `double` when the +/// outlines touch there. +fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: bool, size: f64) -> Tangent { + let n = dir(angle); // The rounding allowed in `p · n` grows with each outline's own size and its distance from the // origin. let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); - let (tol_a, tol_b) = (rounding(a), rounding(b)); + let (tol_a, tol_b) = (rounding(a.o), rounding(b.o)); // Bisection finds a simple root's angle to about the rounding of the support values; the // golden-section search finds a double root's to about 1e-8 radians. let slope = if double { 1e-7 } else { 1e-10 }; - let ha = a.support(n); - let (on_a, on_b) = match kind { - TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), - TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + let (ha, sa) = a.support(angle); + let on_a = a.o.touching(n, ha, tol_a, slope, sa); + let on_b = match kind { + TangentKind::External => { + let (hb, sb) = b.support(angle); + b.o.touching(n, hb, tol_b, slope, sb) + } + TangentKind::Internal => { + let (hb, sb) = b.support(angle + TAU / 2.0); + b.o.touching(-n, hb, tol_b, slope, sb) + } }; // Positions along the line, which runs square to `n` through `n * ha`. let t = Vec2::new(-n.y, n.x); @@ -441,7 +490,7 @@ fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool // stand a little apart. let (from, to) = if double && hi - lo <= 1e-6 * size { // Touching at one point: the narrower outline's width along the line, centered there. - let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min); let mid = (lo + hi) / 2.0; (mid - width / 2.0, mid + width / 2.0) } else if mean(&on_a) <= mean(&on_b) { @@ -575,11 +624,18 @@ fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { #[cfg(test)] mod tests { + use std::cell::Cell; + use kurbo::Rect; use vectorcraft_geom::shapes; use super::*; + thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread. + pub(super) static EXTREMES: Cell = const { Cell::new(0) }; + } + fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -850,6 +906,44 @@ mod tests { assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); } + #[test] + fn each_tangent_measures_only_the_segments_near_where_it_touches() { + // Two regular 2,000-gons about one center, one turned half a step: 4,000 external + // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // measurements per tangent. + let sides = 2_000; + let gon = |turn: f64| { + let pts: Vec = (0..sides).map(|k| (dir(turn + TAU * k as f64 / sides as f64) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let (a, b) = (Outline::convex(&gon(0.0)).unwrap(), Outline::convex(&gon(TAU / (2 * sides) as f64)).unwrap()); + EXTREMES.with(|c| c.set(0)); + let all = common_tangents(&a, &b).unwrap(); + let calls = EXTREMES.with(Cell::get); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2 * sides); + assert!(calls < 1_000 * all.len(), "{calls} measurements for {} tangents", all.len()); + let r = 100.0 * (TAU / (4 * sides) as f64).sin(); + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 2.0 * r).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_very_thin_ellipse_is_measured_exactly() { + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the + // ellipse's tips to the circle. + let thin = Affine::scale_non_uniform(1e6, 1e-7); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + } + // A map whose determinant is lost in the rounding of its entries is still refused. + assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + } + #[test] fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is From 7e1d76ae7d4e8ebd70b48589dfb9b4fdbe9bd775 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 17:31:26 -0800 Subject: [PATCH 2/4] Path Precision Tools: Common Tangents tests a turned thin ellipse and the area limit The thin-ellipse test now also turns the figure 30 degrees and checks that each line still ends at the ellipse's tip. A determinant four times its rounding is accepted and one equal to its rounding is refused, so the limit is tested on both sides. The comment on the limit said the opposite of the rule: an ellipse is measured exactly when its determinant is larger than the rounding of its entries. The segment counter used by the tests is declared next to the function it counts, and the estimate in the work test is corrected to about 8,000 measurements per tangent. --- .../pathops/src/addons/pathtools/tangents.rs | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index c01c80957e..9e198229fd 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -78,7 +78,8 @@ impl Outline { let [a, b, c, d, e, f] = unit.as_coeffs(); let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); // The determinant is rounded by about `f64::EPSILON * norm²`; one no larger than that may - // belong to a map with no area. Any thinner ellipse is measured exactly. + // belong to a map with no area. An ellipse whose determinant is larger is measured + // exactly. if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= f64::EPSILON * norm * norm { return Err(OutlineError::Empty); } @@ -313,8 +314,6 @@ impl Outline { } } -/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where -/// the curve runs square to `n`) and the value there. /// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product /// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared /// with the segment's control polygon length squared. @@ -341,9 +340,17 @@ fn bends_against(s: &CubicBez, sign: f64) -> bool { low < -1e-9 * scale } +#[cfg(test)] +thread_local! { + /// How many times [`each_extreme`] has measured a segment on this thread, for the tests. + static EXTREMES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { #[cfg(test)] - tests::EXTREMES.with(|c| c.set(c.get() + 1)); + EXTREMES.with(|n| n.set(n.get() + 1)); let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); f(s.p3, v3); @@ -631,11 +638,6 @@ mod tests { use super::*; - thread_local! { - /// How many times [`each_extreme`] has measured a segment on this thread. - pub(super) static EXTREMES: Cell = const { Cell::new(0) }; - } - fn circle(cx: f64, cy: f64, r: f64) -> Outline { Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() } @@ -909,7 +911,7 @@ mod tests { #[test] fn each_tangent_measures_only_the_segments_near_where_it_touches() { // Two regular 2,000-gons about one center, one turned half a step: 4,000 external - // tangents. Measuring every segment of both outlines for every tangent takes about 16,000 + // tangents. Measuring every segment of both outlines for every tangent takes about 8,000 // measurements per tangent. let sides = 2_000; let gon = |turn: f64| { @@ -928,19 +930,28 @@ mod tests { #[test] fn a_very_thin_ellipse_is_measured_exactly() { - // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle: the tangents run from the - // ellipse's tips to the circle. - let thin = Affine::scale_non_uniform(1e6, 1e-7); - let all = common_tangents(&Outline::ellipse(thin).unwrap(), &circle(0.0, 100.0, 10.0)).unwrap(); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); - assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); - let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), 5_000)); - for t in &all { - check_against_samples(t, &sa, &sb, 1e-3); - let tip = if (t.from - Point::new(1e6, 0.0)).hypot() < 1e-3 || (t.from - Point::new(-1e6, 0.0)).hypot() < 1e-3 { t.from } else { t.to }; - assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{t:?}"); + // Semi-axes 1e6 and 1e-7, a ratio of 1e13, beside a circle, then the whole figure turned + // 30 degrees: the tangents run from the ellipse's tips to the circle. + for deg in [0.0, 30.0] { + let turn = Affine::rotate(f64::to_radians(deg)); + let thin = turn * Affine::scale_non_uniform(1e6, 1e-7); + let round = turn * Affine::new([10.0, 0.0, 0.0, 10.0, 0.0, 100.0]); + let all = common_tangents(&Outline::ellipse(thin).unwrap(), &Outline::ellipse(round).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(thin, 20_000), sample_ellipse(round, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + // The end on the ellipse, taken back to the unturned figure. + let (from, to) = (turn.inverse() * t.from, turn.inverse() * t.to); + let tip = if (from.x.abs() - 1e6).abs() < 1e-3 { from } else { to }; + assert!((tip.x.abs() - 1e6).abs() < 1e-3 && tip.y.abs() < 1e-6, "{deg} {t:?}"); + } } - // A map whose determinant is lost in the rounding of its entries is still refused. + // A determinant a few times its rounding is taken; one lost in the rounding of the map's + // entries is still refused. + assert!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, 4.0 * f64::EPSILON, 0.0, 0.0])).is_ok()); + assert_eq!(Outline::ellipse(Affine::new([1.0, 0.0, 0.0, f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); assert_eq!(Outline::ellipse(Affine::new([1.0, 1.0, 1.0, 1.0 + f64::EPSILON, 0.0, 0.0])).err(), Some(OutlineError::Empty)); } From d487dae5b3d31bfab978332f92080b75c98eece1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:19:45 -0800 Subject: [PATCH 3/4] Path Precision Tools: Common Tangents refuses a path that turns inward at a join The convexity check compared points sampled along each segment and the curvature inside each segment, but not the corner where one segment meets the next. A segment that leaves its start a little the wrong way could make an inward corner that neither check saw. Each join is now checked by the directions the two segments meet it in, skipping segments of no length. --- .../pathops/src/addons/pathtools/tangents.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 9e198229fd..b8a7ce6b6e 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -156,6 +156,16 @@ impl Outline { if segments.iter().any(|s| bends_against(s, sign)) { return Err(OutlineError::NotConvex); } + // A corner can also turn inward between two of the points: each join is checked by the + // directions the segments leave and reach it in. Segments of no length are passed over. + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot() > 1e-9 * size).map(|v| v / v.hypot()); + let ends: Vec<(Vec2, Vec2)> = segments + .iter() + .filter_map(|s| nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]).zip(nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0]))) + .collect(); + if ends.iter().enumerate().any(|(i, (_, end))| ends[(i + 1) % ends.len()].0.cross(*end) * sign > 1e-9) { + return Err(OutlineError::NotConvex); + } let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); if !center.x.is_finite() || !center.y.is_finite() { return Err(OutlineError::Empty); @@ -982,6 +992,15 @@ mod tests { bp.close_path(); let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); + // A triangle whose first side is a cubic that leaves its start a little the wrong way: the + // corner there turns inward, though the checked points and the curve itself turn one way. + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.curve_to((-1.0, -1.0), (66.0, -2.0), (100.0, 0.0)); + bp.line_to((50.0, 100.0)); + bp.close_path(); + let notch = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(¬ch).err(), Some(OutlineError::NotConvex)); // A square traced twice around winds around twice. let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); From 83f21f44965f725989bff6276f0b1ece48e8c3bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 19:36:17 -0800 Subject: [PATCH 4/4] Path Precision Tools: Common Tangents adds the centerline between tiny paths The centerline was left out whenever the two centers were less than 1e-9 points apart, so two separate paths a billionth of a point wide got their tangents but no centerline. Centers now count as one point only when they are closer than a billionth of the larger path's size. --- crates/engine/src/cmd/addons/pathtools/tangents.rs | 3 ++- .../src/cmd/addons/pathtools/tangents/tests.rs | 13 +++++++++++++ crates/pathops/src/addons/pathtools/tangents.rs | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 4376cbe791..8102777687 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -96,7 +96,8 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result { }; return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); } - let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + // Centers closer than a billionth of the larger path's size count as one point: no line. + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9 * a.size().max(b.size())).then(|| (a.center(), b.center())); let fill = Paint::None; let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs index 5ed6e2b0d6..aef694bbdd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -162,6 +162,19 @@ fn a_convex_bezier_path_and_the_centerline() { } } +#[test] +fn tiny_paths_close_together_still_get_the_centerline() { + // Two circles a ten-billionth of a point wide, half a billionth apart: separate, with all four + // tangents, and centers apart by far more than their sizes' rounding. + let mut s = session(); + let a = circle(&mut s, 1.0, 1.0, 1e-10); + let b = circle(&mut s, 1.0 + 5e-10, 1.0, 1e-10); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(r["ids"].as_array().map(Vec::len), Some(5), "{r}"); + assert_eq!(r["centerline"], r["ids"][4]); +} + #[test] fn the_lines_take_the_current_stroke_and_no_fill() { let mut s = session(); diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index b8a7ce6b6e..a42e628cad 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -259,7 +259,7 @@ impl Outline { } /// The diagonal of the bounds (an ellipse's: of the box its axes span). - fn size(&self) -> f64 { + pub fn size(&self) -> f64 { match self { Outline::Ellipse { m, .. } => { let [a, b, c, d] = *m;