mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 20:06:32 +00:00
Path Precision Tools: Trim at Crossings shows the stretch a click would remove
Hovering with the Trim at Crossings Tool draws in red the stretch a click there would remove, on the same paths and by the same rules as the click, and nothing over empty canvas or hidden and locked paths. A drag draws every stretch its rectangle or freehand line would remove while it reaches at most 32 paths. In isolation mode only paths inside the isolated object are highlighted. What a pick removes moves from the command into vectorcraft_tools::addons::trim::plan, which the command and the tool both use. A preview spends at most a twentieth of the crossing work a click may (Work::share); past that it shows nothing, and the click or release still removes what it reaches. The tool keeps the crossings it found for the document as it is, so moving along one path does not search again, and kept crossings still count against a pick's work budget. Work::spent_since and Work::draw in vectorcraft-pathops measure and charge that work. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md.
This commit is contained in:
@@ -233,11 +233,7 @@ pub fn has_multi(s: &Session) -> std::result::Result<(), String> {
|
||||
/// editing and symbol editing mode isolate their own layer, which does not count here; an object
|
||||
/// isolated inside them counts.
|
||||
pub(crate) fn ordinary_isolation(st: &crate::DocState) -> Option<vectorcraft_doc::NodeId> {
|
||||
st.isolation.filter(|l| {
|
||||
!st.doc.pattern_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.mask_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
&& !st.doc.symbol_edit.as_ref().is_some_and(|e| e.layer == *l)
|
||||
})
|
||||
vectorcraft_tools::ordinary_isolation(&st.doc, st.isolation)
|
||||
}
|
||||
/// Objects are selected ([`has_selection`]), and in isolation mode ([`ordinary_isolation`]) at
|
||||
/// least one of them is inside the isolated object: Object › Lock's and Object › Hide's items.
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
//! Trim at Crossings: remove the stretch of a path between the places where other paths, or the
|
||||
//! path itself, cross it. The command takes the stretch at a point, every stretch a rectangle
|
||||
//! touches, or every stretch a line through some points crosses. It works on every path that can
|
||||
//! be edited, selected or not.
|
||||
|
||||
use std::collections::HashSet;
|
||||
//! be edited, selected or not. What it removes is worked out by
|
||||
//! [`vectorcraft_tools::addons::trim::plan`], which the tool also uses to show it beforehand.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_geom::kurbo::{Line, PathSeg};
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath, hit};
|
||||
use vectorcraft_pathops::addons::pathtools as pt;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_tools::addons::trim::plan::{self, Limits, Pick, Stretches};
|
||||
|
||||
use super::super::super::draw2::replace_with_pieces;
|
||||
use super::super::super::pathops::Beside;
|
||||
@@ -41,16 +39,6 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// What picks the stretches to remove.
|
||||
enum Pick {
|
||||
/// The stretch of the nearest path within the tolerance of the point.
|
||||
At(Point, f64),
|
||||
/// Every stretch the rectangle touches.
|
||||
Rect(Rect),
|
||||
/// Every stretch the line through the points crosses.
|
||||
Line(Vec<Point>, Rect),
|
||||
}
|
||||
|
||||
fn pick(p: &Value) -> Result<Pick> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let given = |key: &str| p.get(key).filter(|v| !v.is_null());
|
||||
@@ -89,194 +77,15 @@ fn pick(p: &Value) -> Result<Pick> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path that takes part: its id, geometry and control-point box.
|
||||
type Part<'a> = (NodeId, &'a PathData, Rect);
|
||||
|
||||
/// The paths that take part, bottom to top: the ones that can be edited, without guides and
|
||||
/// clipping paths. The clipping path of a clip group or a clipped layer is left out whole, the
|
||||
/// members of a compound clipping path included.
|
||||
fn parts(d: &Document) -> Vec<Part<'_>> {
|
||||
let editable = d.editable();
|
||||
let mut masks = HashSet::new();
|
||||
d.walk(|n| {
|
||||
if n.clips()
|
||||
&& let Some(first) = n.children().and_then(|c| c.first())
|
||||
{
|
||||
first.walk(&mut |m| {
|
||||
masks.insert(m.id);
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind
|
||||
&& !masks.contains(&n.id)
|
||||
&& let Some(b) = path.control_bounds()
|
||||
&& editable(n.id)
|
||||
{
|
||||
out.push((n.id, path, b));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Most box tests one command makes between a line's pieces and the paths' segments.
|
||||
const MAX_LINE_TESTS: usize = 60_000_000;
|
||||
/// Most tests one command makes between the boxes of the paths to trim and of the other paths.
|
||||
const MAX_BOX_TESTS: usize = 50_000_000;
|
||||
|
||||
/// Does the line through `pts` cross `sp`? Each piece of the line compared costs one of `budget`;
|
||||
/// `None` once it is spent.
|
||||
fn crossed_by_line(sp: &SubPath, pts: &[Point], budget: &mut usize) -> Option<bool> {
|
||||
let segs: Vec<_> = (0..sp.segment_count())
|
||||
.map(|i| {
|
||||
let c = sp.segment(i);
|
||||
(c, Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3).inflate(1e-9, 1e-9))
|
||||
})
|
||||
.collect();
|
||||
let Some(reach) = segs.iter().map(|s| s.1).reduce(|a, b| a.union(b)) else { return Some(false) };
|
||||
for w in pts.windows(2) {
|
||||
let [a, b] = w else { continue };
|
||||
let piece = Rect::from_points(*a, *b);
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if !reach.overlaps(piece) {
|
||||
continue;
|
||||
}
|
||||
for (c, r) in &segs {
|
||||
*budget = budget.checked_sub(1)?;
|
||||
if r.overlaps(piece) && !PathSeg::Cubic(*c).intersect_line(Line::new(*a, *b)).is_empty() {
|
||||
return Some(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(false)
|
||||
}
|
||||
|
||||
/// Does the rectangle or line of `pick` touch the outline of `piece`? Never for `Pick::At`.
|
||||
fn touches(piece: &SubPath, pick: &Pick, budget: &mut usize) -> Result<bool> {
|
||||
match pick {
|
||||
Pick::At(..) => Ok(false),
|
||||
Pick::Rect(r) => Ok(hit::intersects_rect(&PathData::single(piece.clone()), *r)),
|
||||
Pick::Line(pts, _) => crossed_by_line(piece, pts, budget)
|
||||
.ok_or_else(|| bad("addon.pathtools.trim", "the line is too long, or the paths it passes too many, to check")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` without the stretches `pick` takes (`on`: the place of `Pick::At` on it): its subpaths
|
||||
/// then, and how many stretches went. `None` when none does. A rectangle or a line that touches no
|
||||
/// part of `path` leaves it out before its crossings are looked for.
|
||||
fn trimmed(
|
||||
path: &PathData,
|
||||
others: &[&PathData],
|
||||
pick: &Pick,
|
||||
on: Option<pt::Place>,
|
||||
budget: &mut usize,
|
||||
work: &mut pt::Work,
|
||||
) -> Result<Option<(Vec<SubPath>, usize)>> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let reached = match pick {
|
||||
Pick::At(..) => true,
|
||||
Pick::Rect(r) => hit::intersects_rect(path, *r),
|
||||
Pick::Line(..) => {
|
||||
let mut any = false;
|
||||
for sp in &path.subpaths {
|
||||
if touches(sp, pick, budget)? {
|
||||
any = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
any
|
||||
}
|
||||
};
|
||||
if !reached {
|
||||
return Ok(None);
|
||||
}
|
||||
let places =
|
||||
pt::crossings_on_within(path, others, work).ok_or_else(|| bad(C, "the paths are too many or too tangled to find where they cross"))?;
|
||||
let mut subs = vec![];
|
||||
let mut removed = 0;
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
// The places come in subpath order: this subpath's are one run of them.
|
||||
let run = places.partition_point(|p| p.0 < si)..places.partition_point(|p| p.0 <= si);
|
||||
let here: Vec<(usize, f64)> = places.get(run).unwrap_or_default().iter().map(|&(_, seg, t)| (seg, t)).collect();
|
||||
let spans = pt::spans(sp, &here);
|
||||
let marks: Vec<bool> = match pick {
|
||||
Pick::At(..) => {
|
||||
let at = on.filter(|(s, ..)| *s == si).and_then(|(_, seg, t)| pt::span_at(sp, &spans, seg, t));
|
||||
(0..spans.len()).map(|i| Some(i) == at).collect()
|
||||
}
|
||||
_ => spans.iter().map(|s| touches(&pt::slice(sp, *s), pick, budget)).collect::<Result<_>>()?,
|
||||
};
|
||||
match pt::without_spans(sp, &spans, &marks) {
|
||||
Some(pieces) => {
|
||||
removed += marks.iter().filter(|m| **m).count();
|
||||
subs.extend(pieces);
|
||||
}
|
||||
None => subs.push(sp.clone()),
|
||||
}
|
||||
}
|
||||
Ok((removed > 0).then_some((subs, removed)))
|
||||
}
|
||||
|
||||
fn trim(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "addon.pathtools.trim";
|
||||
let pick = pick(p)?;
|
||||
let st = s.doc()?;
|
||||
let d = &st.doc;
|
||||
let parts = parts(d);
|
||||
// In isolation mode only the isolated object's paths are trimmed; paths outside it still cross them.
|
||||
let root = crate::cmd::ordinary_isolation(st);
|
||||
let in_scope = |id: NodeId| root.is_none_or(|r| id == r || crate::cmd::inside_isolation(d, r, id));
|
||||
// The paths to trim, each with the place `at` falls on.
|
||||
let targets: Vec<(usize, Option<pt::Place>)> = match &pick {
|
||||
Pick::At(at, tolerance) => {
|
||||
let mut best: Option<(usize, pt::Place, f64)> = None;
|
||||
for (i, (id, path, b)) in parts.iter().enumerate() {
|
||||
if !in_scope(*id) {
|
||||
continue;
|
||||
}
|
||||
let b = b.inflate(*tolerance, *tolerance);
|
||||
if !(b.x0 <= at.x && at.x <= b.x1 && b.y0 <= at.y && at.y <= b.y1) {
|
||||
continue;
|
||||
}
|
||||
// Of paths equally near, the one on top.
|
||||
if let Some((si, seg, t, _, dist)) = path.nearest(*at)
|
||||
&& dist <= *tolerance
|
||||
&& best.is_none_or(|b| dist <= b.2)
|
||||
{
|
||||
best = Some((i, (si, seg, t), dist));
|
||||
}
|
||||
}
|
||||
best.map(|(i, on, _)| (i, Some(on))).into_iter().collect()
|
||||
}
|
||||
Pick::Rect(r) | Pick::Line(_, r) => {
|
||||
parts.iter().enumerate().filter(|(_, (id, _, b))| in_scope(*id) && b.overlaps(*r)).map(|(i, _)| (i, None)).collect()
|
||||
}
|
||||
};
|
||||
// Each path to trim has its box tested against every other path's.
|
||||
if targets.len().saturating_mul(parts.len()) > MAX_BOX_TESTS {
|
||||
return Err(bad(C, "the rectangle or line reaches too many paths to check"));
|
||||
}
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
let mut removed = 0;
|
||||
let mut budget = MAX_LINE_TESTS;
|
||||
// One budget of crossing work for every path the command trims.
|
||||
let mut work = pt::Work::default();
|
||||
for (i, on) in targets {
|
||||
let Some((id, path, b)) = parts.get(i) else { continue };
|
||||
let reach = b.inflate(1e-3, 1e-3);
|
||||
let others: Vec<&PathData> =
|
||||
parts.iter().enumerate().filter(|(j, (_, _, ob))| *j != i && reach.overlaps(*ob)).map(|(_, (_, o, _))| *o).collect();
|
||||
let Some((subs, n)) = trimmed(path, &others, &pick, on, &mut budget, &mut work)? else { continue };
|
||||
removed += n;
|
||||
// A path of one subpath becomes a path per piece; the pieces of one with more stay its subpaths.
|
||||
let pieces = match (path.subpaths.len(), subs.is_empty()) {
|
||||
(_, true) => vec![],
|
||||
(1, false) => subs.into_iter().map(PathData::single).collect(),
|
||||
_ => vec![PathData::new(subs)],
|
||||
};
|
||||
plan.push((*id, pieces));
|
||||
}
|
||||
let trimmed = plan::plan(&st.doc, root, &pick, Limits::COMMAND, &mut Stretches::default()).map_err(|e| bad(C, e.message()))?;
|
||||
let removed: usize = trimmed.iter().map(|t| t.count).sum();
|
||||
let plan: Vec<(NodeId, Vec<_>)> = trimmed.into_iter().map(|t| (t.id, t.pieces)).collect();
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [], "removed": 0 }));
|
||||
}
|
||||
|
||||
@@ -480,6 +480,129 @@ fn the_tool_trims_on_release_as_one_step_and_escape_drops_a_drag() {
|
||||
assert_eq!(steps(&s), n + 2);
|
||||
}
|
||||
|
||||
/// The ends of each red path the tool shows.
|
||||
fn highlighted(s: &mut Session, view: crate::ViewInfo) -> Vec<(Point, Point)> {
|
||||
use vectorcraft_geom::kurbo::ParamCurve;
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => {
|
||||
let segs: Vec<_> = path.segments().collect();
|
||||
Some((segs.first()?.start(), segs.last()?.end()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_with_the_tool_shows_the_stretch_its_click_removes() {
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
let mut s = session();
|
||||
let (h, _, _) = across_and_uprights(&mut s);
|
||||
let hidden = line(&mut s, &[(0.0, 200.0), (300.0, 200.0)], false);
|
||||
set_flags(&mut s, hidden, false, false);
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
let n = steps(&s);
|
||||
// Over the middle of the line across: the stretch between the uprights, and nothing changes.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
let shown = highlighted(&mut s, view);
|
||||
assert!(matches!(shown.as_slice(), [(a, b)] if near(*a, 100.0, 100.0) && near(*b, 200.0, 100.0)), "{shown:?}");
|
||||
assert_eq!(steps(&s), n);
|
||||
// Over the hidden path and over empty canvas: nothing.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 200.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 250.0), view).unwrap();
|
||||
assert!(highlighted(&mut s, view).is_empty());
|
||||
// A click where the stretch was shown removes exactly it: the line keeps 0 to 100 and 200 to 300.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 101.0), view).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 101.0), view).unwrap();
|
||||
assert_eq!(steps(&s), n + 1);
|
||||
assert!(near(ends(&s, h).0, 0.0, 100.0) && near(ends(&s, h).1, 100.0, 100.0));
|
||||
let rest = stack(&s).into_iter().find(|id| *id != h && path(&s, *id).subpaths.len() == 1 && near(ends(&s, *id).0, 200.0, 100.0));
|
||||
assert!(rest.is_some_and(|id| near(ends(&s, id).1, 300.0, 100.0)));
|
||||
assert!(highlighted(&mut s, view).is_empty(), "the edit drops the highlight");
|
||||
}
|
||||
|
||||
/// The red paths the tool shows.
|
||||
fn red(s: &mut Session, view: crate::ViewInfo) -> Vec<vectorcraft_geom::BezPath> {
|
||||
s.overlays(view)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
vectorcraft_tools::Overlay::Path { path, color, .. } if color == vectorcraft_tools::builder::HIGHLIGHT_RED => Some(path),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The length of every path in the first layer.
|
||||
fn total_length(s: &Session) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArclen;
|
||||
stack(s).into_iter().flat_map(|id| path(s, id).to_bezpath().segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum()
|
||||
}
|
||||
|
||||
/// `act` removes exactly the red paths shown before it: the paths lose their length, and nothing
|
||||
/// is left on the middle of any of them.
|
||||
fn removes_what_was_shown(s: &mut Session, view: crate::ViewInfo, act: &dyn Fn(&mut Session)) {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let shown = red(s, view);
|
||||
assert!(!shown.is_empty());
|
||||
let shown_length: f64 = shown.iter().flat_map(|p| p.segments().collect::<Vec<_>>()).map(|seg| seg.arclen(1e-9)).sum();
|
||||
let before = total_length(s);
|
||||
act(s);
|
||||
assert!((before - total_length(s) - shown_length).abs() < 1e-3, "{before} - {} != {shown_length}", total_length(s));
|
||||
for p in &shown {
|
||||
let segs: Vec<_> = p.segments().collect();
|
||||
let mid = segs[segs.len() / 2].eval(if segs.len() % 2 == 1 { 0.5 } else { 0.0 });
|
||||
let left = stack(s).into_iter().filter_map(|id| path(s, id).nearest(mid)).map(|n| n.4).fold(f64::INFINITY, f64::min);
|
||||
assert!(left > 0.5, "a path is left at {mid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_tool_shows_before_a_click_or_a_release_is_what_the_command_removes() {
|
||||
use vectorcraft_tools::{Mods, PointerEvent, PointerKind};
|
||||
let view = crate::ViewInfo { smart_guides: false, ..crate::ViewInfo::default() };
|
||||
let ev = |kind, x, y| PointerEvent::new(kind, x, y);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
line(&mut s, &[(50.0, 100.0), (350.0, 100.0)], false);
|
||||
// A Z whose first and last sides cross.
|
||||
line(&mut s, &[(0.0, 160.0), (100.0, 260.0), (100.0, 160.0), (0.0, 260.0)], false);
|
||||
s.select_tool("trimAtCrossings", view).unwrap();
|
||||
s
|
||||
};
|
||||
// A click on the ellipse's top, on the line inside it and on the Z's loop.
|
||||
for (x, y) in [(200.0, 51.0), (200.0, 101.0), (101.0, 210.0)] {
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Move, x, y), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Down, x, y), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Up, x, y), view).unwrap();
|
||||
});
|
||||
}
|
||||
// A rectangle over the ellipse's left side and the line.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 90.0, 90.0), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 120.0, 110.0), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 120.0, 110.0), view).unwrap();
|
||||
});
|
||||
// An Alt line through the ellipse's bottom and the Z's tail.
|
||||
let mut s = setup();
|
||||
s.pointer(&ev(PointerKind::Down, 200.0, 140.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 200.0, 170.0).with_mods(alt), view).unwrap();
|
||||
s.pointer(&ev(PointerKind::Drag, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
removes_what_was_shown(&mut s, view, &|s| {
|
||||
s.pointer(&ev(PointerKind::Up, 10.0, 250.0).with_mods(alt), view).unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_too_long_to_check_against_the_paths_is_refused() {
|
||||
let mut s = session();
|
||||
|
||||
Reference in New Issue
Block a user