Pencil: a redraw stroke in the middle of an open path never closes it (#3793)

A stroke that starts and ends on an open path away from its ends now always
replaces the part between and leaves the path open. Before, a stroke across
the opening (over most of an L, or across a C) could keep the part between
and close the path along the stroke instead. Closing stays where the Pencil
shows the closing cursor: a stroke from one end that finishes on the other.
This commit is contained in:
ncic
2026-11-23 01:42:18 +01:00
parent 3b668aec46
commit aea7ae116a
5 changed files with 17 additions and 133 deletions
+1 -1
View File
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one, the ends beyond them instead, which closes it, when the stroke lies along those, the opening between the ends is smaller than that section and the stroke runs nearer the opening than that section), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; an open one stays open), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+4 -117
View File
@@ -250,83 +250,6 @@ fn redraw_loop(mut sp: SubPath, k: usize, pts: &[Point], tol: Option<f64>, withi
Some(sp)
}
/// How far, on average, the run of `sp`'s segments from anchor `i` forward to anchor `j` lies from
/// stroke `pts` (sampled along both; the stroke thinned to at most 200 points).
fn run_distance(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> f64 {
let (sum, count) = run_distance_sum(sp, i, j, pts);
if count == 0 { f64::INFINITY } else { sum / count as f64 }
}
/// [`run_distance`]'s sum of the samples' distances and their count.
fn run_distance_sum(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> (f64, usize) {
use kurbo::ParamCurve;
let n = sp.anchors.len();
if n == 0 || pts.is_empty() {
return (0.0, 0);
}
let line = thinned(pts);
let to_line = |q: Point| {
line.iter()
.zip(line.iter().skip(1))
.map(|(&a, &b)| straight_distance(q, a, b))
.fold(line.first().map_or(f64::INFINITY, |a| q.distance(*a)), f64::min)
};
let segs = (j + n - i) % n;
let (mut sum, mut count) = (0.0, 0usize);
for k in 0..segs {
let c = sp.segment((i + k) % n);
for m in 1..=8 {
sum += to_line(c.eval(f64::from(m) / 8.0));
count += 1;
}
}
(sum, count)
}
/// Stroke `pts` thinned to at most about 200 points, its last kept, to measure it by.
fn thinned(pts: &[Point]) -> Vec<Point> {
let step = pts.len().div_ceil(200).max(1);
pts.iter().step_by(step).chain(pts.last()).copied().collect()
}
/// How far `q` lies from the straight piece from `a` to `b`.
fn straight_distance(q: Point, a: Point, b: Point) -> f64 {
let ab = b - a;
let t = if ab.hypot2() > 1e-18 { ((q - a).dot(ab) / ab.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
q.distance(a + ab * t)
}
/// Is there an opening in open subpath `sp` for stroke `pts`, from anchor `lo` to anchor `hi` of
/// it, to close? Only when the opening between the subpath's ends is smaller than the part the
/// stroke would replace, and the stroke runs nearer the opening (straight from `lo` to `hi`) than
/// that part. Without this, a tall bump redrawn over most of a line deletes the line's ends and
/// closes it: the ends lie nearer such a stroke than the part under the bump does.
fn closes_opening(sp: &SubPath, lo: usize, hi: usize, pts: &[Point]) -> bool {
use kurbo::ParamCurveArclen;
let Some(last) = sp.anchors.len().checked_sub(1) else { return false };
let (Some(head), Some(tail), Some(a), Some(b)) = (sp.anchors.first(), sp.anchors.get(last), sp.anchors.get(lo), sp.anchors.get(hi)) else {
return false;
};
// Lengths are measured to 0.01: a straight line's opening is as long as the whole line.
let replaced: f64 = (lo..hi).map(|k| sp.segment(k).arclen(0.01)).sum();
if head.p.distance(tail.p) + 0.01 >= replaced {
return false;
}
let Some(run) = sp.anchors.get_range(lo..=hi) else { return false };
let run = PathData::single(SubPath::new(run, false));
let line = thinned(pts);
// Weighted by length, so where the hand slowed down doesn't count for more.
let (mut to_opening, mut to_run, mut total) = (0.0, 0.0, 0.0);
for (&p, &q) in line.iter().zip(line.iter().skip(1)) {
let (len, mid) = (p.distance(q), p.midpoint(q));
let Some(on_run) = run.nearest(mid) else { return false };
to_opening += len * straight_distance(mid, a.p, b.p);
to_run += len * on_run.4;
total += len;
}
to_opening + 1e-6 * total < to_run
}
/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor
/// `end`) in place of its run from `start` forward to `end`.
fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<Item = Point>) -> f64 {
@@ -342,36 +265,13 @@ fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<It
area.abs()
}
/// An open subpath `sp` redrawn by a stroke from anchor `from` to anchor `to` across its open
/// ends: the part between them stays, the ends beyond them go, and the stroke closes the path.
fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
let (lo, hi) = (from.min(to), from.max(to));
let (a_lo, a_hi) = (*sp.anchors.get(lo)?, *sp.anchors.get(hi)?);
// The path runs lo → hi, then the stroke from hi back to lo.
let mut stroke = pts.to_vec();
if from == lo {
stroke.reverse();
}
bend_ends(&mut stroke, Some(a_hi.p), Some(a_lo.p), within);
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(fl)) = (fit.first().copied(), fit.last().copied()) else { return None };
let mut anchors = sp.anchors.get_range(lo..=hi)?;
if let Some(a) = anchors.first_mut() {
*a = Anchor::with_handles(a.p, fl.h_in, a.h_out);
}
if let Some(a) = anchors.last_mut() {
*a = Anchor::with_handles(a.p, a.h_in, f0.h_out);
}
anchors.extend_from_slice(fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default());
Some(SubPath::new(anchors, true))
}
/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within
/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with
/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the
/// way round that leaves the bigger shape. An open one closes only over an opening
/// ([`closes_opening`]). The subpath's index and its new shape; None when the stroke doesn't start
/// and end on the same subpath.
/// way round that leaves the bigger shape. On an open one it is the part between, and the path
/// stays open: it closes only from a stroke that starts at one of its ends and finishes on the
/// other. The subpath's index and its new shape; None when the stroke doesn't start and end on the
/// same subpath.
fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -> Option<(usize, SubPath)> {
let (first, last) = (*pts.first()?, *pts.last()?);
let (si, _, _, _, d_a) = pd.nearest(first)?;
@@ -395,19 +295,6 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
return redraw_loop(sp, from, pts, tol, within).map(|sp| (si, sp));
}
let n = sp.anchors.len();
// On an open subpath the stroke replaces the part it lies along: the run between where it
// starts and ends, or the ends beyond them and the gap between, which closes the path.
if !sp.closed {
let (lo, hi) = (from.min(to), from.max(to));
let inner = run_distance(&sp, lo, hi, pts);
let (s1, c1) = run_distance_sum(&sp, 0, lo, pts);
let (s2, c2) = run_distance_sum(&sp, hi, n - 1, pts);
// Both ends taken: the stroke only spans the gap.
let outer = if c1 + c2 == 0 { 0.0 } else { (s1 + s2) / (c1 + c2) as f64 };
if outer < inner && closes_opening(&sp, lo, hi, pts) {
return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp));
}
}
// The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from
// `end` round to `start`, then the stroke's inner anchors follow.
let (start, end, reversed) = if sp.closed {
+9 -12
View File
@@ -6615,11 +6615,11 @@ fn a_stroke_leaving_an_open_path_across_it_drops_the_side_it_is_near() {
assert!(ends_at(sp, Point::new(100.0, 100.0), Point::new(290.0, 50.0), 0.5), "the long side stays: {sp:?}");
}
/// A stroke drawn over an open shape's open ends, from near one end to near the other, redraws
/// those ends along the stroke and closes the shape, whichever way it is drawn; the shape's body
/// between stays.
/// A stroke drawn across an open shape's opening, from near one end to near the other, redraws the
/// part between where it starts and ends, whichever way it is drawn: the ends stay and the shape
/// stays open. Only a stroke that starts at one end and finishes on the other closes it.
#[test]
fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() {
fn a_stroke_across_an_open_shapes_opening_redraws_the_part_between_and_leaves_it_open() {
for reversed in [false, true] {
let mut s = session();
// A C open on the right: from the top right round the left to the bottom right.
@@ -6643,19 +6643,16 @@ fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() {
s.execute("path.freehand", &json!({"points": stroke, "redraw": {"id": id.0, "within": 4}})).unwrap();
assert_eq!(paths(&s).len(), 1, "reversed {reversed}: no new path");
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}: the shape closed");
assert!(!sp.closed, "reversed {reversed}: still open");
let (e1, e2) = (on(40.0), on(320.0));
assert!(ends_at(sp, Point::new(e1.0, e1.1), Point::new(e2.0, e2.1), 1.0), "reversed {reversed}: both ends stay: {sp:?}");
let bb = kurbo::Shape::bounding_box(&path(&s, id).to_bezpath());
assert!(bb.x1 > 310.0 && bb.x0 < 105.0, "reversed {reversed}: closed along the stroke, the body kept: {bb:?}");
// The old ends (at 40° and 320°) are gone.
for deg in [40.0, 320.0] {
let e = on(deg);
assert!(!sp.anchors.iter().any(|q| q.p.distance(Point::new(e.0, e.1)) < 1.0), "reversed {reversed}: the end at {deg}° is redrawn");
}
assert!(bb.x1 > 310.0 && bb.x0 > 200.0, "reversed {reversed}: the stroke in place of the C's body: {bb:?}");
}
}
/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and
/// the line stays open, as there is no opening for the stroke to close.
/// the line stays open.
#[test]
fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() {
for reversed in [false, true] {
File diff suppressed because one or more lines are too long
+2 -2
View File
File diff suppressed because one or more lines are too long