mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 09:21:55 +01:00
Merge pull request #9787 from dotCooCoo/fix/pathdata-bounds-lone-anchors
Paths: a subpath of one anchor counts in the path's bounds
This commit is contained in:
6 files changed
+183
-19
No files matched your search
@@ -431,6 +431,17 @@ impl Node {
|
||||
}
|
||||
}
|
||||
|
||||
/// The box of what a path, or the paths of a compound path, draw before the strokes' reach
|
||||
/// ([`PathData::drawn_bounds`]): lone anchors of closed subpaths count only with `dots`. Other
|
||||
/// members of a compound path count by their geometric box. `None` when nothing is drawn.
|
||||
fn drawn(&self, symbols: Option<&SymbolBoxes>, dots: bool) -> Option<Rect> {
|
||||
match &self.kind {
|
||||
NodeKind::Path { path, .. } => path.drawn_bounds(dots),
|
||||
NodeKind::Compound { .. } => self.editing_children().iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.drawn(symbols, dots))),
|
||||
_ => self.geometric(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual bounds: what the object paints, its strokes included (paths and compound paths
|
||||
/// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is
|
||||
/// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`],
|
||||
@@ -485,7 +496,9 @@ impl Node {
|
||||
self.geometric(symbols).map(|b| b.inflate(o, o))
|
||||
}
|
||||
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
|
||||
let b = self.geometric(symbols)?;
|
||||
// A lone anchor is drawn only as the dot of a round or projecting cap on a closed subpath.
|
||||
let dots = self.appearance.painted_strokes().any(|s| matches!(s.cap, crate::LineCap::Round | crate::LineCap::Square));
|
||||
let b = self.drawn(symbols, dots).or_else(|| self.geometric(symbols))?;
|
||||
Some(self.appearance.stroked_bounds(b, || self.stroke_path().unwrap_or_default()))
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
|
||||
@@ -469,6 +469,35 @@ fn visual_bounds_include_stroke() {
|
||||
assert_eq!(p.visual_bounds(), Some(Rect::new(-0.5, -0.5, 10.5, 10.5)));
|
||||
}
|
||||
|
||||
/// A lone anchor 20 points right of a stroked square widens the path's geometric box, and its
|
||||
/// visual box only where the stroke draws it: as the dot of a round or projecting cap on a closed
|
||||
/// subpath. An open lone anchor, or a closed one under a butt cap, draws nothing.
|
||||
#[test]
|
||||
fn a_lone_anchor_widens_the_visual_box_only_where_its_cap_draws_a_dot() {
|
||||
use crate::appearance::LineCap;
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let square = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let node = |closed: bool, cap: LineCap| {
|
||||
let mut subpaths = square.subpaths.clone();
|
||||
subpaths.push(SubPath::polyline(&[Point::new(30.0, 5.0)], closed));
|
||||
let mut p = Node::path(NodeId(2), PathData::new(subpaths), Appearance::default_art());
|
||||
let s = p.appearance.stroke_mut().unwrap();
|
||||
(s.cap, s.join) = (cap, crate::appearance::LineJoin::Round);
|
||||
p
|
||||
};
|
||||
for closed in [false, true] {
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
let p = node(closed, cap);
|
||||
let geometric = p.geometric_bounds().unwrap();
|
||||
let visual = p.visual_bounds().unwrap();
|
||||
assert!(geometric.x1 >= 30.0, "{closed} {cap:?}: the geometric box {geometric:?} leaves out the lone anchor");
|
||||
let dot = closed && cap != LineCap::Butt;
|
||||
assert_eq!(visual.x1 > 30.0, dot, "{closed} {cap:?}: the visual box {visual:?}");
|
||||
assert!(dot || visual.x1 < 11.0, "{closed} {cap:?}: the visual box {visual:?} reaches toward the lone anchor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's box from its members' boxes grows by the group's own strokes, leaves out members
|
||||
/// without a box, and is `None` when none has one.
|
||||
#[test]
|
||||
|
||||
@@ -619,7 +619,12 @@ fn moved_type(n: &Node, moves: &[serde_json::Value]) -> Option<Vec<Node>> {
|
||||
}
|
||||
let (_, all) = glyph_outlines(t);
|
||||
let outline = PathData::from_bezpath(&all).transformed(t.xf);
|
||||
let ink = outline.bounds()?;
|
||||
// A contour of one anchor paints only as the dot of a round or projecting character stroke cap.
|
||||
let dots = t
|
||||
.runs
|
||||
.iter()
|
||||
.any(|r| r.style.appearance().painted_strokes().any(|s| matches!(s.cap, vectorcraft_doc::LineCap::Round | vectorcraft_doc::LineCap::Square)));
|
||||
let ink = outline.drawn_bounds(dots)?;
|
||||
let offsets = transform_offsets(moves, &outline)?;
|
||||
if offsets.len() > MAX_TYPE_COPIES {
|
||||
return None;
|
||||
|
||||
@@ -220,16 +220,53 @@ const PAINTED_SLACK: f64 = 1e-4;
|
||||
/// applied, so a stroke a Transform effect moves counts where it is moved to), measured by its
|
||||
/// visual bounds. Those are exact for miter joins (a tip counts where the miter limit keeps it) and
|
||||
/// round joins, and an upper bound for bevel joins, miters the limit cuts, width profiles and
|
||||
/// square-capped dashes; a contour of zero length, which paints nothing, doesn't count. Effects on
|
||||
/// the type object itself are left out: VectorCraft applies them after the envelope bends the type.
|
||||
/// `None` when nothing in it has bounds.
|
||||
/// square-capped dashes; a contour of zero length, which paints nothing in the files' drawn art,
|
||||
/// doesn't count, even where VectorCraft draws it as the dot of a round or projecting cap. Effects
|
||||
/// on the type object itself are left out: VectorCraft applies them after the envelope bends the
|
||||
/// type. `None` when nothing in it has bounds.
|
||||
fn painted_outlines(outlines: &Node) -> Option<Rect> {
|
||||
outlines.children().into_iter().flatten().fold(None, |acc, piece| {
|
||||
let baked = vectorcraft_effects::bake_type_appearance(None, piece);
|
||||
vectorcraft_geom::union_opt(acc, baked.as_ref().unwrap_or(piece).visual_bounds())
|
||||
let baked = baked.as_ref().unwrap_or(piece);
|
||||
let painted = without_zero_length_contours(baked);
|
||||
vectorcraft_geom::union_opt(acc, painted.as_ref().unwrap_or(baked).visual_bounds())
|
||||
})
|
||||
}
|
||||
|
||||
/// `n` with its paths, and the paths in its groups and compound paths, without their subpaths of
|
||||
/// one anchor (contours of zero length, which have no segment); a path with nothing else is left
|
||||
/// empty, with no bounds. `None` when nothing changes.
|
||||
fn without_zero_length_contours(n: &Node) -> Option<Node> {
|
||||
if let Some(path) = n.path_data() {
|
||||
let lone = |s: &vectorcraft_geom::SubPath| s.segment_count() == 0;
|
||||
if !path.subpaths.iter().any(lone) {
|
||||
return None;
|
||||
}
|
||||
let mut kept = n.clone();
|
||||
if let Some(p) = kept.path_data_mut() {
|
||||
p.subpaths.retain(|s| !lone(s));
|
||||
}
|
||||
return Some(kept);
|
||||
}
|
||||
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }) {
|
||||
return None;
|
||||
}
|
||||
let members = n.children()?;
|
||||
let changed: Vec<Option<Node>> = members.iter().map(|c| without_zero_length_contours(c)).collect();
|
||||
if changed.iter().all(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
let mut kept = n.clone();
|
||||
if let Some(children) = kept.children_mut() {
|
||||
for (c, new) in children.iter_mut().zip(changed) {
|
||||
if let Some(new) = new {
|
||||
*c = Arc::new(new);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(kept)
|
||||
}
|
||||
|
||||
/// The box of `content` an envelope of type with Distort Appearance may map from in a file besides
|
||||
/// [`half_stroked_box`]: what it paints, type by its outlines ([`painted_outlines`]), groups by
|
||||
/// their members grown by as far as their own strokes paint along a side, other objects by their
|
||||
@@ -1368,6 +1405,30 @@ mod tests {
|
||||
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
|
||||
}
|
||||
|
||||
/// A piece of type outlines that is only contours of zero length paints nothing either: a dot
|
||||
/// piece with a round 2 point stroke beside a stroked square adds nothing to the square's box.
|
||||
#[test]
|
||||
fn a_piece_of_only_zero_length_contours_paints_nothing() {
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
|
||||
(stroke.join, stroke.cap) = (LineJoin::Round, LineCap::Round);
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))));
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((10.0, 10.0));
|
||||
square.line_to((20.0, 10.0));
|
||||
square.line_to((20.0, 20.0));
|
||||
square.line_to((10.0, 20.0));
|
||||
square.close_path();
|
||||
let mut dot = BezPath::new();
|
||||
dot.move_to((50.0, 50.0));
|
||||
dot.line_to((50.0, 50.0));
|
||||
dot.close_path();
|
||||
let pieces = [(1, square), (2, dot)].map(|(id, bp)| Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&bp), appearance.clone())));
|
||||
let outlines = Node::group(NodeId(3), pieces.to_vec());
|
||||
assert_eq!(painted_outlines(&outlines), Some(Rect::new(9.0, 9.0, 21.0, 21.0)));
|
||||
}
|
||||
|
||||
/// Type that draws nothing adds no box next to other content in the boxes the import tries an
|
||||
/// envelope with Distort Appearance mapped from, loose and in a group, as it adds none to the
|
||||
/// contents' geometric box: a rectangle with a round 4 point stroke beside type of only spaces
|
||||
|
||||
@@ -1488,7 +1488,7 @@ fn painted_bounds(object: &Node, appearance: &Appearance) -> Option<Rect> {
|
||||
let mut out = None;
|
||||
for item in &appearance.items {
|
||||
let painted = match item {
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(),
|
||||
AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.drawn_bounds(false),
|
||||
AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(),
|
||||
_ => None,
|
||||
};
|
||||
@@ -1992,6 +1992,31 @@ mod tests {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0)))
|
||||
}
|
||||
|
||||
/// A lone anchor, which a fill does not paint, does not move what the fill paints when the
|
||||
/// arrowheads are placed against the drawn look: a filled line with a head and a stray anchor
|
||||
/// well outside it still fits a look of the line and its head alone.
|
||||
#[test]
|
||||
fn a_lone_anchor_does_not_move_the_painted_box_heads_are_placed_by() {
|
||||
use vectorcraft_doc::{ArrowAlign, Arrowhead, CustomArrowhead, FillLayer, StrokeLayer};
|
||||
use vectorcraft_geom::{Point, SubPath};
|
||||
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK), 2.0);
|
||||
stroke.end_arrow = Some(Arrowhead::Custom(Arc::new(CustomArrowhead::new("Wedge".into(), wedge))));
|
||||
stroke.arrow_align = ArrowAlign::Tip;
|
||||
let mut appearance = Appearance::default();
|
||||
appearance.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(vectorcraft_doc::color::Color::BLACK))));
|
||||
appearance.items.push(AppearanceItem::Stroke(stroke));
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(100.0, 50.0)], false);
|
||||
let plain = Node::path(NodeId(1), PathData::single(line.clone()), appearance.clone());
|
||||
let want = painted_bounds(&plain, &appearance).unwrap();
|
||||
let look =
|
||||
Node::path(NodeId(2), shapes::rectangle(want), Appearance::basic(Paint::solid(vectorcraft_doc::color::Color::BLACK), Paint::None, 0.0));
|
||||
let stray = SubPath::new(vec![vectorcraft_geom::Anchor::corner(Point::new(50.0, 200.0))], false);
|
||||
let object = Node::path(NodeId(3), PathData::new(vec![line, stray]), appearance.clone());
|
||||
let placed = heads_placed(&object, &look, appearance, Affine::IDENTITY).expect("the heads fit the look");
|
||||
assert!(placed.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.arrow_align == ArrowAlign::Tip)));
|
||||
}
|
||||
|
||||
/// The outline check works from one budget for the object: a look of the outline drawn twice
|
||||
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
|
||||
/// look instead of comparing every copy.
|
||||
|
||||
+43
-12
@@ -673,9 +673,9 @@ impl PathData {
|
||||
/// segment with a control point that is not finite or past `f64::MAX / 16` in x or y is measured
|
||||
/// by its control points.
|
||||
///
|
||||
/// Walks the segments in place, without building the path: the same segments in the same order,
|
||||
/// so the result is bit for bit `curve_bounds(&self.to_bezpath())` (a path of lone anchors, with
|
||||
/// no segment, is `Rect::ZERO`, as there).
|
||||
/// Walks the segments in place, without building the path: the same segments in the same order
|
||||
/// as `curve_bounds(&self.to_bezpath())`. A subpath of one anchor has no segment, and the box
|
||||
/// also holds that anchor's point, so a path of lone anchors measures the box around them.
|
||||
pub fn bounds(&self) -> Option<Rect> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
@@ -685,8 +685,26 @@ impl PathData {
|
||||
{
|
||||
return Some(Rect::from_points(a.p, a.p));
|
||||
}
|
||||
Some(self.measured(|_| true).unwrap_or_default())
|
||||
}
|
||||
/// The box of what a stroke along the path draws, before the stroke's own reach: its segments,
|
||||
/// as in [`PathData::bounds`], and the lone anchors a stroke draws. A lone anchor of an open
|
||||
/// subpath draws nothing. A lone anchor of a closed subpath draws a dot when `dots` is set, as
|
||||
/// a round or projecting cap does, and nothing otherwise. `None` when the path draws nothing.
|
||||
pub fn drawn_bounds(&self, dots: bool) -> Option<Rect> {
|
||||
self.measured(|sp| dots && sp.closed)
|
||||
}
|
||||
/// The box of the segments and of the lone anchors of the subpaths `lone` keeps.
|
||||
fn measured(&self, lone: impl Fn(&SubPath) -> bool) -> Option<Rect> {
|
||||
let mut bbox: Option<Rect> = None;
|
||||
for sp in &self.subpaths {
|
||||
if sp.segment_count() == 0
|
||||
&& lone(sp)
|
||||
&& let Some(a) = sp.anchors.first()
|
||||
{
|
||||
let lone = Rect::from_points(a.p, a.p);
|
||||
bbox = Some(bbox.map_or(lone, |bb| bb.union(lone)));
|
||||
}
|
||||
MEASURED_SEGMENTS.set(MEASURED_SEGMENTS.get().saturating_add(sp.segment_count() as u64));
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
@@ -704,7 +722,7 @@ impl PathData {
|
||||
bbox = Some(bbox.map_or(seg, |bb| bb.union(seg)));
|
||||
}
|
||||
}
|
||||
Some(bbox.unwrap_or_default())
|
||||
bbox
|
||||
}
|
||||
/// Bounds including control handles (used for quick culling).
|
||||
pub fn control_bounds(&self) -> Option<Rect> {
|
||||
@@ -873,7 +891,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `bounds` walks the anchors in place: bit for bit what the kurbo path it stands for gives,
|
||||
/// for lines, curves, open and closed subpaths, lone anchors and empty subpaths.
|
||||
/// joined with the point of each lone anchor, for lines, curves, open and closed subpaths, lone
|
||||
/// anchors and empty subpaths.
|
||||
#[test]
|
||||
fn bounds_match_the_bezpath_bit_for_bit() {
|
||||
use proptest::prelude::*;
|
||||
@@ -881,11 +900,10 @@ mod tests {
|
||||
if pd.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if pd.anchor_count() == 1 {
|
||||
let a = pd.subpaths.iter().find_map(|s| s.anchors.first())?;
|
||||
return Some(Rect::from_points(a.p, a.p));
|
||||
}
|
||||
Some(curve_bounds(&pd.to_bezpath()))
|
||||
let bp = pd.to_bezpath();
|
||||
let segments = bp.segments().next().is_some().then(|| curve_bounds(&bp));
|
||||
let lone = pd.subpaths.iter().filter(|s| s.segment_count() == 0).filter_map(|s| s.anchors.first()).map(|a| Rect::from_points(a.p, a.p));
|
||||
lone.chain(segments).reduce(|bb, r| bb.union(r))
|
||||
}
|
||||
let bits = |r: Option<Rect>| r.map(|r| [r.x0, r.y0, r.x1, r.y1].map(f64::to_bits));
|
||||
let coord = || prop_oneof![(-1e3f64..1e3), Just(0.0), Just(1e-300), Just(-7.25)];
|
||||
@@ -899,10 +917,23 @@ mod tests {
|
||||
proptest!(ProptestConfig::with_cases(2000), |(pd in path)| {
|
||||
prop_assert_eq!(bits(pd.bounds()), bits(reference(&pd)));
|
||||
});
|
||||
// Two lone anchors: no segment, as the path has none.
|
||||
// Two lone anchors: the path has no segment, and the box spans the two points.
|
||||
let lone = PathData::new(vec![SubPath::polyline(&[Point::new(5.0, 5.0)], false), SubPath::polyline(&[Point::new(9.0, 1.0)], true)]);
|
||||
assert_eq!(lone.bounds(), Some(Rect::ZERO));
|
||||
assert_eq!(lone.bounds(), Some(Rect::new(5.0, 1.0, 9.0, 5.0)));
|
||||
assert_eq!(bits(lone.bounds()), bits(reference(&lone)));
|
||||
// A lone anchor beside a segment widens the segment's box to reach it.
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(4.0, 2.0)], false);
|
||||
let beside = PathData::new(vec![line.clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], false)]);
|
||||
let segment_only = PathData::single(line).bounds().unwrap_or_default();
|
||||
let both = beside.bounds().unwrap_or_default();
|
||||
assert!(both.x1 >= 20.0 && both.y0 <= -3.0, "{both:?} leaves out the lone anchor at (20, -3)");
|
||||
assert_eq!(both.union(segment_only), both, "{both:?} leaves out part of the segment's box {segment_only:?}");
|
||||
// What a stroke draws leaves out the open lone anchor, and a closed one without dots.
|
||||
assert_eq!(beside.drawn_bounds(true), Some(segment_only), "an open lone anchor draws nothing");
|
||||
let dot = PathData::new(vec![beside.subpaths[0].clone(), SubPath::polyline(&[Point::new(20.0, -3.0)], true)]);
|
||||
assert_eq!(dot.drawn_bounds(true), dot.bounds(), "a closed lone anchor draws a dot");
|
||||
assert_eq!(dot.drawn_bounds(false), Some(segment_only), "without dots, a closed lone anchor draws nothing");
|
||||
assert_eq!(lone.drawn_bounds(false), None, "lone anchors alone draw nothing");
|
||||
// A NaN anchor differs from itself: kurbo closes such a subpath with a line of its own.
|
||||
let nan = Point::new(f64::NAN, 1.0);
|
||||
let closed = |pts: &[Point]| SubPath::polyline(pts, true);
|
||||
|
||||
Reference in new issue
Block a user