Files
vectorcraft/crates/engine/src/cmd/stepandrepeat.rs
T

325 lines
16 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Object › Step and Repeat: lays out copies of the selection on a grid or fills a sheet, for
//! print-and-cut work (stickers, labels).
use serde_json::{Value, json};
use vectorcraft_geom::{Rect, Vec2, rotate_deg};
use super::edit::selected_roots;
use super::object::group_nodes;
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_selection, switch_or};
use crate::EngineError;
use vectorcraft_doc::{Node, Scaling};
const CMD: &str = "object.stepAndRepeat";
const MAX_CELLS: usize = 10_000;
/// The most objects the copies may hold in all, counting every object inside each copy.
const MAX_COPIED_OBJECTS: usize = 250_000;
const EPS: f64 = 1e-9;
/// How far past a whole point a place may be and still count as on it, in points.
const GRID_EPS: f64 = 1e-6;
/// Whether `n` or an object in it, the art of linked opacity masks included, is pixel-aligned: the
/// objects that the snap after a transform moves.
fn holds_pixel_aligned(n: &Node) -> bool {
n.extras().pixel_aligned
|| n.children().is_some_and(|cs| cs.iter().any(|c| holds_pixel_aligned(c)))
|| n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_pixel_aligned(&m.art))
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"object.stepAndRepeat",
"Step and Repeat…",
["Object", "Transform"],
None,
"{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); when the selection holds a pixel-aligned object, every cell moves by whole points (the pitch is rounded up, with fill the first cell's place is rounded toward the sheet's inside and only cells that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own, with extra pitch only between alternating columns or rows and fill reserving the turn offset on both axes only where turned cells fit), so the copies stay on the pixel grid and the objects in each copy keep their places against each other; otherwise gaps are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; a single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step; the copies are selected → {ids: [id…], rows, columns, count}",
has_selection,
step_and_repeat
)]
}
/// Which cells of the grid are turned by 180°.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Alternate {
None,
Columns,
Rows,
}
/// One cell of a layout: its place in the grid, the offset of its top-left corner from the first
/// cell's, and whether its copy is turned by 180° about the cell's center.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Cell {
pub row: usize,
pub col: usize,
pub dx: f64,
pub dy: f64,
pub turned: bool,
}
/// How many items of `size` with `gap` between them fit in `room` (all at least 0).
pub fn fit_count(room: f64, size: f64, gap: f64) -> usize {
if !(room.is_finite() && size.is_finite() && gap.is_finite()) || size <= 0.0 || room < size - EPS {
return 0;
}
(((room + gap) / (size + gap)) + EPS).floor().max(0.0) as usize
}
/// The `(rows, columns)` of items `w` × `h` with gaps `gx`, `gy` that fit a sheet `sw` × `sh`
/// inside `margin` on every side.
pub fn fill_counts(sw: f64, sh: f64, margin: f64, w: f64, h: f64, gx: f64, gy: f64) -> (usize, usize) {
let m = margin.max(0.0);
(fit_count(sh - 2.0 * m, h, gy), fit_count(sw - 2.0 * m, w, gx))
}
/// The cells of a `rows` × `cols` grid of items `w` × `h` with gaps `gx` between columns and `gy`
/// between rows, in reading order.
pub fn layout(w: f64, h: f64, gx: f64, gy: f64, rows: usize, cols: usize, alt: Alternate) -> Vec<Cell> {
(0..rows)
.flat_map(|row| (0..cols).map(move |col| (row, col)))
.map(|(row, col)| Cell {
row,
col,
dx: col as f64 * (w + gx),
dy: row as f64 * (h + gy),
turned: match alt {
Alternate::None => false,
Alternate::Columns => col % 2 == 1,
Alternate::Rows => row % 2 == 1,
},
})
.collect()
}
fn count_param(p: &Value, key: &str) -> Result<usize> {
match p.get(key).filter(|v| !v.is_null()) {
None => Ok(1),
Some(v) => v
.as_u64()
.filter(|n| (1..=MAX_CELLS as u64).contains(n))
.map(|n| n as usize)
.ok_or_else(|| bad(CMD, format!("`{key}` must be a whole number from 1 to {MAX_CELLS}"))),
}
}
fn sheet_param(p: &Value) -> Result<Option<Rect>> {
let Some(v) = p.get("sheet").filter(|v| !v.is_null()) else { return Ok(None) };
let n = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).ok_or_else(|| bad(CMD, format!("`sheet.{k}` must be a number")));
let (x, y, w, h) = (n("x")?, n("y")?, n("width")?, n("height")?);
if w <= 0.0 || h <= 0.0 {
return Err(bad(CMD, "`sheet` needs a positive width and height"));
}
Ok(Some(Rect::new(x, y, x + w, y + h)))
}
fn step_and_repeat(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["gap", "gapX", "gapY", "margin"], CMD)?;
check_switches(p, &["patterns"], CMD)?;
let fill = switch_or(p, "fill", false, CMD)?;
let alt = match p.get("rotate").filter(|v| !v.is_null()) {
None => Alternate::None,
Some(v) => match v.as_str() {
Some("none") => Alternate::None,
Some("columns") => Alternate::Columns,
Some("rows") => Alternate::Rows,
_ => return Err(bad(CMD, "`rotate` must be \"none\", \"columns\" or \"rows\"")),
},
};
let gap = super::f64_or(p, "gap", 0.0);
let (gx, gy) = (super::f64_or(p, "gapX", gap), super::f64_or(p, "gapY", gap));
let margin = super::f64_or(p, "margin", 0.0);
if !(gx.is_finite() && gy.is_finite() && margin.is_finite()) {
return Err(bad(CMD, "gaps and margin must be finite"));
}
if margin < 0.0 {
return Err(bad(CMD, "`margin` must be 0 or more"));
}
let (rows, cols) = if fill { (1, 1) } else { (count_param(p, "rows")?, count_param(p, "columns")?) };
let sheet = sheet_param(p)?;
let mut roots = selected_roots(s)?;
if roots.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
let d = &s.doc()?.doc;
let cut = match p.get("cutId").filter(|v| !v.is_null()) {
None => None,
Some(v) => {
let id = NodeId(v.as_u64().ok_or_else(|| bad(CMD, "`cutId` must be an object id"))?);
let held = roots.iter().filter_map(|r| d.node(*r)).any(|n| {
let mut found = false;
n.walk(&mut |c| found |= c.id == id);
found
});
if !held {
return Err(bad(CMD, "`cutId` must be part of the selection"));
}
Some(id)
}
};
let measured = cut.map_or_else(|| roots.clone(), |id| vec![id]);
let b = d.bounds_of(&measured, false);
let b = b.ok_or_else(|| EngineError::Other("the selection has no bounds".into()))?;
let (w, h) = (b.width(), b.height());
if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 {
return Err(EngineError::Other("the selection has no area to repeat".into()));
}
if w + gx <= EPS || h + gy <= EPS {
return Err(bad(CMD, "a negative gap must be smaller than the width or height it is between"));
}
let anchor = if fill {
let sheet = sheet.or_else(|| {
let c = d.bounds_of(&roots, false).unwrap_or(b).center();
d.artboards.iter().find(|a| a.rect.contains(c)).or_else(|| d.artboards.first()).map(|a| a.rect)
});
let sheet = sheet.ok_or_else(|| EngineError::Other("no sheet to fill".into()))?;
Some((sheet, margin.max(0.0)))
} else {
None
};
// With a pixel-aligned object in the selection, every cell moves by whole points, so the snap
// leaves each copy as it moved it and the objects in a copy keep their places against each other.
// The pitch and the first cell's place are rounded up, so neighbors never come closer than asked
// and the first cell stays inside the sheet.
let aligned = roots.iter().filter_map(|r| d.node(*r)).any(holds_pixel_aligned);
let whole = |v: f64| if aligned { (v - GRID_EPS).ceil() } else { v };
// A half turn about the center maps x to 2 × center − x. On the pixel grid, twice the center is
// rounded up to whole points, so a turned copy also moves its objects by whole points; it then
// sits up to a point right of and below its cell, and the pitch and the fill make room for that.
let c2 = b.center().to_vec2() * 2.0;
let turn = if aligned && alt != Alternate::None {
let mut rounded = Vec2::new(whole(c2.x), whole(c2.y));
if rounded.x < c2.x - EPS {
rounded.x += 1.0;
}
if rounded.y < c2.y - EPS {
rounded.y += 1.0;
}
rounded - c2
} else {
Vec2::ZERO
};
let center = (c2 + turn) / 2.0;
let clearance = match alt {
Alternate::Columns => Vec2::new(turn.x, 0.0),
Alternate::Rows => Vec2::new(0.0, turn.y),
Alternate::None => Vec2::ZERO,
};
let (gx, gy) = if aligned {
let pitch = |v: f64| {
let rounded = whole(v).max(1.0);
if rounded < v - EPS { rounded + 1.0 } else { rounded }
};
(pitch(w + gx + clearance.x) - w, pitch(h + gy + clearance.y) - h)
} else {
(gx, gy)
};
let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| {
let raw = Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0);
let mut origin = Vec2::new(whole(raw.x), whole(raw.y));
if b.x0 + origin.x < sh.x0 + m - EPS {
origin.x += 1.0;
}
if b.y0 + origin.y < sh.y0 + m - EPS {
origin.y += 1.0;
}
origin
});
let (rows, cols) = match anchor {
Some((sh, m)) => {
let lead = origin - Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0);
let (sw, sh) = (sh.width() - lead.x - 2.0 * m, sh.height() - lead.y - 2.0 * m);
let (rows, cols) = fill_counts(sw, sh, 0.0, w, h, gx, gy);
// Turned cells have odd indices; an unturned cell may follow the last one that fits.
let alternating_count = |room, size, gap, shift, count: usize| count.min((fit_count(room - shift, size, gap) / 2 * 2).saturating_add(1));
match alt {
Alternate::Columns => {
let cols = alternating_count(sw, w, gx, turn.x, cols);
let turned_rows = fit_count(sh - turn.y, h, gy);
if cols > 1 && turned_rows > 0 { (rows.min(turned_rows), cols) } else { (rows, cols.min(1)) }
}
Alternate::Rows => {
let rows = alternating_count(sh, h, gy, turn.y, rows);
let turned_cols = fit_count(sw - turn.x, w, gx);
if rows > 1 && turned_cols > 0 { (rows, cols.min(turned_cols)) } else { (rows.min(1), cols) }
}
Alternate::None => (rows, cols),
}
}
None => (rows, cols),
};
if rows == 0 || cols == 0 {
return Err(EngineError::Other("the selection does not fit the sheet".into()));
}
if rows.saturating_mul(cols) > MAX_CELLS {
return Err(bad(CMD, format!("more than {MAX_CELLS} copies")));
}
// Each copy holds every object of the selection, the art of opacity masks included, and the
// group that a selection of several objects goes into.
let objects = roots.iter().filter_map(|r| d.node(*r)).fold(usize::from(roots.len() > 1), |sum, n| sum.saturating_add(n.count_with_masks()));
if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS {
return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects")));
}
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() };
if rows == 1 && cols == 1 && origin == Vec2::ZERO && roots.len() == 1 {
let selection = &s.doc()?.selection;
let mut next_selection = selection.clone();
next_selection.set([roots[0]]);
if next_selection == *selection {
return Ok(json!({ "ids": [roots[0].0], "rows": 1, "columns": 1, "count": 1 }));
}
}
let cells = layout(w, h, gx, gy, rows, cols, alt);
let place = |c: &Cell| -> Affine {
let t = Affine::translate(origin + Vec2::new(c.dx, c.dy));
if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t }
};
let ids = s.edit("Step and Repeat", |d, sel| {
if roots.len() > 1 {
roots = vec![group_nodes(d, &roots)?];
}
// Every copy is made first, and all of them go in with one insertion.
let originals: Vec<(NodeId, Node)> = roots.iter().filter_map(|id| d.node(*id).map(|n| (*id, n.clone()))).collect();
let mut lists: Vec<(NodeId, Vec<Node>)> = originals.iter().map(|(id, _)| (*id, Vec::with_capacity(cells.len()))).collect();
let mut copied: Vec<NodeId> = vec![];
let mut first = Affine::IDENTITY;
for c in &cells {
let m = place(c);
if c.row == 0 && c.col == 0 {
first = m;
continue;
}
for ((_, original), (_, list)) in originals.iter().zip(lists.iter_mut()) {
let mut n = d.reid(original);
n.transform(m, sc);
super::object::keep_pixel_aligned(&mut n, sc);
copied.push(n.id);
list.push(n);
}
}
if !copied.is_empty() {
// The copy of the last cell goes directly above its original and the first cell's on top.
for (_, list) in &mut lists {
list.reverse();
}
d.insert_beside(lists, false)?;
super::typecmd::refresh_bounds_of(d, &copied);
}
if first != Affine::IDENTITY {
for id in &roots {
if let Some(n) = d.node_mut(*id) {
n.transform(first, sc);
super::object::keep_pixel_aligned(n, sc);
}
}
}
let mut out: Vec<NodeId> = roots.clone();
out.extend(copied);
sel.set(out.iter().copied());
Ok(out)
})?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "rows": rows, "columns": cols, "count": ids.len() }))
}
#[cfg(test)]
mod tests;