mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 14:34:34 +00:00
Part of #6966: Path Precision Tools draws a bounding rectangle or circle around the selection
Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle runs addon.pathtools.boundingRectangle, which draws a live rectangle on the selection's geometric bounding box, strokes left out. Add Bounding Circle runs addon.pathtools.boundingCircle, which draws the smallest live circle that holds the outlines of the selected objects. Paths and compound paths count by their curves, clip groups and clipping sublayers by their clipping paths, other sublayers by their shown objects, images by their corners, and type and other objects by the corners of their bounding box. Each curve is split until its pieces lie within 0.01 pt of their chords (1,024 pieces at most, after which a piece counts by its control points), and the circle's radius is 0.01 pt larger than the smallest circle around those points, so it holds the curves. `offset` adds space around the objects, and `each` draws one shape around each selected object instead of one around them all. Objects with no outline, such as an empty group, and shapes with no size (the rectangle around a straight horizontal line, the circle around a single point) are not drawn; with `each`, `skipped` counts them. The shapes get the current paint and go on top of the current layer or of the isolated group, as Tangent Circle's circles do; inside an isolated compound path they go beside it. The new shapes are selected, and one undo removes them all. The smallest circle is computed in the geometry crate (shapes::enclosing_circle) from the convex hull of the points with a fixed shuffle, relative to one of the points so small art far from the origin keeps its exact circle. While the command gathers points from a large selection, it keeps only the corners of their convex hull, which bounds the memory it takes. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md, ROADMAP. Menu labels in all 28 catalogs and messages in the 24 catalogs with complete messages.
This commit is contained in:
@@ -3,11 +3,12 @@
|
||||
//! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners
|
||||
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
|
||||
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle
|
||||
//! ([`tangent_circle`]).
|
||||
//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]), Tangent Circle
|
||||
//! ([`tangent_circle`]) and Add Bounding Rectangle and Add Bounding Circle ([`bounding`]).
|
||||
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
|
||||
//! and the UI's.
|
||||
|
||||
mod bounding;
|
||||
mod corners;
|
||||
#[cfg(test)]
|
||||
mod effect_tests;
|
||||
@@ -185,6 +186,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
v.extend(trim::specs());
|
||||
v.extend(tangent_circle::specs());
|
||||
v.extend(tangents::specs());
|
||||
v.extend(bounding::specs());
|
||||
v
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: a live rectangle on the selection's geometric
|
||||
//! bounding box, or the smallest live circle around its outlines. The circle is the geometry crate's
|
||||
//! ([`enclosing_circle`](vectorcraft_geom::shapes::enclosing_circle)).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes};
|
||||
|
||||
use super::super::super::edit::selected_roots;
|
||||
use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, number_or, switch_or};
|
||||
use crate::{Result, Session};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// Add Bounding Rectangle's command.
|
||||
pub(crate) const RECTANGLE: &str = "addon.pathtools.boundingRectangle";
|
||||
/// Add Bounding Circle's command.
|
||||
pub(crate) const CIRCLE: &str = "addon.pathtools.boundingCircle";
|
||||
|
||||
/// How far a curve may stray from the points the circle is fitted to, in points. The circle's
|
||||
/// radius grows by as much, so it holds the curves themselves.
|
||||
const FLATNESS: f64 = 0.01;
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"addon.pathtools.boundingRectangle",
|
||||
"Add Bounding Rectangle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them, and it is an error when no rectangle is left → {id: the first rectangle, ids, skipped?}",
|
||||
has_selection,
|
||||
bounding_rectangle
|
||||
),
|
||||
cmd!(
|
||||
"addon.pathtools.boundingCircle",
|
||||
"Add Bounding Circle",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups by their clipping paths, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them, and it is an error when no circle is left → {id: the first circle, ids, skipped?}",
|
||||
has_selection,
|
||||
bounding_circle
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The shape a command draws.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Kind {
|
||||
Rectangle,
|
||||
Circle,
|
||||
}
|
||||
|
||||
fn bounding_rectangle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Rectangle)
|
||||
}
|
||||
|
||||
fn bounding_circle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add(s, p, Kind::Circle)
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value, kind: Kind) -> Result<Value> {
|
||||
let (c, label) = match kind {
|
||||
Kind::Rectangle => (RECTANGLE, "Add Bounding Rectangle"),
|
||||
Kind::Circle => (CIRCLE, "Add Bounding Circle"),
|
||||
};
|
||||
check_switches(p, &["each"], c)?;
|
||||
let each = switch_or(p, "each", false, c)?;
|
||||
let offset = number_or(p, "offset", 0.0, c)?;
|
||||
if !(offset.is_finite() && offset >= 0.0) {
|
||||
return Err(bad(c, "`offset` must be 0 or more"));
|
||||
}
|
||||
let roots = selected_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let groups: Vec<Vec<NodeId>> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] };
|
||||
let mut made: Vec<LiveShape> = vec![];
|
||||
// Objects that get no shape: no outline, or a shape with no size.
|
||||
let mut skipped = 0;
|
||||
for ids in &groups {
|
||||
match shape_around(d, &symbols, ids, kind, offset) {
|
||||
Some(live) => made.push(live),
|
||||
None => skipped += 1,
|
||||
}
|
||||
}
|
||||
if made.is_empty() {
|
||||
return Err(bad(c, "nothing to enclose"));
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
let mut ids = vec![];
|
||||
for live in made {
|
||||
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
|
||||
let mut n = Node::new(d.alloc_id(), kind);
|
||||
look.apply(d, &mut n);
|
||||
ids.push(n.id);
|
||||
d.insert(parent, usize::MAX, n)?;
|
||||
}
|
||||
sel.set(ids.iter().copied());
|
||||
Ok(ids)
|
||||
})?;
|
||||
let first = ids.first().map_or(0, |id| id.0);
|
||||
let mut out = json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() });
|
||||
if skipped > 0 {
|
||||
out["skipped"] = json!(skipped);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The live rectangle or circle around `ids`, grown by `offset`; `None` when they have no bounds
|
||||
/// or the shape would have no width or no height.
|
||||
fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64) -> Option<LiveShape> {
|
||||
match kind {
|
||||
Kind::Rectangle => {
|
||||
let r = d.bounds_of_with(ids, false, symbols)?.inflate(offset, offset);
|
||||
if !r.is_finite() || r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(LiveShape::Rectangle {
|
||||
w: r.width(),
|
||||
h: r.height(),
|
||||
radii: [0.0; 4],
|
||||
kinds: Default::default(),
|
||||
radii_relative: false,
|
||||
xf: Affine::translate(r.origin().to_vec2()),
|
||||
})
|
||||
}
|
||||
Kind::Circle => {
|
||||
let mut gathered = Gathered::new();
|
||||
for n in ids.iter().filter_map(|id| d.node(*id)) {
|
||||
outline_points(n, symbols, &mut gathered, 0);
|
||||
gathered.compact();
|
||||
}
|
||||
let (center, radius) = shapes::enclosing_circle(&gathered.points)?;
|
||||
if radius + offset <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let r = radius + FLATNESS + offset;
|
||||
let b = Rect::new(center.x - r, center.y - r, center.x + r, center.y + r);
|
||||
if !b.is_finite() {
|
||||
return None;
|
||||
}
|
||||
Some(LiveShape::Ellipse { w: b.width(), h: b.height(), pie: (0.0, 360.0), xf: Affine::translate(b.origin().to_vec2()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of
|
||||
/// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its
|
||||
/// contents; the shown contents of a sublayer; the corners of an image; and the corners of the
|
||||
/// geometric bounding box of anything else. A group or layer `depth` levels below the selected
|
||||
/// object that is nested deeper than a document holds ([`vectorcraft_doc::MAX_DEPTH`]) counts by
|
||||
/// the corners of its geometric bounding box.
|
||||
fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) {
|
||||
let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. });
|
||||
if nests && depth >= vectorcraft_doc::MAX_DEPTH {
|
||||
out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten());
|
||||
return;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => {
|
||||
// The anchors count too, so a path of one anchor, which has no segments, is held.
|
||||
out.points.extend(path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)));
|
||||
for seg in path.to_bezpath().segments() {
|
||||
match seg {
|
||||
PathSeg::Line(l) => out.points.extend([l.p0, l.p1]),
|
||||
_ => curve_points(seg.to_cubic(), 0, &mut out.points),
|
||||
}
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
if let Some(c) = children.first() {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
}
|
||||
}
|
||||
NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => {
|
||||
let layer = matches!(n.kind, NodeKind::Layer { .. });
|
||||
for c in n.editing_children().iter().filter(|c| c.visible || !layer) {
|
||||
outline_points(c, symbols, out, depth + 1);
|
||||
out.compact();
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
let r = Rect::new(0.0, 0.0, im.width as f64, im.height as f64);
|
||||
out.points.extend(corners(r).map(|p| im.xf * p));
|
||||
}
|
||||
_ => out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of
|
||||
/// pieces whose control points lie within [`FLATNESS`] of their chord, and the control points of
|
||||
/// pieces still curved after [`MAX_SPLITS`] halvings, which hold their piece. A curve with a point
|
||||
/// that is not finite adds nothing.
|
||||
fn curve_points(c: CubicBez, depth: u32, out: &mut Vec<Point>) {
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS);
|
||||
if flat {
|
||||
out.extend([c.p0, c.p3]);
|
||||
} else if depth >= MAX_SPLITS {
|
||||
out.extend([c.p0, c.p1, c.p2, c.p3]);
|
||||
} else {
|
||||
let (a, b) = c.subdivide();
|
||||
curve_points(a, depth + 1, out);
|
||||
curve_points(b, depth + 1, out);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull.
|
||||
const COMPACT_AT: usize = 1 << 16;
|
||||
|
||||
/// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow
|
||||
/// past `limit`: only the hull decides the circle, so this bounds the memory a large selection of
|
||||
/// curves takes.
|
||||
struct Gathered {
|
||||
points: Vec<Point>,
|
||||
limit: usize,
|
||||
}
|
||||
|
||||
impl Gathered {
|
||||
fn new() -> Self {
|
||||
Self { points: vec![], limit: COMPACT_AT }
|
||||
}
|
||||
|
||||
/// Keeps only the hull's corners once there are more than `limit` points; the next time waits
|
||||
/// until there are twice as many as the hull has, so each point is sorted a few times at most.
|
||||
fn compact(&mut self) {
|
||||
if self.points.len() > self.limit {
|
||||
self.points = shapes::convex_hull(std::mem::take(&mut self.points));
|
||||
self.limit = (self.points.len() * 2).max(COMPACT_AT);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many times [`curve_points`] halves a curve at most: up to 1,024 pieces.
|
||||
const MAX_SPLITS: u32 = 10;
|
||||
|
||||
/// The distance from `p` to the segment from `a` to `b`.
|
||||
fn distance_to_segment(p: Point, a: Point, b: Point) -> f64 {
|
||||
let ab = b - a;
|
||||
let len2 = ab.hypot2();
|
||||
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(p - (a + ab * t)).hypot()
|
||||
}
|
||||
|
||||
fn corners(r: Rect) -> [Point; 4] {
|
||||
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current
|
||||
//! paint and placement on top of the current layer or the isolated group, `each` and `skipped`,
|
||||
//! shapes of no size, clip groups and clipping sublayers, huge curves, and the errors that leave
|
||||
//! the document as it was.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
|
||||
|
||||
use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE};
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn node(s: &Session, id: NodeId) -> Node {
|
||||
s.doc().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn ids_of(v: &Value) -> Vec<NodeId> {
|
||||
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn object_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|_| n += 1);
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether two rectangles agree to within `tol` on every edge.
|
||||
fn rect_near(b: Rect, want: Rect, tol: f64) -> bool {
|
||||
[(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < tol)
|
||||
}
|
||||
|
||||
/// The live shape of `id`.
|
||||
fn live(s: &Session, id: NodeId) -> LiveShape {
|
||||
match &node(s, id).kind {
|
||||
NodeKind::Path { live: Some(live), .. } => live.as_ref().clone(),
|
||||
other => panic!("not a live shape: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of `id`.
|
||||
fn bounds(s: &Session, id: NodeId) -> Rect {
|
||||
s.doc().unwrap().doc.bounds_of(&[id], false).unwrap()
|
||||
}
|
||||
|
||||
/// The last child of `parent`, the top of its stacking order.
|
||||
fn top_of(s: &Session, parent: NodeId) -> NodeId {
|
||||
node(s, parent).children().unwrap().last().unwrap().id
|
||||
}
|
||||
|
||||
/// Runs `command` with `p` and checks that it fails and leaves the document as it was.
|
||||
fn refused(s: &mut Session, command: &str, p: Value) -> String {
|
||||
let (undo, objects) = (undo_len(s), object_count(s));
|
||||
let e = s.execute(command, &p).unwrap_err().to_string();
|
||||
assert_eq!((undo_len(s), object_count(s)), (undo, objects), "{p} changed the document");
|
||||
e
|
||||
}
|
||||
|
||||
/// A live rectangle on the selection's geometric bounding box, strokes left out, with the current
|
||||
/// paint, on top of the current layer, selected; one undo removes it.
|
||||
#[test]
|
||||
fn a_bounding_rectangle_is_the_geometric_box_on_top_of_the_layer() {
|
||||
let mut s = session();
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let b = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 60, "height": 80})).unwrap());
|
||||
assert_eq!(node(&s, a).appearance.stroke_width(), 10.0, "the strokes reach past the geometric box");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let (before, undo) = (object_count(&s), undo_len(&s));
|
||||
let out = s.execute(RECTANGLE, &json!({})).unwrap();
|
||||
let id = id_of(&out);
|
||||
assert_eq!(ids_of(&out), vec![id]);
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
assert!(matches!(live(&s, id), LiveShape::Rectangle { .. }));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 20.0, 160.0, 130.0), 1e-9), "{:?}", bounds(&s, id));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(top_of(&s, layer), id);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert_eq!(object_count(&s), before + 1);
|
||||
// The current paint, as a shape drawn now gets it.
|
||||
let reference = rect(&mut s, 300.0, 300.0, 5.0, 5.0);
|
||||
let (n, r) = (node(&s, id), node(&s, reference));
|
||||
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint()));
|
||||
assert_eq!(n.appearance.stroke_width(), r.appearance.stroke_width());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(object_count(&s), before);
|
||||
}
|
||||
|
||||
/// A bounding circle around a right triangle stands on its hypotenuse; around a circle it is that
|
||||
/// circle, grown by at most the flattening allowance; `offset` grows the radius, and a rectangle's
|
||||
/// sides, by that much.
|
||||
#[test]
|
||||
fn a_bounding_circle_is_the_smallest_circle_around_the_outlines() {
|
||||
let mut s = session();
|
||||
let tri =
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}], "closed": true})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
match live(&s, c) {
|
||||
LiveShape::Ellipse { w, h, pie, .. } => {
|
||||
assert!((w - 100.02).abs() < 1e-9 && (h - 100.02).abs() < 1e-9 && pie == (0.0, 360.0), "{w} {h}");
|
||||
}
|
||||
other => panic!("not a circle: {other:?}"),
|
||||
}
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(-10.01, -20.01, 90.01, 80.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
// A circle of radius 50 and a dot inside it: the bounding circle is the circle itself.
|
||||
let round = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 100, "height": 100})).unwrap());
|
||||
let dot = rect(&mut s, 240.0, 240.0, 2.0, 2.0);
|
||||
s.execute("select.set", &json!({"ids": [round.0, dot.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 5})).unwrap());
|
||||
let got = bounds(&s, c);
|
||||
let want = Rect::new(195.0, 195.0, 305.0, 305.0);
|
||||
assert!(rect_near(got, want, 0.03), "{got:?}");
|
||||
assert!(got.x0 <= want.x0 + 1e-9 && got.x1 >= want.x1 - 1e-9 && got.y0 <= want.y0 + 1e-9 && got.y1 >= want.y1 - 1e-9, "{got:?}");
|
||||
|
||||
s.execute("select.set", &json!({"ids": [tri.0]})).unwrap();
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 4})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(-4.0, -4.0, 84.0, 64.0), 1e-9));
|
||||
}
|
||||
|
||||
/// A shape with no size is not drawn: a straight horizontal line gets no rectangle and a path of
|
||||
/// one anchor no circle, unless `offset` gives them room; with `each` they are counted in
|
||||
/// `skipped`, and alone they are an error.
|
||||
#[test]
|
||||
fn shapes_of_no_size_are_skipped_unless_offset_gives_them_room() {
|
||||
let mut s = session();
|
||||
let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 10, "y": 50}, {"x": 90, "y": 50}]})).unwrap());
|
||||
let lone = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 50, "y": 70}]})).unwrap());
|
||||
let box_ = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({})).contains("nothing to enclose"));
|
||||
let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 2})).unwrap());
|
||||
assert!(rect_near(bounds(&s, r), Rect::new(8.0, 48.0, 92.0, 52.0), 1e-9), "{:?}", bounds(&s, r));
|
||||
// The line has length, so its circle has size.
|
||||
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(9.99, 9.99, 90.01, 90.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
|
||||
assert!(refused(&mut s, CIRCLE, json!({})).contains("nothing to enclose"));
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3})).unwrap());
|
||||
assert!(rect_near(bounds(&s, c), Rect::new(46.99, 66.99, 53.01, 73.01), 1e-9), "{:?}", bounds(&s, c));
|
||||
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(2)), "{out}");
|
||||
assert!(rect_near(bounds(&s, id_of(&out)), Rect::new(200.0, 200.0, 210.0, 210.0), 1e-9));
|
||||
s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (2, Some(1)), "{out}");
|
||||
}
|
||||
|
||||
/// With `each`, every selected object gets a shape of its own, all in one undo step, on top of the
|
||||
/// layer in the selection's stacking order, and the new shapes are selected.
|
||||
#[test]
|
||||
fn each_draws_one_shape_around_each_object() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 100.0, 0.0, 20.0, 30.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap();
|
||||
let undo = undo_len(&s);
|
||||
let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap();
|
||||
let ids = ids_of(&out);
|
||||
assert_eq!(ids.len(), 2);
|
||||
assert!(rect_near(bounds(&s, ids[0]), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9));
|
||||
assert!(rect_near(bounds(&s, ids[1]), Rect::new(100.0, 0.0, 120.0, 30.0), 1e-9));
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
let order: Vec<NodeId> = node(&s, layer).children().unwrap().iter().map(|n| n.id).collect();
|
||||
assert_eq!(order, vec![a, b, ids[0], ids[1]]);
|
||||
assert_eq!(s.doc().unwrap().selection.objects.len(), 2);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// An object with no outline (an empty group) gets no shape and the result counts it; with only
|
||||
/// such objects selected the command draws nothing.
|
||||
#[test]
|
||||
fn each_counts_the_objects_without_an_outline() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let empty = s
|
||||
.edit("Group", |d, _| {
|
||||
let id = d.alloc_id();
|
||||
d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({"each": true})).unwrap();
|
||||
assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(1)), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap();
|
||||
let out = s.execute(CIRCLE, &json!({})).unwrap();
|
||||
assert!(out.get("skipped").is_none(), "{out}");
|
||||
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
|
||||
assert!(refused(&mut s, RECTANGLE, json!({"each": true})).contains("nothing to enclose"));
|
||||
}
|
||||
|
||||
/// Curves over a hundred thousand points across are held by their circle: every point along the
|
||||
/// curves is inside the circle, whose radius is the 0.01 pt allowance larger than the circle around
|
||||
/// the flattened points. The farthest point of the lopsided arc lies between two flattened points,
|
||||
/// about 0.001 pt outside the circle around them, so it needs that allowance.
|
||||
#[test]
|
||||
fn the_circle_holds_huge_curves() {
|
||||
let mut s = session();
|
||||
let d = "M 0 0 C 0 -90000 120000 -90000 120000 0 C 60000 40000 30000 70000 0 0 Z";
|
||||
let blob = id_of(&s.execute("path.create", &json!({"d": d})).unwrap());
|
||||
let arc = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 20 400 380 500 400 0"})).unwrap());
|
||||
for big in [blob, arc] {
|
||||
s.execute("select.set", &json!({"ids": [big.0]})).unwrap();
|
||||
let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") };
|
||||
let (center, r) = (xf * Point::new(w / 2.0, w / 2.0), w / 2.0);
|
||||
let path = node(&s, big).path_data().unwrap().to_bezpath();
|
||||
let mut farthest: f64 = 0.0;
|
||||
for seg in path.segments() {
|
||||
for i in 0..=4000 {
|
||||
let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0);
|
||||
farthest = farthest.max(p.distance(center));
|
||||
}
|
||||
}
|
||||
assert!(farthest <= r + 1e-6, "a point {farthest} from the center is outside the circle of radius {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Clip groups count by their clipping paths; for art inside one, the shape goes on top of the
|
||||
/// current layer, never into the clip group.
|
||||
#[test]
|
||||
fn clip_groups_count_by_their_clipping_paths() {
|
||||
let mut s = session();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let clip = id_of(&s.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [art.0, clip.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let b = bounds(&s, id);
|
||||
assert!((b.width() / 2.0 - 25.01).abs() < 0.03 && b.center().distance(Point::new(35.0, 35.0)) < 0.03, "{b:?}");
|
||||
let layer = s.doc().unwrap().current_layer().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
s.execute("select.set", &json!({"ids": [clip.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer));
|
||||
assert!(rect_near(bounds(&s, id), Rect::new(10.0, 10.0, 60.0, 60.0), 1e-6));
|
||||
}
|
||||
|
||||
/// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a
|
||||
/// sublayer are left out.
|
||||
#[test]
|
||||
fn sublayers_count_by_their_clipping_path_and_shown_art() {
|
||||
let mut s = session();
|
||||
let top = s.doc().unwrap().current_layer().unwrap();
|
||||
let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap());
|
||||
s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap();
|
||||
let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let hidden = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(sub), "the art is in the sublayer");
|
||||
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let (sub_node, symbols) = (d.node(sub).unwrap().clone(), d.symbol_boxes());
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &symbols, &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(50.0, 50.0)) < 1e-9 && (r - 50.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
|
||||
// The top object of the sublayer becomes its clipping path.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let clip = rect(&mut s, 20.0, 20.0, 10.0, 10.0);
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(clip), Some(sub));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let sub_node = d.node(sub).unwrap().clone();
|
||||
let mut g = Gathered::new();
|
||||
super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0);
|
||||
let (center, r) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}");
|
||||
}
|
||||
|
||||
/// In an isolated group the shape goes on top of the group's art; in an isolated compound path it
|
||||
/// goes beside the compound path, never into it.
|
||||
#[test]
|
||||
fn shapes_go_into_an_isolated_group_but_not_an_isolated_compound_path() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": group.0})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap());
|
||||
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group));
|
||||
assert_eq!(top_of(&s, group), id);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
|
||||
let c = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
|
||||
let e = rect(&mut s, 120.0, 100.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
|
||||
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
|
||||
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
|
||||
let members: Vec<u64> = node(&s, compound).children().unwrap().iter().map(|n| n.id.0).collect();
|
||||
s.execute("select.set", &json!({"ids": members})).unwrap();
|
||||
let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_ne!(d.parent_of(id), Some(compound), "the circle does not join the compound path");
|
||||
assert_eq!(d.parent_of(id), d.parent_of(compound));
|
||||
assert_eq!(node(&s, compound).children().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
/// An offset or each that is not one the commands take is an error, and nothing is drawn; with
|
||||
/// nothing selected the commands are not available.
|
||||
#[test]
|
||||
fn bad_params_and_an_empty_selection_draw_nothing() {
|
||||
let mut s = session();
|
||||
assert!(s.execute(RECTANGLE, &json!({})).is_err(), "nothing selected");
|
||||
assert!(s.execute(CIRCLE, &json!({})).is_err(), "nothing selected");
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
for command in [RECTANGLE, CIRCLE] {
|
||||
for p in [json!({"offset": -1}), json!({"offset": "5"}), json!({"each": "yes"})] {
|
||||
refused(&mut s, command, p);
|
||||
}
|
||||
assert!(refused(&mut s, command, json!({"offset": -1})).contains("`offset` must be 0 or more"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Many points keep only their hull's corners, and the circle around them is the one around all
|
||||
/// of the points.
|
||||
#[test]
|
||||
fn gathered_points_keep_their_hull_and_circle() {
|
||||
let mut g = Gathered::new();
|
||||
let c = Point::new(500.0, 300.0);
|
||||
for i in 0..200_000 {
|
||||
let angle = f64::from(i) * 0.618;
|
||||
let r = if i % 1000 == 0 { 250.0 } else { f64::from(i % 200) };
|
||||
g.points.push(c + Vec2::from_angle(angle) * r);
|
||||
g.compact();
|
||||
}
|
||||
assert!(g.points.len() <= COMPACT_AT + 1, "{} points kept", g.points.len());
|
||||
let (center, radius) = shapes::enclosing_circle(&g.points).unwrap();
|
||||
assert!(center.distance(c) < 1e-6 && (radius - 250.0).abs() < 1e-6, "{center:?} {radius}");
|
||||
}
|
||||
Reference in New Issue
Block a user