diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index 62fd3cea..f034be63 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -357,8 +357,10 @@ fn set_transform(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("scale must be between 0.001 and 1000 in magnitude".into())); } } - let els = s.selected_elements_mut()?; - for e in els { + let units = raw_drawings(s); + let in_unit = |id: &ElementId| units.iter().any(|(ids, _)| ids.contains(id)); + let mut els = s.selected_elements_mut()?; + for e in els.iter_mut().filter(|e| !in_unit(&e.id)) { let mut d: Decomposed = e.transform.decompose(); if let Some(v) = x { d.tx = v; @@ -377,9 +379,61 @@ fn set_transform(s: &mut Session, p: &Value) -> Result { } e.transform = d.compose(); } + // A raw drawing turns and scales as one shape, about the centre of its pieces (#297): every + // piece takes the change that gives its first piece the values asked for. + for (ids, bounds) in &units { + let Some(reference) = ids.first().and_then(|id| els.iter().find(|e| e.id == *id)).map(|e| e.transform) else { continue }; + let m = drawing_change(&reference, bounds.center(), [x, y, sx, sy, rot]); + for e in els.iter_mut().filter(|e| ids.contains(&e.id)) { + e.transform = m.mul(&e.transform); + } + } Ok(json!({"ok": true})) } +/// The selected raw drawings of two or more pieces on the active layer: raw pieces that touch, +/// such as a fill and the strokes on its edges (ADR 0042), and their combined bounds. +fn raw_drawings(s: &Session) -> Vec<(Vec, anicraft_geom::Rect)> { + let layer = s.layer; + let (ids, boxes): (Vec, Vec) = s + .selected_elements() + .into_iter() + .filter(|(l, e)| *l == layer && crate::merge::mergeable(e).is_some()) + .map(|(l, e)| (e.id, s.element_bounds_on(l, e.id))) + .filter(|(_, b)| !b.is_empty()) + .unzip(); + crate::merge::touching_groups(&boxes) + .into_iter() + .filter(|g| g.len() > 1) + .map(|g| { + let members: Vec = g.iter().filter_map(|&i| ids.get(i).copied()).collect(); + let b = g.iter().filter_map(|&i| boxes.get(i)).fold(anicraft_geom::Rect::EMPTY, |r, b| r.union(b)); + (members, b) + }) + .collect() +} + +/// The stage-space change that gives `reference` the asked-for `[x, y, sx, sy, rotation°]`: +/// scale, rotation and skew about `pivot`, then a move for the position. +fn drawing_change(reference: &Affine, pivot: Vec2, [x, y, sx, sy, rot]: [Option; 5]) -> Affine { + let from = reference.decompose(); + let mut to = from; + if let Some(v) = sx { + to.sx = v; + } + if let Some(v) = sy { + to.sy = v; + } + if let Some(v) = rot { + to.rotation = v.to_radians(); + } + let linear = |d: &Decomposed| Decomposed { tx: 0.0, ty: 0.0, ..*d }.compose(); + let turn = linear(&from).inverse().map_or(Affine::IDENTITY, |inv| linear(&to).mul(&inv)); + let m = Affine::translate(pivot.x, pivot.y).mul(&turn).mul(&Affine::translate(-pivot.x, -pivot.y)); + let at = m.mul(reference).translation(); + Affine::translate(x.map_or(0.0, |v| v - at.x), y.map_or(0.0, |v| v - at.y)).mul(&m) +} + fn shapes_mut(s: &mut Session) -> Result> { let shapes: Vec<&mut Shape> = s .selected_elements_mut()? diff --git a/crates/engine/src/cmds_modify.rs b/crates/engine/src/cmds_modify.rs index 6ee3ee81..198e337d 100644 --- a/crates/engine/src/cmds_modify.rs +++ b/crates/engine/src/cmds_modify.rs @@ -369,10 +369,14 @@ enum Edge { /// A selected element: its layer and id. type Item = (LayerId, ElementId); -fn moves_for(bounds: &[(Item, Rect)], target: Rect, edge: Edge) -> Vec<(Item, Vec2)> { - bounds +/// What align and distribute place: the elements of one unit (see [`selected_units`]) and their +/// combined bounds. +type Unit = (Vec, Rect); + +fn moves_for(units: &[Unit], target: Rect, edge: Edge) -> Vec<(Item, Vec2)> { + units .iter() - .map(|(id, b)| { + .flat_map(|(items, b)| { let d = match edge { Edge::Left => Vec2::new(target.min.x - b.min.x, 0.0), Edge::HCenter => Vec2::new(target.center().x - b.center().x, 0.0), @@ -381,7 +385,7 @@ fn moves_for(bounds: &[(Item, Rect)], target: Rect, edge: Edge) -> Vec<(Item, Ve Edge::VCenter => Vec2::new(0.0, target.center().y - b.center().y), Edge::Bottom => Vec2::new(0.0, target.max.y - b.max.y), }; - (*id, d) + items.iter().map(move |id| (*id, d)) }) .collect() } @@ -415,44 +419,74 @@ fn translate_each(s: &mut Session, moves: &[(Item, Vec2)]) -> Result { Ok(n) } -/// Each selected element's bounds, over every layer: alignment works across layers. -fn selected_bounds(s: &Session) -> Vec<(Item, Rect)> { - s.selected_elements().iter().map(|(l, e)| ((*l, e.id), s.element_bounds_on(*l, e.id))).filter(|(_, b)| !b.is_empty()).collect() +/// What align and distribute place, over every layer (alignment works across layers): each +/// selected object on its own, and each raw drawing as one (#301). A raw drawing is the selected +/// raw pieces on a layer that touch, such as a fill and the strokes on its edges (ADR 0042), so a +/// shape keeps its outline where it goes. +fn selected_units(s: &Session) -> Vec { + let mut units: Vec = Vec::new(); + let mut raw: Vec<(LayerId, Vec, Vec)> = Vec::new(); + for (l, e) in s.selected_elements() { + let b = s.element_bounds_on(l, e.id); + if b.is_empty() { + continue; + } + if crate::merge::mergeable(&e).is_none() { + units.push((vec![(l, e.id)], b)); + continue; + } + match raw.iter_mut().find(|(k, ..)| *k == l) { + Some((_, ids, boxes)) => { + ids.push((l, e.id)); + boxes.push(b); + } + None => raw.push((l, vec![(l, e.id)], vec![b])), + } + } + for (_, ids, boxes) in raw { + for group in crate::merge::touching_groups(&boxes) { + let items: Vec = group.iter().filter_map(|&i| ids.get(i).copied()).collect(); + let b = group.iter().filter_map(|&i| boxes.get(i)).fold(Rect::EMPTY, |r, b| r.union(b)); + units.push((items, b)); + } + } + units } fn align(s: &mut Session, p: &Value, edge: Edge) -> Result { - let bounds = selected_bounds(s); - if bounds.is_empty() { + let units = selected_units(s); + if units.is_empty() { return Err(EngineError::State("nothing is selected".into())); } - // One element aligns to the stage (there is nothing else to align it with). - let to_stage = opt_bool(p, "to_stage")?.unwrap_or(bounds.len() == 1); + // One element (or one raw drawing) aligns to the stage: there is nothing else to align it with. + let to_stage = opt_bool(p, "to_stage")?.unwrap_or(units.len() == 1); let target = if to_stage { Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32) } else { - bounds.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) + units.iter().fold(Rect::EMPTY, |r, (_, b)| r.union(b)) }; - let moves = moves_for(&bounds, target, edge); + let moves = moves_for(&units, target, edge); let n = translate_each(s, &moves)?; Ok(json!({"moved": n, "to_stage": to_stage})) } fn distribute(s: &mut Session, horizontal: bool) -> Result { - let mut bounds = selected_bounds(s); - if bounds.len() < 3 { + let mut units = selected_units(s); + if units.len() < 3 { return Err(EngineError::State("select at least three elements to distribute".into())); } let key = |b: &Rect| if horizontal { b.center().x } else { b.center().y }; - bounds.sort_by(|a, b| key(&a.1).total_cmp(&key(&b.1))); - let (Some(first), Some(last)) = (bounds.first(), bounds.last()) else { return Ok(json!({"moved": 0})) }; + units.sort_by(|a, b| key(&a.1).total_cmp(&key(&b.1))); + let (Some(first), Some(last)) = (units.first(), units.last()) else { return Ok(json!({"moved": 0})) }; let (a, z) = (key(&first.1), key(&last.1)); - let step = (z - a) / (bounds.len() - 1) as f32; - let moves: Vec<(Item, Vec2)> = bounds + let step = (z - a) / (units.len() - 1) as f32; + let moves: Vec<(Item, Vec2)> = units .iter() .enumerate() - .map(|(i, (id, b))| { + .flat_map(|(i, (items, b))| { let d = a + step * i as f32 - key(b); - (*id, if horizontal { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }) + let d = if horizontal { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }; + items.iter().map(move |id| (*id, d)) }) .collect(); let n = translate_each(s, &moves)?; diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index f55b2ad8..cf12bd22 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -34,6 +34,55 @@ pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect { s.path.bounds().transformed(m).inflate(pad + 2.0 * SNAP) } +/// Splits raw pieces into the drawings they make: pieces whose bounds touch go in one group, so a +/// fill and the strokes on its edges move, turn and align as one shape (#297, #301). `boxes` are +/// the pieces' bounds in one space; each group lists indexes into it, in order. +pub(crate) fn touching_groups(boxes: &[Rect]) -> Vec> { + // Every entry of `parent` is an index into it, so the lookups below stay in range. + fn root(parent: &mut [usize], i: usize) -> usize { + let mut r = i; + while parent[r] != r { + r = parent[r]; + } + let mut j = i; + while parent[j] != r { + let next = parent[j]; + parent[j] = r; + j = next; + } + r + } + let grown: Vec = boxes.iter().map(|b| b.inflate(SNAP)).collect(); + let mut parent: Vec = (0..boxes.len()).collect(); + // Sweep along x: only pieces whose x spans overlap can touch. + let mut order: Vec = (0..boxes.len()).collect(); + order.sort_by(|&a, &b| grown[a].min.x.total_cmp(&grown[b].min.x)); + for (k, &i) in order.iter().enumerate() { + for &j in order.iter().skip(k + 1) { + if grown[j].min.x > grown[i].max.x { + break; + } + if !grown[i].intersect(&grown[j]).is_empty() { + let (a, b) = (root(&mut parent, i), root(&mut parent, j)); + parent[a.max(b)] = a.min(b); + } + } + } + let mut group_of: Vec> = vec![None; boxes.len()]; + let mut groups: Vec> = Vec::new(); + for i in 0..boxes.len() { + let r = root(&mut parent, i); + match group_of[r] { + Some(g) => groups[g].push(i), + None => { + group_of[r] = Some(groups.len()); + groups.push(vec![i]); + } + } + } + groups +} + /// Where new raw shapes go in the drawing's stacking (the Brush tool's paint modes, ADR 0033). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub(crate) enum Order { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0334ece1..2e553d94 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -299,6 +299,80 @@ fn align_and_distribute() { assert!((s.selection_bounds().max.x - s.doc.stage.width as f32).abs() < 1e-3); } +/// #301, #297: a raw rectangle (one fill and one stroke per side, ADR 0042) aligns, distributes, +/// turns and scales as one shape, so its outline stays on its fill. +#[test] +fn a_raw_drawing_aligns_distributes_and_turns_as_one() { + use anicraft_geom::Rect; + fn raw_rect(s: &mut Session) { + run( + s, + "draw.rect", + json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": "#3366ff", "stroke": "#000000", "stroke_width": 4, "object": false}), + ); + } + fn pieces(s: &Session) -> Vec { + s.visible_elements().iter().filter(|e| crate::merge::mergeable(e).is_some()).map(|e| s.element_bounds(e.id)).collect() + } + // Where each piece sits in the drawing's box: what aligning and distributing must keep. + fn layout(s: &Session) -> Vec<[f32; 4]> { + let p = pieces(s); + let all = p.iter().fold(Rect::EMPTY, |r, b| r.union(b)); + p.iter().map(|b| [b.min.x - all.min.x, b.min.y - all.min.y, b.max.x - all.min.x, b.max.y - all.min.y]).collect() + } + fn same(a: &[[f32; 4]], b: &[[f32; 4]]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.iter().zip(y).all(|(p, q)| (p - q).abs() < 0.01)) + } + for cmd in + ["align.left", "align.hcenter", "align.right", "align.top", "align.vcenter", "align.bottom", "align.distribute_h", "align.distribute_v"] + { + let mut s = Session::default(); + raw_rect(&mut s); + let shape = layout(&s); + assert_eq!(shape.len(), 5, "one fill and four sides"); + for (x, y) in [(400, 300), (600, 40)] { + run(&mut s, "draw.rect", json!({"x": x, "y": y, "w": 50, "h": 50, "fill": "#ff0000", "stroke": null, "object": true})); + } + run(&mut s, "edit.select_all", json!({})); + let v = run(&mut s, cmd, json!({})); + assert!(same(&layout(&s), &shape), "{cmd} {v}: the rectangle came apart: {:?}", pieces(&s)); + } + // Alone, the drawing is one element: it aligns to the stage. + let mut s = Session::default(); + raw_rect(&mut s); + let shape = layout(&s); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "align.left", json!({})); + assert!(same(&layout(&s), &shape)); + assert!(s.selection_bounds().min.x.abs() < 1e-3, "{:?}", s.selection_bounds()); + + // The Properties panel's Rotation and Scale fields: about the drawing's centre, as Rotate 90° + // does. + let mut s = Session::default(); + raw_rect(&mut s); + run(&mut s, "edit.select_all", json!({})); + let mut turned = Session::default(); + raw_rect(&mut turned); + run(&mut turned, "edit.select_all", json!({})); + run(&mut turned, "modify.rotate_cw", json!({})); + run(&mut s, "element.set_transform", json!({"rotation": 90})); + let (got, want) = (pieces(&s), pieces(&turned)); + assert!(got.iter().zip(&want).all(|(a, b)| (a.min - b.min).length() < 0.01 && (a.max - b.max).length() < 0.01), "{got:?} vs {want:?}"); + assert!(s.visible_elements().iter().all(|e| (e.transform.decompose().rotation.to_degrees() - 90.0).abs() < 1e-3), "each piece reads 90°"); + run(&mut s, "element.set_transform", json!({"rotation": 0})); + run(&mut s, "element.set_transform", json!({"sx": 2})); + let fill = + s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).map(|e| s.element_bounds(e.id)).unwrap(); + assert!( + (fill.min.x - 0.0).abs() < 0.01 && (fill.max.x - 400.0).abs() < 0.01 && (fill.min.y - 100.0).abs() < 0.01, + "twice as wide about its centre: {fill:?}" + ); + run(&mut s, "element.set_transform", json!({"sx": 1})); + let mut fresh = Session::default(); + raw_rect(&mut fresh); + assert!(same(&layout(&s), &layout(&fresh)) && (s.selection_bounds().min - fresh.selection_bounds().min).length() < 0.01, "back where it was"); +} + #[test] fn svg_frame_export_writes_vectors_and_asks_before_replacing() { let dir = std::env::temp_dir().join(format!("anicraft-svg-{}", std::process::id()));