Merge main into feat/editable-flares

This commit is contained in:
dotCooCoo committed 2026-11-15 06:55:47 -08:00
commit ea3dec020c
458 files changed
+36345 -2489

No files matched your search

+2 -2
View File
@@ -178,10 +178,10 @@ impl Tool for ExtendPathTool {
let (k, n) = (end.sp.anchors.len(), ext.anchors.len());
// From the old end on; a stretched last curve (no anchor added) shows whole.
let from = if n > k { k - 1 } else { n.saturating_sub(2) };
let tail = if end.start { ext.anchors.get(..n - from) } else { ext.anchors.get(from..) };
let tail = if end.start { ext.anchors.get_range(..n - from) } else { ext.anchors.get_range(from..) };
if let Some(tail) = tail {
let mut bp = vectorcraft_geom::BezPath::new();
SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp);
SubPath::new(tail, false).to_bezpath_into(&mut bp);
out.push(Overlay::Path { path: bp, color: GREY, width: 1.0, dashed: true });
}
}
+2 -2
View File
@@ -478,9 +478,9 @@ impl SmartPenTool {
} else {
straighten_segment(&mut sp, prev);
}
let tail = sp.anchors.get(prev..)?;
let tail = sp.anchors.get_range(prev..)?;
let mut bp = BezPath::new();
SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp);
SubPath::new(tail, false).to_bezpath_into(&mut bp);
Some(bp)
}
}
+97 -7
View File
@@ -1,7 +1,7 @@
use super::cache::RegionCache;
use super::lookup::{
connected_edges, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, lp_stroke_paint, node_outline, visible_edge_near,
visible_face_at,
connected_edges, edges, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, lp_stroke_paint, node_outline,
visible_edge_near, visible_face_at,
};
use super::map::{HIGHLIGHT_RED, sorted_roots};
use super::{
@@ -711,8 +711,14 @@ pub const LP_SELECT_WIDTH_RANGE: (f64, f64) = (1.0, 20.0);
/// with Shift held at the press, each of them leaves the selection if it is selected and joins it
/// otherwise. A double-click on a face selects it and the faces of its group that are not parted
/// from it by a stroked edge; on an edge, it selects the edge and the edges joined to it end to end
/// that have its stroke paint ([`LivePaintSelectionTool::reach_at`]). With Shift held, each of them
/// leaves the selection if it is selected and joins it otherwise.
/// that have its stroke paint ([`LivePaintSelectionTool::reach_at`]). A triple-click on a face
/// selects every face of its group with that face's fill; on an edge, every edge of its group with
/// that edge's stroke paint ([`LivePaintSelectionTool::same_paint_at`]). With Shift held, each part a
/// double-click reaches leaves the selection if it is selected and joins it otherwise, and after a
/// Shift-triple-click each part with the clicked part's paint is toggled from the selection there
/// was before the three clicks. Clicks of the three made without Shift select as they do alone, so
/// when Shift is first held at a later click, the parts are toggled from the selection there was
/// before that click.
/// A click and a marquee change the selection on release, so Escape between the press
/// and the release (which removes the marquee) leaves the selection as it was. The tool does not
/// highlight or select the faces and edges of a Live Paint group that is locked, on a locked layer
@@ -733,6 +739,33 @@ pub struct LivePaintSelectionTool {
width: f64,
/// The drag in progress, from the press to the release.
drag: Option<LpDrag>,
/// The part each of the last two clicks toggled with Shift held, the latest last (None for a
/// click that toggled nothing). A click or marquee without Shift clears both.
recent: [Option<NodeId>; 2],
/// The parts the last double-click, the two clicks before it and the Shift-clicks after it
/// toggled, each listed once when toggled an odd number of times. A Shift-triple-click toggles
/// them back as it toggles the parts with the clicked part's paint, so the selection ends as it
/// was before the clicks with those parts toggled.
toggled: Vec<NodeId>,
}
/// `a` (which lists each id once) with each id of `b` toggled in turn: an id `b` lists an odd number
/// of times is removed when `a` holds it and added at the end otherwise, in `b`'s order.
fn toggle_ids(a: &mut Vec<NodeId>, b: &[NodeId]) {
use std::collections::HashSet;
let mut odd = HashSet::new();
for id in b {
if !odd.insert(*id) {
odd.remove(id);
}
}
let held: HashSet<NodeId> = a.iter().copied().collect();
a.retain(|x| !odd.contains(x));
for id in b {
if !held.contains(id) && odd.remove(id) {
a.push(*id);
}
}
}
/// A press and drag of the Live Paint Selection tool.
@@ -770,6 +803,8 @@ impl Default for LivePaintSelectionTool {
color: HIGHLIGHT_RED,
width: LP_SELECT_WIDTH,
drag: None,
recent: [None; 2],
toggled: vec![],
}
}
}
@@ -812,6 +847,25 @@ impl LivePaintSelectionTool {
let Some(group) = cx.doc.node(gid) else { return vec![] };
if edge { connected_edges(group, part.id, &lp_stroke_paint(part)) } else { flood_faces(group, part.id) }
}
/// What a triple-click at `p` selects, Alt held or not: on the face a click there picks
/// ([`LivePaintSelectionTool::picks_edge`]), that face and every other face of its group that is
/// not hidden and has its fill; on the edge a click picks, that edge and every other edge of its
/// group that is not hidden and draws with the stroke paint it draws with ([`lp_stroke_paint`]).
/// The part under the pointer comes first. Empty where a click selects no face or edge.
fn same_paint_at(&self, cx: &ToolContext, p: Point, alt: bool) -> Vec<NodeId> {
let Some(edge) = self.picks_edge(alt) else { return vec![] };
let Some((gid, Some(part))) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, &|id| lp_selectable(cx, id)) else { return vec![] };
let Some(group) = cx.doc.node(gid) else { return vec![] };
let others: Vec<NodeId> = if edge {
let like = lp_stroke_paint(part);
edges(group).into_iter().filter(|e| e.visible && e.id != part.id && lp_stroke_paint(e) == like).map(|e| e.id).collect()
} else {
let like = part.appearance.fill_paint();
faces(group).into_iter().filter(|f| f.visible && f.id != part.id && f.appearance.fill_paint() == like).map(|f| f.id).collect()
};
std::iter::once(part.id).chain(others).collect()
}
}
/// The faces (with `faces`) and edges (with `edges`) that marquee `r` touches, among the faces and
@@ -918,6 +972,17 @@ impl Tool for LivePaintSelectionTool {
let d = LpDrag { cur: p, ..d };
let Some(r) = d.marquee(cx) else {
// A click selects what the press picked.
// A click without Shift replaces the selection, so what earlier clicks toggled
// no longer counts.
if d.shift {
self.recent = [self.recent[1], d.hit];
if let Some(id) = d.hit {
toggle_ids(&mut self.toggled, &[id]);
}
} else {
self.recent = [None; 2];
self.toggled.clear();
}
return match (d.hit, d.shift) {
(Some(id), true) => vec![Action::Exec("select.toggle".into(), json!({ "id": id.0 }))],
(Some(id), false) => vec![Action::Exec("select.set".into(), json!({ "ids": [id.0] }))],
@@ -925,6 +990,8 @@ impl Tool for LivePaintSelectionTool {
(None, false) => vec![Action::Exec("select.none".into(), json!({}))],
};
};
self.recent = [None; 2];
self.toggled.clear();
let ids = lp_parts_in(cx, r, self.fills, self.strokes);
match (ids.is_empty(), d.shift) {
(true, true) => vec![],
@@ -937,15 +1004,36 @@ impl Tool for LivePaintSelectionTool {
// The two clicks before it already selected the part under the pointer (or, with
// Shift, toggled it twice); the double-click selects the part with what it reaches.
let ids = self.reach_at(cx, p, ev.mods.alt);
self.toggled.clear();
if ev.mods.shift {
let clicks: Vec<NodeId> = self.recent.iter().flatten().copied().collect();
toggle_ids(&mut self.toggled, &clicks);
toggle_ids(&mut self.toggled, &ids);
}
match (ids.is_empty(), ev.mods.shift) {
(true, _) => vec![],
(false, true) => vec![Action::Exec("select.toggle".into(), json!({ "ids": json_ids(&ids) }))],
(false, false) => vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))],
}
}
// The tool takes no action on a triple-click; its third press and release select as a
// click does.
PointerKind::TripleClick => vec![],
PointerKind::TripleClick => {
// The clicks before it already selected the part under the pointer; the
// triple-click selects the part with every part of its group that has its paint.
// With Shift held, the double-click and the third click toggled parts too, and the
// triple-click toggles those back.
let ids = self.same_paint_at(cx, p, ev.mods.alt);
let toggled = std::mem::take(&mut self.toggled);
self.recent = [None; 2];
if ids.is_empty() {
return vec![];
}
if !ev.mods.shift {
return vec![Action::Exec("select.set".into(), json!({ "ids": json_ids(&ids) }))];
}
let mut flip = ids;
toggle_ids(&mut flip, &toggled);
if flip.is_empty() { vec![] } else { vec![Action::Exec("select.toggle".into(), json!({ "ids": json_ids(&flip) }))] }
}
}
}
@@ -963,6 +1051,8 @@ impl Tool for LivePaintSelectionTool {
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.drag = None;
self.recent = [None; 2];
self.toggled.clear();
vec![]
}
+154 -7
View File
@@ -2573,20 +2573,167 @@ fn live_paint_selection_double_click_selects_connected_faces_or_edges() {
assert!(dbl(&mut t, 25.0, 1.0, alt).is_empty());
}
/// A triple-click on a face selects every face of its group with that face's fill, joined to it or
/// not; on an edge (Alt), every edge of its group that draws with that edge's stroke paint. Shift
/// toggles them. Hidden parts, other groups and parts with another paint are left out.
#[test]
fn live_paint_selection_triple_click_adds_nothing_to_its_clicks() {
fn live_paint_selection_triple_click_selects_every_part_of_the_same_paint() {
let mut d = Document::new(500.0, 500.0);
let (_, [a, ..], _) = live_strip(&mut d);
let (_, [a, b, c], [ab, bc, top_a, top_b, top_c, bottom]) = live_strip(&mut d);
let (other, [_, other_top, ..]) = live_square(&mut d, Rect::new(200.0, 0.0, 300.0, 100.0));
let other_face = faces(d.node(other).unwrap())[0].id;
let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0));
// A and C are red and B is blue; the other group's face is red and its top edge black, too.
for (id, fill) in [(a, &red), (b, &blue), (c, &red), (other_face, &red)] {
d.node_mut(id).unwrap().appearance.set_fill(fill.clone());
}
d.node_mut(other_top).unwrap().appearance.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
let s = Selection::default();
let p = paint();
let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))];
let toggle = |ids: &[NodeId]| vec![Action::Exec("select.toggle".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))];
let alt = Mods { alt: true, ..Default::default() };
let shift = Mods { shift: true, ..Default::default() };
let tri = |d: &Document, t: &mut LivePaintSelectionTool, x: f64, y: f64, m: Mods| {
let cx = cx(d, &s, &p);
t.pointer(&cx, &ev(PointerKind::TripleClick, x, y).with_mods(m))
};
let mut t = LivePaintSelectionTool::default();
// A face: every face of its group with its fill, even across the stroked edge BC; the clicked face first.
assert_eq!(tri(&d, &mut t, 125.0, 25.0, Mods::default()), set(&[c, a]));
assert_eq!(tri(&d, &mut t, 75.0, 25.0, Mods::default()), set(&[b]));
// An edge: every edge of its group that draws with its stroke paint, joined to it or not.
assert_eq!(tri(&d, &mut t, 25.0, 1.0, alt), set(&[top_a, top_b, bottom]));
assert_eq!(tri(&d, &mut t, 125.0, 1.0, alt), set(&[top_c, bc]));
assert_eq!(tri(&d, &mut t, 50.0, 25.0, alt), set(&[ab]));
// With Shift held, the parts leave the selection or join it.
assert_eq!(tri(&d, &mut t, 25.0, 25.0, shift), toggle(&[a, c]));
assert_eq!(tri(&d, &mut t, 125.0, 1.0, Mods { alt: true, shift: true, ..Default::default() }), toggle(&[top_c, bc]));
// Away from the group, a triple-click adds nothing to what its clicks did.
assert!(tri(&d, &mut t, 400.0, 400.0, Mods::default()).is_empty());
// A hidden face of the same fill is left out.
d.node_mut(c).unwrap().visible = false;
assert_eq!(tri(&d, &mut t, 25.0, 25.0, Mods::default()), set(&[a]));
// On the other group, a triple-click selects that group's parts alone.
assert_eq!(tri(&d, &mut t, 250.0, 50.0, Mods::default()), set(&[other_face]));
assert_eq!(tri(&d, &mut t, 250.0, 1.0, alt), set(&[other_top]));
// Select Fills off: the triple-click picks the edge nearest the pointer; both off: nothing.
t.set_option("selectFills", &json!(false));
assert_eq!(tri(&d, &mut t, 25.0, 1.0, Mods::default()), set(&[top_a, top_b, bottom]));
t.set_option("selectStrokes", &json!(false));
assert!(tri(&d, &mut t, 25.0, 25.0, Mods::default()).is_empty());
assert!(tri(&d, &mut t, 25.0, 1.0, alt).is_empty());
}
/// The whole event series of a triple-click (three presses and releases, the double-click after
/// the second release and the triple-click after the third), applied to a selection: without
/// Shift the selection ends as the parts with the clicked part's paint, and with Shift as the
/// selection from before the clicks with those parts toggled, whatever the double-click reached.
#[test]
fn live_paint_selection_triple_click_series_ends_with_the_same_paint_parts() {
let mut d = Document::new(500.0, 500.0);
let (_, [a, b, c], [_, bc, top_a, top_b, top_c, bottom]) = live_strip(&mut d);
let red = Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0));
// A and C are red and B is blue; a double-click on A also reaches B across the unstroked edge AB.
for (id, fill) in [(a, &red), (b, &blue), (c, &red)] {
d.node_mut(id).unwrap().appearance.set_fill(fill.clone());
}
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let apply = |sel: &mut Vec<u64>, acts: Vec<Action>| {
for act in acts {
let Action::Exec(cmd, args) = act else { panic!("{act:?}") };
let ids: Vec<u64> = match (args.get("ids"), args.get("id")) {
(Some(v), _) => v.as_array().unwrap().iter().map(|i| i.as_u64().unwrap()).collect(),
(None, Some(i)) => vec![i.as_u64().unwrap()],
(None, None) => vec![],
};
match cmd.as_str() {
"select.set" => *sel = ids,
"select.none" => sel.clear(),
"select.toggle" => {
for i in ids {
match sel.iter().position(|x| *x == i) {
Some(k) => {
sel.remove(k);
}
None => sel.push(i),
}
}
}
other => panic!("{other}"),
}
}
};
// The first click at `first`, every later event at (`x`, `y`).
let series = |t: &mut LivePaintSelectionTool, sel: &mut Vec<u64>, first: (f64, f64), x: f64, y: f64, m: Mods| {
for kind in [PointerKind::Down, PointerKind::Up] {
apply(sel, t.pointer(&cx, &ev(kind, first.0, first.1).with_mods(m)));
}
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
apply(sel, t.pointer(&cx, &ev(kind, x, y).with_mods(m)));
}
};
let sorted = |ids: &[NodeId]| {
let mut v: Vec<u64> = ids.iter().map(|i| i.0).collect();
v.sort_unstable();
v
};
let alt = Mods { alt: true, ..Default::default() };
let shift = Mods { shift: true, ..Default::default() };
let mut t = LivePaintSelectionTool::default();
// The third click's press and release select the face under the pointer, as a click does.
assert_eq!(lp_click(&mut t, &cx, ev(PointerKind::Down, 25.0, 25.0)), vec![Action::Exec("select.set".into(), json!({ "ids": [a.0] }))]);
for m in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { shift: true, ..Default::default() }] {
assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 25.0).with_mods(m)).is_empty());
assert!(t.pointer(&cx, &ev(PointerKind::TripleClick, 25.0, 1.0).with_mods(m)).is_empty());
for (start, first, x, y, m, want) in [
(vec![], (25.0, 25.0), 25.0, 25.0, Mods::default(), sorted(&[a, c])),
(vec![top_c.0], (25.0, 25.0), 25.0, 25.0, Mods::default(), sorted(&[a, c])),
(vec![], (25.0, 25.0), 25.0, 25.0, shift, sorted(&[a, c])),
(vec![top_c.0, c.0], (25.0, 25.0), 25.0, 25.0, shift, sorted(&[a, top_c])),
(vec![], (25.0, 1.0), 25.0, 1.0, Mods { alt: true, shift: true, ..Default::default() }, sorted(&[top_a, top_b, bottom])),
(vec![bc.0], (125.0, 1.0), 125.0, 1.0, alt, sorted(&[top_c, bc])),
// The first click on A and the rest on B, beside it: B alone has B's fill.
(vec![], (49.0, 25.0), 51.0, 25.0, shift, sorted(&[b])),
(vec![c.0], (49.0, 25.0), 51.0, 25.0, shift, sorted(&[b, c])),
] {
let mut sel = start.clone();
series(&mut t, &mut sel, first, x, y, m);
sel.sort_unstable();
assert_eq!(sel, want, "from {start:?} at {first:?} then ({x}, {y}) with {m:?}");
}
// Shift first held at the third click: the two clicks and the double-click select A and B, and
// the parts with A's fill are toggled from that selection.
let mut sel = vec![top_c.0];
for (kind, m) in [
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::DoubleClick, Mods::default()),
(PointerKind::Down, shift),
(PointerKind::Up, shift),
(PointerKind::TripleClick, shift),
] {
apply(&mut sel, t.pointer(&cx, &ev(kind, 25.0, 25.0).with_mods(m)));
}
sel.sort_unstable();
assert_eq!(sel, sorted(&[b, c]));
// A Shift-click on C, then a click on A without Shift, which selects A alone, and Shift held
// from the double-click on: the parts with A's fill are toggled from that selection.
let mut sel = vec![];
for (kind, x, m) in [
(PointerKind::Down, 125.0, shift),
(PointerKind::Up, 125.0, shift),
(PointerKind::Down, 25.0, Mods::default()),
(PointerKind::Up, 25.0, Mods::default()),
(PointerKind::DoubleClick, 25.0, shift),
(PointerKind::Down, 25.0, shift),
(PointerKind::Up, 25.0, shift),
(PointerKind::TripleClick, 25.0, shift),
] {
apply(&mut sel, t.pointer(&cx, &ev(kind, x, 25.0).with_mods(m)));
}
assert_eq!(sel, vec![c.0]);
}
#[test]
+10
View File
@@ -188,6 +188,8 @@ fn snapped(d: Vec2, unsnapped: Vec2, shift: bool, guides: &[Overlay]) -> bool {
pub struct DirectSelectionTool {
group: bool,
state: State,
/// How far the move's last preview carried the anchors or the objects ([`Tool::readout`]).
moved: Option<Vec2>,
/// The spine point last clicked (blend, anchor): its handles show and can be dragged.
spine: Option<(NodeId, usize)>,
/// Other points of that spine picked with it (Shift-click adds or takes one away); dragging
@@ -251,6 +253,7 @@ impl DirectSelectionTool {
Self {
group,
state: State::Idle,
moved: None,
spine: None,
spine_more: vec![],
mesh: MeshEdit::default(),
@@ -733,6 +736,10 @@ impl Tool for DirectSelectionTool {
fn busy(&self) -> bool {
!matches!(self.state, State::Idle) || self.guide.busy()
}
fn readout(&self, _cx: &ToolContext) -> Option<crate::Readout> {
let moving = matches!(self.state, State::MoveAnchors { began: true, .. } | State::MoveObject { began: true, .. });
self.moved.filter(|_| moving).map(crate::Readout::drag)
}
fn options(&self) -> Value {
self.mesh.options()
}
@@ -1486,6 +1493,7 @@ impl DirectSelectionTool {
(d, self.guides) = (q - grab, guides);
}
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
self.moved = Some(d);
out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y})));
out
}
@@ -1538,6 +1546,7 @@ impl DirectSelectionTool {
(d, self.guides) = (q - held, guides);
}
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
self.moved = Some(d);
out.push(Action::Preview("path.moveAnchors".into(), json!({"dx": d.x, "dy": d.y})));
return out;
}
@@ -1553,6 +1562,7 @@ impl DirectSelectionTool {
(d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) };
}
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
self.moved = Some(d);
out.push(Action::Preview(
"object.transform".into(),
json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(d)), "copy": ev.mods.alt}),
+1 -1
View File
@@ -547,7 +547,7 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) {
None => out[0].h_in = h_in,
}
}
sp.anchors = out;
sp.anchors = out.into();
}
/// Apply a liquify stroke (its dabs, at the brush's intensity) to `path`. `salt` decorrelates
+5 -3
View File
@@ -378,9 +378,11 @@ impl PerspectiveGrid {
if (self.origin[1] - self.horizon).abs() < 1e-6 {
return Err("ground level must differ from the horizon".into());
}
// A moved plane stays in front of the viewer.
let behind = |p: Plane| self.axes(p).is_some_and(|[.., n]| 1.0 + self.offset(p) * self.axis_col(n)[2] <= 1e-9);
if Plane::ALL.iter().any(|p| !self.offset(*p).is_finite() || self.offset(*p).abs() > MAX_DEPTH || behind(*p)) {
// A moved plane stays in front of the viewer, both where Automatic Plane Positioning holds
// it and in its own place, which it goes back to.
let behind = |p: Plane, d: f64| self.axes(p).is_some_and(|[.., n]| 1.0 + d * self.axis_col(n)[2] <= 1e-9);
let bad = |p: Plane, d: f64| !d.is_finite() || d.abs() > MAX_DEPTH || behind(p, d);
if Plane::ALL.iter().any(|p| bad(*p, self.offset(*p)) || bad(*p, self.placed_offset(*p))) {
return Err("a plane is moved too far (behind the viewer)".into());
}
self.validate_definition()
+51 -9
View File
@@ -131,17 +131,32 @@ impl PerspectiveGrid {
for plane in self.shown_planes() {
let depth = self.offset(plane);
let Some(h) = self.homography_at(plane, depth) else { continue };
let Some(q) = h.inverse().and_then(|hi| hi.apply(p)) else { continue };
let Some(hi) = h.inverse() else { continue };
let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { continue };
// The drawn lines nearest the pointer along each axis, and their neighbors: the
// projection skews and shrinks the cells, so the intersection nearest on the page can be
// one over from the nearest in the plane.
let near = |v: f64, step: f64, last: usize| {
let i = (v / step).round().clamp(0.0, last as f64) as i64;
(i - 2..=i + 2).filter(move |k| (0..=last as i64).contains(k)).map(move |k| k as f64 * step)
// On each drawn line, the intersections either side of the point of the line nearest
// the pointer on the page. The projection keeps the order of points along a line, so
// the nearest intersection on that line is one of those two, however skewed the cells.
let mut candidates = Vec::with_capacity(2 * (nu + nv + 2));
let mut along = |line: &dyn Fn(f64) -> Point, step: f64, last: usize, coord: fn(Point) -> f64| {
let (Some(a), Some(b)) = (h.apply(line(0.0)), h.apply(line(last as f64 * step))) else { return };
let ab = b - a;
let len2 = ab.x * ab.x + ab.y * ab.y;
let t = if len2 > 0.0 { (((p - a).x * ab.x + (p - a).y * ab.y) / len2).clamp(0.0, 1.0) } else { 0.0 };
let Some(at) = hi.apply(a + ab * t).map(coord).filter(|v| v.is_finite()) else { return };
let k = (at / step).floor().clamp(0.0, last as f64);
for k in [k, (k + 1.0).min(last as f64)] {
candidates.push(line(k * step));
}
};
for (u, v) in near(q.x, su, nu).flat_map(|u| near(q.y, sv, nv).map(move |v| (u, v))) {
let q = Point::new(u, v);
for i in 0..=nu {
let u = i as f64 * su;
along(&|v| Point::new(u, v), sv, nv, |q| q.y);
}
for i in 0..=nv {
let v = i as f64 * sv;
along(&|u| Point::new(u, v), su, nu, |q| q.x);
}
for q in candidates {
let Some(d) = h.apply(q).map(|at| at.distance(p)) else { continue };
if d <= tol
&& best.is_none_or(|b| d < b.0)
@@ -268,6 +283,33 @@ mod tests {
assert!(g.infer_at(&d, past, 3.0, PlaneTargets::ALL).is_none());
}
#[test]
fn a_held_plane_still_checks_its_own_place() {
// Held at x = 0, the left wall's own place must stay in front of the viewer too: it goes
// back there once positioning ends.
let g = PerspectiveGrid { plane: Plane::Left, inferred: Some([0.0; 3]), ..grid() };
assert!(g.merged(&json!({"leftOffset": -800})).is_err());
assert!(PerspectiveGrid { inferred: None, ..g.clone() }.merged(&json!({"leftOffset": -800})).is_err());
let moved = g.merged(&json!({"leftOffset": 40})).unwrap();
assert_eq!((moved.placed_offset(Plane::Left), moved.offset(Plane::Left), moved.inferred), (40.0, 0.0, Some([0.0; 3])));
}
#[test]
fn the_nearest_intersection_on_the_page_is_found_on_a_skewed_plane() {
// The left vanishing point next to the origin skews the left wall's cells hard: the
// intersection nearest on the page lies many cells from the pointer's inverse.
let g = PerspectiveGrid { vp_left: 399.0, plane: Plane::Left, inferred: Some([0.0; 3]), ..grid() };
let d = Document::new(800.0, 600.0);
let gridlines = PlaneTargets { anchors: false, gridlines: true };
let p = Point::new(400.0, 219.761194);
let want = Point::new(10.0 * g.cell, 10.0 * g.cell);
assert!((g.to_page(Plane::Left, want).unwrap() - p).hypot() < 0.5);
let (_, at) = g.infer_at(&d, p, 6.0, gridlines).unwrap();
for (got, want) in at.iter().zip([0.0, want.y, want.x]) {
assert!((got - want).abs() < 1e-6, "{at:?}");
}
}
#[test]
fn a_hidden_path_inside_art_in_perspective_has_no_anchor_to_take() {
let g = PerspectiveGrid { plane: Plane::Right, ..grid() };
+29 -1
View File
@@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Anchor, AnchorKind, BezPath, PathData, Point, Sub
use vectorcraft_pathops as po;
use vectorcraft_pathops::{Cap, Join};
use crate::{Action, Tool, ToolContext};
use crate::{Action, PenPose, Tool, ToolContext};
pub use anchor::AnchorTool;
pub use curvature::{
@@ -87,6 +87,34 @@ pub fn pressure_size(size: f64, variation: f64, pressure: f64) -> f64 {
/// The narrowest a Blob Brush or Eraser stroke gets, in points (their Size field's minimum).
pub const MIN_BRUSH_SIZE: f64 = 0.1;
/// A pen's tilt as a lean on the page (each tilt's tangent) and its angle from upright in degrees,
/// as Pointer Events' tiltX and tiltY convert to an altitude and an azimuth.
fn pen_lean(tilt: [f32; 2]) -> ([f64; 2], f64) {
let [x, y] = tilt.map(|d| f64::from(d).to_radians().tan());
([x, y], x.hypot(y).atan().to_degrees())
}
/// Which way pose `q` leans, in degrees counter-clockwise on the page from leaning to the right,
/// when it leans 1° or more from upright (`path.eraseRegion` keeps the bearing before a pen
/// nearer upright than that).
pub(crate) fn pen_bearing(q: PenPose) -> Option<f64> {
let ([x, y], from_upright) = pen_lean(q.tilt?);
(from_upright >= 1.0).then(|| (-y).atan2(x).to_degrees())
}
/// The 0..1 that each of the Eraser's variation modes Pressure, Tilt, Bearing and Rotation reads
/// from a pen at `pressure` (0..1) held as `pose`, leaning toward `bearing` (degrees, from
/// [`pen_bearing`]): 0 gives the value less its variation and 1 the value plus it, as
/// `path.eraseRegion` reads a stroke's points. Tilt reads 1 upright and 0 lying flat; Bearing and
/// Rotation read ½ plus the angle over 360°, the rotation turned counter-clockwise. What the pen
/// does not give reads ½, the value itself.
pub(crate) fn pen_controls(pressure: f64, pose: Option<PenPose>, bearing: Option<f64>) -> [f64; 4] {
let tilt = pose.and_then(|q| q.tilt).map_or(0.5, |t| 1.0 - pen_lean(t).1 / 90.0);
let rotation = pose.and_then(|q| q.rotation).map_or(0.5, |r| 0.5 + vectorcraft_geom::normalize_deg(-f64::from(r)) / 360.0);
let bearing = bearing.map_or(0.5, |b| 0.5 + b / 360.0);
[pressure, tilt, bearing, rotation].map(|c| if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 })
}
/// Create a drawing tool by id (None = not one of ours).
pub fn create(id: &str) -> Option<Box<dyn Tool>> {
Some(match id {
+147 -32
View File
@@ -12,7 +12,10 @@
//! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and
//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY,
//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob
//! Brush and Eraser also record pressure when their Size varies with Pressure. The other tools
//! Brush and Eraser also record pressure when their Size varies with Pressure, and the Eraser
//! records the pressure, tilt and rotation that its Angle, Roundness and Size variations follow;
//! while it erases, its tip outline at the pointer takes the angle, roundness and size the pen
//! gives there. The other tools
//! collect the drag polyline (shown as an overlay) and run one command on release. With Shift
//! held, the Blob Brush's points stay on the horizontal or
//! vertical line through the press point. Alt held at the press, or before the Blob Brush's drag
@@ -29,6 +32,7 @@ use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{Value, json};
use vectorcraft_brush::{Calligraphic, Variation};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, PathSeg, Point, Rect, Vec2, shapes};
use vectorcraft_pathops as po;
@@ -88,10 +92,11 @@ pub struct GestureTool {
previewed: usize,
id: &'static str,
points: Vec<Point>,
/// The pen pressure of each of `points` (the Paintbrush, and the Blob Brush and the Eraser
/// with `size_pressure`).
/// The pen pressure of each of `points` (the Paintbrush, the Blob Brush with Size on Pressure,
/// and the Eraser with any of its variations on Pressure).
pressures: Vec<f32>,
/// The pen's tilt and rotation at each of `points` (the Paintbrush only).
/// The pen's tilt and rotation at each of `points` (the Paintbrush, and the Eraser with any of
/// its variations on Tilt, Bearing or Rotation).
poses: Vec<Option<PenPose>>,
active: bool,
began: bool,
@@ -117,16 +122,22 @@ pub struct GestureTool {
pub fidelity: f64,
/// Brush / eraser diameter in points (the Eraser's across its tip's long axis).
pub size: f64,
/// Blob Brush and Eraser Tool Options' Size set to Pressure (else Fixed): the tip is `size` −
/// `size_variation` wide at the lightest pen pressure and `size` + `size_variation` at the
/// heaviest.
pub size_pressure: bool,
/// Blob Brush and Eraser Tool Options' Size mode: Fixed or Pressure for the Blob Brush (with
/// Pressure the tip is `size` − `size_variation` wide at the lightest pen pressure and `size` +
/// `size_variation` at the heaviest), and any [`Variation`] for the Eraser.
pub size_mode: Variation,
/// Blob Brush and Eraser Tool Options' Size Variation, in points.
pub size_variation: f64,
/// The angle of the Blob Brush or Eraser tip's long axis, in degrees counter-clockwise from horizontal.
pub angle: f64,
/// The Blob Brush or Eraser tip's short axis in percent of its long one (100: round).
pub roundness: f64,
/// Eraser Tool Options' Angle mode and its Variation in degrees (0 to 180).
pub angle_mode: Variation,
pub angle_variation: f64,
/// Eraser Tool Options' Roundness mode and its Variation in percent (0 to 100).
pub roundness_mode: Variation,
pub roundness_variation: f64,
/// Fill new pencil/brush strokes.
pub fill: bool,
/// "Keep selected": select the path a Pencil, Paintbrush or Blob Brush stroke draws, continues
@@ -176,6 +187,9 @@ pub struct GestureTool {
tip_at: Option<Point>,
/// A pen pressed less than fully at a point of the stroke whose pressure is kept.
light: bool,
/// 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<f64>,
/// 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
@@ -829,10 +843,14 @@ impl GestureTool {
redraw: None,
fidelity,
size: 10.0,
size_pressure: false,
size_mode: Variation::Fixed,
size_variation: 0.0,
angle: 0.0,
roundness: 100.0,
angle_mode: Variation::Fixed,
angle_variation: 0.0,
roundness_mode: Variation::Fixed,
roundness_variation: 0.0,
fill: false,
keep_selected: id != "blobBrush",
// Off, as Pencil Tool Options ships it: Alt keeps drawing a closed path until it is on.
@@ -852,6 +870,7 @@ impl GestureTool {
pressed: Point::ZERO,
tip_at: None,
light: false,
bearing: None,
length: 0.0,
area: Cell::new(None),
area_pending: Cell::new(false),
@@ -908,15 +927,40 @@ impl GestureTool {
self.length += last.distance(p);
}
self.points.push(p);
if self.id == "paintbrush" || (self.varies_size() && self.size_pressure) {
let modes = self.tip_modes();
// The poses go out beside the pressures (`stroke_json`), so a stroke that keeps one keeps both.
let posed = self.id == "paintbrush" || modes.iter().any(|m| matches!(m, Variation::Tilt | Variation::Bearing | Variation::Rotation));
if posed || modes.contains(&Variation::Pressure) {
self.pressures.push(ev.pressure);
self.light |= ev.pressure < 1.0;
}
if self.id == "paintbrush" {
self.poses.push(ev.pen.map(PenPose::sanitized));
if posed {
let pose = ev.pen.map(PenPose::sanitized);
self.bearing = pose.and_then(super::pen_bearing).or(self.bearing);
self.poses.push(pose);
}
}
/// Give the Eraser's last stroke sample the pen's tilt and rotation of the event `ev`, a drag
/// within a pixel of that sample that adds none: a pen turned or tilted in place turns its tip
/// there, in the outline and in what the release erases. The sample keeps its pressure, which
/// the area outline of the drag was built with, and its pose when `ev` reads none.
fn refresh_last_pose(&mut self, ev: &PointerEvent) {
if self.id != "eraser" || self.poses.len() != self.points.len() || ev.pen.is_none() {
return;
}
let pose = ev.pen.map(PenPose::sanitized);
let Some(last) = self.poses.last_mut() else { return };
let had_bearing = last.and_then(super::pen_bearing).is_some();
*last = pose;
// The bearing is that of the last sample the pen leaned at, as `push` keeps it.
self.bearing = match pose.and_then(super::pen_bearing) {
Some(b) => Some(b),
None if had_bearing => self.poses.iter().rev().find_map(|q| q.and_then(super::pen_bearing)),
None => self.bearing,
};
}
/// Would a press with `m` held draw a straight Pencil line? Shift or Alt held, unless Alt lends
/// the Smooth tool: the rule `PointerKind::Down` sets `straight` by.
fn straight_at_press(&self, m: Mods) -> bool {
@@ -975,12 +1019,14 @@ impl GestureTool {
}
/// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline
/// `size` across at its angle and roundness, at the zoom, black on a white halo so it reads on
/// `size` across at its angle and roundness (the Eraser's as the pen varies them while it
/// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on
/// any art. Precise cursors show only the crosshair, and smoothing shows no tip.
fn tip_outline(&self, cx: &ToolContext) -> Vec<Overlay> {
let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] };
let tip = if self.id == "blobBrush" { blob_tip(self.angle, self.roundness) } else { eraser_tip(self.angle, self.roundness) };
let r = self.size / 2.0;
let [angle, roundness, size] = self.tip_now();
let tip = if self.id == "blobBrush" { blob_tip(angle, roundness) } else { eraser_tip(angle, roundness) };
let r = size / 2.0;
// A tolerance relative to the radius: four arcs at any size or zoom.
let circle = kurbo::Shape::to_path(&kurbo::Circle::new(Point::ORIGIN, r), 0.1 * r.max(1e-6));
let path = Affine::translate(at.to_vec2()) * tip * circle;
@@ -999,6 +1045,7 @@ impl GestureTool {
self.previewed = 0;
self.shift_line = None;
self.light = false;
self.bearing = None;
self.length = 0.0;
self.area.set(None);
self.area_pending.set(false);
@@ -1064,7 +1111,53 @@ impl GestureTool {
/// keeps its Size).
fn size_pressures(&self) -> Option<&[f32]> {
let pressed = self.pressures.len() == self.points.len() && self.light;
(self.varies_size() && self.size_pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
(self.tip_modes()[2] == Variation::Pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
}
/// How the tip's angle, roundness and size vary: the Eraser's three modes, the Blob Brush's
/// Size mode (its angle and roundness stay fixed), and Fixed for the other tools. A mode whose
/// Variation is 0 is Fixed.
fn tip_modes(&self) -> [Variation; 3] {
let fixed_at_zero = |mode: Variation, v: f64| if v > 0.0 { mode } else { Variation::Fixed };
match self.id {
"eraser" => [
fixed_at_zero(self.angle_mode, self.angle_variation),
fixed_at_zero(self.roundness_mode, self.roundness_variation),
fixed_at_zero(self.size_mode, self.size_variation),
],
"blobBrush" => [Variation::Fixed, Variation::Fixed, fixed_at_zero(self.size_mode, self.size_variation)],
_ => [Variation::Fixed; 3],
}
}
/// The Eraser's angle, roundness and size where its tip outline shows: while it erases, each
/// value on a mode that follows the pen goes from the value less its Variation to the value
/// plus it as the pen reads now (the pressure once the pen has pressed less than fully, the
/// tilt and rotation of the last point, and the bearing of the last point the pen leaned 1° or
/// 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;
}
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);
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() {
let c = match mode {
Variation::Pressure => controls[0],
Variation::Tilt => controls[1],
Variation::Bearing => controls[2],
Variation::Rotation => controls[3],
Variation::Fixed | Variation::Random => continue,
};
// The size goes past a nib's 1296 pt, as `path.eraseRegion` sweeps it.
*v = if i == 2 { super::pressure_size(*v, variations[i], c) } else { Calligraphic::moved(i, *v, variations[i] * (2.0 * c - 1.0)) };
}
let [angle, roundness, size] = out;
[angle, roundness.clamp(1.0, 100.0), size.max(super::MIN_BRUSH_SIZE)]
}
/// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation]` when a pen read its tilt or
@@ -1254,7 +1347,7 @@ impl GestureTool {
json!({
"points": self.stroke_json(),
"size": self.size,
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
"sizeMode": self.size_mode.id(),
"sizeVariation": self.size_variation,
"fidelity": self.fidelity,
"angle": self.angle,
@@ -1268,10 +1361,14 @@ impl GestureTool {
json!({
"points": self.stroke_json(),
"size": self.size,
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
"sizeMode": self.size_mode.id(),
"sizeVariation": self.size_variation,
"angle": self.angle,
"roundness": self.roundness
"angleMode": self.angle_mode.id(),
"angleVariation": self.angle_variation,
"roundness": self.roundness,
"roundnessMode": self.roundness_mode.id(),
"roundnessVariation": self.roundness_variation
}),
)],
"knife" if pts.len() >= 2 => vec![Action::Exec("path.knife".into(), json!({"points": points_json(pts)}))],
@@ -1385,6 +1482,9 @@ impl Tool for GestureTool {
let release_end = kept.unwrap_or(end);
self.near_start = self.release_closes_near_start(cx, release_end);
self.connects = self.connects_at(cx, release_end).is_some();
if self.points.last().is_some_and(|l| l.distance(p) < cx.tol(1.0)) {
self.refresh_last_pose(ev);
}
return vec![];
}
self.push(p, ev);
@@ -1438,13 +1538,17 @@ impl Tool for GestureTool {
}
} else if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) {
self.push(end, ev);
} else if self.grid_snaps(cx)
&& !self.smoothing
&& self.points.len() > 1
&& let Some(last) = self.points.last_mut()
{
// The last step was where the button went up: it moves where that snaps.
*last = end;
} else {
// A release within a pixel of the last step gives it the pen's pose there.
self.refresh_last_pose(ev);
if self.grid_snaps(cx)
&& !self.smoothing
&& self.points.len() > 1
&& let Some(last) = self.points.last_mut()
{
// The last step was where the button went up: it moves where that snaps.
*last = end;
}
}
let out = if cancel { vec![Action::Cancel] } else { self.finish(cx, ev.mods) };
self.active = false;
@@ -1666,7 +1770,7 @@ impl Tool for GestureTool {
json!({
"fidelity": self.fidelity,
"size": self.size,
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
"sizeMode": self.size_mode.id(),
"sizeVariation": self.size_variation,
"angle": self.angle,
"roundness": self.roundness,
@@ -1676,10 +1780,14 @@ impl Tool for GestureTool {
}
"eraser" => json!({
"size": self.size,
"sizeMode": if self.size_pressure { "pressure" } else { "fixed" },
"sizeMode": self.size_mode.id(),
"sizeVariation": self.size_variation,
"angle": self.angle,
"roundness": self.roundness
"angleMode": self.angle_mode.id(),
"angleVariation": self.angle_variation,
"roundness": self.roundness,
"roundnessMode": self.roundness_mode.id(),
"roundnessVariation": self.roundness_variation
}),
_ => Value::Null,
}
@@ -1688,12 +1796,19 @@ impl Tool for GestureTool {
match key {
"fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(super::min_fidelity(self.id), 100.0),
"size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0),
"sizeMode" if self.varies_size() => match v.as_str() {
Some("pressure") => self.size_pressure = true,
Some("fixed") => self.size_pressure = false,
// The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size
// take any mode.
"sizeMode" if self.varies_size() => match v.as_str().and_then(Variation::parse) {
Some(m) if self.id == "eraser" || matches!(m, Variation::Fixed | Variation::Pressure) => self.size_mode = m,
_ => {}
},
"angleMode" if self.id == "eraser" => self.angle_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.angle_mode),
"roundnessMode" if self.id == "eraser" => self.roundness_mode = v.as_str().and_then(Variation::parse).unwrap_or(self.roundness_mode),
"sizeVariation" if self.varies_size() => self.size_variation = v.as_f64().unwrap_or(self.size_variation).clamp(0.0, 1000.0),
"angleVariation" if self.id == "eraser" => self.angle_variation = v.as_f64().unwrap_or(self.angle_variation).clamp(0.0, 180.0),
"roundnessVariation" if self.id == "eraser" => {
self.roundness_variation = v.as_f64().unwrap_or(self.roundness_variation).clamp(0.0, 100.0)
}
"angle" => self.angle = v.as_f64().unwrap_or(self.angle).clamp(-180.0, 180.0),
"roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0),
"fill" => self.fill = v.as_bool().unwrap_or(self.fill),
+167 -2
View File
@@ -527,10 +527,20 @@ fn blob_brush_sends_keep_selected_and_merge_only_with_selection() {
"{acts:?}"
);
}
// The Eraser keeps Size (Fixed by default), Angle and Roundness: a round tip by default.
// The Eraser keeps Size, Angle and Roundness, each Fixed by default: a round tip by default.
assert_eq!(
GestureTool::new("eraser").options(),
json!({"size": 10.0, "sizeMode": "fixed", "sizeVariation": 0.0, "angle": 0.0, "roundness": 100.0})
json!({
"size": 10.0,
"sizeMode": "fixed",
"sizeVariation": 0.0,
"angle": 0.0,
"angleMode": "fixed",
"angleVariation": 0.0,
"roundness": 100.0,
"roundnessMode": "fixed",
"roundnessVariation": 0.0
})
);
}
@@ -2768,6 +2778,161 @@ fn the_blob_brush_and_the_eraser_show_their_tip_at_the_pointer() {
}
}
/// Eraser Tool Options' Angle, Roundness and Size variation menus: the Eraser keeps each mode and
/// Variation, the release sends them with the pen's readings along the drag, and while it erases
/// its tip outline at the pointer takes the angle, roundness and size the pen gives there. The Blob
/// Brush's Size takes Fixed and Pressure only, and it has no Angle or Roundness menus.
#[test]
fn the_eraser_tip_follows_its_variation_modes() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
// The bounds of the tip outline, the last two overlays (its halo and its line).
let tip = |t: &GestureTool| match &t.overlays(&cx)[..] {
[.., Overlay::Path { path: halo, width: 3.0, .. }, Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => {
assert_eq!(halo, path);
vectorcraft_geom::Shape::bounding_box(path)
}
o => 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 mut t = GestureTool::new("eraser");
assert_eq!(
(t.options()["angleMode"].clone(), t.options()["roundnessMode"].clone(), t.options()["sizeMode"].clone()),
(json!("fixed"), json!("fixed"), json!("fixed")),
"Fixed by default"
);
for (k, v) in [
("size", json!(20)),
("roundness", json!(25)),
("angleMode", json!("rotation")),
("angleVariation", json!(90)),
("roundnessMode", json!("random")),
("roundnessVariation", json!(10)),
("sizeMode", json!("tilt")),
("sizeVariation", json!(8)),
] {
t.set_option(k, &v);
}
let o = t.options();
assert_eq!(
[&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]],
[&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)]
);
// A mode it does not have leaves the mode as it was; a Variation is kept within its range.
t.set_option("angleMode", &json!("wheel"));
t.set_option("roundnessVariation", &json!(500));
assert_eq!((t.options()["angleMode"].clone(), t.options()["roundnessVariation"].clone()), (json!("rotation"), json!(100.0)));
t.set_option("roundnessVariation", &json!(10));
// Before a press the outline is the set tip: 20 by 5 pt, lying level.
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 100.0, 50.0));
near(tip(&t), (90.0, 47.5, 110.0, 52.5));
// Erasing with the barrel turned half way round and the pen upright, the tip stands upright and
// is 28 by 7 pt; Random leaves the roundness as set.
let pen = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(180.0) });
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (196.5, 36.0, 203.5, 64.0));
let acts = t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") };
assert_eq!(c, "path.eraseRegion");
assert_eq!(
[&v["angleMode"], &v["angleVariation"], &v["roundnessMode"], &v["roundnessVariation"], &v["sizeMode"], &v["sizeVariation"]],
[&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)]
);
assert_eq!(
v["points"],
json!([[100.0, 50.0, 0.5, 0.0, 0.0, 180.0], [200.0, 50.0, 0.5, 0.0, 0.0, 180.0]]),
"the pen's readings go with the points"
);
// A mouse drag, which reads no tilt or rotation, keeps the set tip.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 50.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 50.0));
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 50.0));
// A point without a reading after one with it goes back to the set tip there, as the release
// erases it.
t.pointer(&cx, &PointerEvent { pen, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
// The Blob Brush's Size is Fixed or Pressure, and its Angle and Roundness have no menus.
let mut b = GestureTool::new("blobBrush");
b.set_option("sizeMode", &json!("tilt"));
b.set_option("angleMode", &json!("rotation"));
assert_eq!(b.options()["sizeMode"], json!("fixed"));
assert!(b.options().get("angleMode").is_none() && b.options().get("roundnessVariation").is_none());
b.set_option("sizeMode", &json!("pressure"));
assert_eq!(b.options()["sizeMode"], json!("pressure"));
}
/// The Eraser's tip outline follows a pen turned in place, which adds no stroke point, and the
/// release erases with that reading; and its size passes 1296 pt as `path.eraseRegion` sweeps it.
#[test]
fn the_eraser_tip_turns_in_place_and_passes_a_nib_size() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let tip = |t: &GestureTool| match &t.overlays(&cx)[..] {
[.., Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }] => vectorcraft_geom::Shape::bounding_box(path),
o => 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 mut t = GestureTool::new("eraser");
for (k, v) in [("size", json!(20)), ("roundness", json!(25)), ("angleMode", json!("rotation")), ("angleVariation", json!(90))] {
t.set_option(k, &v);
}
let level = Some(PenPose { tilt: None, rotation: Some(0.0) });
let turned = Some(PenPose { tilt: None, rotation: Some(180.0) });
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
// The barrel turns half way round with the pointer still: the tip stands upright.
t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (197.5, 40.0, 202.5, 60.0));
let acts = t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
// A release at the last point erases with the pose the pen has as it lifts.
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
let acts = t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
// A release there that reads no pose keeps the last one.
t.pointer(&cx, &PointerEvent { pen: level, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen: turned, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
let acts = t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
assert_eq!(v["points"], json!([[100.0, 50.0, 0.5, null, null, 0.0], [200.0, 50.0, 0.5, null, null, 180.0]]));
// With Angle on Bearing, a pen that leaned only at the last point and stands up there again
// leaves no bearing: the tip lies level, as set.
t.set_option("angleMode", &json!("bearing"));
let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None });
let leaning = Some(PenPose { tilt: Some([0.0, 45.0]), rotation: None });
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen: leaning, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
assert!(tip(&t).height() > 6.0, "{:?}", tip(&t));
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (190.0, 47.5, 210.0, 52.5));
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Up, 200.0, 50.0) });
// Size 1000 with a Variation of 1000 on Tilt, the pen upright: a tip 2000 pt across.
let mut t = GestureTool::new("eraser");
for (k, v) in [("size", json!(1000)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(1000))] {
t.set_option(k, &v);
}
let upright = Some(PenPose { tilt: Some([0.0, 0.0]), rotation: None });
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Down, 100.0, 50.0) });
t.pointer(&cx, &PointerEvent { pen: upright, pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, 200.0, 50.0) });
near(tip(&t), (-800.0, -950.0, 1200.0, 1050.0));
}
#[test]
fn smooth_needs_selection_and_brackets_resize() {
let (d, _) = doc_with_rect();
+256 -20
View File
@@ -1,8 +1,10 @@
//! Flare, Reshape, Shaper and Graph tools.
//!
//! Flare: drag sets the center and its size and turns the rays as the pointer moves up or down
//! (Shift holds their turn; click without dragging opens the Flare Tool Options), then a click
//! sets the end point of the rings; Space held during either drag moves the flare. The rest comes
//! (Shift holds their turn, ↑/↓ add or remove rays and Ctrl/Cmd keeps the center's size while the
//! drag sizes the halo; click without dragging opens the Flare Tool Options), then a click sets the
//! end point of the rings (↑/↓ add or remove rings and ~ places them anew); Space held during
//! either drag moves the flare. The rest comes
//! from the tool's options (the Flare Tool Options, which last). With one flare selected, the tool
//! shows its center and end handles, and dragging either changes the flare's length and direction
//! (`shape.editFlare`). Reshape: a click on a selected
@@ -59,8 +61,19 @@ pub struct FlareTool {
/// The pointer at the last press or drag, from which Space held moves the flare.
last: Point,
began: bool,
/// Ray count changed with ↑/↓ during the gesture (None = the options' count).
/// Ray count changed with ↑/↓ during the center drag (None = the options' count).
rays: Option<u64>,
/// Ring count changed with ↑/↓ while the rings' end point is placed (None = the options' count).
rings: Option<u64>,
/// The rings' placement ~ chose (`shape.flare`'s `ringSeed`; None = the placement `seed` gives).
ring_seed: Option<u64>,
/// Whether backquote (the ~ key) was held at the last pointer event.
quote: bool,
/// Ctrl/Cmd held in the center drag: the center's diameter, the Halo growth (%) and the
/// pointer's distance from the center when the key went down.
held: Option<(f64, f64, f64)>,
/// The Halo growth (%) the drag set while Ctrl/Cmd held the center (None = the options').
growth: Option<f64>,
/// The rays' turn (`shape.flare`'s `rotation`, degrees) the center drag set.
turn: f64,
/// The options' values, in [`FLARE_OPTIONS`] order.
@@ -111,6 +124,11 @@ impl Default for FlareTool {
last: Point::ZERO,
began: false,
rays: None,
rings: None,
ring_seed: None,
quote: false,
held: None,
growth: None,
turn: 0.0,
values: FLARE_OPTIONS.map(|(_, default, _, _)| default),
rays_on: true,
@@ -158,9 +176,27 @@ fn ray_turn(turn: f64, dy: f64, shift: bool) -> f64 {
(turn + dy * RAY_DEGREES_PER_POINT).rem_euclid(360.0)
}
/// The ring placement ~ chooses after `last`, with the pointer at `at`: a new number below 2^53, so
/// a JSON client reads it exactly, and never `last` again.
fn next_ring_seed(last: Option<u64>, at: Point) -> u64 {
let mut x = last.unwrap_or(0x9e37_79b9_7f4a_7c15) ^ at.x.to_bits() ^ at.y.to_bits().rotate_left(29);
loop {
// SplitMix64.
x = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = x;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
let seed = (z ^ (z >> 31)) & ((1 << 53) - 1);
if Some(seed) != last {
return seed;
}
}
}
impl FlareTool {
/// `shape.flare`'s params: the options, with the dragged center and diameter, the rays' turn,
/// the ray count ↑/↓ chose and the rings' end point once clicked.
/// the ray and ring counts ↑/↓ chose, the Halo growth Ctrl/Cmd set, the ring placement ~ chose
/// and the rings' end point once placed.
fn params(&self, c: Point, diameter: f64, end: Option<Point>) -> Value {
let mut v = flare_params(&self.options(), c);
v["diameter"] = json!(diameter.max(1.0));
@@ -168,12 +204,62 @@ impl FlareTool {
if let Some(r) = self.rays.filter(|_| self.rays_on) {
v["rays"] = json!(r);
}
if let Some(r) = self.rings.filter(|_| self.rings_on) {
v["rings"] = json!(r);
}
if let Some(g) = self.growth {
v["growth"] = json!(g);
}
if let Some(s) = self.ring_seed.filter(|_| self.rings_on) {
v["ringSeed"] = json!(s);
}
if let Some(e) = end {
v["x2"] = json!(e.x);
v["y2"] = json!(e.y);
}
v
}
/// Flare Tool Options value `key` as the tool has it.
fn option(&self, key: &str) -> f64 {
FLARE_OPTIONS.iter().position(|(k, ..)| *k == key).map_or(0.0, |i| self.values[i])
}
/// Count `now` (else the options' `key`) one up or down, within the options' range for `key`.
fn step_count(&self, key: &str, now: Option<u64>, up: bool) -> u64 {
let most = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key).map_or(0.0, |o| o.3) as u64;
let r = now.unwrap_or(self.option(key) as u64);
if up { (r + 1).min(most) } else { r.saturating_sub(1).min(most) }
}
/// Ctrl/Cmd in the center drag, with the pointer `dist` from the center after `before` at the
/// last drag: once the flare has begun, the center keeps the diameter it showed when the key
/// went down, and the halo's radius keeps its ratio to the pointer's distance through the Halo
/// growth, within the options' 0 to 300 %. Letting the key go sizes the center with the drag
/// again, and the flare keeps the new Halo growth. The key is pressed while dragging: a press
/// made with it already held goes to the selection tool the session lends for Ctrl/Cmd.
fn hold_center(&mut self, before: f64, dist: f64, cmd: bool) {
match (cmd, self.held) {
(true, None) if self.began && before > 0.0 => {
let growth = self.growth.unwrap_or_else(|| self.option("growth"));
self.held = Some((2.0 * before, growth, before));
}
(false, Some(_)) => self.held = None,
_ => {}
}
if let Some((_, growth, at)) = self.held {
let most = FLARE_OPTIONS.iter().find(|(k, ..)| *k == "growth").map_or(0.0, |o| o.3);
let g = (100.0 + growth) * dist / at - 100.0;
if g.is_finite() {
self.growth = Some(g.clamp(0.0, most));
}
}
}
/// The center's diameter with the pointer `dist` from it: twice that, unless Ctrl/Cmd holds it.
fn center_diameter(&self, dist: f64) -> f64 {
self.held.map_or(2.0 * dist, |(d, ..)| d)
}
}
impl Tool for FlareTool {
@@ -185,6 +271,12 @@ impl Tool for FlareTool {
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
self.hover = ev.pos;
// ~ pressed while the rings' end point is placed places the rings anew (Rings on).
let quote_pressed = ev.backquote && !self.quote;
self.quote = ev.backquote;
if quote_pressed && self.rings_on && self.placed.is_some() && matches!(ev.kind, PointerKind::Drag | PointerKind::Move | PointerKind::Up) {
self.ring_seed = Some(next_ring_seed(self.ring_seed, ev.pos));
}
if let Some(mut h) = self.handle {
return match ev.kind {
PointerKind::Drag if h.began => vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))],
@@ -218,29 +310,36 @@ impl Tool for FlareTool {
if self.placed.is_none() {
self.drag = Some((ev.pos, ev.pos));
self.rays = None;
self.rings = None;
self.ring_seed = None;
self.held = None;
self.growth = None;
self.turn = 0.0;
}
self.last = ev.pos;
vec![]
}
PointerKind::Drag => {
if let Some((mut c, _)) = self.drag {
if let Some((mut c, p)) = self.drag {
// Space held moves the center with the pointer, so the size and the turn stay.
let before = p.distance(c);
let dy = ev.pos.y - self.last.y;
crate::shape::space_moves(&mut c, &mut self.last, ev, self.began);
self.drag = Some((c, ev.pos));
if !ev.mods.space {
self.turn = ray_turn(self.turn, dy, ev.mods.shift);
}
if !self.began && ev.pos.distance(c) >= cx.tol(3.0) {
self.began = true;
return vec![
Action::Begin("Flare".into()),
Action::Preview("shape.flare".into(), self.params(c, 2.0 * ev.pos.distance(c), None)),
];
let dist = ev.pos.distance(c);
let begins = !self.began && dist >= cx.tol(3.0);
self.began |= begins;
// With the key held from the start, the center keeps the first size the flare shows.
self.hold_center(if begins { dist } else { before }, dist, ev.mods.cmd);
let preview = Action::Preview("shape.flare".into(), self.params(c, self.center_diameter(dist), None));
if begins {
return vec![Action::Begin("Flare".into()), preview];
}
if self.began {
return vec![Action::Preview("shape.flare".into(), self.params(c, 2.0 * ev.pos.distance(c), None))];
return vec![preview];
}
} else if let Some((mut c, d)) = self.placed {
// Space held moves the whole flare, rings' end point included.
@@ -259,7 +358,8 @@ impl Tool for FlareTool {
let Some((c, p)) = self.drag.take() else { return vec![] };
if self.began {
// Keep the interaction open: the next click places the end point.
self.placed = Some((c, 2.0 * p.distance(c)));
self.placed = Some((c, self.center_diameter(p.distance(c))));
self.held = None;
vec![]
} else {
vec![Action::Dialog("flare".into(), json!({ "x": c.x, "y": c.y }))]
@@ -275,13 +375,18 @@ impl Tool for FlareTool {
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
// ↑/↓ while drawing add/remove rays.
if matches!(key, ToolKey::Up | ToolKey::Down) && self.began && self.rays_on {
let r = self.rays.unwrap_or_else(|| self.options()["rays"].as_u64().unwrap_or(0));
self.rays = Some(if key == ToolKey::Up { (r + 1).min(50) } else { r.saturating_sub(1) });
// ↑/↓ add/remove rays in the center drag and rings while the rings' end point is placed.
if matches!(key, ToolKey::Up | ToolKey::Down) && self.began {
let up = key == ToolKey::Up;
let preview = match (self.drag, self.placed) {
(Some((c, p)), _) => self.params(c, 2.0 * p.distance(c), None),
(_, Some((c, d))) => self.params(c, d, Some(self.hover)),
(Some((c, p)), _) if self.rays_on => {
self.rays = Some(self.step_count("rays", self.rays, up));
self.params(c, self.center_diameter(p.distance(c)), None)
}
(_, Some((c, d))) if self.rings_on => {
self.rings = Some(self.step_count("rings", self.rings, up));
self.params(c, d, Some(self.hover))
}
_ => return vec![],
};
return vec![Action::Preview("shape.flare".into(), preview)];
@@ -293,6 +398,10 @@ impl Tool for FlareTool {
}
if key == ToolKey::Escape && self.busy() {
self.rays = None;
self.rings = None;
self.ring_seed = None;
self.held = None;
self.growth = None;
self.drag = None;
self.placed = None;
let began = std::mem::take(&mut self.began);
@@ -303,6 +412,7 @@ impl Tool for FlareTool {
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
// Switching away after the centre drag keeps the flare with the rings its options give.
self.drag = None;
self.held = None;
if self.handle.take().is_some_and(|h| h.began) {
return vec![Action::Commit];
}
@@ -311,7 +421,8 @@ impl Tool for FlareTool {
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
match (self.drag, self.placed) {
(Some((c, p)), _) => {
vec![Overlay::Path { path: ellipse_path(c, p.distance(c), p.distance(c), 0.0), color: BLUE, width: 1.0, dashed: false }]
let r = self.center_diameter(p.distance(c)) / 2.0;
vec![Overlay::Path { path: ellipse_path(c, r, r, 0.0), color: BLUE, width: 1.0, dashed: false }]
}
(_, Some((c, _))) => vec![Overlay::Line { a: c, b: self.hover, color: BLUE, dashed: true }],
// The selected flare's center and end handles.
@@ -973,6 +1084,131 @@ mod tests {
assert_eq!((v["cx"].as_f64(), v["cy"].as_f64(), v["x2"].as_f64()), (Some(120.0), Some(110.0), Some(340.0)));
}
/// ↑/↓ change the rays in the center drag and the rings while the rings' end point is placed,
/// within the options' 0 to 50; with Rings off they leave the second drag alone.
#[test]
fn flare_arrows_change_the_rays_then_the_rings() {
use crate::testutil::*;
use vectorcraft_doc::Selection;
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let counts = |v: &Value| (v["rays"].as_u64(), v["rings"].as_u64());
let mut t = FlareTool::default();
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0));
assert_eq!(counts(&flare_preview(&t.key(&cx, ToolKey::Up, Mods::default()))), (Some(16), Some(10)));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 140.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 320.0, 300.0));
assert_eq!(counts(&flare_preview(&t.key(&cx, ToolKey::Up, Mods::default()))), (Some(16), Some(11)));
t.key(&cx, ToolKey::Down, Mods::default());
assert_eq!(counts(&flare_preview(&t.key(&cx, ToolKey::Down, Mods::default()))), (Some(16), Some(9)));
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 330.0, 300.0));
assert_eq!(a.last(), Some(&Action::Commit));
assert_eq!(counts(&flare_preview(&a)), (Some(16), Some(9)));
// The next flare starts from the options' counts; the counts stop at 0 and 50.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 140.0, 100.0));
let mut v = Value::Null;
for _ in 0..12 {
v = flare_preview(&t.key(&cx, ToolKey::Down, Mods::default()));
}
assert_eq!(counts(&v), (Some(15), Some(0)));
for _ in 0..60 {
v = flare_preview(&t.key(&cx, ToolKey::Up, Mods::default()));
}
assert_eq!(counts(&v), (Some(15), Some(50)));
t.key(&cx, ToolKey::Escape, Mods::default());
// Rings off: the arrows do nothing in the second drag.
t.set_option("ringsOn", &json!(false));
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 140.0, 100.0));
assert!(t.key(&cx, ToolKey::Up, Mods::default()).is_empty());
}
/// ~ (backquote) pressed while the rings' end point is placed gives the rings a new placement
/// each time, which the flare drawn keeps; holding it, the center drag, Rings off and the next
/// flare give none.
#[test]
fn flare_tilde_places_the_rings_anew() {
use crate::testutil::*;
use vectorcraft_doc::Selection;
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let quote = |kind, x, y, held| PointerEvent { backquote: held, ..PointerEvent::new(kind, x, y) };
let seed = |a: &[Action]| flare_preview(a).get("ringSeed").and_then(Value::as_u64);
let mut t = FlareTool::default();
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
// In the center drag ~ does nothing.
assert_eq!(seed(&t.pointer(&cx, &quote(PointerKind::Drag, 140.0, 100.0, true))), None);
t.pointer(&cx, &quote(PointerKind::Drag, 141.0, 100.0, false));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 141.0, 100.0));
assert_eq!(seed(&t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 200.0))), None);
let first = seed(&t.pointer(&cx, &quote(PointerKind::Move, 200.0, 200.0, true)));
assert!(first.is_some_and(|s| s < 1 << 53));
// Held, it places them once; pressed again, anew.
assert_eq!(seed(&t.pointer(&cx, &quote(PointerKind::Move, 210.0, 200.0, true))), first);
t.pointer(&cx, &quote(PointerKind::Down, 210.0, 200.0, false));
t.pointer(&cx, &quote(PointerKind::Drag, 220.0, 200.0, false));
let second = seed(&t.pointer(&cx, &quote(PointerKind::Drag, 220.0, 200.0, true)));
assert!(second.is_some() && second != first);
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 230.0, 200.0));
assert_eq!((a.last(), seed(&a)), (Some(&Action::Commit), second));
// The next flare starts without one, and with Rings off ~ does not change the flare.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
assert_eq!(seed(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0))), None);
t.set_option("ringsOn", &json!(false));
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 140.0, 100.0));
assert_eq!(seed(&t.pointer(&cx, &quote(PointerKind::Move, 200.0, 200.0, true))), None);
assert_eq!(t.ring_seed, None);
}
/// Ctrl/Cmd in the center drag keeps the center's diameter as the last drag showed it, and the
/// drag sizes the halo through the Halo growth (0 to 300 %); let go, the drag sizes the center
/// again and the flare keeps the new growth.
#[test]
fn flare_ctrl_keeps_the_center_and_the_drag_sizes_the_halo() {
use crate::testutil::*;
use vectorcraft_doc::Selection;
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let cmd = Mods { cmd: true, ..Default::default() };
let sized = |a: &[Action]| {
let v = flare_preview(a);
(v["diameter"].as_f64().unwrap_or(0.0), v["growth"].as_f64().unwrap_or(0.0))
};
let mut t = FlareTool::default();
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 140.0, 100.0))), (80.0, 20.0));
// The key goes down with the pointer's next move: the center stays as the last drag showed it.
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 180.0, 100.0).with_mods(cmd))), (80.0, 140.0));
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0).with_mods(cmd))), (80.0, 0.0));
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 900.0, 100.0).with_mods(cmd))), (80.0, 300.0));
assert_eq!(sized(&t.key(&cx, ToolKey::Up, Mods::default())), (80.0, 300.0));
// Let go: the center follows the drag again and the growth stays.
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 100.0))), (100.0, 300.0));
// Pressed again, the hold starts from the new center and growth.
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 100.0).with_mods(cmd))), (100.0, 100.0));
// A release with the key held places the held center; the second drag draws with it.
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 125.0, 100.0).with_mods(cmd));
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0));
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 300.0, 330.0));
assert_eq!((a.last(), sized(&a)), (Some(&Action::Commit), (100.0, 100.0)));
// With the key held from the press, the center keeps the first size the flare shows; the
// next flare starts from the options' growth.
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0));
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 110.0).with_mods(cmd))), (20.0, 20.0));
assert_eq!(sized(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 120.0).with_mods(cmd))), (20.0, 140.0));
}
#[test]
fn reshape_drag_honors_measurement_labels() {
use crate::testutil::*;
+8
View File
@@ -57,10 +57,12 @@ pub use catalog::{TOOL_GROUPS, ToolInfo, tool_info};
mod context;
mod cursor;
mod input;
mod readout;
pub use context::{GlyphSnap, MarqueeMode, PaintDefaults, PixelOp, PixelSnap, ScreenFrame, ToolContext};
pub use cursor::Cursor;
pub use input::{Action, Mods, PenPose, PointerEvent, PointerKind, ToolKey};
pub use readout::Readout;
/// Visual feedback drawn by the UI in screen space (coordinates here are document space).
#[derive(Clone, Debug, PartialEq)]
@@ -265,6 +267,12 @@ pub trait Tool: Send {
fn wants_rehover(&self) -> bool {
false
}
/// What the Info panel shows for the tool as it is now: the drag in progress (a move of the
/// selection, a gradient vector, a Scale, Rotate, Reflect or Shear tool drag), or the
/// Paintbrush's brush. None for a tool with nothing of its own to show.
fn readout(&self, _cx: &ToolContext) -> Option<Readout> {
None
}
/// Called when the user switches away (finish pending work).
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
vec![]
+2 -2
View File
@@ -607,7 +607,7 @@ fn a_drag_from_the_first_anchor_always_closes() {
fn alt_mid_close_keeps_the_turned_outgoing_handle() {
use vectorcraft_geom::{Anchor, SubPath};
let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))];
let (mut d, id, s) = drawing(SubPath { anchors, closed: false });
let (mut d, id, s) = drawing(SubPath::new(anchors, false));
let p = paint();
let mut t = PenTool { drawing: true, ..PenTool::default() };
assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0)));
@@ -634,7 +634,7 @@ fn alt_mid_close_keeps_the_turned_outgoing_handle() {
fn space_moves_the_closing_anchor() {
use vectorcraft_geom::{Anchor, SubPath};
let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))];
let (mut d, id, s) = drawing(SubPath { anchors, closed: false });
let (mut d, id, s) = drawing(SubPath::new(anchors, false));
let p = paint();
let mut t = PenTool { drawing: true, ..PenTool::default() };
assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0)));
+76
View File
@@ -0,0 +1,76 @@
//! What the tool in use gives the Info panel to show ([`crate::Tool::readout`]).
use serde_json::{Value, json};
use vectorcraft_geom::{Point, Vec2};
/// The Info panel's values for the tool in use. Lengths and points are in document units, and
/// angles are in degrees as the matching command takes them: counter-clockwise for
/// `object.rotate`'s `angle` and `object.reflect`'s `axis`, and `object.shear`'s `angle`.
#[derive(Clone, Debug, PartialEq)]
pub enum Readout {
/// A drag that moves the selection or draws a gradient vector: how far it has gone in x and y.
Drag { dx: f64, dy: f64 },
/// A Scale tool drag: the horizontal and vertical scale (1 leaves the size as it is).
Scale { sx: f64, sy: f64 },
/// A Rotate tool drag: where the center of the selection's bounding box is, and the angle
/// turned.
Rotate { center: Point, angle: f64 },
/// A Reflect tool drag: where the center of the selection's bounding box is, and the angle of
/// the axis.
Reflect { center: Point, angle: f64 },
/// A Shear tool drag: where the center of the selection's bounding box is, the angle of the
/// shear axis (0 horizontal, 90 vertical) and the shear angle.
Shear { center: Point, axis: f64, angle: f64 },
/// The Paintbrush: the brush it paints with, if any.
Brush { name: Option<String> },
}
impl Readout {
/// The readout of a drag by `d`.
pub fn drag(d: Vec2) -> Self {
Readout::Drag { dx: d.x, dy: d.y }
}
/// The length of a [`Readout::Drag`] and its angle, as the Measure tool gives them.
pub fn distance_angle(&self) -> Option<(f64, f64)> {
match *self {
Readout::Drag { dx, dy } => {
let (dist, angle, ..) = crate::xform::measure(Point::ORIGIN, Point::new(dx, dy));
Some((dist, angle))
}
_ => None,
}
}
/// The readout as `info.readout` reports it.
pub fn to_json(&self) -> Value {
let at = |p: Point| json!([p.x, p.y]);
match self {
Readout::Drag { dx, dy } => {
let (distance, angle) = self.distance_angle().unwrap_or_default();
json!({ "kind": "drag", "dx": dx, "dy": dy, "distance": distance, "angle": angle })
}
Readout::Scale { sx, sy } => json!({ "kind": "scale", "width": sx * 100.0, "height": sy * 100.0 }),
Readout::Rotate { center, angle } => json!({ "kind": "rotate", "center": at(*center), "angle": angle }),
Readout::Reflect { center, angle } => json!({ "kind": "reflect", "center": at(*center), "angle": angle }),
Readout::Shear { center, axis, angle } => json!({ "kind": "shear", "center": at(*center), "axis": axis, "angle": angle }),
Readout::Brush { name } => json!({ "kind": "brush", "brush": name }),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_drag_gives_its_length_and_its_angle_up_the_page() {
let r = Readout::drag(Vec2::new(30.0, -40.0));
let (d, a) = r.distance_angle().unwrap();
assert!((d - 50.0).abs() < 1e-9 && (a - 53.13010235415598).abs() < 1e-9, "{d} {a}");
assert_eq!(r.to_json()["dx"], 30.0);
assert_eq!(Readout::Scale { sx: 1.5, sy: 0.5 }.to_json(), json!({"kind": "scale", "width": 150.0, "height": 50.0}));
assert_eq!(Readout::Scale { sx: 1.0, sy: 1.0 }.distance_angle(), None);
assert_eq!(Readout::Brush { name: None }.to_json(), json!({"kind": "brush", "brush": null}));
}
}
+7
View File
@@ -172,6 +172,8 @@ pub struct SelectionTool {
/// The params of the move's last preview: in Shaper's Construction mode the move ends with
/// them and `releaseOutside` ([`construction`]).
last_move: Option<Value>,
/// How far the move's last preview carried the selection ([`Tool::readout`]).
moved: Option<Vec2>,
/// Held state used for the most recent bounding-box preview.
last_backquote: bool,
/// Pointer position used for the most recent bounding-box preview.
@@ -898,6 +900,10 @@ impl Tool for SelectionTool {
matches!(self.state, State::Moving { began: true, .. })
}
fn readout(&self, _cx: &ToolContext) -> Option<crate::Readout> {
self.moved.filter(|_| self.moving()).map(crate::Readout::drag)
}
fn transforming(&self) -> bool {
match &self.state {
State::Moving { began: true, .. } | State::Scaling { .. } | State::Rotating { .. } => true,
@@ -1753,6 +1759,7 @@ impl SelectionTool {
params["patterns"] = json!(true);
}
self.last_move = Some(params.clone());
self.moved = Some(d);
out.push(Action::Preview("object.transform".into(), params));
out
}
+2
View File
@@ -43,6 +43,8 @@ const ROWS: &[Row] = &[
(&["blobBrush"], None, &["fidelity", "keepSelected", "mergeOnlySelection"]),
// Eraser Tool Options' tip shape.
(&["blobBrush", "eraser"], None, &["angle", "roundness"]),
// Eraser Tool Options' Angle and Roundness variation menus and fields.
(&["eraser"], None, &["angleMode", "angleVariation", "roundnessMode", "roundnessVariation"]),
// Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`).
(&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]),
// Live Paint Bucket Options (`builder::LivePaintBucketTool`).
+3
View File
@@ -299,6 +299,9 @@ impl Tool for BrushPaintTool {
fn busy(&self) -> bool {
self.inner.busy()
}
fn readout(&self, cx: &ToolContext) -> Option<crate::Readout> {
Some(crate::Readout::Brush { name: self.brush_name(cx) })
}
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
let acts = self.inner.deactivate(cx);
self.map(cx, acts)
+6
View File
@@ -545,6 +545,12 @@ impl Tool for GradientTool {
self.gesture.as_ref().is_some_and(|g| g.began) || self.free.as_ref().is_some_and(freeform::Gesture::began)
}
/// The vector a drag on the art has drawn so far.
fn readout(&self, _cx: &ToolContext) -> Option<crate::Readout> {
let (start, end) = self.gesture.as_ref().filter(|g| g.began)?.vector?;
Some(crate::Readout::drag(end - start))
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
// A freeform gradient: its points instead of the bar.
match (ev.kind, &mut self.free) {
+48 -8
View File
@@ -20,7 +20,7 @@ use super::target_overlays;
use crate::bbox::rotate_for_drag;
use crate::guides::{PointSnap, Targets, snap_pick};
use crate::select::{matrix_json, selection_bounds, selection_box};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Readout, Tool, ToolContext, ToolKey};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TransformKind {
@@ -98,6 +98,8 @@ pub struct TransformTool {
origin: Option<(Point, Vec<NodeId>)>,
drag: Option<Drag>,
measure: Option<(Point, String)>,
/// What the Info panel shows for the drag in progress.
readout: Option<Readout>,
/// Snap feedback while hovering ("anchor" / "center" label), and for the dragged pointer.
hover: Vec<Overlay>,
/// What the dragged pointer snaps to, gathered when the drag begins.
@@ -126,7 +128,7 @@ pub fn reflect_matrix(o: Point, theta: f64) -> Affine {
impl TransformTool {
pub fn new(kind: TransformKind) -> Self {
Self { kind, origin: None, drag: None, measure: None, hover: vec![], snap: None }
Self { kind, origin: None, drag: None, measure: None, readout: None, hover: vec![], snap: None }
}
/// The effective reference point: the custom one if it belongs to the current selection,
@@ -154,12 +156,44 @@ impl TransformTool {
/// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the
/// line the pointer draws on the page.
pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
let (m, a, b) = self.solve(angle, o, start, p, shift, bounds);
(m, self.label(a, b))
}
/// The canvas label for the two values [`Self::solve`] gives.
fn label(&self, a: f64, b: f64) -> String {
match self.kind {
TransformKind::Rotate => format!("{:.1}°", -a),
TransformKind::Reflect => format!("{a:.1}°"),
TransformKind::Scale => format!("W: {:.1}%\nH: {:.1}%", a * 100.0, b * 100.0),
TransformKind::Shear => format!("{:.1}°", if a == 0.0 { b } else { -b }),
}
}
/// What the Info panel shows for the transform `m` of a selection with `bounds`, with the two
/// values [`Self::solve`] gives.
fn readout_of(&self, m: Affine, a: f64, b: f64, bounds: Rect) -> Readout {
let center = m * bounds.center();
match self.kind {
TransformKind::Rotate => Readout::Rotate { center, angle: a },
TransformKind::Reflect => Readout::Reflect { center, angle: a },
TransformKind::Scale => Readout::Scale { sx: a, sy: b },
TransformKind::Shear => Readout::Shear { center, axis: a, angle: b },
}
}
/// [`TransformTool::matrix_in`]'s transform, with the two values of its readout: the angle
/// turned, in degrees counter-clockwise as `object.rotate` takes it (Rotate), the angle of the
/// axis in degrees counter-clockwise (Reflect), the scale along the box's width and height
/// (Scale), or the angle of the shear axis (0 horizontal, 90 vertical) and the shear angle as
/// `object.shear` takes it (Shear).
fn solve(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, f64, f64) {
let frame = OrientedBox { angle, rect: Rect::ZERO };
let local = |v: Vec2| frame.to_doc().inverse() * v.to_point();
match self.kind {
TransformKind::Rotate => {
let (a, deg) = rotate_for_drag(o, start, p, shift);
(a, format!("{:.1}°", -deg))
(a, deg, 0.0)
}
TransformKind::Reflect => {
let mut v = p - o;
@@ -169,7 +203,7 @@ impl TransformTool {
v = (frame.to_doc() * vectorcraft_geom::constrain_angle(local(v).to_vec2(), 45.0).to_point()).to_vec2();
}
let theta = v.y.atan2(v.x);
(reflect_matrix(o, theta), format!("{:.1}°", vectorcraft_geom::normalize_deg(-theta.to_degrees())))
(reflect_matrix(o, theta), vectorcraft_geom::normalize_deg(-theta.to_degrees()), 0.0)
}
TransformKind::Scale => {
let d0 = local(start - o).to_vec2();
@@ -184,7 +218,7 @@ impl TransformTool {
}
let clamp = |s: f64| if s.abs() < 1e-4 { 1e-4f64.copysign(s) } else { s };
let (sx, sy) = (clamp(sx), clamp(sy));
(about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), format!("W: {:.1}%\nH: {:.1}%", sx * 100.0, sy * 100.0))
(about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), sx, sy)
}
TransformKind::Shear => {
// The shear axis follows the dominant drag direction. Shift keeps the drag on that
@@ -223,7 +257,7 @@ impl TransformTool {
};
}
}
(m, format!("{:.1}°", (-k.atan()).to_degrees()))
if horizontal { (m, 0.0, (-k.atan()).to_degrees()) } else { (m, 90.0, k.atan().to_degrees()) }
}
}
}
@@ -231,6 +265,7 @@ impl TransformTool {
/// Ends the drag, its snapping and readouts with it.
fn end_drag(&mut self) -> Option<Drag> {
self.measure = None;
self.readout = None;
self.snap = None;
self.hover.clear();
self.drag.take()
@@ -250,6 +285,10 @@ impl Tool for TransformTool {
self.drag.is_some_and(|d| d.began)
}
fn readout(&self, _cx: &ToolContext) -> Option<Readout> {
self.readout.clone()
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
match ev.kind {
@@ -294,10 +333,11 @@ impl Tool for TransformTool {
}
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
self.hover = guides;
let (m, text) = self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
let (m, a, b) = self.solve(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
(d.last, d.pointer, d.shift) = (m, p, ev.mods.shift);
self.drag = Some(d);
self.measure = Some((p, text));
self.measure = Some((p, self.label(a, b)));
self.readout = Some(self.readout_of(m, a, b, d.bounds));
out.push(preview(m, ev.mods.alt, ev.backquote));
out
}