diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 47190a2cdf..de893c79da 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "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), 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)} (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), 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)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 8d2a344ffe..81909da76f 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -443,10 +443,18 @@ fn changed_aligned(before: &[Arc], after: &[Arc], out: &mut Vec, angle: Option) -> Option Option { + let ratio = |was: f64, now: f64| if was == now { 1.0 } else { now / was }; + let xf = match (old, new) { + (LiveShape::Rectangle { w, h, xf, .. }, LiveShape::Rectangle { w: w2, h: h2, xf: xf2, .. }) + | (LiveShape::Ellipse { w, h, xf, .. }, LiveShape::Ellipse { w: w2, h: h2, xf: xf2, .. }) => { + if xf == xf2 && w == w2 && h == h2 { + return None; + } + *xf2 * Affine::scale_non_uniform(ratio(*w, *w2), ratio(*h, *h2)) * xf.inverse() + } + (LiveShape::Polygon { radius, xf, .. }, LiveShape::Polygon { radius: r2, xf: xf2, .. }) => { + if xf == xf2 && radius == r2 { + return None; + } + *xf2 * Affine::scale(ratio(*radius, *r2)) * xf.inverse() + } + (LiveShape::Line { a, b }, LiveShape::Line { a: a2, b: b2 }) => { + let (d, d2) = (*b - *a, *b2 - *a2); + let len2 = d.hypot2(); + if (a == a2 && b == b2) || len2 <= 0.0 { + return None; + } + // `d2` divided by `d` as complex numbers: the turn and even scale between them. + let (c, s) = ((d2.x * d.x + d2.y * d.y) / len2, (d2.y * d.x - d2.x * d.y) / len2); + let turn = Affine::new([c, s, -s, c, 0.0, 0.0]); + Affine::translate(*a2 - turn * *a) * turn + } + _ => return None, + }; + xf.as_coeffs().iter().all(|c| c.is_finite()).then_some(xf) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { - check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?; + check_switches( + p, + &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii", "strokes", "patterns"], + "object.setLiveShape", + )?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -317,50 +361,87 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return ok(); } + // The live shapes that the polygon, rectangle, ellipse and line values change: each as it is and + // as it becomes. + let mut reshaped = std::collections::BTreeMap::new(); + for id in &ids { + let Some(NodeKind::Path { live: Some(old), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + let mut new = (**old).clone(); + let mut edited = false; + if let l @ LiveShape::Polygon { .. } = &mut new + && (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal) + { + if let Some(n) = sides { + l.set_sides(n); + } + if equal { + l.make_sides_equal(); + } + if let Some(a) = polygon_angle { + l.set_polygon_angle(a); + } + // A side length sets the radius that gives it (with the new side count). + if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) { + l.set_polygon_radius(r); + } + edited = true; + } + if let Some(a) = rectangle_angle + && let l @ LiveShape::Rectangle { .. } = &mut new + { + l.set_shape_angle(a); + edited = true; + } + if let l @ LiveShape::Ellipse { .. } = &mut new + && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) + { + if let Some(a) = ellipse_angle { + l.set_shape_angle(a); + } + if let LiveShape::Ellipse { pie, .. } = l { + *pie = pie_of(*pie); + } + edited = true; + } + if let Some(line) = lines.get(id) { + new = line.clone(); + edited = true; + } + if edited { + reshaped.insert(*id, ((**old).clone(), new)); + } + } + // A shape that moves, turns or scales takes the rest of the object along as a transform does: + // Scale Strokes & Effects and Transform Patterns come from `strokes` and `patterns` or the + // preferences, and are noted in the journal so a replay does the same. Corner radii in the rest + // of the object keep their size, as the shape's own do; Scale Corners does not apply. + let carried: Vec = reshaped.iter().filter(|(_, (old, new))| carry(old, new).is_some()).map(|(id, _)| *id).collect(); + let scales = reshaped.values().any(|(old, new)| carry(old, new).is_some_and(|xf| Scaling::factor(xf).is_some())); + let base = if scales { + let sc = scaling_options(s, p); + s.note_journal("strokes", serde_json::json!(sc.strokes)); + sc + } else { + Scaling::default() + }; + let sc = Scaling { patterns: !carried.is_empty() && transform_patterns(s, p, &carried)?, keep_corners: true, ..base }; s.edit("Live Shape", |d, sel| { + // Each object once, however often `ids` or `items` names it. + for (id, (old, new)) in &reshaped { + let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; + if let Some(xf) = carry(old, new) { + // The bounding box keeps its angle: a shape angle is the shape's own. + let bbox_angle = n.bbox_angle; + n.transform(xf, sc); + n.bbox_angle = bbox_angle; + } + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *live = Some(Box::new(new.clone())); + *path = new.to_path(); + } + } for id in &ids { let Some(NodeKind::Path { path, live, .. }) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - if let Some(l @ LiveShape::Polygon { .. }) = live.as_deref_mut() - && (sides.is_some() || polygon_angle.is_some() || polygon_radius.is_some() || side.is_some() || equal) - { - if let Some(n) = sides { - l.set_sides(n); - } - if equal { - l.make_sides_equal(); - } - if let Some(a) = polygon_angle { - l.set_polygon_angle(a); - } - // A side length sets the radius that gives it (with the new side count). - if let Some(r) = side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius) { - l.set_polygon_radius(r); - } - *path = l.to_path(); - } - if let Some(a) = rectangle_angle - && let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut() - { - l.set_shape_angle(a); - *path = l.to_path(); - } - if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() - && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) - { - if let Some(a) = ellipse_angle { - l.set_shape_angle(a); - } - if let LiveShape::Ellipse { pie, .. } = l { - *pie = pie_of(*pie); - } - *path = l.to_path(); - } - if let Some(new) = lines.get(id) - && let Some(l) = live.as_deref_mut() - { - *l = new.clone(); - *path = l.to_path(); - } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { @@ -385,8 +466,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { }; recut(path, live, partial, &picked, radius, kind); } + // The snap to the pixel grid moves the patterns of a carried shape when the carry did. for id in &ids { - super::pixelgrid::resnap(d, *id); + let snap = Scaling { patterns: sc.patterns && carried.contains(id), ..Scaling::default() }; + super::pixelgrid::resnap_with(d, *id, snap); } // A shape named in `ids` and not selected is not checked after the edit: one that a turn or // a new radius would take past the coordinate limit is an error here, and nothing changes. diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 527957f234..1a15e44aa3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -63,15 +63,15 @@ pub(super) fn scaling_options(s: &Session, p: &Value) -> Scaling { } /// Transform Patterns: do the pattern fills and strokes of `ids` transform with them (`patterns` -/// param, else General › Transform Pattern Tiles)? Noted in the journal when they use a pattern, -/// so a replay moves their tiles alike whatever the preference is then. +/// param, else General › Transform Pattern Tiles)? Noted in the journal when they or the art of +/// their linked opacity masks use a pattern, so a replay moves their tiles alike whatever the preference is then. pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Result { let on = bool_or(p, "patterns", s.prefs.transform_pattern_tiles); let d = &s.doc()?.doc; let mut uses = false; let paths = d.index_paths(ids.iter().copied()); for n in ids.iter().filter_map(|id| paths.get(id)).filter_map(|p| d.node_at(p)) { - n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None)); + uses |= uses_pattern_with_masks(n); } if uses { s.note_journal("patterns", json!(on)); @@ -79,6 +79,17 @@ pub(crate) fn transform_patterns(s: &mut Session, p: &Value, ids: &[NodeId]) -> Ok(on) } +/// Whether `n`, a descendant or the art of a linked opacity mask among them (and theirs) has a +/// pattern fill or stroke: what Transform Patterns moves when `n` is transformed. +fn uses_pattern_with_masks(n: &vectorcraft_doc::Node) -> bool { + let mut uses = false; + n.walk(&mut |c| { + uses |= vectorcraft_doc::pattern::uses_pattern(c, None) + || c.extras().mask.as_deref().is_some_and(|m| m.linked && uses_pattern_with_masks(&m.art)); + }); + uses +} + /// Transform Objects (`objects` param, on unless it is false): off, a transform leaves the art /// where it is and, with Transform Patterns, moves only its pattern tiles. pub(crate) fn transforms_objects(p: &Value) -> bool { diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 4641467aa4..7f46a8edcd 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -6,8 +6,8 @@ use std::collections::BTreeSet; use serde_json::{Value, json}; use vectorcraft_doc::{AnchorRef, LiveCorners, LiveShape, NodeKind}; -use vectorcraft_geom::Affine; use vectorcraft_geom::shapes::CornerKind; +use vectorcraft_geom::{Affine, Point}; use crate::*; @@ -887,6 +887,164 @@ fn a_line_takes_its_length_and_angle() { assert_eq!(steps(&s), n); } +/// Each live shape edit that moves, turns or scales the shape (Rectangle, Ellipse and Polygon +/// Angle, Polygon Radius, Side Length, Make Sides Equal, Line Length and Line Angle) takes a linked +/// opacity mask and a placed gradient along, so they keep their place in the shape's own frame; a +/// new side count or pie leaves them where they are. Scale Strokes & Effects comes from `strokes`, +/// and the bounding box keeps its angle. +#[test] +fn shape_edits_take_a_linked_mask_and_placed_gradient_along() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let add = |s: &mut Session, cmd: &str, p: Value| NodeId(s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap()); + // Each shape gets a placed linear gradient fill and a linked opacity mask off its center. + let dress = |s: &mut Session, id: NodeId, start: [f64; 2], end: [f64; 2], mask: [f64; 2]| { + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setGradientGeom", &json!({"ids": [id.0], "start": start, "end": end})).unwrap(); + let m = s.execute("shape.rectangle", &json!({"x": mask[0], "y": mask[1], "width": 20, "height": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, m]})).unwrap(); + }; + let rect = add(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 60})); + dress(&mut s, rect, [20.0, 30.0], [90.0, 50.0], [15.0, 40.0]); + let ellipse = add(&mut s, "shape.ellipse", json!({"x": 200, "y": 200, "width": 120, "height": 80})); + dress(&mut s, ellipse, [210.0, 240.0], [300.0, 220.0], [270.0, 205.0]); + let polygon = add(&mut s, "shape.polygon", json!({"cx": 200, "cy": 100, "radius": 50, "sides": 6})); + dress(&mut s, polygon, [170.0, 90.0], [230.0, 120.0], [205.0, 70.0]); + let line = add(&mut s, "shape.line", json!({"x1": 100, "y1": 300, "x2": 200, "y2": 300})); + dress(&mut s, line, [100.0, 300.0], [200.0, 300.0], [120.0, 290.0]); + // The shape's own frame: its untransformed unit box, a polygon's unit circle, or a line from 0 to 1 along x. + let frame = |l: &LiveShape| match l { + LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => *xf * Affine::scale_non_uniform(*w, *h), + LiveShape::Polygon { radius, xf, .. } => *xf * Affine::scale(*radius), + LiveShape::Line { a, b } => { + let d = *b - *a; + Affine::new([d.x, d.y, -d.y, d.x, a.x, a.y]) + } + l => panic!("{l:?}"), + }; + // The mask art's center and the gradient's start in the shape's frame, the gradient's value at the + // frame's origin and its two unit points (a linear gradient's isolines, which a shear keeps but + // its end point does not), and the mask art's center in the document. + let local = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + let to_doc = frame(n.live_shape().unwrap()); + let to_local = to_doc.inverse(); + let mask = n.extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap().center(); + let vectorcraft_color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("a gradient fill") }; + let geom = g.geom.unwrap(); + let along = geom.end - geom.start; + let t = |x: f64, y: f64| (to_doc * Point::new(x, y) - geom.start).dot(along) / along.hypot2(); + ([to_local * mask, to_local * geom.start, Point::new(t(0.0, 0.0), t(1.0, 0.0)), Point::new(t(0.0, 1.0), 0.0)], mask) + }; + let edits = [ + (rect, json!({"rectangleAngle": 30})), + (ellipse, json!({"ellipseAngle": 50})), + (polygon, json!({"polygonAngle": 20})), + (polygon, json!({"polygonRadius": 80})), + (polygon, json!({"sideLength": 30})), + (polygon, json!({"makeSidesEqual": true})), + (line, json!({"lineLength": 50})), + (line, json!({"lineAngle": 90})), + (line, json!({"lineLength": 140, "lineAngle": 210})), + ]; + // Every edit is checked, and the ones that leave the mask or gradient behind are listed together. + let mut left_behind = Vec::new(); + for (id, edit) in edits { + if edit.get("makeSidesEqual").is_some() { + // Scaled unevenly and turned first, so Make Sides Equal has a shear and an uneven scale to drop. + s.execute("object.scale", &json!({"ids": [polygon.0], "sx": 200, "sy": 100})).unwrap(); + s.execute("object.rotate", &json!({"ids": [polygon.0], "angle": 30})).unwrap(); + s.execute("object.scale", &json!({"ids": [polygon.0], "sx": 100, "sy": 150})).unwrap(); + } + let angle = s.doc().unwrap().doc.node(id).unwrap().bbox_angle; + let (was, _) = local(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([id.0]); + run(&mut s, p); + let now = local(&s, id).0; + if now.iter().zip(&was).any(|(now, then)| now.distance(*then) >= 1e-9) { + left_behind.push(format!("{edit}: {now:?} from {was:?}")); + } + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().bbox_angle, angle, "{edit}: the bounding box keeps its angle"); + } + assert!(left_behind.is_empty(), "moved off the shape:\n{}", left_behind.join("\n")); + // A new side count or pie keeps the shape's place, angle and size: the mask stays where it is. + for (id, edit) in [(polygon, json!({"sides": 8})), (ellipse, json!({"pieStart": 30, "pieEnd": 200}))] { + let (_, was) = local(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([id.0]); + run(&mut s, p); + assert_eq!(local(&s, id).1, was, "{edit}"); + } + // With Scale Strokes & Effects off a new radius keeps the stroke's weight; on, the stroke scales with it. + let weight = |s: &Session| s.doc().unwrap().doc.node(polygon).unwrap().appearance.stroke_width(); + s.execute("stroke.set", &json!({"ids": [polygon.0], "weight": 4})).unwrap(); + run(&mut s, json!({"ids": [polygon.0], "polygonRadius": 160, "strokes": false})); + assert!((weight(&s) - 4.0).abs() < 1e-9, "{}", weight(&s)); + run(&mut s, json!({"ids": [polygon.0], "polygonRadius": 320, "strokes": true})); + assert!((weight(&s) - 8.0).abs() < 1e-9, "the stroke scaled with the shape: {}", weight(&s)); + for bad in [json!({"ids": [polygon.0], "polygonRadius": 50, "strokes": "yes"}), json!({"ids": [polygon.0], "polygonRadius": 50, "patterns": 1})] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + } + // An object named twice moves once, and a rounded rectangle in its mask keeps its corner radius + // with Scale Corners on, as the shape's own corners do. + let star = add(&mut s, "shape.polygon", json!({"cx": 300, "cy": 300, "radius": 40, "sides": 5})); + s.execute("paint.setFill", &json!({"ids": [star.0], "gradient": {"kind": "linear"}})).unwrap(); + s.execute("paint.setGradientGeom", &json!({"ids": [star.0], "start": [280, 300], "end": [320, 310]})).unwrap(); + let m = add(&mut s, "shape.rectangle", json!({"x": 290, "y": 280, "width": 30, "height": 20, "radius": 5})); + s.execute("transparency.makeOpacityMask", &json!({"ids": [star.0, m.0]})).unwrap(); + s.prefs.scale_corners = true; + let (was, _) = local(&s, star); + run(&mut s, json!({"ids": [star.0, star.0], "polygonRadius": 80})); + let (now, _) = local(&s, star); + assert!(now.iter().zip(&was).all(|(now, then)| now.distance(*then) < 1e-9), "moved once: {now:?} from {was:?}"); + let n = s.doc().unwrap().doc.node(star).unwrap(); + let art = &n.extras().mask.as_deref().unwrap().art; + let rect = match &art.kind { + NodeKind::Group { children, .. } => &children[0], + _ => art, + }; + let Some(LiveShape::Rectangle { radii, xf, w, .. }) = rect.live_shape() else { panic!("a live rectangle in the mask") }; + assert!((w * xf.as_coeffs()[0] - 60.0).abs() < 1e-9, "the mask doubled with the shape: {w}, {xf:?}"); + assert!((radii[0] * xf.as_coeffs()[0] - 5.0).abs() < 1e-9, "the corner keeps its radius: {radii:?}, {xf:?}"); +} + +/// A pixel-aligned line that a new angle carries off the pixel grid snaps back to it, and with +/// `patterns` on its pattern moves with the snap as well as with the turn; with `patterns` off the +/// pattern stays where it was. +#[test] +fn a_pixel_aligned_line_takes_its_pattern_through_the_snap() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let line = |s: &mut Session, aligned: bool| { + let id = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0.5, "x2": 100, "y2": 0.5})).unwrap()["id"].as_u64().unwrap()); + let n = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap(); + n.appearance.set_stroke(vectorcraft_color::Paint::Pattern { pattern: "P".into(), xf: Affine::default() }); + n.extras_mut().pixel_aligned = aligned; + id + }; + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().clone(); + let pattern = |s: &Session, id: NodeId| match node(s, id).appearance.stroke_paint() { + vectorcraft_color::Paint::Pattern { xf, .. } => xf, + p => panic!("a pattern stroke: {p:?}"), + }; + let origin = |s: &Session, id: NodeId| node(s, id).geometric_bounds().unwrap().origin(); + for patterns in [true, false] { + let (aligned, free) = (line(&mut s, true), line(&mut s, false)); + run(&mut s, json!({"ids": [aligned.0, free.0], "lineAngle": 90, "patterns": patterns})); + let snapped = origin(&s, aligned) - origin(&s, free); + assert!(snapped.hypot() > 1e-6, "the aligned line snapped to the grid: {snapped:?}"); + if patterns { + let want = Affine::translate(snapped) * pattern(&s, free); + let got = pattern(&s, aligned); + let off = got.as_coeffs().iter().zip(want.as_coeffs()).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + assert!(off < 1e-9, "the pattern moved with the snap: {got:?}, want {want:?}"); + } else { + assert_eq!(pattern(&s, aligned), Affine::default(), "the pattern stays where it was"); + } + } +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index e2e2d3dae7..28f34e13ab 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1266,6 +1266,22 @@ fn transform_pattern_tiles_is_the_transforms_default() { assert_eq!(tiles(&s), [0.5, 0.0, 0.0, 0.5, 5.0, 0.0]); } +/// A transform of an object whose pattern is only in its linked opacity mask notes Transform +/// Patterns in the journal too, so a replay moves the mask's tiles alike. +#[test] +fn transform_patterns_is_journaled_for_a_pattern_in_a_linked_mask() { + let mut s = new_doc(); + // The mask art is the patterned square above the polygon. + let id = NodeId(s.execute("shape.polygon", &json!({"cx": 125, "cy": 125, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap()); + let art = patterned_square(&mut s); + s.execute("transparency.makeOpacityMask", &json!({"ids": [id.0, art.0]})).unwrap(); + set_pref(&mut s, "transformPatternTiles", json!(true)); + s.execute("object.move", &json!({"ids": [id.0], "dx": 10, "dy": 0})).unwrap(); + assert_eq!(s.journal.last().unwrap().1["patterns"], json!(true), "object.move"); + s.execute("object.setLiveShape", &json!({"ids": [id.0], "polygonAngle": 20})).unwrap(); + assert_eq!(s.journal.last().unwrap().1["patterns"], json!(true), "object.setLiveShape"); +} + /// A 50 pt square at (100, 100) with a 1 pt stroke, filled with a 20 pt pattern, selected. fn patterned_square(s: &mut Session) -> NodeId { let tile = square(s, 0.0, 0.0); diff --git a/docs/mcp.md b/docs/mcp.md index 6d44ea3762..de2ebf6ddf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2437,7 +2437,8 @@ undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `object.transformAgain` and `object.setBounds`; `anchors`, `releaseOutside` and `drawBehind` in `object.transform`; `big` in `object.nudge`; `absolute` in `object.rotate`; `proportional` in `object.setBounds`; `patterns` in `object.align`, `object.distribute` and `object.distributeSpacing`; `visible`, `locked`, `isolate` and `knockoutShape` in `object.setProps`; and -`invertPie`, `makeSidesEqual` and `relativeRadii` in `object.setLiveShape`. A null is read as a key left out. +`invertPie`, `makeSidesEqual`, `relativeRadii`, `strokes` and `patterns` in `object.setLiveShape`. A null is read as a +key left out. They also refuse a string or another value that is not a number with `` `opacity` must be a number, not "50" ``, naming the key, and leave the document and its undo history as they were: `opacity` in `object.setProps`; `radius` and @@ -8729,6 +8730,14 @@ midpoint; any finite value is brought into 0 to 360). With both, the length appl and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is one undo step. +A new `rectangleAngle`, `ellipseAngle`, `polygonAngle`, `polygonRadius` or `sideLength`, `makeSidesEqual`, `lineLength` +or `lineAngle` moves, scales or turns the object as a transform does: a linked opacity mask and placed gradients go +with the shape, pattern tiles go with it when `patterns` (or General › Transform Pattern Tiles) is on, and strokes and +effects scale when `strokes` (or Scale Strokes & Effects) is on. Corner radii in the mask keep their size, as the +shape's own do, whatever Scale Corners is set to. A line takes the turn and even scale that take its old ends to its new +ones; a line whose ends met takes none. The bounding box keeps its angle. An object named more than once in `ids` or +`items` moves once. A new `sides` or pie leaves the rest of the object where it is. + A live rectangle's Rectangle Angle and a live ellipse's Ellipse Angle are `rectangleAngle` and `ellipseAngle` (degrees counterclockwise, 0 for a shape drawn level; any number is read modulo 360). The help page (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists