diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 088796173..407780177 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -26,11 +26,16 @@ impl WidthProfile { pub fn at(&self, t: f64) -> (f64, f64) { Self::at_points(&self.points, t) } - /// [`Self::at`] of a profile's points (a preset's or a saved profile's). Each side runs through - /// its points on a monotone cubic curve (Fritsch–Carlson): it flows through a width point - /// without a kink, turns flat at a point wider or narrower than both neighbours, and never - /// goes past either point of the span it is in (#5714). Points on one straight line stay on - /// it. A step (two points at one position, [`Self::around`]) ends the curve on each side of it. + /// [`Self::at`] of a profile's points (a preset's or a saved profile's). + /// + /// Each side runs through its points on a cubic Hermite curve, its slope at each one the + /// weighted harmonic mean of the secants either side (Fritsch–Carlson). That is C1 continuous + /// and monotone between points, so it never overshoots them, a point eases into its neighbours + /// instead of making a corner, and moving one reshapes the curve as far as its neighbours' + /// neighbours (their slopes depend on it). The ends of a run use the one-sided PCHIP slope + /// from its first two secants, or the secant when it has only two points, so a two-point + /// profile stays a straight taper and the lens is a parabola. Two points at one `t` are still + /// a step: each run either side ends independently at it. pub fn at_points(p: &[(f64, f64, f64)], t: f64) -> (f64, f64) { if p.is_empty() { return (1.0, 1.0); @@ -71,9 +76,10 @@ impl WidthProfile { // Two swells between narrow necks. ProfilePreset { id: "wave", label: "Wave", points: &[(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)] }, ]; - /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. Each - /// side stays between the widths of the two points of each span ([`Self::at_points`]), but the - /// two sides needn't peak together, so a span counts its wider left and its wider right. + /// The widest the stroke gets, as a multiple of its weight, 1 for a profile without points. + /// Each side's smooth curve stays between the widths of the two points of each span + /// ([`Self::at_points`]), but the two sides needn't peak together, so a span counts its wider + /// left and its wider right. pub fn widest(&self) -> f64 { let p = &self.points; if p.is_empty() { @@ -249,11 +255,27 @@ impl AngleProfile { /// How close two width points' positions are to make a step ([`WidthProfile::around`]). const STEP: f64 = 1e-7; +/// The one-sided three-point PCHIP slope at the start of a run, from the first two secants. +/// A sign change caps the slope, and a slope that turns back on the first secant is flattened. +/// Runs of only two points use their secant instead (see [`tangent`]). +fn end_slope(h0: f64, h1: f64, d0: f64, d1: f64) -> f64 { + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if !m.is_finite() || m * d0 <= 0.0 { + return 0.0; + } + if d0 * d1 < 0.0 { + return if d0 > 0.0 { m.min(3.0 * d0) } else { m.max(3.0 * d0) }; + } + m +} + /// The slope of one side (`v` reads it from a point) of width profile `p` at its point `j`, in /// width per unit of position: Fritsch–Carlson's choice for a monotone cubic curve. It is 0 where -/// the point is wider or narrower than both neighbours, the weighted harmonic mean of the slopes -/// of the spans on either side elsewhere (never more than three times either, so no span -/// overshoots its points), and the span's own slope at an end of the profile or beside a step. +/// the point is wider or narrower than both neighbours, and the weighted harmonic mean of the +/// slopes of the spans on either side elsewhere (never more than three times either, so no span +/// overshoots its points). The ends of a run take the one-sided three-point PCHIP slope, or their +/// secant when the run has only two points; a step ends the run on each side, so the points either +/// side of it do not see across it. fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f64 { let Some(q) = p.get(j) else { return 0.0 }; let before = j.checked_sub(1).and_then(|k| p.get(k)).filter(|a| q.0 - a.0 > STEP); @@ -268,8 +290,18 @@ fn tangent(p: &[(f64, f64, f64)], j: usize, v: fn(&(f64, f64, f64)) -> f64) -> f let (h0, h1) = (q.0 - a.0, b.0 - q.0); 3.0 * (h0 + h1) / ((2.0 * h1 + h0) / d0 + (h1 + 2.0 * h0) / d1) } - (Some(a), None) => slope(a, q), - (None, Some(b)) => slope(q, b), + // The end of a run: its previous two points set a one-sided three-point slope, or its + // secant when the run has only two points (the point before `a` is on the other side of a + // step, or does not exist). + (Some(a), None) => { + let Some(prev) = j.checked_sub(2).and_then(|k| p.get(k)).filter(|z| a.0 - z.0 > STEP) else { return slope(a, q) }; + end_slope(q.0 - a.0, a.0 - prev.0, slope(a, q), slope(prev, a)) + } + // The start of a run, symmetrically. + (None, Some(b)) => { + let Some(next) = p.get(j + 2).filter(|z| z.0 - b.0 > STEP) else { return slope(q, b) }; + end_slope(b.0 - q.0, next.0 - b.0, slope(q, b), slope(b, next)) + } (None, None) => 0.0, } } @@ -424,12 +456,12 @@ mod tests { #[test] fn widths_run_smoothly_through_width_points() { // A swell in the middle: flat at its widest, and a quarter of the way along above the - // straight ramp from 1 to 3 (2). + // straight ramp from 1 to 3 (2) because the end eases out of the first point. let swell = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 2.0), (1.0, 1.0, 1.0)] }; let (before, after) = slopes(&swell, 0.5); assert!(before.abs() < 1e-4 && after.abs() < 1e-4, "{before} {after}"); let (l, r) = swell.at(0.25); - assert!((l - 2.25).abs() < 1e-12 && (r - 1.625).abs() < 1e-12, "{l} {r}"); + assert!((l - 2.5).abs() < 1e-12 && (r - 1.75).abs() < 1e-12, "{l} {r}"); // Rising on both sides of a point: the slope is the same either side of it. let rise = WidthProfile { points: vec![(0.0, 0.0, 0.0), (0.3, 1.0, 1.0), (1.0, 4.0, 4.0)] }; let (before, after) = slopes(&rise, 0.3); diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index 0a1b3e1a5..aa2ba0100 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -197,12 +197,85 @@ fn strokes_without_pressure_round_trip_unchanged() { fn profile_interp() { let p = WidthProfile::lens(); assert_eq!(p.at(0.5), (1.0, 1.0)); - // Half way up the lens the width curves above the straight ramp (0.5), flattening into its - // widest point (#5714). - assert_eq!(p.at(0.25), (0.625, 0.625)); + // The lens is a parabola between its ends, so a quarter of the way along is 0.75: above the + // 0.5 a straight taper would give. + assert_eq!(p.at(0.25), (0.75, 0.75)); assert_eq!(p.at(2.0), (0.0, 0.0)); } +/// The width runs smoothly between points: it passes through them, has one slope either side +/// of one, and never overshoots the widths its points set. +#[test] +fn profile_is_smooth_between_points() { + let p = [(0.0, 1.0, 2.0), (0.5, 0.2, 2.0), (1.0, 1.0, 2.0)]; + assert!((WidthProfile::at_points(&p, 0.5).0 - 0.2).abs() < 1e-12); + let slope = |t: f64| (WidthProfile::at_points(&p, t + 1e-6).0 - WidthProfile::at_points(&p, t - 1e-6).0) / 2e-6; + // A local minimum at the middle point is flat there, so the two sides agree. + assert!(slope(0.5).abs() < 1e-3, "{}", slope(0.5)); + for k in 0..=100 { + let w = WidthProfile::at_points(&p, k as f64 / 100.0).0; + assert!((0.2..=1.0).contains(&w), "{w} at {k}"); + } + // The side with no points of its own stays flat. + for k in 0..=100 { + assert!((WidthProfile::at_points(&p, k as f64 / 100.0).1 - 2.0).abs() < 1e-12); + } +} + +/// A run with only two points takes its secant as both end slopes, so it stays a straight +/// taper on each side instead of becoming a smoothstep. +#[test] +fn profile_two_point_runs_are_linear() { + let p = [(0.0, 0.0, 1.0), (1.0, 1.0, 0.0)]; + for k in 0..=100 { + let t = k as f64 / 100.0; + let (l, r) = WidthProfile::at_points(&p, t); + assert!((l - t).abs() < 1e-12, "left {l} at {t}"); + assert!((r - (1.0 - t)).abs() < 1e-12, "right {r} at {t}"); + } +} + +/// The lens's one-sided end slopes make it a parabola: at a quarter of the way it is 0.75, +/// above the 0.5 a straight line between its points would give. +#[test] +fn profile_lens_is_convex() { + let p = WidthProfile::lens(); + assert!((p.at(0.25).0 - 0.75).abs() < 1e-12); + assert!((p.at(0.75).0 - 0.75).abs() < 1e-12); + for k in 1..25 { + let t = k as f64 / 100.0; + assert!(p.at(t).0 > 2.0 * t, "{} at {t}", p.at(t).0); + assert!(p.at(1.0 - t).0 > 2.0 * t, "{} at {}", p.at(1.0 - t).0, 1.0 - t); + } +} + +/// A step still steps, and the smooth runs either side meet it flat. +#[test] +fn profile_steps_stay_steps() { + let p = [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 2.0, 2.0)]; + assert_eq!(WidthProfile::at_points(&p, 0.5), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 + 1e-6), (2.0, 2.0)); + assert_eq!(WidthProfile::at_points(&p, 0.5 - 1e-6), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.25), (1.0, 1.0)); + assert_eq!(WidthProfile::at_points(&p, 0.75), (2.0, 2.0)); +} + +/// Moving a point only reshapes the segments beside it (local influence), not the whole path. +#[test] +fn profile_points_only_affect_the_curve_around_them() { + // A monotone run, so no neighbouring slope is held flat by a local extremum. + let a = [(0.0, 0.0, 0.0), (0.25, 0.3, 0.3), (0.5, 0.5, 0.5), (0.75, 0.7, 0.7), (1.0, 1.0, 1.0)]; + let mut b = a; + b[3] = (0.75, 0.9, 0.9); + // Moving p[3] changes the slopes at p[2] and p[3], so p[1] and p[4] also shape the + // curve: nothing before p[1] may move. + for k in 0..=24 { + let t = k as f64 / 100.0; + assert_eq!(WidthProfile::at_points(&a, t), WidthProfile::at_points(&b, t), "at {t}"); + } + assert_ne!(WidthProfile::at_points(&a, 0.3), WidthProfile::at_points(&b, 0.3)); +} + #[test] fn profile_presets_round_trip_their_ids() { for p in WidthProfile::PRESETS { diff --git a/crates/doc/src/reach.rs b/crates/doc/src/reach.rs index f6b9a4d01..8279507e0 100644 --- a/crates/doc/src/reach.rs +++ b/crates/doc/src/reach.rs @@ -80,10 +80,8 @@ fn head_ends(st: &StrokeLayer, bp: &BezPath) -> Vec<(Point, Vec2, bool)> { /// at `t`): the profile at that fraction of the subpath's length, or wider where an end of the /// segment is a corner. The stroke draws the sides there straight to the corner's join and inner /// meeting point, which can lie outside the exact width all along the segment. -fn profile_at(profile: &WidthProfile, segs: &[PathSeg], closed: bool, i: usize, t: f64) -> (f64, f64) { +fn profile_at(profile: &WidthProfile, segs: &[PathSeg], lens: &[f64], total: f64, closed: bool, i: usize, t: f64) -> (f64, f64) { let n = segs.len(); - let lens: Vec = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); - let total: f64 = lens.iter().sum::().max(1e-12); let before = lens[..i].iter().sum::(); let mut w = profile.at((before + segs[i].subsegment(0.0..t).arclen(ARCLEN_ACCURACY)) / total); let corner = |a: usize, b: usize| (closed || a < b) && kink(&segs[a], &segs[b]); @@ -306,7 +304,8 @@ impl StrokeLayer { /// Does this stroke along `bp` (filled with `rule`) paint within `tol` of `p`? Inside and /// outside strokes of closed paths count on their own side only (and within `tol` of the - /// path); a width profile counts at its width where `p` is nearest. + /// path); a width profile counts at the width of every segment that can reach `p`, as the + /// wider side of a farther one can paint past the nearest. pub fn hits(&self, bp: &BezPath, rule: FillRule, p: Point, tol: f64) -> bool { let reach = self.reach() + tol; if self.width.is_nan() || self.width <= 0.0 || !bp.bounding_box().inflate(reach, reach).contains(p) { @@ -330,17 +329,27 @@ impl StrokeLayer { let segs = drawn(&els[r]); let (half, region) = self.body(closed); let full = half * self.profile_max() * dash_caps.unwrap_or(1.0); - // The nearest point on this subpath. - let near = segs.iter().enumerate().map(|(i, s)| (i, s.nearest(p, 1e-9))).min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq)); - if let Some((i, nr)) = near - && nr.distance_sq.sqrt() <= full + tol - { + // Every segment near enough to reach `p`: with a width profile the wider side of a + // farther segment can paint past the nearest one, so the nearest alone is not enough. + let near = segs.iter().enumerate().filter_map(|(i, s)| { + let nr = s.nearest(p, 1e-9); + (nr.distance_sq.sqrt() <= full + tol).then_some((i, nr)) + }); + // The lengths are only needed when a profiled candidate reaches `p`; compute them + // once for the whole subpath rather than once per candidate. + let mut lengths: Option<(Vec, f64)> = None; + for (i, nr) in near { let d = nr.distance_sq.sqrt(); let factor = if dash_caps.is_some() { full / half.max(1e-12) } else { self.profile.as_ref().map_or(1.0, |pr| { - let (l, rt) = profile_at(pr, &segs, closed, i, nr.t); + let (lens, total) = lengths.get_or_insert_with(|| { + let lens: Vec = segs.iter().map(|s| s.arclen(ARCLEN_ACCURACY)).collect(); + let total = lens.iter().sum::().max(1e-12); + (lens, total) + }); + let (l, rt) = profile_at(pr, &segs, lens, *total, closed, i, nr.t); // Nearest to a segment's end, `p` is beside a join or past a cap, which // spans the widths of both sides. let at_end = nr.t <= 1e-9 || nr.t >= 1.0 - 1e-9; diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index c96dcb477..acb980204 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -173,6 +173,18 @@ fn bar(hw: f64) -> f64 { /// Where the notch of the (open) arrow sits, as a fraction of the length. const NOTCH: f64 = 0.7; +/// How far [`super::stroke_pieces`] trims the line under each end's head: the head's inset from +/// the tip, along the path. Both are 0 without a head at that end, and in [`ArrowAlign::Extend`], +/// where the stroke keeps its full length. +pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) { + if st.arrow_align != ArrowAlign::Tip { + return (0.0, 0.0); + } + let cap = cap_extent(st.cap, st.width); + let inset_of = |kind: Option, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap)); + (inset_of(st.start_arrow, false), inset_of(st.end_arrow, true)) +} + /// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end. fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 { let l = len(hw); diff --git a/crates/effects/src/stroke/gradient.rs b/crates/effects/src/stroke/gradient.rs index 1cb79e9c7..4bddf80b0 100644 --- a/crates/effects/src/stroke/gradient.rs +++ b/crates/effects/src/stroke/gradient.rs @@ -18,11 +18,11 @@ use std::collections::VecDeque; use kurbo::{BezPath, Point, Shape, Vec2}; use vectorcraft_doc::color::{Gradient, GradientGeom, GradientPaint, Paint}; use vectorcraft_doc::live::{H_DOWN, H_LEFT, H_RIGHT, H_UP}; -use vectorcraft_doc::{GradientMesh, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; +use vectorcraft_doc::{GradientMesh, LineCap, LineJoin, MeshPoint, StrokeAlign, StrokeGradientMode, StrokeLayer}; use vectorcraft_geom::FillRule; use super::width::{flatten, left, length, split_at}; -use super::{aligned_width, cap_extent, is_closed, segments, subpaths, unit}; +use super::{aligned_width, arrow, cap_extent, is_closed, segments, subpaths, unit}; /// Largest stretch of a rib on a turn's bisector (1 / cos of half the turn, about 74°) before the /// corner gets a fan of ribs round its outside. @@ -97,7 +97,10 @@ impl Lay<'_> { /// How far a rib at fraction `t` reaches either side of the path to cover the stroke there. fn cover(&self, t: f64) -> f64 { - self.half(t) + self.margin + // A square cap's corners stand √2 of the half-width out from where the dash ends, and a + // dash can end just past a corner: reach that far, or they paint outside every slice. + let diag = if self.st.dash.is_some() && self.st.cap == LineCap::Square { std::f64::consts::SQRT_2 } else { 1.0 }; + self.half(t) * diag + self.margin } /// The across band at fraction `t` of a subpath whose visible side is `side` (`Some(true)`: @@ -162,6 +165,9 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, return vec![]; } let heads = (st.head_reach(false), st.head_reach(true)); + // With a tip-aligned arrowhead the stroke's line, and with it the width profile, stops at the + // head's inset from the tip (`stroke_pieces`). + let trims = arrow::trims(st); let mut lay = Lay { st, hw, margin, ext: (0.0, 0.0) }; // Caps reach as far past the ends as the stroke is wide there. let cap = |t: f64| cap_extent(st.cap, 2.0 * lay.half(t)); @@ -170,27 +176,34 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, let count = subs.len(); let mut out = vec![]; for (k, (range, closed)) in subs.into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[range]), closed, tol.max(1e-4)); - let side = - (st.align != StrokeAlign::Center && closed_path && closed).then(|| band_on_left(bp, rule, &pts, st.align, (4.0 * tol).min(hw / 2.0))); + let segs = segments(&bp.elements()[range]); + let flat = flatten(&segs, closed, tol.max(1e-4)); + let side = (st.align != StrokeAlign::Center && closed_path && closed) + .then(|| band_on_left(bp, rule, &flat.pts, st.align, (4.0 * tol).min(hw / 2.0))); // Arrowheads sit on the start of the first subpath and the end of the last one. let heads = (if k == 0 { heads.0 } else { 0.0 }, if k + 1 == count { heads.1 } else { 0.0 }); - let ribs = match pts.len() { + let trims = (if k == 0 { trims.0 } else { 0.0 }, if k + 1 == count { trims.1 } else { 0.0 }); + let ribs = match flat.pts.len() { 0 => continue, // A subpath of no length: a dot (round and projecting caps paint it). 1 => { let (d, b, e) = (Vec2::new(1.0, 0.0), lay.band(0.0, side), lay.ext.0.max(lay.ext.1)); let r = lay.cover(0.0); - vec![Rib::square(pts[0] - d * e, d, r, 0.0, b), Rib::square(pts[0] + d * e, d, r, 0.0, b)] + vec![Rib::square(flat.pts[0] - d * e, d, r, 0.0, b), Rib::square(flat.pts[0] + d * e, d, r, 0.0, b)] } _ => { - let total = length(&pts, closed); + let total = length(&flat.pts, closed); if total <= 1e-12 { continue; } let steps = if max_dt < 1.0 { (1.0 / max_dt).ceil() as usize } else { 1 }; let profile = st.profile.iter().flat_map(|p| p.points.iter().map(|q| q.0)); let heads = if closed { (0.0, 0.0) } else { heads }; + // A tip-aligned arrowhead shortens the line it sits on, and the stroke's outline + // reads the width profile along the shortened line (`stroke_pieces`); the ribs + // must read it there too, or on a profile that changes fast they cover a narrower + // band than the stroke paints. + let span = if closed { (0.0, total) } else { (trims.0.min(total), (total - trims.1).max(trims.0)) }; // Where an arrowhead's reach ends gets a rib of its own, so the ribs that reach // across a head run all the way there instead of narrowing towards the next corner // from the head's tip, which leaves the corners of its base outside (#5964). @@ -200,11 +213,11 @@ fn strips(bp: &BezPath, rule: FillRule, st: &StrokeLayer, tol: f64, margin: f64, .copied() .chain(profile) .chain((1..steps).map(|i| i as f64 / steps as f64)) - .map(|t| t * total) + .map(|t| span.0 + (span.1 - span.0) * t) .chain(head_ends) .collect(); - let (pts, _) = split_at(&pts, &corner, closed, &at); - strip(&lay, &pts, closed, total, side, heads) + let (pts, _, _) = split_at(&flat, closed, &at, &segs); + strip(&lay, &pts, closed, total, side, heads, span) } }; out.push(ribs); @@ -226,8 +239,9 @@ fn band_on_left(bp: &BezPath, rule: FillRule, pts: &[Point], align: StrokeAlign, } /// The ribs along one flattened subpath `pts` of length `total` (`heads`: how far arrowheads -/// reach from its start and end). -fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option, heads: (f64, f64)) -> Vec { +/// reach from its start and end). `span` is the stretch of the subpath the width profile is laid +/// along: the whole of it, or what is left between tip-aligned arrowheads. +fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option, heads: (f64, f64), span: (f64, f64)) -> Vec { let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let dir: Vec = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -249,7 +263,9 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option, // stroke is wide anywhere: where a stroke crosses or runs close by itself, a narrow part // reaching that far would paint over a wide part beside it (#5960). The start of a closed // subpath is also its end. Ribs near an arrowhead reach across it. - let cover: Vec = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(along[i] / total) }).collect(); + // The fraction of the profile at how far `s` is along the subpath: the profile spans `span`. + let t_at = |s: f64| if span.1 > span.0 { ((s - span.0) / (span.1 - span.0)).clamp(0.0, 1.0) } else { 0.0 }; + let cover: Vec = (0..n).map(|i| if closed && i == 0 { lay.cover(0.0).max(lay.cover(1.0)) } else { lay.cover(t_at(along[i])) }).collect(); let window = match lay.st.dash { Some(_) if lay.st.profile.is_some() => cap_extent(lay.st.cap, 2.0 * lay.hw * lay.st.profile_max()), _ => 0.0, @@ -279,7 +295,7 @@ fn strip(lay: &Lay, pts: &[Point], closed: bool, total: f64, side: Option, let (first, last) = if closed { (0, n) } else { (1, n - 1) }; for i in first..last { let v = i % n; - let t = along[v] / total; + let t = t_at(along[v]); let ribs = lay.turn(pts[v], dir[(v + seg_count - 1) % seg_count], dir[v % seg_count], reach(v), t, lay.band(t, side)); // A closed subpath starts after the fan of its first corner and ends with it. let skip = if closed && i == 0 { ribs.len() - 1 } else { 0 }; diff --git a/crates/effects/src/stroke/tests.rs b/crates/effects/src/stroke/tests.rs index 46969ff63..fc3f2eee4 100644 --- a/crates/effects/src/stroke/tests.rs +++ b/crates/effects/src/stroke/tests.rs @@ -232,16 +232,14 @@ fn line_outline_uses_the_profile_dashes_or_a_plain_stroke() { let plain = line_outline(&l, &stroke(10.0, |_| {}), 10.0, 1e-3); assert!(near(plain.area().abs(), 1000.0, 1e-6)); let lens = line_outline(&l, &stroke(10.0, |s| s.profile = Some(WidthProfile::lens())), 10.0, 1e-3); - // The lens swells on a cubic, flat at the middle: 7/12 of the full-width band (#5714). - assert!(near(lens.area().abs(), 1000.0 * 7.0 / 12.0, 0.05)); - // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). Half of the lens - // rises as w(u) = u + u² − u³ (u from 0 to 1 across that half): the dash over 0..25 covers - // its first half, ∫₀^½ w = 29/192, the one over 50..75 the wider other half, 83/192. + // The lens is a parabola between its ends: 2/3 of the full-width band. + assert!(near(lens.area().abs(), 2000.0 / 3.0, 0.1)); + // Each dash takes its widths from where it sits along the lens (0 → 1 → 0). let st = stroke(10.0, |s| { s.profile = Some(WidthProfile::lens()); s.dash = Some(dashed(&[25.0, 25.0], 0.0)); }); - assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 500.0 * (29.0 + 83.0) / 192.0, 0.05)); + assert!(near(line_outline(&l, &st, 10.0, 1e-3).area().abs(), 1000.0 / 3.0, 0.1)); assert!(line_outline(&BezPath::new(), &st, 10.0, 1e-3).elements().is_empty()); } diff --git a/crates/effects/src/stroke/tests_fit.rs b/crates/effects/src/stroke/tests_fit.rs index b427fdbce..b389cab85 100644 --- a/crates/effects/src/stroke/tests_fit.rs +++ b/crates/effects/src/stroke/tests_fit.rs @@ -155,9 +155,10 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![10.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip. + // The dash over 40..50 is near the lens's widest point; the one over 0..10 near its tip, + // where the smooth profile is thinner than a straight ramp (a parabola's first tenth). assert!(o.contains(Point::new(45.0, 4.0)) && o.contains(Point::new(45.0, -4.0)), "middle dash is wide"); - assert!(!o.contains(Point::new(5.0, 2.0)) && o.contains(Point::new(5.0, 0.3)), "first dash is thin"); + assert!(o.contains(Point::new(5.0, 0.8)) && !o.contains(Point::new(5.0, 1.2)), "first dash is thin"); assert!(!o.contains(Point::new(15.0, 0.0)), "gaps stay empty"); // Dots too: a round dot near the middle is bigger than one near an end. let st = stroke(10.0, |s| { @@ -166,7 +167,7 @@ fn each_dash_takes_its_width_from_the_profile_along_the_whole_path() { s.dash = Some(Dash { pattern: vec![0.0, 10.0], offset: 0.0, align_corners: false }); }); let o = line_outline(&line(100.0), &st, 10.0, 1e-3); - assert!(o.contains(Point::new(50.0, 4.5)) && !o.contains(Point::new(10.0, 1.5)) && o.contains(Point::new(10.0, 0.5))); + assert!(o.contains(Point::new(50.0, 4.5)) && o.contains(Point::new(10.0, 1.4)) && !o.contains(Point::new(10.0, 2.0))); } /// An L whose corner turns 90° at (100, 0), or a sharp V turning back at (100, 0). diff --git a/crates/effects/src/stroke/tests_gradient.rs b/crates/effects/src/stroke/tests_gradient.rs index a0056d6b3..ea966ea07 100644 --- a/crates/effects/src/stroke/tests_gradient.rs +++ b/crates/effects/src/stroke/tests_gradient.rs @@ -138,9 +138,8 @@ fn across_runs_from_the_left_edge_to_the_right() { let mut lens = st.clone(); lens.profile = Some(WidthProfile::lens()); let sl = slices(&line, &lens); - // A quarter of the way along, the lens is 0.625 as wide (its curve, #5714): its top edge is - // 3.125 up. - assert!(param(&sl, Point::new(25.0, -3.0)).unwrap() < 0.05); + // A quarter of the way along, the lens is three quarters as wide: its top edge is 3.75 up. + assert!(param(&sl, Point::new(25.0, -3.6)).unwrap() < 0.05); assert!((param(&sl, Point::new(50.0, -2.5)).unwrap() - 0.25).abs() < 0.02); } diff --git a/crates/effects/src/stroke/width.rs b/crates/effects/src/stroke/width.rs index 4a9dc2678..0b307cc6b 100644 --- a/crates/effects/src/stroke/width.rs +++ b/crates/effects/src/stroke/width.rs @@ -3,17 +3,18 @@ //! A stroke with a [`WidthProfile`] is drawn as a filled outline: each subpath is flattened, and //! at every sample the left and right offsets `width/2 · factor(t)` (t = fraction of the //! subpath's length) are placed along the normal. Corners of the path take the stroke's miter, -//! round or bevel join on their outer side (smooth points bend round), open subpaths get butt, -//! round or projecting caps (the round cap blends the two side widths), and closed subpaths become -//! two loops of opposite orientation filled with the non-zero rule. Dashes are pieces of a longer -//! subpath and read the profile where they sit along it ([`outline_spans`]). +//! round or bevel join on their outer side (smooth points offset along the curve's normal), open +//! subpaths get butt, round or projecting caps (the round cap blends the two side widths), and +//! closed subpaths become two loops of opposite orientation filled with the non-zero rule. Dashes +//! are pieces of a longer subpath and read the profile where they sit along it ([`outline_spans`]). use std::f64::consts::PI; -use kurbo::{BezPath, ParamCurve, PathEl, PathSeg, Point, Rect, Vec2}; +use kurbo::{BezPath, ParamCurve, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Vec2}; use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer, WidthProfile}; +use vectorcraft_pathops::fit_cubics_through; -use super::{kink, segments, subpaths, unit}; +use super::{kink, segments, subpaths, tangent, unit}; /// Filled outline of `bp` stroked with `width` scaled by `profile`, with the caps, joins and miter /// limit of `st`, flattened to `tol`. @@ -24,15 +25,16 @@ pub fn width_outline(bp: &BezPath, width: f64, profile: &WidthProfile, st: &Stro /// Outline only flattened segments near `near`, retaining each run's original fractions of its /// whole subpath for the width profile. `None` means no segments could be omitted. pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64, near: Rect) -> Option { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); let mut out = BezPath::new(); let mut cut = false; for (r, closed) in subpaths(bp) { if closed { return None; } - let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol); - let n = pts.len(); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + let n = flat.pts.len(); if n < 2 { continue; } @@ -41,7 +43,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil let mut kept = Vec::with_capacity(count); let mut total = 0.0; for i in 0..count { - let (a, b) = (pts[i], pts[i + 1]); + let (a, b) = (flat.pts[i], flat.pts[i + 1]); let len = a.distance(b); if !len.is_finite() { return None; @@ -51,7 +53,7 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil kept.push(!(a.x.max(b.x) < near.x0 || a.x.min(b.x) > near.x1 || a.y.max(b.y) < near.y0 || a.y.min(b.y) > near.y1)); } if kept.iter().all(|v| *v) { - ctx.subpath(&mut out, &pts, &corner, closed, (0.0, 1.0)); + ctx.subpath(&mut out, &flat, &segs, closed, (0.0, 1.0), count as f64); continue; } cut = true; @@ -59,27 +61,31 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil continue; } let mut walked = 0.0; - let mut run = Vec::new(); - let mut run_corner = Vec::new(); + let mut run: Option = None; let mut from = 0.0; for i in 0..count { if kept[i] { - if run.is_empty() { + if run.is_none() { from = walked / total; - run.push(pts[i]); - run_corner.push(corner[i]); + run = Some(Flat { pts: vec![flat.pts[i]], corner: vec![flat.corner[i]], seg_of: vec![], param: vec![] }); } - run.push(pts[i + 1]); - run_corner.push(corner[i + 1]); - } else if run.len() > 1 { - ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total)); - run.clear(); - run_corner.clear(); + if let Some(part) = run.as_mut() { + part.pts.push(flat.pts[i + 1]); + part.corner.push(flat.corner[i + 1]); + part.seg_of.push(flat.seg_of[i]); + part.param.push(flat.param[i]); + } + } else if let Some(part) = run.take() + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } walked += lengths[i]; } - if run.len() > 1 { - ctx.subpath(&mut out, &run, &run_corner, false, (from, walked / total)); + if let Some(part) = run + && part.pts.len() > 1 + { + ctx.subpath(&mut out, &part, &segs, false, (from, walked / total), count as f64); } } cut.then_some(out) @@ -89,12 +95,15 @@ pub(super) fn width_outline_near(bp: &BezPath, width: f64, profile: &WidthProfil /// `spans[i]` of the subpath it was cut from (see [`Dashed::spans`](super::Dashed::spans)); /// subpaths without a span are whole. pub(super) fn outline_spans(bp: &BezPath, spans: &[(f64, f64)], width: f64, profile: &WidthProfile, st: &StrokeLayer, tol: f64) -> BezPath { - let ctx = Ctx { half: width / 2.0, profile, cap: st.cap, join: st.join, miter_limit: st.miter_limit, tol: tol.max(1e-4) }; + let ctx = Ctx::new(width, profile, st, tol); let mut out = BezPath::new(); for (i, (r, closed)) in subpaths(bp).into_iter().enumerate() { - let (pts, corner) = flatten(&segments(&bp.elements()[r]), closed, ctx.tol); - if pts.len() > 1 { - ctx.subpath(&mut out, &pts, &corner, closed, spans.get(i).copied().unwrap_or((0.0, 1.0))); + let segs = segments(&bp.elements()[r]); + let flat = flatten(&segs, closed, ctx.tol); + if flat.pts.len() > 1 { + let span = spans.get(i).copied().unwrap_or((0.0, 1.0)); + let pieces = if closed { flat.pts.len() } else { flat.pts.len() - 1 }.max(1); + ctx.subpath(&mut out, &flat, &segs, closed, span, pieces as f64 / (span.1 - span.0)); } } out @@ -105,19 +114,34 @@ pub(super) fn left(t: Vec2) -> Vec2 { Vec2::new(t.y, -t.x) } +/// A flattened subpath: its points, which of them are corners, and the source segment and +/// parameter range that drew each flattened piece (so a sample added between two points can read +/// that piece's tangent instead of the chord's direction). +pub(super) struct Flat { + pub(super) pts: Vec, + pub(super) corner: Vec, + pub(super) seg_of: Vec, + /// The source segment's parameter range for each flattened piece. Restricting the tangent + /// search to this range keeps a sample on the branch that drew it when a cubic loops back + /// near itself. + pub(super) param: Vec<(f64, f64)>, +} + /// The flattened points of one subpath (consecutive duplicates removed; a closed one doesn't /// repeat its start), each marked when it is a corner of the path. -pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec, Vec) { - let Some(s0) = segs.first() else { return (vec![], vec![]) }; - let (mut pts, mut corner) = (vec![s0.start()], vec![false]); - // The first and the last segment that drew something. - let (mut first, mut prev): (Option<&PathSeg>, Option<&PathSeg>) = (None, None); - for seg in segs { - let at = pts.len() - 1; +pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> Flat { + let Some(s0) = segs.first() else { return Flat { pts: vec![], corner: vec![], seg_of: vec![], param: vec![] } }; + let mut flat = Flat { pts: vec![s0.start()], corner: vec![false], seg_of: vec![], param: vec![] }; + // The last segment that drew something, and the last parameter it reached. + let mut prev: Option<&PathSeg> = None; + let mut last_added: Option<(usize, f64)> = None; + for (si, seg) in segs.iter().enumerate() { + let at = flat.pts.len() - 1; + let before = flat.pts.len(); let mut push = |p: Point| { - if pts.last().is_none_or(|l| l.distance(p) > 1e-9) { - pts.push(p); - corner.push(false); + if flat.pts.last().is_none_or(|l| l.distance(p) > 1e-9) { + flat.pts.push(p); + flat.corner.push(false); } }; match seg { @@ -130,77 +154,151 @@ pub(super) fn flatten(segs: &[PathSeg], closed: bool, tol: f64) -> (Vec, } }), } - if pts.len() > at + 1 { - match prev { - Some(p) => corner[at] = kink(p, seg), - None => first = Some(seg), + if flat.pts.len() > before { + let end = flat.pts.len() - 1; + flat.seg_of.resize(end, si); + for slot in flat.seg_of.iter_mut().take(end).skip(at) { + *slot = si; + } + // Find each new point's source parameter, never going backwards. A point is on the + // curve, so its nearest parameter is exact except at a self-intersection, where the + // monotone search picks the branch that continues this flattened piece. + let mut ts = Vec::with_capacity(end - at + 1); + ts.push(0.0); + let mut t = 0.0; + for p in &flat.pts[at + 1..=end] { + if t >= 1.0 - 1e-12 { + t = 1.0; + } else { + let sub = seg.subsegment(t..1.0); + let nr = sub.nearest(*p, 1e-9); + t = (t + (1.0 - t) * nr.t).clamp(0.0, 1.0); + } + ts.push(t); + } + flat.param.extend(ts.windows(2).map(|w| (w[0], w[1]))); + last_added = ts.last().map(|t| (si, *t)); + if let Some(p) = prev { + flat.corner[at] = kink(p, seg); } prev = Some(seg); } } if closed { - if pts.len() > 1 && pts[0].distance(pts[pts.len() - 1]) <= 1e-9 { - pts.pop(); - corner.pop(); + if flat.pts.len() > 1 && flat.pts[0].distance(flat.pts[flat.pts.len() - 1]) <= 1e-9 { + flat.pts.pop(); + flat.corner.pop(); } - if let (Some(a), Some(b)) = (prev, first) { - corner[0] = kink(a, b); + if let (Some(a), Some(b)) = (segs.last(), segs.first()) { + flat.corner[0] = kink(a, b); + } + // The closing piece comes from the last source segment even when its endpoint is the + // already-present start point and did not add a flattened point. Keep a tangent (and its + // whole parameter range) for it. + flat.seg_of.truncate(flat.pts.len()); + flat.param.truncate(flat.pts.len()); + if flat.seg_of.len() < flat.pts.len() { + let last = segs.len().saturating_sub(1); + // A closing curve with interior flattened points has already reached a parameter + // before its end (the duplicated start point was not added); the missing piece starts + // where it left off, not at 0. + let start = match last_added { + Some((si, t)) if si == last => t, + _ => 0.0, + }; + flat.seg_of.resize(flat.pts.len(), last); + flat.param.resize(flat.pts.len(), (start, 1.0)); } } - (pts, corner) + flat } -/// The most samples added between two width points. -const MAX_SPAN_SAMPLES: usize = 64; -/// The most samples [`densify`] adds between width points along one piece of a subpath. -const MAX_CURVE_SAMPLES: usize = 4096; - -/// Insert samples where the profile has width points (the two points of a discontinuous point -/// share one sample), and between them where the profile's curve ([`WidthProfile::at`]) bends, so -/// that a straight run follows it to within `tol` with a stroke of half width `half`. `span` maps -/// the subpath onto the profile (see [`outline_spans`]). -fn densify(pts: &[Point], corner: &[bool], closed: bool, profile: &WidthProfile, span: (f64, f64), half: f64, tol: f64) -> (Vec, Vec) { - let total = length(pts, closed); +/// Insert samples where the profile has width points and between them, so its smooth curve is +/// drawn as a smooth outline along straight runs too (the two points of a discontinuous point +/// share one sample). `span` maps the subpath onto the profile (see [`outline_spans`]). +fn densify( + flat: &Flat, + segs: &[PathSeg], + closed: bool, + profile: &WidthProfile, + span: (f64, f64), + density: f64, +) -> (Vec, Vec, Vec) { + // Two samples per profile segment: the segment end plus its midpoint. The outline is fitted + // with cubics through these points, so a smooth width curve needs far fewer samples than it + // did when every pair of samples became a separate cubic. A profile with a strong bend gets + // one more subdivision; a flat profile draws the same straight pieces as before. + const SAMPLES: usize = 2; + const MAX_SAMPLES: usize = 8; + // The gap (in width factor) the straight line between two samples may leave: small enough + // that a sharp peak like the lens' needs one more piece, large enough that a long taper's + // gentle bend does not. + const BEND: f64 = 0.05; + let total = length(&flat.pts, closed); let range = span.1 - span.0; if total <= 1e-12 || range <= 1e-12 { - return (pts.to_vec(), corner.to_vec()); + return split_at(flat, closed, &[], segs); } - let along = |t: f64| (t - span.0) / range * total; // Where the profile's points fall along this piece (a span past 1 wraps round a closed path). - let mut marks: Vec = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).map(along).collect(); - let mut added = 0; - for shift in [0.0, 1.0] { - for w in profile.points.windows(2) { - let (a, b) = (&w[0], &w[1]); - let (t0, t1) = (a.0 + shift, b.0 + shift); - if t1 - t0 <= 1e-7 || t1 <= span.0 || t0 >= span.1 { - continue; - } - // A span whose curve is the straight line between its points (a two-point taper, - // points on one line) needs nothing between them. A cubic off the line is off it at a - // quarter or three quarters of the way. - let off_line = |u: f64| { - let (l, r) = profile.at(a.0 + (b.0 - a.0) * u); - half * (l - (a.1 + (b.1 - a.1) * u)).abs().max((r - (a.2 + (b.2 - a.2) * u)).abs()) - }; - if off_line(0.25) <= tol * 1e-3 && off_line(0.75) <= tol * 1e-3 { - continue; - } - // A monotone cubic span bends by at most 12 times its change in width over the span - // squared, so the chords of `n` equal parts stray at most 1.5 · change / n² from it. - let change = half * (b.1 - a.1).abs().max((b.2 - a.2).abs()); - let n = (1.5 * change / tol).sqrt().ceil(); - let n = if n.is_finite() { n.clamp(1.0, MAX_SPAN_SAMPLES as f64) as usize } else { MAX_SPAN_SAMPLES }; - for k in 1..n { - if added >= MAX_CURVE_SAMPLES { - break; - } - marks.push(along(t0 + (t1 - t0) * k as f64 / n as f64)); - added += 1; - } + let mut ts: Vec = profile.points.iter().flat_map(|p| [p.0, p.0 + 1.0]).collect(); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); + // A flat profile draws the same straight pieces as before: sample only its points. + let constant = profile.points.first().is_some_and(|f| profile.points.iter().all(|p| (p.1 - f.1).abs() <= 1e-12 && (p.2 - f.2).abs() <= 1e-12)); + let cap = (4096 / ts.len().max(1)).max(1); + // A curved path's flattened points already sample the width along the subpath. On a dense + // piece the profile's own points are enough; a straight run has only its ends, so it needs + // the extra samples. This keeps curved, profiled art close to a uniform stroke's size. + let mut marks = Vec::with_capacity(ts.len() * SAMPLES); + for w in ts.windows(2) { + let (a, b) = (w[0], w[1]); + let samples = if constant { + 1 + } else { + // `ts` has the profile both at t and t + 1 for a dash crossing a closed seam; the + // shifted copy has the same shape, so measure its bend on the unshifted segment. + let start = a.rem_euclid(1.0); + let end = start + (b - a); + let want = adaptive_samples(profile, start, end, SAMPLES, MAX_SAMPLES, BEND).min(cap); + // How many of the flattened path's points already fall in this profile segment. + // `density` is measured on the whole subpath, not on this piece, so outlining only + // the piece near the view picks the same samples as outlining the whole subpath. + let existing = (b - a) * density; + if existing >= want as f64 { 1 } else { want } + }; + for k in 0..samples { + marks.push(a + (b - a) * k as f64 / samples as f64); } } - split_at(pts, corner, closed, &marks) + if let Some(&last) = ts.last() { + marks.push(last); + } + let marks: Vec = marks.into_iter().map(|t| (t - span.0) / range * total).collect(); + split_at(flat, closed, &marks, segs) +} + +/// How many pieces one profile segment needs so a cubic fit through their ends keeps the width +/// curve. A straight taper is already straight; a visible bend gets progressively more samples. +fn adaptive_samples(profile: &WidthProfile, t0: f64, t1: f64, base: usize, max: usize, bend: f64) -> usize { + let mut samples = base.max(1); + while samples < max { + // One probe in the middle of each piece: how far the curve leaves the straight line + // between the piece's ends. The more pieces, the closer the line follows the curve, so + // the loop only stops when the pieces it has are fine enough (or at `max`). + let mut dev = 0.0_f64; + for k in 0..samples { + let (a, b) = (k as f64 / samples as f64, (k + 1) as f64 / samples as f64); + let (la, ra) = profile.at(t0 + (t1 - t0) * a); + let (lb, rb) = profile.at(t0 + (t1 - t0) * b); + let (lm, rm) = profile.at(t0 + (t1 - t0) * (a + b) / 2.0); + dev = dev.max((lm - (la + lb) / 2.0).abs()).max((rm - (ra + rb) / 2.0).abs()); + } + if dev <= bend { + break; + } + samples *= 2; + } + samples } /// Length of a flattened subpath (see [`flatten`]). @@ -212,31 +310,70 @@ pub(super) fn length(pts: &[Point], closed: bool) -> f64 { /// A flattened subpath (see [`flatten`]) with points added `marks` along it (distances from its /// start; those on a point or off the subpath are ignored). -pub(super) fn split_at(pts: &[Point], corner: &[bool], closed: bool, marks: &[f64]) -> (Vec, Vec) { +pub(super) fn split_at(flat: &Flat, closed: bool, marks: &[f64], segs: &[PathSeg]) -> (Vec, Vec, Vec) { + let Flat { pts, corner, seg_of, param } = flat; let n = pts.len(); let seg_count = if closed { n } else { n.saturating_sub(1) }; - let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); + // The source's direction at a source parameter. The chord direction is the secant, not the + // tangent: using it for points added inside a chord jogs the normal at every flatten vertex. + let source_at = |si: usize, t: f64| -> Vec2 { segs.get(si).map_or(Vec2::new(1.0, 0.0), |seg| tangent(seg, t)) }; + // A point added inside a flattened piece searches only that piece's source parameter range: + // a looping cubic can pass near itself, and a full-segment nearest would take the other + // branch's tangent. + let source_near = |p: Point, i: usize| -> Vec2 { + let Some(si) = seg_of.get(i).copied() else { return Vec2::new(1.0, 0.0) }; + let Some(seg) = segs.get(si) else { return Vec2::new(1.0, 0.0) }; + let (t0, t1) = param.get(i).copied().unwrap_or((0.0, 1.0)); + if t1 - t0 > 1e-12 { + let sub = seg.subsegment(t0..t1); + tangent(seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t) + } else { + tangent(seg, t0) + } + }; + // At a shared point, average the arriving and leaving directions unless it is a corner. + let dir_at = |i: usize| -> Vec2 { + let incoming = if i == 0 { + if closed { seg_of.last().copied().zip(param.last().copied()) } else { None } + } else { + seg_of.get(i - 1).copied().zip(param.get(i - 1).copied()) + }; + let outgoing = seg_of.get(i).copied().zip(param.get(i).copied()); + let a = incoming.map(|(si, (_, t))| source_at(si, t)); + let b = outgoing.map(|(si, (t, _))| source_at(si, t)); + match (a, b) { + (Some(a), Some(b)) if !corner[i] => { + let sum = a + b; + if sum.hypot() > 1e-9 { unit(sum) } else { b } + } + (_, Some(b)) => b, + (Some(a), None) => a, + (None, None) => Vec2::new(1.0, 0.0), + } + }; + let mut out = (Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len()), Vec::with_capacity(n + marks.len())); let mut acc = 0.0; - // Sorted once, so each segment finds its marks by search, not by a pass over all of them. - let mut marks = marks.to_vec(); - marks.sort_by(f64::total_cmp); for i in 0..seg_count { let (a, b) = (pts[i], pts[(i + 1) % n]); let len = a.distance(b); out.0.push(a); out.1.push(corner[i]); - let from = marks.partition_point(|d| *d <= acc + 1e-9); - let mut inner: Vec = marks.iter().skip(from).copied().take_while(|d| *d < acc + len - 1e-9).collect(); + out.2.push(dir_at(i)); + let mut inner: Vec = marks.iter().copied().filter(|d| *d > acc + 1e-9 && *d < acc + len - 1e-9).collect(); + inner.sort_by(f64::total_cmp); inner.dedup_by(|a, b| (*a - *b).abs() <= 1e-9); for d in inner { - out.0.push(a.lerp(b, (d - acc) / len)); + let p = a.lerp(b, (d - acc) / len); + out.0.push(p); out.1.push(false); + out.2.push(source_near(p, i)); } acc += len; } if !closed && n > 0 { out.0.push(pts[n - 1]); out.1.push(corner[n - 1]); + out.2.push(dir_at(n - 1)); } out } @@ -249,6 +386,8 @@ struct Ctx<'a> { join: LineJoin, miter_limit: f64, tol: f64, + /// The profile has one (left, right) width everywhere. + uniform: bool, } /// A vertex of a flattened subpath: where it is, the directions in and out, the lengths of the @@ -257,14 +396,31 @@ struct Vertex { p: Point, a: Vec2, b: Vec2, + /// The smooth tangent: the source curve's direction at this sample, or the average of its + /// arriving and leaving directions at a smooth join. A smooth point offsets along this + /// normal, not the chord bisector; otherwise the chord normal inside each flattened piece and + /// the bisector at each flatten vertex alternate and the edge is scalloped. + n: Vec2, la: f64, lb: f64, corner: bool, } -impl Ctx<'_> { - fn subpath(&self, out: &mut BezPath, pts: &[Point], corner: &[bool], closed: bool, span: (f64, f64)) { - let (pts, corner) = densify(pts, corner, closed, self.profile, span, self.half, self.tol); +impl<'a> Ctx<'a> { + fn new(width: f64, profile: &'a WidthProfile, st: &StrokeLayer, tol: f64) -> Self { + Self { + half: width / 2.0, + profile, + cap: st.cap, + join: st.join, + miter_limit: st.miter_limit, + tol: tol.max(1e-4), + uniform: profile.points.first().is_some_and(|f| profile.points.iter().all(|p| p.1 == f.1 && p.2 == f.2)), + } + } + + fn subpath(&self, out: &mut BezPath, flat: &Flat, segs: &[PathSeg], closed: bool, span: (f64, f64), density: f64) { + let (pts, corner, dirs) = densify(flat, segs, closed, self.profile, span, density); let n = pts.len(); let seg_count = if closed { n } else { n - 1 }; let seg_dir: Vec = (0..seg_count).map(|i| unit(pts[(i + 1) % n] - pts[i])).collect(); @@ -280,117 +436,398 @@ impl Ctx<'_> { // at a discontinuous point). let width_at = |d: f64| { let t = span.0 + (span.1 - span.0) * d / total; - let (b, a) = self.profile.around(if t > 1.0 { t - 1.0 } else { t }); + // A closed path joins its own start and end: a profile with different widths there + // is a step, not a stretch across the seam. + let (b, a) = if closed && span == (0.0, 1.0) && d <= 1e-12 { + (self.profile.around(1.0).0, self.profile.around(0.0).1) + } else { + self.profile.around(if t > 1.0 { t - 1.0 } else { t }) + }; let side = |(l, r): (f64, f64)| (self.half * l.max(0.0), self.half * r.max(0.0)); (side(b), side(a)) }; - let mut lpts = Vec::with_capacity(n); - let mut rpts = Vec::with_capacity(n); + let mut lpts: Vec<(Point, bool)> = Vec::with_capacity(n); + let mut rpts: Vec<(Point, bool)> = Vec::with_capacity(n); + // Only a butt cap makes the side end at a corner; square and round caps stay tangent to it. + let end_sharp = matches!(self.cap, LineCap::Butt); for (i, &p) in pts.iter().enumerate() { - let (before, after) = width_at(cum[i]); + let ((wl_b, wr_b), (wl_a, wr_a)) = width_at(cum[i]); if !closed && (i == 0 || i == n - 1) { - let nm = left(seg_dir[i.min(seg_count - 1)]); - let (wl, wr) = if i == 0 { after } else { before }; - lpts.push(p + nm * wl); - rpts.push(p - nm * wr); + let nm = left(dirs[i]); + let (wl, wr) = if i == 0 { (wl_a, wr_a) } else { (wl_b, wr_b) }; + lpts.push((p + nm * wl, end_sharp)); + rpts.push((p - nm * wr, end_sharp)); continue; } let ip = if i == 0 { seg_count - 1 } else { i - 1 }; - let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; + let v = Vertex { p, a: seg_dir[ip], b: seg_dir[i], n: dirs[i], la: cum[ip + 1] - cum[ip], lb: cum[i + 1] - cum[i], corner: corner[i] }; // A step: the side goes straight out (or in) from the width before to the one after. - for (k, (wl, wr)) in [before, after].into_iter().enumerate() { - if k == 0 || (wl, wr) != before { - self.join(&mut lpts, &v, wl, 1.0); - self.join(&mut rpts, &v, wr, -1.0); - } + // Both ends of that straight piece are corners: the run before it must not round + // into the step. + let (step_l, step_r) = (wl_a != wl_b, wr_a != wr_b); + self.join(&mut lpts, &v, wl_b, 1.0, step_l); + self.join(&mut rpts, &v, wr_b, -1.0, step_r); + if step_l { + self.join(&mut lpts, &v, wl_a, 1.0, true); + } + if step_r { + self.join(&mut rpts, &v, wr_a, -1.0, true); } } if closed { - polygon(out, lpts.into_iter()); - polygon(out, rpts.into_iter().rev()); + polygon(out, lpts.into_iter(), self.tol); + polygon(out, rpts.into_iter().rev(), self.tol); return; } - let (t0, t1) = (seg_dir[0], seg_dir[seg_count - 1]); + let (t0, t1) = (dirs[0], dirs[n - 1]); let ((wl0, wr0), (wl1, wr1)) = (width_at(0.0).1, width_at(total).0); let mut ring = lpts; // End cap: from the left side around the end to the right side. - cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap); + cap_points(&mut ring, pts[n - 1], left(t1), t1, wl1, wr1, self.cap, self.tol); ring.extend(rpts.into_iter().rev()); // Start cap: from the right side around the start back to the left side. - cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap); - polygon(out, ring.into_iter()); + cap_points(&mut ring, pts[0], -left(t0), -t0, wr0, wl0, self.cap, self.tol); + polygon(out, ring.into_iter(), self.tol); } - /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path: the - /// join on the outer side of a turn, the inner miter point (or a detour through the vertex - /// when that would overshoot a segment) on the inner side. - fn join(&self, pts: &mut Vec, v: &Vertex, w: f64, side: f64) { + /// The offset points at `v` on one side (`side` 1: left, −1: right), `w` from the path. A + /// smooth point follows the vertex normal, the offset of the curve itself; a corner takes the + /// join on its outer side and the inner miter point (or a detour through the vertex when that + /// would overshoot a segment) on its inner side. + /// + /// Each point says whether the outline is sharp there: a path corner, a miter tip, a width + /// step or a butt cap end. Only those break the smooth fitting; a rapid width change makes + /// the offset turn sharply, but it is not a corner and must not be fitted as one. + fn join(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, w: f64, side: f64, step: bool) { let (na, nb) = (left(v.a) * side, left(v.b) * side); let mid = na + nb; // Cosine of half the turn; the miter point is `w / c` out along `mid`. let c = mid.hypot() / 2.0; - let miter = |pts: &mut Vec| pts.push(v.p + mid * (w / (2.0 * c * c))); if w <= 0.0 { - pts.push(v.p); - } else if v.b.dot(na) <= 0.0 { + pts.push((v.p, true)); + return; + } + let miter = if c > 1e-9 { Some(v.p + mid * (w / (2.0 * c * c))) } else { None }; + // The offset of the smooth path itself is at `w` along the path normal. The polyline + // miter (`w / c`) is the offset of the flattened segments, not of the curve: at a tight + // curve it spiked every sample outward and left a scalloped edge. The source curve's + // tangent is the smooth normal; a corner still uses its two chords for the join. + let smooth = v.p + left(v.n) * (w * side); + if v.b.dot(na) <= 0.0 { // Outer side: the path turns away from it. - let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; - match self.join { - _ if excess <= self.tol => miter(pts), - LineJoin::Miter if v.corner && 1.0 / c <= self.miter_limit => miter(pts), - LineJoin::Miter | LineJoin::Bevel if v.corner => pts.extend([v.p + na * w, v.p + nb * w]), - _ => self.arc(pts, v, na, nb, w), + if !v.corner { + // A smooth point has no join: its offset is along the path normal. + pts.push((smooth, step)); + } else { + let excess = if c > 1e-9 { w * (1.0 / c - 1.0) } else { f64::INFINITY }; + match self.join { + _ if excess <= self.tol => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter if c > 1e-9 && 1.0 / c <= self.miter_limit => pts.push((miter.unwrap_or(v.p), true)), + LineJoin::Miter | LineJoin::Bevel => pts.extend([(v.p + na * w, true), (v.p + nb * w, true)]), + _ => self.arc(pts, v, na, nb, w, step), + } } - } else if c > 1e-9 && w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { - miter(pts); + } else if c <= 1e-9 { + // A reversal has no inner miter; go through the vertex. That is a notch in the + // outline, so it stays sharp: fitting a curve through it would loop. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); + } else if !v.corner { + // A smooth point's inner offset follows its normal too. With a constant profile, once + // the half-width reaches the local radius of curvature the offset crosses the centre of + // curvature and comes back as a reversed contour, which the non-zero fill rules into a + // hole. The stroke covers that centre, so cut through it instead: the cut is inside the + // painted region and does not show. (With varying widths the crossing usually marks a + // real caustic; a cut there would show as a slit, so leave it to the offset.) + let turn = 2.0 * c.clamp(-1.0, 1.0).acos(); + let radius = if turn > 1e-9 { 0.5 * (v.la + v.lb) / turn } else { f64::INFINITY }; + if self.uniform && w >= radius { + pts.push((smooth, true)); + pts.push((v.p, true)); + pts.push((smooth, true)); + } else { + pts.push((smooth, step)); + } + } else if w * (1.0 - c * c).sqrt() / c <= v.la.min(v.lb) { + // A corner's inner offset is its miter while that stays inside both segments. + pts.push((miter.unwrap_or(v.p), true)); } else { - pts.extend([v.p + na * w, v.p, v.p + nb * w]); + // The inner offset of a corner cuts through the vertex; keep that notch sharp. + pts.extend([(v.p + na * w, true), (v.p, true), (v.p + nb * w, true)]); } } /// A round join from `na` to `nb` (unit normals) at radius `w` around `v`; a full reversal - /// rounds through the direction of travel. - fn arc(&self, pts: &mut Vec, v: &Vertex, na: Vec2, nb: Vec2, w: f64) { + /// rounds through the direction of travel. `sharp` marks a step at the join's ends. + fn arc(&self, pts: &mut Vec<(Point, bool)>, v: &Vertex, na: Vec2, nb: Vec2, w: f64, sharp: bool) { let phi = if (na + nb).hypot() < 1e-9 { if Vec2::new(-na.y, na.x).dot(v.a) > 0.0 { PI } else { -PI } } else { na.cross(nb).atan2(na.dot(nb)) }; let step = 2.0 * (1.0 - (self.tol / w).min(1.0)).acos(); let steps = ((phi.abs() / step.max(1e-3)).ceil() as usize).clamp(1, 256); for k in 0..=steps { let (s, c) = (phi * k as f64 / steps as f64).sin_cos(); - pts.push(v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w); + pts.push((v.p + Vec2::new(na.x * c - na.y * s, na.x * s + na.y * c) * w, sharp)); } } } /// Cap points between `c + u·r0` and `c − u·r1`, bulging towards `v`. -fn cap_points(ring: &mut Vec, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap) { +#[allow(clippy::too_many_arguments)] +fn cap_points(ring: &mut Vec<(Point, bool)>, c: Point, u: Vec2, v: Vec2, r0: f64, r1: f64, cap: LineCap, tol: f64) { match cap { LineCap::Butt => {} LineCap::Square => { let h = (r0 + r1) / 2.0; - ring.push(c + u * r0 + v * h); - ring.push(c - u * r1 + v * h); + ring.push((c + u * r0 + v * h, true)); + ring.push((c - u * r1 + v * h, true)); } LineCap::Round => { - let steps = 16; + // Enough steps that the cap's facets stay within `tol`, as a round join does. + let r = r0.max(r1).max(1e-9); + let step = 2.0 * (1.0 - (tol / r).min(1.0)).acos(); + let steps = ((PI / step.max(1e-6)).ceil() as usize).clamp(8, 256); for k in 1..steps { - let a = std::f64::consts::PI * k as f64 / steps as f64; + let a = PI * k as f64 / steps as f64; let r = r0 + (r1 - r0) * (k as f64 / steps as f64); - ring.push(c + u * (a.cos() * r) + v * (a.sin() * r)); + ring.push((c + u * (a.cos() * r) + v * (a.sin() * r), false)); } } } } -fn polygon(out: &mut BezPath, mut pts: impl Iterator) { - let Some(first) = pts.next() else { return }; - out.move_to(first); - for p in pts { - out.line_to(p); +/// Append `pts` as a closed contour (a width outline's ring or loop), through a smooth run's +/// points as cubic curves. Sampled as line segments, a curved, wide stroke shows the facets of +/// its offset whenever it is magnified; the cubics keep it smooth. A run whose points are +/// collinear stays a line, and the points marked sharp — caps, miter joins, width steps and path +/// corners — stay sharp. A rapid width change turns the offset sharply without being a corner: +/// marking corners here rather than measuring turns keeps that turn smooth. +fn polygon(out: &mut BezPath, pts: impl Iterator, tol: f64) { + let mut ring: Vec<(Point, bool)> = Vec::new(); + for (p, sharp) in pts { + if !p.x.is_finite() || !p.y.is_finite() { + return; + } + if let Some(last) = ring.last_mut() + && last.0.distance(p) <= 1e-9 + { + last.1 |= sharp; + continue; + } + ring.push((p, sharp)); + } + if ring.len() > 1 + && ring[0].0.distance(ring[ring.len() - 1].0) <= 1e-9 + && let Some(last) = ring.pop() + { + ring[0].1 |= last.1; + } + let n = ring.len(); + if n == 0 { + return; + } + if n < 3 { + out.move_to(ring[0].0); + if n == 2 { + out.line_to(ring[1].0); + } + out.close_path(); + return; + } + // Start at a sharp point when there is one, so no run has to wrap: `smooth_run` starts from + // whichever point is current, and starting anywhere else would bridge over the skipped arc. + match ring.iter().position(|&(_, sharp)| sharp) { + None => { + // A smooth closed loop: fit across the seam, so it doesn't start with a kink. + let pts: Vec = ring.iter().map(|&(p, _)| p).collect(); + out.move_to(pts[0]); + smooth_run(out, &pts, true, tol); + } + Some(first) => { + out.move_to(ring[first].0); + // From each sharp point to the next; the sharp points themselves stay sharp. + let mut i = first; + loop { + let mut j = (i + 1) % n; + while !ring[j].1 { + j = (j + 1) % n; + } + // A contour with a single sharp point comes back to it: the run is the whole + // loop, fitted non-cyclically so that point stays sharp. + let steps = if j == i { n } else { (j + n - i) % n }; + if steps == 1 { + out.line_to(ring[j].0); + } else { + let run: Vec = (0..=steps).map(|k| ring[(i + k) % n].0).collect(); + smooth_run(out, &run, false, tol); + } + if j == first { + break; + } + i = j; + } + } } out.close_path(); } +/// The derivative of the run at each point, in points per point of chord length. Each coordinate +/// is a shape-preserving cubic Hermite (Fritsch–Carlson): between two points it stays within their +/// coordinate range, so a cubic through a fast width pinch cannot bulge past the pinch and cross +/// the other side, and it has a flat slope at a local extremum. A Catmull–Rom tangent (the secant +/// across the neighbours) does neither: it overshoots a V and, with the uneven sample spacing of a +/// flattened path, leaves a scalloped edge. +fn tangents(run: &[Point], cyclic: bool) -> Vec { + let n = run.len(); + let segs = if cyclic { n } else { n.saturating_sub(1) }; + let mut h = vec![0.0; segs]; + for (i, hi) in h.iter_mut().enumerate() { + *hi = run[i].distance(run[(i + 1) % n]); + } + let slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 { + return 0.0; + } + let (w0, w1) = (2.0 * h1 + h0, h1 + 2.0 * h0); + let m = (w0 + w1) / (w0 / d0 + w1 / d1); + if m.is_finite() { m } else { 0.0 } + }; + // The one-sided slope of a run's end uses its two end secants, instead of only the last one. + // A coarse sample then still leaves the end of a profile curve with the right slope. + let end_slope = |d0: f64, d1: f64, h0: f64, h1: f64| { + if d0 * d1 <= 0.0 || h0 + h1 <= 1e-12 { + return 0.0; + } + let m = ((2.0 * h0 + h1) * d0 - h0 * d1) / (h0 + h1); + if m.is_finite() && m * d0 > 0.0 { + let cap = 3.0 * d0.abs(); + m.clamp(-cap, cap) + } else { + 0.0 + } + }; + let delta = |i: usize| -> Vec2 { + let hi = h[i % segs]; + if hi > 1e-12 { (run[(i + 1) % n] - run[i % n]) / hi } else { Vec2::ZERO } + }; + let mut out = vec![Vec2::ZERO; n]; + for (i, m) in out.iter_mut().enumerate() { + let (d0, d1) = (delta((i + n - 1) % n), delta(i % segs)); + let (h0, h1) = (h[(i + n - 1) % segs], h[i % segs]); + if h0 <= 1e-12 || h1 <= 1e-12 { + *m = if h1 > 1e-12 { d1 } else { d0 }; + } else if cyclic || (i > 0 && i + 1 < n) { + *m = Vec2::new(slope(d0.x, d1.x, h0, h1), slope(d0.y, d1.y, h0, h1)); + } else if i == 0 { + *m = if n >= 3 { + let (a, b) = (delta(0), delta(1)); + Vec2::new(end_slope(a.x, b.x, h[0], h[1]), end_slope(a.y, b.y, h[0], h[1])) + } else { + d1 + }; + } else { + *m = if n >= 3 { + let (a, b) = (delta(n - 2), delta(n - 3)); + Vec2::new(end_slope(a.x, b.x, h[n - 2], h[n - 3]), end_slope(a.y, b.y, h[n - 2], h[n - 3])) + } else { + d0 + }; + } + // A shape-preserving slope is flat in a coordinate at that coordinate's local extremum. + // Where both are extrema at one sample (a loop or a pinch in the sampled edge) the flat + // tangent would make a line and a kink; the secant across the sample keeps the curve C1 + // there, and the extremum itself is what trims the loop later. + if m.hypot() <= 1e-12 { + let prev = if cyclic || i > 0 { run[(i + n - 1) % n] } else { run[i] }; + let next = if cyclic || i + 1 < n { run[(i + 1) % n] } else { run[i] }; + let sec = next - prev; + if sec.hypot() > 1e-12 { + *m = sec.normalize(); + } + } + } + out +} + +/// Append a run of points as a fitted chain of cubics (or one line when they are collinear). +/// +/// A cubic through every flattened point, as this used to emit, keeps the outline smooth but puts +/// three coordinates per point into the file; a small, thin stroke then exports several times the +/// path data of the same stroke without a profile. Fit a chain within the outline tolerance +/// instead: the result is still G1 continuous and stays within `tol` of the sampled edge, but a +/// smooth side is a few cubics rather than one per flatten step. Profile bends that need finer +/// detail produce more cubics; straight runs stay lines. +fn smooth_run(out: &mut BezPath, run: &[Point], cyclic: bool, tol: f64) { + let n = run.len(); + if n < 2 { + return; + } + if !cyclic && is_straight(run, tol) { + out.line_to(run[n - 1]); + return; + } + let tans = tangents(run, cyclic); + let tol = tol.max(1e-6); + // A short run is one or two profile features, not flattened path detail. Fitting it loosely + // enough to save path data can let a handle cross the narrow side of a V; keep the + // shape-preserving per-point cubics there. + let segs = if cyclic { n } else { n - 1 }; + if n <= 3 { + for i in 0..segs { + let j = (i + 1) % n; + let h = run[i].distance(run[j]); + let (m0, m1) = (tans[i] * (h / 3.0), tans[j] * (h / 3.0)); + if m0.hypot() <= 1e-12 || m1.hypot() <= 1e-12 { + out.line_to(run[j]); + } else { + out.curve_to(run[i] + m0, run[j] - m1, run[j]); + } + } + return; + } + let unit_or = |v: Vec2, fallback: Vec2| { + let len = v.hypot(); + if len > 1e-12 { + v / len + } else { + let len = fallback.hypot(); + if len > 1e-12 { fallback / len } else { Vec2::new(1.0, 0.0) } + } + }; + let t0 = unit_or(tans[0], run[1] - run[0]); + let (pts, t0, t1) = if cyclic { + // Fit the seam too: the fit starts and arrives with the same tangent, so closing the + // contour adds no kink. + let mut pts = Vec::with_capacity(n + 1); + pts.extend_from_slice(run); + pts.push(run[0]); + (pts, t0, t0) + } else { + (run.to_vec(), t0, unit_or(tans[n - 1], run[n - 1] - run[n - 2])) + }; + // Fit tighter than the flattening tolerance: the fit's error is the whole outline's error, + // and a least-squares fit may sit on one side of the sampled edge, which would otherwise + // shift a profile's area visibly. The points lie on the outline's own curve, so the fit follows + // their curve between them rather than the chords through them. + let cubics = fit_cubics_through(&pts, t0, t1, tol * 0.1); + if cubics.is_empty() { + out.line_to(run[n - 1]); + return; + } + for c in cubics { + out.curve_to(c.p1, c.p2, c.p3); + } +} + +/// Are the run's points within the flattening tolerance of its chord? +fn is_straight(run: &[Point], tol: f64) -> bool { + let (a, b) = (run[0], run[run.len() - 1]); + let d = b - a; + let l = d.hypot(); + if l <= 1e-12 { + return false; + } + run.iter().all(|p| (d.cross(*p - a) / l).abs() <= tol.max(1e-6) * 0.25) +} + #[cfg(test)] mod tests { use super::*; @@ -423,13 +860,12 @@ mod tests { assert!((area(&width_outline(&line(), 10.0, &p, &capped(LineCap::Square), 0.01)) - 1100.0).abs() < 1e-6); } - /// The Lens outline swells on its curve, and a profile with one side at zero paints only the other side. + /// The lens eases up to full width and back down (a parabolic bump averaging two thirds of + /// the width); a one-sided profile keeps its side at zero and stays on the other. #[test] - fn lens_profile_swells_smoothly_and_one_sided_profiles_stay_on_their_side() { - // Each half of the lens rises on a cubic from 0 to full width, flat at the middle: it - // covers 7/12 of the full-width band (a diamond would cover half). + fn lens_profile_is_a_smooth_bump_and_one_sided_profiles_stay_on_their_side() { let a = area(&width_outline(&line(), 10.0, &WidthProfile::lens(), &capped(LineCap::Butt), 0.01)); - assert!((a - 1000.0 * 7.0 / 12.0).abs() < 0.5, "{a}"); + assert!((a - 2000.0 / 3.0).abs() < 0.1, "{a}"); let one = WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 1.0, 0.0)] }; let o = width_outline(&line(), 10.0, &one, &capped(LineCap::Butt), 0.01); assert!((area(&o) - 500.0).abs() < 1e-6); @@ -453,41 +889,103 @@ mod tests { assert!(a.is_finite() && (a - 3000.0).abs() < 150.0, "{a}"); } - /// #5714: between width points a straight run follows the profile's smooth curve, not a - /// straight line from one width to the next. #[test] - fn a_straight_run_follows_the_curve_between_width_points() { - // 5 pt either side at the ends, 15 pt at the middle: a quarter of the way along the curve - // is at 2.25 × 5 = 11.25 pt (a straight ramp would be at 10 pt). - let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 3.0, 3.0), (1.0, 1.0, 1.0)] }; - let o = width_outline(&line(), 10.0, &p, &capped(LineCap::Butt), 0.01); - for y in [-11.0, 11.0] { - assert!(o.contains(kurbo::Point::new(25.0, y)), "inside at y {y}"); - } - for y in [-11.5, 11.5] { - assert!(!o.contains(kurbo::Point::new(25.0, y)), "outside at y {y}"); - } - // Round the widest point the side is flat: no corner sticks out above 15 pt. - let bb = o.bounding_box(); - assert!((bb.y0 + 15.0).abs() < 1e-6 && (bb.y1 - 15.0).abs() < 1e-6, "{bb:?}"); + fn a_closed_path_steps_where_its_profile_ends_differ() { + let mut sq = BezPath::new(); + sq.move_to((0.0, 0.0)); + sq.line_to((100.0, 0.0)); + sq.line_to((100.0, 100.0)); + sq.line_to((0.0, 100.0)); + sq.close_path(); + // 5 pt at the seam's start, 10 pt at its end: the ring must step between them, not + // stretch the last width point round the corner. + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 2.0, 2.0)] }; + let o = width_outline(&sq, 10.0, &p, &capped(LineCap::Butt), 0.01); + let at = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-9 && (p.y - y).abs() < 1e-9; + let step = o.elements().windows(2).any(|w| match (w[0], w[1]) { + (PathEl::MoveTo(a), PathEl::LineTo(b)) | (PathEl::LineTo(a), PathEl::LineTo(b)) => { + at(a, -10.0, -10.0) && at(b, -5.0, -5.0) || at(a, -5.0, -5.0) && at(b, -10.0, -10.0) + } + _ => false, + }); + assert!(step, "{o:?}"); } - /// A taper is a straight ramp: its outline gets no samples between the width points. #[test] - fn a_straight_taper_gets_no_samples_between_its_points() { - let o = width_outline(&line(), 10.0, &WidthProfile::taper_end(), &capped(LineCap::Butt), 0.01); - assert_eq!(o.elements().len(), 5, "{:?}", o.elements()); + fn added_samples_follow_the_curve_not_the_flattened_chord() { + // A cubic with a tight S: its chords are far from its tangents. A sample inserted inside a + // chord must take the curve's direction there; the chord's direction is what made a wide + // profile scallop at every flatten vertex. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((0.0, 120.0), (120.0, -120.0), (120.0, 0.0)); + let segs = segments(b.elements()); + let flat = flatten(&segs, false, 2.0); + assert!(flat.pts.len() >= 3); + let mut marks = vec![]; + let mut acc = 0.0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + marks.push(acc + len / 2.0); + acc += len; + } + let (all, _, dirs) = split_at(&flat, false, &marks, &segs); + assert!(all.len() > flat.pts.len()); + let seg = segs[0]; + for (p, d) in all.iter().zip(&dirs) { + let want = tangent(&seg, seg.nearest(*p, 1e-9).t); + assert!(d.dot(want) > 0.999, "{d:?} vs {want:?} at {p:?}"); + } } - /// A profile read from a file may have thousands of points and absurd widths: the samples added - /// between them stay bounded and the outline finite. #[test] - fn samples_between_width_points_are_capped() { - let points = (0..=10_000).map(|i| (i as f64 / 10_000.0, if i % 2 == 0 { 0.0 } else { 1e12 }, 1.0)).collect(); - let o = width_outline(&line(), 10.0, &WidthProfile { points }, &capped(LineCap::Butt), 0.01); - let n = o.elements().len(); - assert!(n < 2 * (2 * 10_001 + MAX_CURVE_SAMPLES) + 64, "{n}"); - assert!(o.bounding_box().area().is_finite()); + fn a_wiggly_profile_on_a_curve_fits_without_kinks() { + // A rapid width change turns the offset sharply; that is not a path corner, so the + // outline must stay tangent-continuous through it (the old turn-angle test did not). + let c = kurbo::Circle::new((0.0, 0.0), 50.0).to_path(1e-3); + let p = WidthProfile { + points: vec![(0.0, 1.0, 1.0), (0.15, 3.0, 0.4), (0.3, 0.2, 2.8), (0.5, 2.5, 0.3), (0.7, 0.4, 2.2), (0.85, 2.0, 0.5), (1.0, 1.0, 1.0)], + }; + let o = width_outline(&c, 10.0, &p, &capped(LineCap::Butt), 0.01); + let mut cursor = None; + let mut prev: Option = None; + let mut kinks = 0; + let mut check = |a: Vec2, b: Vec2| { + let (la, lb) = (a.hypot(), b.hypot()); + if la > 1e-9 && lb > 1e-9 && (a.dot(b) <= 0.0 || a.cross(b).abs() / (la * lb) > 1e-6) { + kinks += 1; + } + }; + for el in o.elements() { + match el { + PathEl::MoveTo(p) => { + cursor = Some(*p); + prev = None; + } + PathEl::LineTo(p) => { + if let Some(q) = cursor { + let d = *p - q; + if let Some(a) = prev { + check(a, d); + } + prev = Some(d); + } + cursor = Some(*p); + } + PathEl::CurveTo(a, b, p) => { + if let Some(q) = cursor { + let d = if a.distance(q) > 1e-9 { *a - q } else { *b - q }; + if let Some(prev) = prev { + check(prev, d); + } + prev = Some(if p.distance(*b) > 1e-9 { *p - *b } else { *p - *a }); + } + cursor = Some(*p); + } + PathEl::QuadTo(_, _) | PathEl::ClosePath => {} + } + } + assert_eq!(kinks, 0, "{o:?}"); } #[test] @@ -512,4 +1010,108 @@ mod tests { let want = 2.0 * std::f64::consts::PI * 50.0 * 10.0; assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); } + + #[test] + fn a_uniform_circle_narrower_than_its_stroke_has_no_hole() { + // Half-width 15 on a radius-5 circle: the inner offset crosses the centre. The constant + // stroke still covers the centre, so the outline must not leave a hole there. + let c = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let o = width_outline(&c, 30.0, &p, &capped(LineCap::Butt), 0.01); + assert!(o.contains(Point::new(0.0, 0.0)), "{o:?}"); + } + + #[test] + fn a_quick_width_change_does_not_overshoot_its_samples() { + // Width falls to a point and comes back, unevenly on either side: the fitted edge must not + // dip past the point (that crossed the other edge and left a scalloped neck). + let mut run = vec![Point::new(0.0, 0.0), Point::new(10.0, -1.0), Point::new(20.0, -0.3)]; + let (mut a, mut b) = (BezPath::new(), BezPath::new()); + a.move_to(run[0]); + b.move_to(run[0]); + smooth_run(&mut a, &run, false, 0.0); + // Reverse the same points: the fit must stay inside the V from either direction too. + run.reverse(); + smooth_run(&mut b, &run, false, 0.0); + for path in [a, b] { + let mut start = Point::ZERO; + for el in path.elements() { + match el { + PathEl::MoveTo(p) => start = *p, + PathEl::CurveTo(c1, c2, p) => { + for c in [c1, c2] { + assert!(c.y >= -1.0 - 1e-9, "{c:?} in {path:?}"); + assert!(c.y <= start.y.max(p.y) + 1e-9, "{c:?} in {path:?}"); + } + start = *p; + } + _ => {} + } + } + } + } + + #[test] + fn added_samples_stay_on_their_flattened_branch() { + // This cubic loops back near itself. At a coarse tolerance a chord midpoint can be closer + // to the other branch; a full-segment nearest would then take that branch's tangent and + // spike the offset. Each inserted sample must use the parameter range of its own piece. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((150.0, 100.0), (-50.0, 100.0), (100.0, 0.0)); + let segs = segments(b.elements()); + let seg = segs[0]; + let flat = flatten(&segs, false, 2.0); + let mut acc = 0.0; + let mut divergent = 0; + for i in 0..flat.pts.len() - 1 { + let len = flat.pts[i].distance(flat.pts[i + 1]); + if len <= 1e-12 { + continue; + } + let (t0, t1) = flat.param[i]; + let sub = seg.subsegment(t0..t1); + for k in 1..16 { + let (out, _, dirs) = split_at(&flat, false, &[acc + len * k as f64 / 16.0], &segs); + assert!(out.len() >= i + 2, "no sample inserted in piece {i}"); + let p = out[i + 1]; + let want = tangent(&seg, t0 + (t1 - t0) * sub.nearest(p, 1e-9).t); + assert!(dirs[i + 1].dot(want) > 0.999, "piece {i}, k {k}: {:?} vs {want:?}", dirs[i + 1]); + let full = tangent(&seg, seg.nearest(p, 1e-9).t); + if full.dot(want) < 0.9 { + divergent += 1; + } + } + acc += len; + } + assert!(divergent > 0, "the fixture did not cross the other branch"); + } + + #[test] + fn a_coarse_wide_circle_keeps_its_offset() { + // A wide stroke flattened coarsely: offsetting each flattened segment by its miter + // (`w / cos(θ/2)`) scalloped the circle outward at every sample. Smooth points follow the + // curve's normal instead, so the ring is the annulus between radii 10 and 30. + let c = kurbo::Circle::new((0.0, 0.0), 20.0).to_path(0.5); + let p = WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)] }; + let a = area(&width_outline(&c, 20.0, &p, &capped(LineCap::Butt), 0.5)); + let want = std::f64::consts::PI * (30.0 * 30.0 - 10.0 * 10.0); + assert!((a - want).abs() / want < 0.01, "{a} vs {want}"); + } + + #[test] + fn profiled_outlines_stay_compact() { + // A smooth profile is fitted with cubics, so it must not turn every profile sample into + // exported path data. Compare it with the same curved path's uniform outline. + let circle = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(0.01); + let count = |points| { + let p = WidthProfile { points }; + width_outline(&circle, 5.0, &p, &capped(LineCap::Butt), 0.01).elements().len() + }; + let uniform = count(vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + let lens = count(WidthProfile::lens().points); + let wave = count(vec![(0.0, 0.3, 0.3), (0.25, 1.0, 1.0), (0.5, 0.3, 0.3), (0.75, 1.0, 1.0), (1.0, 0.3, 0.3)]); + assert!(lens <= uniform * 3 / 2, "lens {lens} vs uniform {uniform}"); + assert!(wave <= uniform * 3 / 2, "wave {wave} vs uniform {uniform}"); + } } diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index 166c88725..d3394d148 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -73,14 +73,13 @@ fn arrowheads_are_part_of_the_outline() { assert_eq!(path_of(&n).subpaths.len(), 1, "line and head are one shape"); } -/// Outline Stroke of a Lens-profile line covers 7/12 of the full-width rectangle. +/// Outline Stroke of a Lens-profile line covers 2/3 of the full-width rectangle. #[test] -fn a_lens_profile_outlines_to_seven_twelfths_of_the_rectangle() { +fn a_lens_profile_outlines_to_two_thirds_of_the_rectangle() { let mut s = session(); line(&mut s, json!({"weight": 10, "profile": "lens"})); let n = outline(&mut s); - // Each half of the lens swells on a cubic, flat at the middle (#5714). - assert!(near(area(&n), 7.0 / 12.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); + assert!(near(area(&n), 2.0 / 3.0 * 10.0 * 100.0, 2.0), "{}", area(&n)); } #[test] diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 4c837c300..6aa324aa9 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -221,9 +221,9 @@ fn new_width_point_adjust_adjoining_uses_sampled_widths() { let (mut s, id) = line_session(); let original = vec![(0.0, 9.0, 9.0), (0.25, 1.0, 0.0), (0.75, 3.0, 0.0), (1.0, 7.0, 7.0)]; s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": original})).unwrap(); - // At t=0.5 the old left side is where the profile's curve is there (#5714) and the right - // side is 0pt. Indexed editing of that sampled point is the existing convention: scale the - // nonzero side, add from zero. + // At t=0.5 the old left side is where the profile's curve is there and the right side is + // 0pt. Indexed editing of that sampled point is the existing convention: scale the nonzero + // side, add from zero. let sampled = vectorcraft_doc::WidthProfile { points: original }.at(0.5).0; let index = if indexed { Some(set(&mut s, json!({"id": id.0, "t": 0.5, "left": sampled * 5.0, "right": 0}))) } else { None }; set(&mut s, json!({"id": id.0, "index": index, "t": 0.5, "left": 20, "right": 5, "adjustAdjoining": true})); diff --git a/crates/pathops/src/fit.rs b/crates/pathops/src/fit.rs index 6b1f4eb0c..0411a71f4 100644 --- a/crates/pathops/src/fit.rs +++ b/crates/pathops/src/fit.rs @@ -17,6 +17,9 @@ const MAX_BULGE_SAMPLES: f64 = 1024.0; /// About how many points of a long piece its first fit uses. const COARSE_POINTS: usize = 16; +/// Most times [`fit_through_rec`] splits a run of points, which bounds its recursion. +const MAX_SPLITS: usize = 40; + /// Unit vector or `None` if (nearly) zero. pub(crate) fn unit(v: Vec2) -> Option { let l = v.hypot(); @@ -37,7 +40,7 @@ pub(crate) fn end_tangent(c: &CubicBez) -> Vec2 { /// /// `t0` is the unit tangent leaving `pts[0]`; `t1` is the unit tangent arriving at the last point /// (forward direction). Consecutive output cubics are G1 continuous. -pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { +pub fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec { let pts = dedup(pts); if pts.len() < 2 { return Vec::new(); @@ -48,6 +51,43 @@ pub(crate) fn fit_cubics(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> Vec Vec { + let pts = dedup(pts); + let mut out = Vec::new(); + if pts.len() < 2 { + return out; + } + fit_through_rec(&pts, t0, t1, tol.max(1e-9), &mut out, 0); + out +} + +/// Fits all of `pts` with one cubic, splitting at its worst point until each piece is within `tol` +/// of its points (see [`fit_cubics_through`]). `depth` bounds the recursion on hostile points. +fn fit_through_rec(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64, out: &mut Vec, depth: usize) { + let n = pts.len(); + if n == 2 { + let d = pts[0].distance(pts[1]) / 3.0; + out.push(CubicBez::new(pts[0], pts[0] + t0 * d, pts[1] - t1 * d, pts[1])); + return; + } + let (curve, err, split) = fit_single_tol(pts, t0, t1, tol); + if err <= tol || depth >= MAX_SPLITS { + out.push(curve); + return; + } + let split = split.clamp(1, n - 2); + let tc = unit(pts[split + 1] - pts[split - 1]).unwrap_or(t0); + fit_through_rec(&pts[..=split], t0, tc, tol, out, depth + 1); + fit_through_rec(&pts[split..], tc, t1, tol, out, depth + 1); +} + /// The curves of `pieces`, which follow each other along `pts` from its first point, leaving it /// along `t0`. Each curve takes up to [`MAX_JOINS`] of the pieces after its first one, as long as /// the fit of them together is within `tol`. @@ -152,6 +192,32 @@ pub(crate) fn fit_single(pts: &[Point], t0: Vec2, t1: Vec2) -> (CubicBez, f64, u fit_single_from(pts, chord_params(pts), t0, t1) } +/// [`fit_single`] that stops reparameterising once the curve is within `tol` of its points: a +/// curve already that close needs no better fit, and each Newton round reads every point. +fn fit_single_tol(pts: &[Point], t0: Vec2, t1: Vec2, tol: f64) -> (CubicBez, f64, usize) { + let mut u = chord_params(pts); + let mut best = generate(pts, &u, t0, t1); + let (mut best_err, mut best_split) = max_error(pts, &best, &u); + for _ in 0..MAX_REPARAM { + if best_err <= tol { + break; + } + for (i, ui) in u.iter_mut().enumerate() { + *ui = newton(&best, pts[i], *ui); + } + let c = generate(pts, &u, t0, t1); + let (e, s) = max_error(pts, &c, &u); + if e < best_err { + best = c; + best_err = e; + best_split = s; + } else { + break; + } + } + (best, best_err, best_split) +} + /// [`fit_single`] starting from the parameters `u` (one per point, 0 to 1) instead of the /// chord-length ones. pub(crate) fn fit_single_from(pts: &[Point], u: Vec, t0: Vec2, t1: Vec2) -> (CubicBez, f64, usize) { @@ -334,6 +400,25 @@ mod tests { assert!(out[0].p1.distance(c.p1) < 1.0, "{:?}", out[0]); } + /// A curve's samples are followed between the points, not chopped to the chords through + /// them: a smooth outline fitted from coarse samples must keep its bow (an outline's area + /// depends on it), unlike a polyline's samples. + #[test] + fn through_fit_bows_between_coarse_points() { + // The parabola y = 4t(1 - t) over x = 100t, sampled at 8 points. + let node = |t: f64| Point::new(100.0 * t, 4.0 * t * (1.0 - t)); + let pts: Vec = (0..=8).map(|i| node(i as f64 / 8.0)).collect(); + let (t0, t1) = (Vec2::new(1.0, 0.04).normalize(), Vec2::new(1.0, -0.04).normalize()); + let out = fit_cubics_through(&pts, t0, t1, 0.001); + for c in &out { + for k in 0..=100 { + let q = c.eval(k as f64 / 100.0); + let want = 4.0 * (q.x / 100.0) * (1.0 - q.x / 100.0); + assert!((q.y - want).abs() < 0.01, "{:?} at {q:?} wants {want}", c); + } + } + } + #[test] fn splits_when_needed() { // A zig-zag cannot be fitted with one cubic. diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index b7af34c89..291c95678 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -26,6 +26,7 @@ pub use edit::{ remove_anchor, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, smooth_options, split_into_grid, }; +pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; pub use planar::{ diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index 8a6567f39..dc16e6430 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -92,6 +92,11 @@ fn a_long_profile_stroke_keeps_its_widths_when_outlined_near_the_view() { let near = render(&mut renderer, &d, at); assert_eq!(renderer.strokes.values().any(|e| e.crop.is_some()), cropped, "{name}: crop choice"); let full = whole(&d, at); + // The cropped outline fits cubics through the same samples, but its fit starts at the + // crop rather than at the subpath's end, so a cubic may put its control points + // differently (the same curve). The rasteriser then flattens it into a slightly + // different polygon, which shows as one level on an anti-aliased edge pixel. Anything + // more would be a wrong width. let mismatched: Vec<_> = near .pixels .as_chunks::<4>() @@ -99,7 +104,7 @@ fn a_long_profile_stroke_keeps_its_widths_when_outlined_near_the_view() { .iter() .zip(full.pixels.as_chunks::<4>().0.iter()) .enumerate() - .filter(|(_, (a, b))| a != b) + .filter(|(_, (a, b))| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 1)) .take(8) .map(|(i, (a, b))| (i % SIZE as usize, i / SIZE as usize, a.to_vec(), b.to_vec())) .collect(); diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index f8b686cca..4c5b972f1 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -247,6 +247,8 @@ fn new_width_point_profile_and_compound_target() { assert!(d.fields.get("index").is_none_or(Value::is_null)); let actual_t = d.f64("t", -1.0); assert!((actual_t - 0.25).abs() < 1e-6, "compound={compound} pointer={quarter:?} actual_t={actual_t} want=0.25"); + // The two-point profile is linear: at a quarter its sides are 1.25 and 0.75 of + // 1..2 and 0.5..1.5, on a 10pt stroke (5pt half). assert!((d.f64("side1", 0.0) - 6.25).abs() < 1e-6); assert!((d.f64("side2", 0.0) - 3.75).abs() < 1e-6); assert!(!d.bool("linked")); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 18d50447f..dfc6c06f3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1315,7 +1315,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Cmd/Ctrl-click on the Gradient panel's Gradient Fill box or on the Tools panel's Gradient button resets the gradient of the active Fill or Stroke to the linear White, Black gradient, as one undo step ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. + - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2183,6 +2183,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-22 | minor | G2: Effect › Sketch › Conté Crayon (Foreground Level, Background Level, Texture, Scaling, Relief, Light Direction, Invert; a black crayon in the dark areas and a white one in the light areas on textured mid-grey paper; ranges and defaults unverified VectorCraft choices); measured Photoshop-style filters 57/57, the Effect Gallery remains (4–6 h); area score unchanged (49%, estimated). | | 2026-10-22 | minor | File formats: Affinity import gains master pages, tables, paragraph formats, text scale, shadows, glows, outlines (also on stroked shapes), overlays, underlines, strikethrough and editable embedded documents, strokes styled None left out, CMYK pixel layers through the document's CMYK profile, text placed as Affinity places it (AF.5, from storytold/designcraft#291); synthetic, corpus and local-thumbnail tests; score and hours unchanged (estimated). Hostile files stay bounded: one budget for the whole read (layers, pixels, characters, table cells, embedded documents included), a work budget for overlays, capped master page copies, objects past `MAX_COORD` left out; the import fuzzer and limit tests cover tables, paragraphs, effects, overlays, master pages, CMYK pixels and embedded documents. | | 2026-10-22 | minor | Recolor Artwork Edit chips scroll within the available screen height (#3416); small palettes retain their tab height; scores and estimates unchanged. | +| 2026-10-21 | minor | Width-profile outlines offset samples added inside a flattened chord along the source curve's exact tangent, so a zoomed outline no longer jogs at flatten vertices; a regression test covers added samples. Scores and estimates unchanged. | | 2026-10-22 | minor | Font pickers list recently applied families first (#3515), using the existing recent-font limit; search, filters, previews and keyboard selection share the same rows. Scores and estimates unchanged. | | 2026-10-21 | minor | Plug-ins: filters keep data with the document (`documentData`), as its foreign data, so the native file needs no section of its own (G17); engine and unit regressions. Scores and hours unchanged. | | 2026-10-21 | minor | Print: PDF/X-1a and PDF/X-3 flattening in a CMYK document rasterizes as ink amounts, so CMYK colours under an image with see-through pixels keep their numbers, K included, instead of going through RGB (#2160); own-fixture test; scores and hours unchanged (estimated) | @@ -2199,6 +2200,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-21 | minor | Snap to Glyph (#3124) removed from View navigation missing lists and menu stubs; scores and hours unchanged at this rounding | | 2026-10-21 | minor | Type core: System Layout (Character panel menu, whole document, off by default) is done; scores and hours unchanged | | 2026-10-22 | minor | Ruby (ふりがな) for live text: `type.ruby` sets/removes a reading over a byte range, above or below (right of the column in vertical type), aligned, sized and overhanging or squeezed; saved natively, laid out with line growth, drawn on the canvas and in SVG/PDF (outlines where ruby is present); scores and hours unchanged | +| 2026-10-23 | minor | Width-profile outlines sample adaptively: two samples per profile segment, refined where the width bends, and only where the flattened path does not already sample the width. The sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt by default) instead of one cubic per flatten step. On the reviewer's 1,500-ellipse fixture (20–200 pt ellipses, 3–12 pt weights) the PDF falls to 3.59 MB and the SVG to 6.79 MB (reported main baselines 4.48 MB and 9.30 MB, about 0.80× and 0.73×), and `profiled_outlines_stay_compact` guards the path-element count. Scores and estimates unchanged. | | 2026-10-21 | minor | 3D: original Standard, Diffuse, Top Left and Right lighting presets; command access, effective-setting recognition and preview/history; scores and estimates unchanged | | 2026-10-21 | minor | Properties: one selected clip group has Edit Clipping Path and Edit Contents at the top of the panel (public doc cited) (G1). Scores and hours unchanged. | | 2026-10-21 | minor | Print: the Print dialog's Media list carries the Japanese papers — JIS B4 (257 × 364 mm), JIS B5 (182 × 257 mm) and JIS B6 next to the ISO B4/B5, which keep their ISO 216 sizes, plus はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判; the JSON id or the dialog label names a paper, any case and spacing. Print score and hours unchanged. | @@ -2212,6 +2214,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-10-19 | minor | Plug-ins: parameters with labels, units, help, groups and conditions in their dialogs, `string` and `numberList` types, up to 256 per plug-in (G17); manifest and kittest dialog regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Plug-ins: exporter plug-ins add write-only file formats to Export As and `document.export` (G17); engine, ABI and headless Export As regressions. Scores and hours unchanged. | | 2026-10-19 | minor | Libraries panel: the list fills the panel and scrolls (also while a drag nears its edges); items drag before or after others of their kind and into or out of groups, and groups drag by their headers (`library.moveItem` `before`/`after`, `library.moveGroup`). Scores and estimates unchanged. | +| 2026-10-19 | minor | Width profiles run as a smooth C1 curve between their points (a monotone cubic Hermite, Fritsch-Carlson) instead of straight lines, sampled along the path so the outline follows it on straight runs; steps between coincident points still step. Regression tests cover easing, monotonicity, locality and steps. Scores and estimates unchanged. | | 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | | 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | | 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. |