diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a1f1785923..7d6f997cf9 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -190,6 +190,10 @@ pub struct GestureTool { /// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from /// upright ([`super::pen_bearing`]), for the Eraser's tip outline. bearing: Option, + /// `bearing` as it was at each of `poses`, for the outline of the area the Eraser's drag covers. + bearings: Vec>, + /// The first of `bearings` that the pen gave: the release gives it to the points before it. + first_bearing: Option, /// The length of the stroke, in points. length: f64, /// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built @@ -878,6 +882,8 @@ impl GestureTool { tip_at: None, light: false, bearing: None, + bearings: vec![], + first_bearing: None, length: 0.0, area: Cell::new(None), area_pending: Cell::new(false), @@ -945,6 +951,8 @@ impl GestureTool { let pose = ev.pen.map(PenPose::sanitized); self.bearing = pose.and_then(super::pen_bearing).or(self.bearing); self.poses.push(pose); + self.bearings.push(self.bearing); + self.first_bearing = self.first_bearing.or(self.bearing); } } @@ -966,6 +974,14 @@ impl GestureTool { None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)), None => self.bearing, }; + if let Some(b) = self.bearings.last_mut() { + *b = self.bearing; + } + // The bearings carry forward, so the last sample gives the first bearing only when the one + // before it has none. + if self.bearings.len().checked_sub(2).and_then(|i| self.bearings.get(i)).copied().flatten().is_none() { + self.first_bearing = self.bearing; + } } /// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends @@ -1053,6 +1069,8 @@ impl GestureTool { self.shift_line = None; self.light = false; self.bearing = None; + self.bearings.clear(); + self.first_bearing = None; self.length = 0.0; self.area.set(None); self.area_pending.set(false); @@ -1113,12 +1131,74 @@ impl GestureTool { matches!(self.id, "blobBrush" | "eraser") } - /// The pen pressure of each point of a Blob Brush or Eraser stroke whose Size varies with - /// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure - /// keeps its Size). - fn size_pressures(&self) -> Option<&[f32]> { - let pressed = self.pressures.len() == self.points.len() && self.light; - (self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice()) + /// Which of the tip's angle, roundness and size vary along a Blob Brush or Eraser stroke: those + /// on a mode the pen gave a reading for anywhere along it (a pressure less than full, a tilt, a + /// bearing or a rotation). Random draws one value from the whole drag at the release, and the + /// outline shows the value itself. + fn tip_varies(&self) -> [bool; 3] { + let (pressed, posed) = (self.reads_pressures(), self.reads_poses()); + let reads = |mode: Variation| match mode { + Variation::Pressure => pressed, + Variation::Tilt => posed && self.poses.iter().flatten().any(|q| q.tilt.is_some()), + Variation::Bearing => posed && self.bearings.iter().any(Option::is_some), + Variation::Rotation => posed && self.poses.iter().flatten().any(|q| q.rotation.is_some()), + Variation::Fixed | Variation::Random => false, + }; + if self.smoothing { + return [false; 3]; + } + self.tip_modes().map(reads) + } + + /// Does the release read the stroke's pressures ([`Self::stroke_json`]): one for every point, + /// with the pen pressed less than fully somewhere? A mode set to Pressure during the drag + /// leaves the points before it without one. + fn reads_pressures(&self) -> bool { + self.light && self.pressures.len() == self.points.len() + } + + /// Does the release read the stroke's tilts and rotations ([`Self::stroke_json`]): a pose for + /// every point? A mode set to Tilt, Bearing or Rotation during the drag leaves the points + /// before it without one. + fn reads_poses(&self) -> bool { + self.poses.len() == self.points.len() + } + + /// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there + /// ([`Self::controls_of_point`]). + fn tip_of_point(&self, i: usize) -> [f64; 3] { + self.tip_of_controls(self.controls_of_point(i)) + } + + /// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads + /// the pen there: the pressure and tilt halfway between those at the two points, and the + /// bearing and rotation halfway between them the shorter way round. A tip whose angle follows + /// the pressure from 0 at one point to 1 at the next lies level there, not turned as at + /// either end. + fn tip_between(&self, j: usize) -> [f64; 3] { + let (a, b) = (self.controls_of_point(j), self.controls_of_point(j + 1)); + // Bearing and rotation read ½ plus the angle over 360° ([`super::pen_controls`]). + let turn = |a: f64, b: f64| { + let (a, b) = ((a - 0.5) * 360.0, (b - 0.5) * 360.0); + 0.5 + vectorcraft_geom::normalize_deg(a + vectorcraft_geom::normalize_deg(b - a) / 2.0) / 360.0 + }; + self.tip_of_controls([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0, turn(a[2], b[2]), turn(a[3], b[3])]) + } + + /// What each of the variation modes Pressure, Tilt, Bearing and Rotation reads at point `i` of + /// the stroke, as `path.eraseRegion` reads the pen there ([`super::pen_controls`]): the + /// pressure once the pen has pressed less than fully, the tilt and rotation of the point, and + /// the bearing of the last point up to it that the pen leaned 1° or more at, or before the + /// first such point the bearing of that first one. What the release does not read + /// ([`Self::reads_pressures`], [`Self::reads_poses`]) reads ½, the values themselves. + fn controls_of_point(&self, i: usize) -> [f64; 4] { + let pressure = if self.reads_pressures() { self.pressures.get(i).map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; + let (pose, bearing) = if self.reads_poses() { + (self.poses.get(i).copied().flatten(), self.bearings.get(i).copied().flatten().or(self.first_bearing)) + } else { + (None, None) + }; + super::pen_controls(pressure, pose, bearing) } /// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's @@ -1144,12 +1224,25 @@ impl GestureTool { /// more at), as `path.eraseRegion` reads the stroke; before a press, and for Random, Fixed and a /// pen that gives no reading, the values themselves. The Blob Brush's are its own values. fn tip_now(&self) -> [f64; 3] { - let base = [self.angle, self.roundness, self.size]; if self.id != "eraser" || !self.active { - return base; + return [self.angle, self.roundness, self.size]; } let pressure = if self.light { self.pressures.last().map_or(0.5, |p| f64::from(*p)) } else { 0.5 }; - let controls = super::pen_controls(pressure, self.poses.last().copied().flatten(), self.bearing); + self.tip_for(pressure, self.poses.last().copied().flatten(), self.bearing) + } + + /// The tip's angle, roundness and size for a pen at `pressure` held as `pose`, leaning toward + /// `bearing`: each value on a mode that follows the pen goes from the value less its Variation + /// to the value plus it ([`super::pen_controls`]); for Random, Fixed and what the pen does not + /// give, the values themselves. + fn tip_for(&self, pressure: f64, pose: Option, bearing: Option) -> [f64; 3] { + self.tip_of_controls(super::pen_controls(pressure, pose, bearing)) + } + + /// The tip's angle, roundness and size where the modes Pressure, Tilt, Bearing and Rotation + /// read `controls` (0..1 each, [`super::pen_controls`]). + fn tip_of_controls(&self, controls: [f64; 4]) -> [f64; 3] { + let base = [self.angle, self.roundness, self.size]; let variations = [self.angle_variation, self.roundness_variation, self.size_variation]; let mut out = base; for (i, (v, mode)) in out.iter_mut().zip(self.tip_modes()).enumerate() { @@ -1660,31 +1753,39 @@ impl Tool for GestureTool { }; let color = if self.id == "eraser" { [0x80, 0x80, 0x80] } else { FEEDBACK }; // A tip that is not round shows the outline of the area it covers, each step of the drag - // as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush - // tip: a line as wide as the brush would end square, where the stroke it adds is round at - // both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). - if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing { - let pressures = self.size_pressures(); + // with the tip the pen gives there on the modes that follow the pen. So does a round Blob + // Brush tip: a line as wide as the brush would end square, where the stroke it adds is + // round at both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]). + let [angle_varies, roundness_varies, size_varies] = self.tip_varies(); + // An angle varies the tip only when it is not round. + let shaped = roundness_varies || (angle_varies && self.roundness < 100.0); + if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || shaped || self.id == "blobBrush") && !self.smoothing { let key = AreaKey { blob: self.id == "blobBrush", size: self.size, - variation: self.size_variation, + variation: if size_varies { self.size_variation } else { 0.0 }, angle: self.angle, roundness: self.roundness, - pressure: pressures.is_some(), + varies: shaped || size_varies, + shaped, + pressed: self.reads_pressures() && self.tip_modes().contains(&Variation::Pressure), + first_bearing: self.first_bearing.filter(|_| self.reads_poses() && self.tip_modes().contains(&Variation::Bearing)), + modes: self.tip_modes(), + variations: [self.angle_variation, self.roundness_variation, self.size_variation], }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); - area.step(&self.points, pressures); + let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; + area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); self.area_pending.set(area.pending(&self.points)); self.area.set(Some(area)); - } else if let Some(pressures) = self.size_pressures() { - // With Size set to Pressure, each step of the drag shows as wide as the pen pressed there. - for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) { - let pressure = f64::from(p[0] + p[1]) / 2.0; - let width = super::pressure_size(self.size, self.size_variation, pressure) * cx.zoom; + } else if size_varies { + // With Size on a mode that follows the pen, each step of the drag shows as wide as the + // tip the pen gives at its ends. + for (j, seg) in self.points.windows(2).enumerate() { + let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom; o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false }); } } else { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index a56322db40..5a33e6e77f 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -2,10 +2,11 @@ //! tip covers, built a bounded amount at a time. //! //! The drag is cut into pieces of up to [`PIECE_SEGMENTS`] segments (one segment each when the -//! Size varies with pressure). A call outlines again, in the space where the tip is round, only the +//! tip varies along the drag). A call outlines again, in the space where the tip is round, only the //! pieces it added segments to. A piece's outline then loses the parts that lie inside the area //! of another piece, found through a grid of squares that lists the segments near each square, so -//! the pieces show as one outline. One call takes at most [`POINTS_PER_CALL`] new points and does at most +//! the pieces show as one outline. When the tip's angle or roundness varies, each segment has its +//! own space where its tip is round, and the grid is on the page. One call takes at most [`POINTS_PER_CALL`] new points and does at most //! [`WORK_PER_CALL`] units of work, plus the one step it was in; what is left waits for the next //! call ([`AreaPreview::pending`]). Until then a piece shows the outline it last finished, and the //! points not yet taken show as a thin line. The settled pieces show as paths of up to @@ -15,14 +16,15 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; +use vectorcraft_brush::Variation; use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathData, PathEl, PathSeg, Point, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{Cap, Join}; use super::super::{MIN_BRUSH_SIZE, blob_tip, eraser_tip, pressure_size}; -/// The most segments of a drag that one piece of its outline holds, when the Size does not vary -/// with pressure (a piece then holds one segment). +/// The most segments of a drag that one piece of its outline holds, when the tip does not vary +/// along the drag (a piece then holds one segment). pub(super) const PIECE_SEGMENTS: usize = 32; /// The most points of a drag one call takes. pub(super) const POINTS_PER_CALL: usize = 256; @@ -68,10 +70,26 @@ pub(super) struct AreaKey { pub variation: f64, pub angle: f64, pub roundness: f64, - /// Each segment is as wide as the pen pressed there. - pub pressure: bool, + /// Each segment takes its own tip from the pen's readings at its ends ([`AreaPreview::step`]): + /// its own size, and with `shaped` its own angle and roundness. + pub varies: bool, + /// Each segment's tip has its own angle and roundness. + pub shaped: bool, + /// The tips at the points take the pen's pressure there: once the pen presses less than fully, + /// a point pressed fully takes the tip of full pressure instead of that of a stroke without + /// pressure. + pub pressed: bool, + /// The bearing the tips take at the points before the pen first leaned, when a tip follows the + /// bearing: the first lean gives it to the points already outlined. + pub first_bearing: Option, + /// The modes and Variations of the angle, roundness and size that the tips at the points follow. + pub modes: [Variation; 3], + pub variations: [f64; 3], } +/// A tip's angle in degrees, roundness in percent and size in points. +pub(super) type Tip = [f64; 3]; + /// The work of the last call. #[derive(Clone, Copy, Default, Debug)] pub(super) struct AreaWork { @@ -129,16 +147,24 @@ struct Check { pub(super) struct AreaPreview { key: AreaKey, first: Point, + /// The map from the page to the grid's space: where the tip is round, or the page itself when + /// each segment's tip has its own angle and roundness. squash: Affine, stretch: Affine, - /// The side of the grid's squares, where the tip is round. + /// The side of the grid's squares, in the grid's space. side: f64, - /// The points taken, where the tip is round. + /// The points taken, in the grid's space. sq: Vec, /// The last point taken, on the page. last: Point, - /// The tip's radius along each segment, where the tip is round. + /// The tip at the last point taken, when the tip varies along the drag. + last_tip: Option, + /// The tip's radius along each segment, where its tip is round. It is also as far as the + /// segment's area reaches from the segment in the grid's space. radius: Vec, + /// The map from the grid's space to the space where each segment's tip is round, when each + /// segment's tip has its own angle and roundness (empty otherwise: the grid's space). + to_round: Vec, pieces: Vec, squares: HashMap<(i64, i64), Vec>, /// How many listings the squares hold ([`LISTINGS`]). @@ -156,8 +182,12 @@ pub(super) struct AreaPreview { impl AreaPreview { /// The outline of a drag that starts at `first`. pub(super) fn new(key: AreaKey, first: Point) -> Self { - let stretch = if key.blob { blob_tip(key.angle, key.roundness) } else { eraser_tip(key.angle, key.roundness) }; - let widest = if key.pressure { pressure_size(key.size, key.variation, 1.0) } else { key.size }; + let stretch = match key { + AreaKey { shaped: true, .. } => Affine::IDENTITY, + AreaKey { blob: true, .. } => blob_tip(key.angle, key.roundness), + _ => eraser_tip(key.angle, key.roundness), + }; + let widest = if key.varies { pressure_size(key.size, key.variation, 1.0) } else { key.size }; Self { key, first, @@ -166,7 +196,9 @@ impl AreaPreview { side: widest.max(MIN_BRUSH_SIZE), sq: vec![], last: first, + last_tip: None, radius: vec![], + to_round: vec![], pieces: vec![], squares: HashMap::new(), listed: 0, @@ -208,28 +240,49 @@ impl AreaPreview { } /// Take the points of the drag `pts` added since the last call and check outlines, within this - /// call's limits. `pressures` holds the pen pressure at each point when the Size varies with it. - pub(super) fn step(&mut self, pts: &[Point], pressures: Option<&[f32]>) { + /// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and + /// segment `j` takes `middle(j)`, the tip halfway along it. A last point whose tip changed since + /// it was taken (a pen turned or tilted in place) gives its segment the new tip. + pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip, middle: &dyn Fn(usize) -> Tip) { self.work = AreaWork::default(); let mut changed = BTreeSet::new(); + if self.key.varies + && let Some(j) = self.sq.len().checked_sub(2) + && self.last_tip.is_some_and(|t| t != tip(j + 1)) + { + let k = self.piece_of(j); + let old = self.radius[j]; + self.set_tip(j, middle(j)); + self.last_tip = Some(tip(j + 1)); + changed.insert(k); + // The pieces near the old tip or the new one are checked again. + let new = self.radius[j]; + self.radius[j] = old.max(new); + self.near(j, k, false); + self.radius[j] = new; + } while self.sq.len() < pts.len() && self.work.points < POINTS_PER_CALL && self.work.work < WORK_PER_CALL { let i = self.sq.len(); self.sq.push(self.squash * pts[i]); self.last = pts[i]; self.work.points += 1; + if self.key.varies { + self.last_tip = Some(tip(i)); + } let Some(j) = i.checked_sub(1) else { continue }; - let size = match pressures.filter(|_| self.key.pressure).and_then(|f| f.get(j..=i)) { - Some(f) => pressure_size(self.key.size, self.key.variation, f64::from(f[0] + f[1]) / 2.0), - None => self.key.size, - }; - self.radius.push(size / 2.0); - if self.key.pressure || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { + if self.key.varies { + self.radius.push(0.0); + self.set_tip(j, middle(j)); + } else { + self.radius.push(self.key.size / 2.0); + } + if self.key.varies || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) { self.pieces.push(Piece { from: j, to: j, outline: vec![], shown: BezPath::new() }); } let k = self.pieces.len() - 1; self.pieces[k].to = j + 1; changed.insert(k); - self.list(j, k); + self.near(j, k, true); } for k in changed { self.outline_piece(k); @@ -237,6 +290,24 @@ impl AreaPreview { self.check_some(); } + /// Give segment `j` the tip `[angle, roundness, size]`, the tip halfway along it: its radius, + /// and with `shaped` the map to the space where that tip is round. + fn set_tip(&mut self, j: usize, [angle, roundness, size]: Tip) { + self.radius[j] = size.max(MIN_BRUSH_SIZE) / 2.0; + if self.key.shaped { + let round = eraser_tip(angle, roundness).inverse(); + match self.to_round.get_mut(j) { + Some(m) => *m = round, + None => self.to_round.push(round), + } + } + } + + /// The map from the grid's space to the space where segment `m`'s tip is round. + fn round_of(&self, m: usize) -> Affine { + self.to_round.get(m).copied().unwrap_or(Affine::IDENTITY) + } + /// The paths to show: the settled pieces' outlines, joined [`BLOCK_PIECES`] at a time, the /// growing last piece's and a thin line over the points of `pts` not taken yet. The joined /// paths with a changed piece are joined again, newest first, at most @@ -281,13 +352,13 @@ impl AreaPreview { /// How many pieces no longer grow: all of them but a last one with room for more segments. fn settled_count(&self) -> usize { - let growing = !self.key.pressure && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); + let growing = !self.key.varies && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS); self.pieces.len() - usize::from(growing) } /// The piece that holds segment `j`. fn piece_of(&self, j: usize) -> usize { - if self.key.pressure { j } else { j / PIECE_SEGMENTS } + if self.key.varies { j } else { j / PIECE_SEGMENTS } } /// The square of the grid that holds `p`; `None` far outside any document. @@ -317,16 +388,16 @@ impl AreaPreview { Some(keys) } - /// List segment `j` of piece `k` in the squares its area reaches, and mark the other pieces - /// whose outline its area can reach to be checked again. - fn list(&mut self, j: usize, k: usize) { + /// With `add`, list segment `j` of piece `k` in the squares its area reaches; either way, mark + /// the other pieces whose outline its area can reach to be checked again. + fn near(&mut self, j: usize, k: usize, add: bool) { let (a, b, r) = (self.sq[j], self.sq[j + 1], self.radius[j]); let mut near = vec![]; match self.squares_along(a, b, SEGMENT_SAMPLES) { Some(keys) => { for key in keys { self.work.work += 1; - if self.listed >= LISTINGS { + if self.listed >= LISTINGS || !add { near.extend(self.squares.get(&key).into_iter().flatten().map(|m| *m as usize)); continue; } @@ -350,7 +421,7 @@ impl AreaPreview { } } } - if self.wide.len() < WIDE_SEGMENTS { + if add && self.wide.len() < WIDE_SEGMENTS { self.wide.push(j); } } @@ -374,10 +445,21 @@ impl AreaPreview { fn outline_piece(&mut self, k: usize) { let settled = self.settled_count(); let Some(p) = self.pieces.get(k) else { return }; - let pts = &self.sq[p.from..=p.to]; let width = 2.0 * self.radius[p.from]; - self.work.outlined += pts.len(); - let area = po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath(); + self.work.outlined += p.to + 1 - p.from; + // A piece whose tip has its own angle and roundness (one segment) is outlined where that + // tip is round and taken back to the grid's space. + let area = match self.to_round.get(p.from) { + Some(&round) => { + let pts = [round * self.sq[p.from], round * self.sq[p.to]]; + round.inverse() + * po::outline_stroke(&PathData::single(SubPath::polyline(&pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + None => { + let pts = &self.sq[p.from..=p.to]; + po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath() + } + }; let outline = segments(&area); let shown = self.stretch * area; if let Some(p) = self.pieces.get_mut(k) { @@ -454,7 +536,11 @@ impl AreaPreview { /// The stretches of `seg` (from and to, 0 at its start, 1 at its end) that lie inside no area /// of a segment of the drag but `own`. fn visible(&mut self, seg: PathSeg, own: std::ops::Range) -> Vec<(f64, f64)> { - let inside = |s: &Self, q: Point, m: usize| distance_to_segment(q, s.sq[m], s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE); + // Each segment's area is tested where its tip is round. + let inside = |s: &Self, q: Point, m: usize| { + let round = s.round_of(m); + distance_to_segment(round * q, round * s.sq[m], round * s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE) + }; match seg { PathSeg::Line(line) => { let len = line.p0.distance(line.p1); @@ -482,7 +568,14 @@ impl AreaPreview { keys }; let near = self.candidates(keys, &own); - let spans = near.iter().filter_map(|&m| capsule_span(line, self.sq[m], self.sq[m + 1], self.radius[m] * (1.0 - INSIDE))).collect(); + // A map keeps a line's points where they are along it. + let spans = near + .iter() + .filter_map(|&m| { + let round = self.round_of(m); + capsule_span(round * line, round * self.sq[m], round * self.sq[m + 1], self.radius[m] * (1.0 - INSIDE)) + }) + .collect(); gaps(&merge_spans(spans)) } _ => { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..7aba70d4b6 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2933,6 +2933,317 @@ fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() { near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0)); } +/// The outline of the area an Eraser drag covers takes, at each step, the tip the pen gives there +/// on the modes that follow it, as the release erases: turned, made rounder or larger, turned +/// again when the pen turns in place, and turned anew when a Variation changes. A round tip whose Size follows the pen shows each step as +/// wide as that tip, and a mouse, which reads no tilt or rotation, keeps the set tip. +#[test] +fn the_eraser_drag_area_follows_its_variation_modes() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + // Precise cursors: no tip outline, only the outline of the area. + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let set = |t: &mut GestureTool, options: &[(&str, Value)]| { + for (k, v) in options { + t.set_option(k, v); + } + }; + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let turned = Some(PenPose { tilt: None, rotation: Some(180.0) }); + let level = Some(PenPose { tilt: None, rotation: Some(0.0) }); + let press = |t: &mut GestureTool, pen: Option, kind: PointerKind, x: f64| { + t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(kind, x, 150.0) }); + }; + + // A tip 20 by 5 pt lying level, its angle on the barrel's rotation by up to 90°. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))]); + // With the barrel turned half way round all along, the tip stands upright: along the + // horizontal drag from x 50 to x 150 the area reaches 2.5 pt either side and 10 pt above and + // below. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + // The barrel turns back with the pointer still: the step takes the tip halfway between the + // two, turned 45°, which reaches √(10² + 2.5²) / √2 pt from the drag every way. + press(&mut t, level, PointerKind::Drag, 150.0); + let r = (100.0f64 + 6.25).sqrt() / 2f64.sqrt(); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, level, PointerKind::Up, 150.0); + // A Variation changed during the drag gives the outline the new tip: with 45° the turned + // barrel turns the tip 45°. + press(&mut t, turned, PointerKind::Down, 50.0); + press(&mut t, turned, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + t.set_option("angleVariation", &json!(45)); + near(bounds(&t), (50.0 - r, 150.0 - r, 150.0 + r, 150.0 + r)); + press(&mut t, turned, PointerKind::Up, 150.0); + t.set_option("angleVariation", &json!(90)); + // A mouse drag keeps the set tip, lying level. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0)); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)); + + // A round tip whose Roundness follows the tilt by up to 75%, the angle 90°: with the pen + // lying flat the tip is 25% round and stands upright. + let mut t = GestureTool::new("eraser"); + set(&mut t, &[("size", json!(20)), ("angle", json!(90)), ("roundnessMode", json!("tilt")), ("roundnessVariation", json!(75))]); + let flat = Some(PenPose { tilt: Some([90.0, 0.0]), rotation: None }); + press(&mut t, flat, PointerKind::Down, 50.0); + press(&mut t, flat, PointerKind::Drag, 150.0); + near(bounds(&t), (47.5, 140.0, 152.5, 160.0)); + press(&mut t, flat, PointerKind::Up, 150.0); + + // Size on Tilt by up to 8 pt, the pen upright: a tip 28 pt long, 7 pt wide standing upright, + // and a round one 28 pt across. + for (roundness, want) in [(25.0, (46.5, 136.0, 153.5, 164.0)), (100.0, (36.0, 136.0, 164.0, 164.0))] { + let mut t = GestureTool::new("eraser"); + set( + &mut t, + &[("size", json!(20)), ("angle", json!(90)), ("roundness", json!(roundness)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(8))], + ); + press(&mut t, upright, PointerKind::Down, 50.0); + press(&mut t, upright, PointerKind::Drag, 150.0); + if roundness < 100.0 { + near(bounds(&t), want); + } else { + let o = t.overlays(&cx); + assert!(matches!(&o[..], [Overlay::Path { width, .. }] if *width == 28.0), "{o:?}"); + } + press(&mut t, upright, PointerKind::Up, 150.0); + } +} + +/// The outline of an Eraser drag shows the tips the release erases with: once the pen presses less +/// than fully, the steps already outlined take the tip of the pressure at their points, and a mode +/// set to Tilt during the drag, whose tilts the release does not read, leaves the tip as set. +#[test] +fn the_eraser_drag_area_matches_the_release_when_pressure_or_a_mode_starts_during_the_drag() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + let near = |b: vectorcraft_geom::Rect, want: (f64, f64, f64, f64)| { + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None }); + let leaning = Some(PenPose { tilt: Some([45.0, 0.0]), rotation: None }); + let press = |t: &mut GestureTool, pen: Option, pressure: f32, kind: PointerKind, x: f64| { + t.pointer(&cx, &PointerEvent { pen, pressure, ..PointerEvent::new(kind, x, 150.0) }); + }; + + // A tip 20 by 5 pt lying level, its angle on Pressure by up to 90° and its Roundness on Tilt + // by up to 75%, so that each step has its own tip from the press on. The pen leans 45°, which + // keeps the Roundness at 25%. + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(20)), + ("roundness", json!(25)), + ("angleMode", json!("pressure")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("tilt")), + ("roundnessVariation", json!(75)), + ] { + t.set_option(k, &v); + } + // Pressed fully, the drag reads as a stroke without pressure: the tip lies level. + press(&mut t, leaning, 1.0, PointerKind::Down, 50.0); + press(&mut t, leaning, 1.0, PointerKind::Drag, 100.0); + press(&mut t, leaning, 1.0, PointerKind::Drag, 150.0); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + // The pen lifts to no pressure: the release reads full pressure at the first three points, the + // tip turned 90°, and none at the last, turned -90°. The first two steps stand upright, and + // the last, halfway between full pressure and none, lies level. + press(&mut t, leaning, 0.0, PointerKind::Drag, 200.0); + near(bounds(&t), (47.5, 140.0, 210.0, 160.0)); + press(&mut t, leaning, 0.0, PointerKind::Up, 200.0); + + // The same tip with its angle on Pressure by up to 90°, pressed halfway all along, and + // Roundness on Tilt by up to 75% set after the first two points: the release reads no tilt, + // so the tip stays 20 by 5 pt lying level, though the pen stands upright, which would make it + // round. + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("pressure")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + press(&mut t, None, 0.5, PointerKind::Down, 50.0); + press(&mut t, None, 0.5, PointerKind::Drag, 100.0); + t.set_option("roundnessMode", &json!("tilt")); + t.set_option("roundnessVariation", &json!(75)); + press(&mut t, upright, 0.5, PointerKind::Drag, 150.0); + near(bounds(&t), (40.0, 147.5, 160.0, 152.5)); + let released = t.stroke_json(); + assert!(released.as_array().is_some_and(|a| a.iter().all(|p| p.as_array().is_some_and(|p| p.len() == 3))), "{released}"); + press(&mut t, upright, 0.5, PointerKind::Up, 150.0); +} + +/// The release gives the points of an Eraser drag before the pen first leans the bearing of that +/// first lean, so the outline of a drag that starts upright and then leans is the outline of the +/// same drag leaning that way from the press, the steps already outlined included. +#[test] +fn the_eraser_drag_area_gives_the_first_lean_to_the_points_before_it() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + // A tip 20 by 5 pt lying level, its angle on Bearing by up to 90° and its Roundness on + // Rotation by up to 50%, so that each step has its own tip from the press on. The barrel stays + // turned 30° all along. `in_place` is a tilt given last, by a drag within a pixel of the last + // point. + let drag = |poses: [[f32; 2]; 5], in_place: Option<[f32; 2]>| { + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(20)), + ("roundness", json!(25)), + ("angleMode", json!("bearing")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("rotation")), + ("roundnessVariation", json!(50)), + ] { + t.set_option(k, &v); + } + let mut shown = vec![]; + for (i, (tilt, x)) in poses.into_iter().zip([50.0, 100.0, 150.0, 200.0, 250.0]).enumerate() { + let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag }; + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); + if i > 0 { + shown.push(bounds(&t)); + } + } + if let Some(tilt) = in_place { + let pen = Some(PenPose { tilt: Some(tilt), rotation: Some(30.0) }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 250.2, 150.0) }); + shown.push(bounds(&t)); + } + shown.last().copied().unwrap_or_else(|| panic!("no outline")) + }; + let same = |b: (vectorcraft_geom::Rect, vectorcraft_geom::Rect)| { + assert!([b.0.x0 - b.1.x0, b.0.y0 - b.1.y0, b.0.x1 - b.1.x1, b.0.y1 - b.1.y1].iter().all(|e| e.abs() < 0.01), "{b:?}"); + }; + let leaning = drag([[0.0, 45.0]; 5], None); + // Upright for four points, outlined as they come, then leaning toward the bottom of the page. + same((drag([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 45.0]], None), leaning)); + // Upright for all five, then leaning that way in place at the last. + same((drag([[0.0, 0.0]; 5], Some([0.0, 45.0])), drag([[0.0, 45.0]; 5], Some([0.0, 45.0])))); +} + +/// Each step of an Eraser drag's outline takes the tip the release erases with halfway along it: +/// with the angle on Pressure by up to 90°, a step from no pressure (the tip turned -90°) to full +/// pressure (turned 90°) shows the tip lying level, as the release turns it through level there, +/// though the tips at its ends are the same upright tip. +#[test] +fn the_eraser_drag_area_takes_the_tip_halfway_along_each_step() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("pressure")), ("angleVariation", json!(90))] { + t.set_option(k, &v); + } + t.pointer(&cx, &PointerEvent { pressure: 0.0, ..PointerEvent::new(PointerKind::Down, 50.0, 150.0) }); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 150.0, 150.0) }); + drain_area(&t, &cx); + let o = t.overlays(&cx); + let b = o + .iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")); + // The level tip 20 by 5 pt swept from x 50 to 150. + let want = (40.0, 147.5, 160.0, 152.5); + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?}"); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); +} + +/// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a +/// bounded amount per frame, and once finished it shows nothing inside the area: no point of it +/// lies well inside the area of any step, each step with the tip halfway along it. +#[test] +fn the_outline_of_a_long_varied_eraser_drag_is_bounded_and_shows_nothing_inside() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [ + ("size", json!(12)), + ("roundness", json!(40)), + ("angleMode", json!("pressure")), + ("angleVariation", json!(90)), + ("roundnessMode", json!("pressure")), + ("roundnessVariation", json!(30)), + ("sizeMode", json!("pressure")), + ("sizeVariation", json!(4)), + ] { + t.set_option(k, &v); + } + long_area_drag(&mut t, &cx, 700, |i| 0.2 + 0.7 * ((i % 37) as f32 / 37.0)); + drain_area(&t, &cx); + let shown = shown_points(&t.overlays(&cx)); + assert!(!shown.is_empty()); + let steps: Vec<(Affine, Point, Point, f64)> = (0..t.points.len() - 1) + .map(|j| { + let [angle, roundness, size] = t.tip_between(j); + let round = eraser_tip(angle, roundness).inverse(); + (round, round * t.points[j], round * t.points[j + 1], size / 2.0) + }) + .collect(); + for &(q, _) in &shown { + // A curve of an outline is checked at the middles of its pieces, so where it crosses the + // end of a narrow tip's area, the end of a piece can lie a little way inside it. + for &(round, a, b, r) in &steps { + let d = distance_to_line(round * q, (a, b)); + assert!(d > r * 0.85, "a point of the outline {d} from a step, inside its area of radius {r}, at {q:?}"); + } + } +} + #[test] fn smooth_needs_selection_and_brackets_resize() { let (d, _) = doc_with_rect(); diff --git a/docs/mcp.md b/docs/mcp.md index 743a510fb9..884bd6ada3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5765,7 +5765,9 @@ the drag takes what the pen read there (the points' pressure, tilt and rotation, drag without that reading, such as a mouse drag, erases at the value itself. One Random value per drag, which way Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app -the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. +the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the +outline of the area a drag covers takes, at each step, the tip the pen's readings give halfway along it. A Random +value shows as the value itself there, since the release draws it. `tool.setOption {tool: "eraser"}` takes the same keys. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b583d66802..905e5b2f9b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1179,8 +1179,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle. With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points. Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). - Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows keeps the set Angle and Roundness, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). - The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. With Size set to Pressure the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). + Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). + The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`).