mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-06 05:53:08 -05:00
Live Corners: a pixel-grid snap converts relative radii as an anchor move does
With relative rounding, a move that bent a straightened corner converted its stored radius to a fraction of the bent corner's maximum. When the pixel-grid snap then straightened the corner again, the radius stayed in those units, so the move changed the radius and recorded an undo step although no anchor moved, and the corner rounded at the wrong size when bent later. The snap of a path with Live Corners now converts the radii of corners it straightens or bends, with the same rule as an anchor edit, and a move the snap takes back counts as no change when the radii differ only by rounding. The help of object.setLiveShape, path.moveAnchor and path.moveAnchors and docs/mcp.md now say that a straightened corner keeps its radius and the path stays live.
This commit is contained in:
1 parent
ab55c77d89
commit
de2a7a958b
7 files changed
+89
-20
No files matched your search
+21
-13
@@ -294,6 +294,24 @@ pub fn set_corners(path: &mut PathData, live: &mut Option<Box<LiveShape>>, corne
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert relative `radii` (fractions, one per anchor of the outline) after the outline changed
|
||||
/// from `before` to `after`: a corner that straightened keeps its document length as a fraction of
|
||||
/// `after`'s length, and a corner that bent again takes that length back as a fraction of its new
|
||||
/// maximum. Other radii are left as they are.
|
||||
pub fn rebase_relative_radii(before: &PathData, after: &PathData, radii: &mut [f64]) {
|
||||
let (old_corners, new_corners) = (path_corners(before), path_corners(after));
|
||||
let (old_dormant_scale, new_dormant_scale) = (dormant_radius_scale(before), dormant_radius_scale(after));
|
||||
for (index, r) in radii.iter_mut().enumerate() {
|
||||
let old = old_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &old_corners[i]);
|
||||
let new = new_corners.binary_search_by_key(&index, |c| c.index).ok().map(|i| &new_corners[i]);
|
||||
match (old, new) {
|
||||
(Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale,
|
||||
(None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Edit the anchors of the uncut outline that `anchors` (of the path as drawn) come from, while the
|
||||
/// path keeps its Live Corners: `edit` gets the outline in document space and those of its anchors,
|
||||
/// and the path is cut again with the same radii and kinds. A live rectangle or polygon becomes a
|
||||
@@ -340,20 +358,10 @@ pub fn edit_corner_anchors(
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
let before = relative.then(|| (path_corners(&base), dormant_radius_scale(&base)));
|
||||
let before = relative.then(|| base.clone());
|
||||
edit(&mut base, &on_base);
|
||||
if let Some((before, old_dormant_scale)) = before {
|
||||
let after = path_corners(&base);
|
||||
let new_dormant_scale = dormant_radius_scale(&base);
|
||||
for (index, r) in radii.iter_mut().enumerate() {
|
||||
let old = before.binary_search_by_key(&index, |c| c.index).ok().map(|i| &before[i]);
|
||||
let new = after.binary_search_by_key(&index, |c| c.index).ok().map(|i| &after[i]);
|
||||
match (old, new) {
|
||||
(Some(c), None) => *r = (*r).clamp(0.0, 1.0) * c.max_radius() / new_dormant_scale,
|
||||
(None, Some(c)) => *r = (*r * old_dormant_scale / c.max_radius()).clamp(0.0, 1.0),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(before) = before {
|
||||
rebase_relative_radii(&before, &base, &mut radii);
|
||||
}
|
||||
let l = LiveShape::Path { base, radii, kinds, radii_relative: relative };
|
||||
*path = l.to_path();
|
||||
|
||||
@@ -103,7 +103,7 @@ pub use appearance::{
|
||||
};
|
||||
pub use assets::ExportAsset;
|
||||
pub use compound_shape::ShapeMode;
|
||||
pub use corners::{LiveCorners, edit_corner_anchors};
|
||||
pub use corners::{LiveCorners, edit_corner_anchors, rebase_relative_radii};
|
||||
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
|
||||
pub use graph::{
|
||||
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
|
||||
|
||||
@@ -314,7 +314,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding: store radii as fractions of each corner's maximum so they scale with the shape; it applies to a whole live rectangle, live polygon or path with Live Corners; a plain path, an ellipse and a line are left as they are, with no undo step), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), points?: n (a live star's point count, a whole number from 2 to 1000; its corners keep the radius they shared; a new point count drops its selected anchors and segments; not with radius or kind), ratio?: above 0 and up to 1 (a live star's inner radius over its outer radius; the outer radius stays; a change to the corners a rounded star cuts drops its selected anchors and segments, and is an error with radius or kind), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it), strokes?, patterns?: bool (Scale Strokes & Effects and Transform Patterns, as object.scale takes them; default: the preferences)} (a new angle, polygon radius or side length, makeSidesEqual, lineLength or lineAngle moves, scales or turns the object as a transform does, so a linked opacity mask, placed gradients and (with `patterns`) pattern tiles go with the shape, and with `strokes` its strokes and effects scale, while corner radii in the mask keep their size; a line takes the turn and even scale that take its old ends to its new ones; the bounding box keeps its angle; rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once no corner stores a radius or a corner kind other than round (a corner that an anchor move straightens draws no arc but keeps its radius and the path stays live); sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -586,14 +586,19 @@ fn round_strokes(n: &mut Node) -> bool {
|
||||
/// Snap path object `n`'s horizontal and vertical straight segments ([`snap_segments`]). A path
|
||||
/// with Live Corners snaps the outline its corners are cut from. Another live shape is moved and
|
||||
/// scaled as a whole instead, from its path's bounds to the bounds of the snapped path, so that it
|
||||
/// stays a live shape. Returns whether it changed.
|
||||
/// stays a live shape. Relative radii of corners the snap straightens or bends are converted as an
|
||||
/// anchor edit converts them ([`vectorcraft_doc::rebase_relative_radii`]). Returns whether it changed.
|
||||
fn snap_path_node(n: &mut Node, half: bool, sc: Scaling) -> bool {
|
||||
let NodeKind::Path { path, live, .. } = &mut n.kind else { return false };
|
||||
let Some(shape) = live.as_deref_mut() else { return snap_segments(path, half) };
|
||||
if let LiveShape::Path { base, .. } = shape {
|
||||
if let LiveShape::Path { base, radii, radii_relative, .. } = shape {
|
||||
let before = radii_relative.then(|| base.clone());
|
||||
if !snap_segments(base, half) {
|
||||
return false;
|
||||
}
|
||||
if let Some(before) = before {
|
||||
vectorcraft_doc::rebase_relative_radii(&before, base, radii);
|
||||
}
|
||||
*path = shape.to_path();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchors",
|
||||
[],
|
||||
None,
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with rounded Live Corners, each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target; refused while an object of a symbol instance's art is selected",
|
||||
"{dx, dy (a move by 0, or one that the pixel-grid snap of pixel-aligned paths takes back, changes nothing and records no undo step), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); with Live Corners that store a radius (rounded, or straightened by an earlier move), each selected anchor's uncut corner moves by (dx, dy) and is recut at its radius, so a grabbed arc end can move off a snap target, and a straightened corner that bends again rounds again; refused while an object of a symbol instance's art is selected",
|
||||
has_selection,
|
||||
move_anchors
|
||||
),
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Anchor Point",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with rounded Live Corners, the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y)",
|
||||
"{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again",
|
||||
has_doc,
|
||||
move_anchor
|
||||
),
|
||||
@@ -266,6 +266,22 @@ fn snap_undoes(s: &Session, ids: impl IntoIterator<Item = NodeId>, apply: impl F
|
||||
let (Some(NodeKind::Path { path, live, .. }), Some(anchors)) = (st.doc.node(id).map(|n| &n.kind), st.selection.anchors.get(&id)) else {
|
||||
continue;
|
||||
};
|
||||
// Relative radii of corners the edit bent and the snap straightened again are converted
|
||||
// twice, and can come back off by rounding: an outline back where it was, with the same
|
||||
// kinds and those radii, counts as no change.
|
||||
if let Some(vectorcraft_doc::LiveShape::Path { base, radii, kinds, radii_relative: true }) = live.as_deref() {
|
||||
if let Some(NodeKind::Path { path: after_path, live: after, .. }) = doc.node_mut(id).map(|n| &mut n.kind)
|
||||
&& let Some(vectorcraft_doc::LiveShape::Path { base: b, radii: r, kinds: k, radii_relative: true }) = after.as_deref()
|
||||
&& b == base
|
||||
&& k == kinds
|
||||
&& r.len() == radii.len()
|
||||
&& r.iter().zip(radii).all(|(x, y)| (x - y).abs() <= 1e-12 * x.abs().max(y.abs()).max(1.0))
|
||||
{
|
||||
after.clone_from(live);
|
||||
after_path.clone_from(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A live path keeps its variant through an anchor edit, so only a rectangle or polygon
|
||||
// needs the comparison below.
|
||||
if !matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Rectangle { .. } | vectorcraft_doc::LiveShape::Polygon { .. })) {
|
||||
|
||||
@@ -329,6 +329,45 @@ fn a_path_with_live_corners_snaps_its_inner_edges() {
|
||||
assert!(pts.iter().all(|p| (p.1 - 20.3).abs() > 1e-6), "{pts:?}");
|
||||
}
|
||||
|
||||
/// With relative radii, a move that bends a straightened corner and that the snap takes back
|
||||
/// leaves the path, its stored radius and the undo history as they were, and the corner rounds at
|
||||
/// its radius when a later move bends it.
|
||||
#[test]
|
||||
fn a_snap_that_takes_back_a_move_keeps_a_straightened_corners_relative_radius() {
|
||||
let mut s = new_doc();
|
||||
let id = path(&mut s, "M10 10 L40 20 L70 10 L70 40 L10 40 Z", 2.0);
|
||||
s.execute("object.setLiveShape", &json!({"id": id, "corners": [1], "radius": 4})).unwrap();
|
||||
// The corner's two anchors as drawn are 1 and 2: straighten it.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": -10.0})).unwrap();
|
||||
s.execute("object.setLiveShape", &json!({"id": id, "relativeRadii": true})).unwrap();
|
||||
s.execute("object.setPixelAligned", &json!({"ids": [id]})).unwrap();
|
||||
let live = |s: &Session| {
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
|
||||
let NodeKind::Path { path, live: Some(live), .. } = &n.kind else { panic!("no Live Corners") };
|
||||
(path.clone(), live.clone())
|
||||
};
|
||||
let (path_before, live_before) = live(&s);
|
||||
assert_eq!(points(&s, id), [(10.0, 10.0), (40.0, 10.0), (70.0, 10.0), (70.0, 40.0), (10.0, 40.0)]);
|
||||
let undo = undo_len(&s);
|
||||
// The straight corner and the anchor after it: the move bends the corner, the snap undoes it.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 2]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 0.3})).unwrap();
|
||||
let (path_after, live_after) = live(&s);
|
||||
assert_eq!(path_after, path_before);
|
||||
assert_eq!(live_after, live_before, "the stored radius is unchanged");
|
||||
assert_eq!(undo_len(&s), undo, "no undo step for a move the snap took back");
|
||||
// Bend it again: it rounds at 4 points.
|
||||
s.execute("select.set", &json!({"ids": []})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
s.execute("path.moveAnchors", &json!({"dx": 0.0, "dy": 10.0})).unwrap();
|
||||
let (path, live) = live(&s);
|
||||
let c = vectorcraft_doc::LiveCorners::new(&path, Some(&*live)).unwrap();
|
||||
assert!((c.drawn_radius(1) - 4.0).abs() < 1e-6, "{live:?}");
|
||||
}
|
||||
|
||||
/// `path.setAnchors` and `object.setLiveShape` snap a pixel-aligned path again after they replace
|
||||
/// its geometry.
|
||||
#[test]
|
||||
|
||||
+2
-1
@@ -9247,7 +9247,8 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a
|
||||
an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded.
|
||||
`path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that
|
||||
keeps its kind, leave the document as it is and record no undo step.
|
||||
On a path with rounded Live Corners, `path.moveAnchor` and `path.moveAnchors` (and the arrow keys) move the uncut corner
|
||||
On a path with Live Corners that store a radius (rounded, or straightened by an earlier move), `path.moveAnchor` and
|
||||
`path.moveAnchors` (and the arrow keys) move the uncut corner
|
||||
each moved anchor belongs to by the drag delta and cut the corners again at their radii. The corners stay live; a live
|
||||
rectangle or polygon becomes a path with live corners. The delta is measured from the drawn anchor, but the recut can
|
||||
move that anchor again: a grabbed arc end can finish away from a snap target, and `path.moveAnchor` can leave the drawn
|
||||
|
||||
Reference in new issue
Block a user