diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2a39d50010..c5d13cd0fa 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2626,6 +2626,83 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal } } +/// How far from y = 0 the outlines under `nodes` reach where they cross the vertical line at `x`. +fn reach_at(nodes: &[Node], x: f64) -> f64 { + let mut reach = 0.0f64; + for n in nodes { + n.walk(&mut |c| { + for sp in c.path_data().into_iter().flat_map(|p| &p.subpaths) { + for i in 0..sp.segment_count() { + let s = sp.segment(i); + let (a, b, c, d) = (s.p0.x, s.p1.x, s.p2.x, s.p3.x); + let roots = kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (c - 2.0 * b + a), d - 3.0 * c + 3.0 * b - a); + for t in roots.into_iter().filter(|t| (-1e-9..=1.0 + 1e-9).contains(t)) { + reach = reach.max(kurbo::ParamCurve::eval(&s, t.clamp(0.0, 1.0)).y.abs()); + } + } + } + }); + } + reach +} + +/// A pattern tile whose scale follows the pen is as tall as the scale at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn pattern_brush_scale_from_the_pen_keeps_a_short_peak() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(300.0)); + // One 10 × 4 pt tile on a 10 pt path: 100 % (2 pt either side) but for a peak at 2.2 pt, where + // the scale reaches 300 % (6 pt either side). + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&doc, &b, &line(0.0, 0.0, 10.0, 0.0), &peak); + // At the peak 300 %, half way up it 200 %, and 100 % on either side of it. + for (x, want) in [(2.2, 6.0), (2.15, 4.0), (2.25, 4.0), (1.0, 2.0), (2.05, 2.0), (2.4, 2.0), (8.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// An art brush whose width follows the pen is as wide as the pen gives at a short peak of the +/// pressure, even where the peak falls between the positions the bent outline is checked at. +#[test] +fn art_brush_width_from_the_pen_keeps_a_short_peak() { + let mut b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut b.kind { + (a.width, a.width_mode, a.width_max) = (100.0, Some(Variation::Pressure), Some(300.0)); + } + // 4 pt art on a 100 pt path: 2 pt either side but for a peak at 22 pt, where it is 6 pt. + let peak = pressed(vec![(0.0, 0.0), (0.21, 0.0), (0.22, 1.0), (0.23, 0.0), (1.0, 0.0)]); + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 100.0, 0.0), &peak); + for (x, want) in [(22.0, 6.0), (21.5, 4.0), (22.5, 4.0), (10.0, 2.0), (20.5, 2.0), (24.0, 2.0), (80.0, 2.0)] { + assert!(near(reach_at(&out, x), want, 0.05), "at {x} pt: {} pt either side, not {want}", reach_at(&out, x)); + } +} + +/// A pen recording sampled many times along a straight ramp draws as many anchors as the ramp's +/// two ends do: samples that leave the scale on the same straight course are not split at. +#[test] +fn pen_samples_on_a_straight_ramp_add_no_anchors() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 1000.0, 0.0); + let ramp = |n: usize| pressed((0..=n).map(|i| (i as f64 / n as f64, i as f64 / n as f64)).collect()); + let anchors = |out: &[Node]| { + let mut count = 0; + for n in out { + n.walk(&mut |c| count += c.path_data().map_or(0, |p| p.subpaths.iter().map(|s| s.anchors.len()).sum::())); + } + count + }; + let pattern = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + let mut art = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut art.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::Pressure), Some(300.0)); + } + for b in [&pattern, &art] { + let (few, many) = (stroke_pieces(&doc, b, &bp, &ramp(1)), stroke_pieces(&doc, b, &bp, &ramp(2000))); + assert_eq!(anchors(&many), anchors(&few), "{}", b.name); + } +} + /// On a closed path, a tile that Approximate Path starts before the path's start takes the scale /// recorded at the end of the stroke there, where the tile is drawn. #[test] diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 7ffcb472ff..3cfa54db21 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -40,23 +40,32 @@ const MASK_STEPS: usize = 32; /// through the bend to within [`fit_tol`] of `doc_tol`, the flattening tolerance in document /// space, so the art keeps its curves (#3926). Where that cannot be done in no more anchors than /// chords would take, the path is flattened with `flat_tol` (art space) and subdivided so no chord -/// is longer than `max_du` along x, as it always was. Stroke widths scale by `width_scale`. -/// Text, images and symbol instances can't bend and are dropped. The art of a linked opacity mask -/// bends with the object it masks. -pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, doc_tol: f64, width_scale: f64) -> Option { +/// is longer than `max_du` along x, as it always was. Both routes also split the art where it +/// crosses each of `breaks` (art x, in order), so a turn of the map there is not stepped over. +/// Stroke widths scale by `width_scale`. Text, images and symbol instances can't bend and are +/// dropped. The art of a linked opacity mask bends with the object it masks. +pub(crate) fn warp_node( + n: &Node, + f: &dyn Fn(Point) -> Point, + flat_tol: f64, + max_du: f64, + doc_tol: f64, + width_scale: f64, + breaks: &[f64], +) -> Option { let mut out = n.clone(); out.appearance.scale_strokes(width_scale); match &mut out.kind { NodeKind::Path { path, live, .. } => { *live = None; - *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol)); + *path = warp_path(path, f, flat_tol, max_du, fit_tol(doc_tol), breaks); if path.is_empty() { return None; } } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Compound { children, .. } => { let kids: Vec> = - children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale)).map(Arc::new).collect(); + children.iter().filter_map(|c| warp_node(c, f, flat_tol, max_du, doc_tol, width_scale, breaks)).map(Arc::new).collect(); if kids.is_empty() { return None; } @@ -64,7 +73,7 @@ pub(crate) fn warp_node(n: &Node, f: &dyn Fn(Point) -> Point, flat_tol: f64, max } _ => return None, } - map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale)); + map_mask(&mut out, |art| warp_node(art, f, flat_tol, max_du, doc_tol, width_scale, breaks)); Some(out) } @@ -80,12 +89,13 @@ fn map_mask(n: &mut Node, map: impl FnOnce(&Node) -> Option) { } /// Each subpath of `p` through `f`: fitted cubics when they take no more anchors than the chords -/// would, else the chords. Points `f` cannot place (not finite) are left out of the chords. -fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64) -> PathData { +/// would, else the chords, both split at `breaks` ([`warp_node`]). Points `f` cannot place (not +/// finite) are left out of the chords. +fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f64, fit_tol: f64, breaks: &[f64]) -> PathData { let mut subs = vec![]; for sp in &p.subpaths { - let Some(dense) = densified(sp, flat_tol, max_du) else { continue }; - if let Some(fit) = fitted(sp, f, fit_tol, dense.len()) { + let Some(dense) = densified(sp, flat_tol, max_du, breaks) else { continue }; + if let Some(fit) = fitted(sp, f, fit_tol, dense.len(), breaks) { subs.push(fit); continue; } @@ -98,8 +108,9 @@ fn warp_path(p: &PathData, f: &dyn Fn(Point) -> Point, flat_tol: f64, max_du: f6 } /// `sp` flattened with `flat_tol` and its chords subdivided so none is longer than `max_du` along -/// x, in art space: the points the chord route maps. `None` below two points. -fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { +/// x, in art space, with a point where a chord crosses each of `breaks` (art x, in order): the +/// points the chord route maps. `None` below two points. +fn densified(sp: &SubPath, flat_tol: f64, max_du: f64, breaks: &[f64]) -> Option> { let mut bp = BezPath::new(); sp.to_bezpath_into(&mut bp); let mut pts = vec![]; @@ -118,16 +129,57 @@ fn densified(sp: &SubPath, flat_tol: f64, max_du: f64) -> Option> { let mut dense = vec![*pts.first()?]; for (i, (&a, &b)) in pts.iter().zip(pts.iter().cycle().skip(1)).take(segs).enumerate() { let k = (((b.x - a.x).abs() / max_du).ceil() as usize).clamp(1, MAX_SUB); + // The breaks the chord crosses, as parameters along it in order, go in among the even ones. + let mut cuts: Vec = crossed(breaks, a.x, b.x).iter().map(|&x| (x - a.x) / (b.x - a.x)).collect(); + cuts.sort_by(f64::total_cmp); + let mut cuts = cuts.into_iter().peekable(); for j in 1..=k { + let even = j as f64 / k as f64; + while let Some(t) = cuts.next_if(|&t| t < even) { + dense.push(a.lerp(b, t)); + } if sp.closed && i == segs - 1 && j == k { break; } - dense.push(a.lerp(b, j as f64 / k as f64)); + dense.push(a.lerp(b, even)); } } Some(dense) } +/// The values of `breaks` (in order) strictly between `a` and `b`, either way round. +fn crossed(breaks: &[f64], a: f64, b: f64) -> &[f64] { + let (lo, hi) = (a.min(b), a.max(b)); + let from = breaks.partition_point(|&x| x <= lo); + let to = from + breaks[from..].partition_point(|&x| x < hi); + &breaks[from..to] +} + +/// The parameters of `c` (in order, strictly between its ends) where its x is one of `breaks`; +/// `line` when `c` is a line with its handles at thirds, whose x runs evenly. +fn crossings(c: &CubicBez, line: bool, breaks: &[f64]) -> Vec { + let xs = [c.p0.x, c.p1.x, c.p2.x, c.p3.x]; + let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &x| (lo.min(x), hi.max(x))); + let inside = crossed(breaks, lo, hi); + if inside.is_empty() { + return vec![]; + } + let [a, b, cc, d] = xs; + let mut ts: Vec = vec![]; + for &x in inside { + if line { + ts.push((x - a) / (d - a)); + } else { + ts.extend(kurbo::common::solve_cubic(a - x, 3.0 * (b - a), 3.0 * (cc - 2.0 * b + a), d - 3.0 * cc + 3.0 * b - a)); + } + } + // Pieces are no shorter than the step the fit reads their ends' directions over. + ts.retain(|t| t.is_finite() && *t > FIT_DT && *t < 1.0 - FIT_DT); + ts.sort_by(f64::total_cmp); + ts.dedup_by(|t, prev| *t - *prev <= FIT_DT); + ts +} + /// Times an art segment is halved at most while looking for cubics that fit it. const FIT_DEPTH: u32 = 12; /// Parameter step of the finite differences that stand in for the bend's derivative. @@ -156,7 +208,10 @@ fn fit_tol(doc_tol: f64) -> f64 { /// bend at the same parameters, so the distance measured is never less than the true one. The /// halving is our own rather than kurbo's `fit_to_bezpath`, which halves until the floats run out /// on a map that never fits; the depth and the anchor count bound this one. -fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Option { +/// +/// A segment is first split where its x crosses one of `breaks` (art x, in order), so a turn of +/// the map there lands on an anchor rather than between the checked positions. +fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize, breaks: &[f64]) -> Option { if !(tol.is_finite() && tol > 0.0) { return None; } @@ -174,7 +229,11 @@ fn fitted(sp: &SubPath, f: &dyn Fn(Point) -> Point, tol: f64, most: usize) -> Op // A line's handles sit on its ends, which stalls its parameter there; thirds keep it even. let c = if line { CubicBez::new(c.p0, c.p0.lerp(c.p3, 1.0 / 3.0), c.p0.lerp(c.p3, 2.0 / 3.0), c.p3) } else { c }; let at = |t: f64| Some(f(c.eval(t))).filter(|q| q.is_finite()); - fit_into(&at, (0.0, 1.0), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + let mut t0 = 0.0; + for t1 in crossings(&c, line, breaks).into_iter().chain([1.0]) { + fit_into(&at, (t0, t1), line, tol, FIT_DEPTH, &mut bp, &mut room)?; + t0 = t1; + } } if sp.closed { bp.close_path(); @@ -316,6 +375,16 @@ impl AlongMap { fn max_scale(&self) -> f64 { (0..3).map(|i| self.slope(i).abs()).fold(1e-6, f64::max) } + + /// The art x (offset from the art's left edge) that [`AlongMap::at`] takes to arc length `s`, + /// when a piece with width spans it. + fn x_at(&self, s: f64) -> Option { + (0..3).find_map(|i| { + let ((x0, x1), (s0, s1)) = ((self.xs[i], self.xs[i + 1]), (self.ss[i], self.ss[i + 1])); + let spans = x1 - x0 > 1e-12 && (s1 - s0).abs() > 1e-12 && s0.min(s1) <= s && s <= s0.max(s1); + spans.then(|| x0 + (s - s0) / (s1 - s0) * (x1 - x0)) + }) + } } /// The affine that reproduces `f` over `b` to within `tol`, if one does. @@ -414,12 +483,14 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option f64) -> Option { +/// of each object in the art take the factor at the middle of the object. `marks` are the arc +/// lengths (in order) of the recorded pen samples `widen` runs in a straight line between; the art +/// is split where `widen` turns at one by more than the bent outline's tolerance ([`pen_breaks`]). +fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, widen: &dyn Fn(f64) -> f64, marks: &[f64]) -> Option { let cy = b.center().y; let x0 = b.x0; let f = move |p: Point| { @@ -430,7 +501,45 @@ fn bend_widened(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64, wid let art = widen_strokes(art, &factor); let scale = along.max_scale().max(cross.abs()).max(1e-6); let flat_tol = tolerance(b.height().max(b.width()) * scale) / scale; - warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs()) + // A change of `dw` in `widen` moves the art's top and bottom edges `dw × reach` across. + let reach = b.height() / 2.0 * cross.abs(); + let mut breaks: Vec = + pen_breaks(marks, along.span(), widen, fit_tol(flat_tol * scale) / reach).into_iter().filter_map(|s| along.x_at(s)).map(|x| x + x0).collect(); + breaks.sort_by(f64::total_cmp); + breaks.dedup(); + warp_node(&art, &f, flat_tol, MAX_SEG / along.max_scale(), flat_tol * scale, cross.abs(), &breaks) +} + +/// The arc lengths among `marks` (in order) strictly within `(s0, s1)` at which the art is split: +/// those where `widen` is more than `tol` from the straight line between the ones kept on either +/// side (the span's ends to begin with), chosen by splitting at the farthest one until every +/// sample left out is within `tol` of that line. `widen` runs straight between samples, so it +/// is then within `tol` of the line between kept samples all along, and samples on a straight +/// course add no splits. +fn pen_breaks(marks: &[f64], (s0, s1): (f64, f64), widen: &dyn Fn(f64) -> f64, tol: f64) -> Vec { + if !(s1 > s0 && tol > 0.0) { + return vec![]; + } + let inside = { + let from = marks.partition_point(|&s| s <= s0); + &marks[from..from + marks[from..].partition_point(|&s| s < s1)] + }; + if inside.is_empty() { + return vec![]; + } + let pts: Vec<(f64, f64)> = std::iter::once(s0).chain(inside.iter().copied()).chain([s1]).map(|s| (s, widen(s))).collect(); + let mut keep = vec![false; pts.len()]; + let mut spans = vec![(0, pts.len() - 1)]; + while let Some((i, j)) = spans.pop() { + let ((sa, wa), (sb, wb)) = (pts[i], pts[j]); + let off = |&(s, w): &(f64, f64)| (w - if sb > sa { wa + (wb - wa) * (s - sa) / (sb - sa) } else { wa }).abs(); + let far = (i + 1..j).map(|k| (k, off(&pts[k]))).filter(|&(_, d)| d > tol).max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((k, _)) = far { + keep[k] = true; + spans.extend([(i, k), (k, j)]); + } + } + pts.iter().zip(keep).filter(|&(_, k)| k).map(|(p, _)| p.0).collect() } /// `n` with the strokes of it and of everything inside it scaled by `factor` of the object they @@ -465,8 +574,17 @@ fn art_runs(t: &Track) -> Vec<(f64, f64)> { bounds.windows(2).map(|w| (w[0], w[1])).collect() } -/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1. -fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, Rect), cross: f64, widen: &dyn Fn(f64) -> f64) -> Option { +/// The art on [s0, s1] of `t`, `cross` across where `widen` (0..=1, by arc length) is 1 (`marks` +/// as [`bend_widened`] takes them). +fn art_on_run( + t: &Track, + (s0, s1): (f64, f64), + a: &ArtBrush, + (art, b): (&Node, Rect), + cross: f64, + widen: &dyn Fn(f64) -> f64, + marks: &[f64], +) -> Option { let l = s1 - s0; if l <= 1e-9 { return None; @@ -489,7 +607,7 @@ fn art_on_run(t: &Track, (s0, s1): (f64, f64), a: &ArtBrush, (art, b): (&Node, R } } }; - bend_widened(t, art, b, along, cross, widen) + bend_widened(t, art, b, along, cross, widen, marks) } /// An art brush's art along `bp`. With a width that follows the pen (its pressure, tilt, bearing @@ -515,9 +633,13 @@ pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) let p = a.width_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5); (light + (heavy - light) * p) / width }; + let marks = match a.width_mode { + Some(m) if light != heavy && width > 0.0 => pen_marks(stroke, m, l), + _ => vec![], + }; let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, l)] }; for run in runs { - if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen) { + if let Some(n) = art_on_run(&t, run, a, (&art, b), cross, &widen, &marks) { out.push(n); } } @@ -671,7 +793,7 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) if mid <= 0.0 || marks.is_none_or(even) { return tile_on(t, tile, s0, s1, mid); } - bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid) + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid, marks.unwrap_or_default()) } /// The most side tiles a run of a pattern brush places. @@ -966,7 +1088,7 @@ fn auto_corner(t: &Track, i: usize, source: CornerSource, side: &(Node, Rect), k } let s = if tw > 1e-9 { len / tw } else { 1.0 }; let max_du = MAX_SEG / (2.0 * k * s.max(1.0)); - let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k); + let warp = |f: &dyn Fn(Point) -> Point| warp_node(art, f, flat_tol, max_du, flat_tol * k, k, &[]); // Art point → (distance along from the left edge, stretched to `len`, and offset across). let along = move |q: Point| { let (x, y) = local(q); @@ -1393,7 +1515,7 @@ mod tests { let f = |p: Point| t.map(along.at(p.x - x0), p.y - cy); let tol = tolerance(b.height().max(b.width())); let exact = traced(art, &f, 1000); - let chords: Vec = densified(art, tol, MAX_SEG).expect("the tile flattens").into_iter().map(f).collect(); + let chords: Vec = densified(art, tol, MAX_SEG, &[]).expect("the tile flattens").into_iter().map(f).collect(); let curves = traced(sp, &|p| p, 200); let (e_curves, e_chords) = (apart(&curves, &exact), apart(&chords, &exact)); // Checked at eight points a piece, so a little room between them. @@ -1419,7 +1541,7 @@ mod tests { let allowed: usize = path .subpaths .iter() - .filter_map(|sp| densified(sp, 0.25, 1.5)) + .filter_map(|sp| densified(sp, 0.25, 1.5, &[])) .map(|dense| 1 + (FIT_CHECKS + 3) * (2 * dense.len() + FIT_DEPTH as usize + 1) + dense.len()) .sum(); let finite = |n: &Node| match &n.kind { @@ -1441,7 +1563,7 @@ mod tests { calls.set(calls.get() + 1); if calls.get() > allowed { Point::new(f64::NAN, f64::NAN) } else { f(p) } }; - let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0); + let out = warp_node(&tile, &counted, 0.25, 1.5, 0.25, 1.0, &[]); assert!(calls.get() <= allowed, "map {i} was called {} times, {allowed} allowed", calls.get()); match (i, &out) { (3, out) => assert!(out.is_none(), "a map that places nothing draws nothing"), @@ -1491,7 +1613,7 @@ mod tests { let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(*mask.art, stroked(1), "{name} run: an unlinked mask stays where it was"); - let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5).expect("the art is drawn"); + let out = bend_widened(t, &masked(true), b, along, 2.0, &|_| 0.5, &[]).expect("the art is drawn"); let mask = out.extras().mask.as_ref().expect("the mask is kept"); assert_eq!(mask.art.kind, out.kind, "{name} run, widened: the mask's art bends with the art"); assert_eq!(mask.art.appearance, out.appearance, "{name} run, widened: the mask's strokes narrow with the art's");