Clean Up: remove hairline slivers thinner than a set width

Object > Path > Clean Up gets a Hairline Slivers option, off by default,
with a Sliver Width (0.001 to 3 pt, 0.03 mm by default). It removes
closed paths and compound paths with a visible fill, no visible stroke
and no effect when no circle that wide fits anywhere inside their fill:
shapes that
look like single lines in Outline view but have almost no area.
Select > Object > Hairline Slivers... selects the objects Clean Up would
remove, only inside the isolated group while one is isolated.

- vectorcraft-pathops: thinner_than measures the largest circle that
  fits in a fill. Bounds, the area against the outline length, and the
  width of the convex hull settle most shapes; the rest go through a
  cell search on the path's edges and then on the resolved outline.
  thinner_than_within takes the search's work from a budget, and one
  budget covers a whole document, so a run over thousands of shapes
  ends in bounded time.
- Shapes too complex to measure, and shapes still unmeasured when the
  budget runs out, are kept, and the reply's warning counts them.
- A compound path is measured as one fill. Hidden, locked and template
  objects, art on locked artboards, guides, the clipping paths of groups
  and layers, and the members of live and generated art are left alone.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-22 05:17:47 -08:00
1 parent db9acab4da
commit 3de7547b2a
12 files changed
+1099 -10

No files matched your search

+156 -6
View File
@@ -8,7 +8,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject};
use vectorcraft_geom::{FillRule, PathData, SubPath};
use vectorcraft_pathops as po;
use vectorcraft_pathops::{BoolOp, PathfinderOp};
@@ -190,7 +190,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clean Up…",
["Object", "Path"],
None,
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}",
"{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}",
has_doc,
clean_up
),
@@ -1662,12 +1662,150 @@ fn is_painted(a: &Appearance) -> bool {
})
}
/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value.
pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4;
/// The widths Hairline Slivers takes, in points.
pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive<f64> = 0.001..=3.0;
/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string
/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`].
pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result<f64> {
let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH);
if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) {
let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end());
return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt")));
}
Ok(w)
}
/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths
/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke),
/// whose fill no circle `width` across fits inside? A compound path is measured as one fill.
/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]).
/// A hidden member of a compound path is measured too, since the compound path paints it.
fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option<bool> {
// A shape with no fill that paints is left to Unpainted Objects.
if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) {
return Some(false);
}
let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind {
NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule),
NodeKind::Compound { children, rule } => {
let mut all = vec![];
for c in children {
let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) };
all.extend(path.subpaths.iter());
}
(all, *rule)
}
_ => return Some(false),
};
// Paths of one anchor are stray points, and open paths are lines.
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) {
return Some(false);
}
po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget)
}
/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an
/// effect on the object or on one of its fills and strokes?
fn draws_beyond_its_fill(a: &Appearance) -> bool {
a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty())
}
/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a
/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping
/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers
/// leaves its members alone.
fn holds_generated_art(n: &Node) -> bool {
let e = n.extras();
vectorcraft_tools::builder::is_live_paint(n)
|| e.type_outlines
|| e.clip_pieces
|| e.graph.is_some()
|| e.shaper.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.trace.is_some()
|| e.objects_on_path.is_some()
|| e.live_paint_gaps.is_some()
|| e.compound_shape
}
/// The objects Hairline Slivers finds in `d` for `width`.
pub(crate) struct Slivers {
pub ids: Vec<NodeId>,
/// Closed paths and compound paths whose fill couldn't be measured, which are left as they are.
pub unmeasured: Vec<NodeId>,
}
/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any.
pub(crate) fn unmeasured_warning(count: usize) -> Option<String> {
(count > 0).then(|| {
format!(
"Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are"
)
})
}
/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not
/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and
/// groups of the whole document. A compound path counts as one object. The clipping paths of groups
/// and layers (and all of a clipping group used as one), the members of live and generated art, and
/// the members of groups and layers whose own stroke or effect paints them are left out.
pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers {
struct Walk<'a> {
width: f64,
locks: LockedArtboards<'a>,
within: &'a dyn Fn(NodeId) -> bool,
// One budget for the whole document, so that thousands of shapes that need a search take
// a bounded time; the shapes after it runs out count as unmeasured.
budget: po::ThicknessBudget,
out: Vec<(NodeId, Option<bool>)>,
}
fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) {
if !n.visible || n.locked || n.is_template() || clip_path {
return;
}
match &n.kind {
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) {
return;
}
let clips = n.clips();
for (i, c) in children.iter().enumerate() {
visit(c, clips && i == 0, w);
}
}
// Art on a locked artboard, or outside `within`, is left out before it is measured.
NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => {
match is_hairline_sliver(n, w.width, &mut w.budget) {
Some(false) => {}
found => w.out.push((n.id, found)),
}
}
_ => {}
}
}
let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] };
for l in &d.layers {
visit(l, false, &mut w);
}
let mut found = w.out;
let editable = d.editable();
found.retain(|(id, _)| editable(*id));
let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some());
Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() }
}
fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.path.cleanUp";
let stray = switch_or(p, "strayPoints", true, C)?;
let unpainted = switch_or(p, "unpaintedObjects", true, C)?;
let empty_text = switch_or(p, "emptyTextPaths", true, C)?;
let found = {
let slivers = switch_or(p, "hairlineSlivers", false, C)?;
let width = sliver_width(p, "sliverWidth", C)?;
let (found, warning) = {
let d = &s.doc()?.doc;
let mut v = vec![];
fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec<NodeId>, opts: (bool, bool, bool)) {
@@ -1709,10 +1847,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
let editable = d.editable();
v.retain(|id| editable(*id));
v
let mut warning = None;
if slivers {
let found = hairline_slivers(d, width, &|_| true);
let listed: BTreeSet<NodeId> = v.iter().copied().collect();
// A shape another option removes isn't left as it is.
warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count());
v.extend(found.ids.into_iter().filter(|id| !listed.contains(id)));
}
(v, warning)
};
let reply = |removed: usize| match &warning {
Some(w) => json!({ "removed": removed, "warning": w }),
None => json!({ "removed": removed }),
};
if found.is_empty() {
return Ok(json!({ "removed": 0 }));
return Ok(reply(0));
}
s.edit("Clean Up", |d, _| {
let mut gone = Beside::replacing(d, &found);
@@ -1723,7 +1873,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result<Value> {
}
gone.finish(d)
})?;
Ok(json!({ "removed": found.len() }))
Ok(reply(found.len()))
}
// ---------- Divide Objects Below ----------
@@ -529,6 +529,7 @@ pub(super) const ALLOWED: &[&str] = &[
"select.object.brushStrokes",
"select.object.clippingMasks",
"select.object.directionHandles",
"select.object.hairlineSlivers",
"select.object.notAlignedToPixelGrid",
"select.object.pointText",
"select.object.slices",
+28
View File
@@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning};
use super::wand::{fill_of, stroke_of};
use super::{
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
@@ -196,6 +197,15 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| p.anchor_count() == 1))),
cmd!(
"select.object.hairlineSlivers",
"Hairline Slivers…",
["Select", "Object"],
None,
"{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}",
has_doc,
select_hairline_slivers
),
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
.path_data()
.is_some_and(|p| !p.is_closed()))),
@@ -1423,6 +1433,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
}
/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes
/// ([`hairline_slivers`]), inside the isolated group while one is isolated.
fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "select.object.hairlineSlivers";
let width = sliver_width(p, "width", C)?;
let st = s.doc()?;
let (d, iso) = (&st.doc, st.isolation);
let locks = d.locked_artboards();
let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id));
let warning = unmeasured_warning(found.unmeasured.len());
s.select(|_, sel| sel.set(found.ids))?;
let count = s.doc()?.selection.objects.len();
Ok(match warning {
Some(w) => json!({ "count": count, "warning": w }),
None => json!({ "count": count }),
})
}
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
/// does not look at the paths inside it.
+1 -1
View File
@@ -32,7 +32,7 @@ pub use cmd::distortcmds::{perspective_click, width_point_pair};
pub use cmd::flare::flare_settings;
pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject};
pub use cmd::params::{check_keys, check_params};
pub use cmd::pathops::auto_simplify_level;
pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level};
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step};
pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE;
+308
View File
@@ -1066,6 +1066,314 @@ fn clean_up_removes_junk() {
assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none());
}
/// A path drawn by `d`, filled black with no stroke.
fn filled(s: &mut Session, d: &str) -> NodeId {
let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap());
fill_only(s, id);
id
}
fn fill_only(s: &mut Session, id: NodeId) {
s.edit("t", |d, _| {
d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into();
Ok(())
})
.unwrap();
}
/// Hairline Slivers' test art: (the slivers, the shapes with a width).
fn sliver_art(s: &mut Session) -> (Vec<NodeId>, Vec<NodeId>) {
// A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide
// and tall. A long one across the page. A compound path of two slivers.
let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z");
let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z");
let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z");
let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, two);
// Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it
// draws a line), an open path, and a compound path of a sliver and a square.
let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z");
let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap());
fill_only(s, dot);
let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z");
s.edit("t", |d, _| {
d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into();
Ok(())
})
.unwrap();
let open = filled(s, "M500 10 L540 40 L500.001 10.0015");
let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z");
let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z");
s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap();
let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
fill_only(s, mixed);
s.execute("select.none", &json!({})).unwrap();
(vec![triangle, long, two], vec![strip, dot, stroked, open, mixed])
}
#[test]
fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() {
let mut s = session();
let (slivers, kept) = sliver_art(&mut s);
// Off by default.
assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0);
// A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is
// at 0 % opacity paints nothing either.
let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z");
let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z");
s.edit("t", |d, _| {
d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0);
if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() {
f.opacity = 0.0;
}
d.node_mut(clear).unwrap().appearance = a.into();
Ok(())
})
.unwrap();
let kept = [kept, vec![unpainted, clear]].concat();
let undo = s.doc().unwrap().history.undo.len();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left");
for (k, id) in kept.iter().enumerate() {
assert!(d.node(*id).is_some(), "shape {k} with a width went");
}
assert_eq!(r["removed"], slivers.len());
// One undo step brings every sliver back.
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some()));
// A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot.
let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"});
assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1);
assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some());
}
/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or
/// locked slivers.
#[test]
fn select_hairline_slivers_selects_what_clean_up_removes() {
let mut s = session();
let (slivers, _) = sliver_art(&mut s);
let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z");
let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z");
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
d.node_mut(locked).unwrap().locked = true;
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], slivers.len());
let mut selected: Vec<NodeId> = s.doc().unwrap().selection.objects.to_vec();
selected.sort_unstable();
let mut want = slivers.clone();
want.sort_unstable();
assert_eq!(selected, want);
// Inside an isolated group, only the slivers in it are selected.
let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z");
let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z");
s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
// A sliver in a group is selected as Clean Up finds it.
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1);
assert!(s.doc().unwrap().selection.objects.contains(&inner));
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1);
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]);
s.execute("object.exitIsolation", &json!({})).unwrap();
// A template layer that was unlocked afterward.
let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z");
s.edit("t", |d, _| {
let n = d.node_mut(template).unwrap();
if let NodeKind::Layer { template, .. } = &mut n.kind {
*template = true;
}
n.locked = false;
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(template).unwrap().is_template());
s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert!(!s.doc().unwrap().selection.objects.contains(&traced));
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some());
}
/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint
/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's
/// clipping path; Clean Up's other options keep the layer's clipping path too.
#[test]
fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() {
let mut s = session();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.execute("select.set", &json!({"ids": [rough.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap();
let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z");
let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z");
s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap();
s.execute("livePaint.make", &json!({})).unwrap();
// A group's own 5 pt stroke draws along its member.
let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [member.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into();
Ok(())
})
.unwrap();
// A thin part of type's glyph outlines.
let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z");
s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap();
let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(outlines).unwrap().extras_mut().type_outlines = true;
Ok(())
})
.unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
// A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects
// removes the clipping path.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z");
let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z");
let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z");
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went");
// A clip group whose clipping path is a sliver.
let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z");
let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
// A guide drawn as a sliver, and a sliver with an effect on its stroke.
let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z");
let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind {
*guide = true;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(mask).is_some(), "the clip group's clipping path went");
assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went");
// A layer clipped by a group (as an opened file can have it): its sliver member clips too.
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z");
let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z");
s.execute("select.set", &json!({"ids": [bare.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind {
*clip = true;
let i = children.iter().position(|c| c.id == g).unwrap();
let c = children.remove(i);
children.insert(0, c);
}
Ok(())
})
.unwrap();
assert!(s.doc().unwrap().doc.node(layer).unwrap().clips());
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
s.execute("object.path.cleanUp", &only).unwrap();
assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went");
}
/// A sliver on a locked artboard is left alone.
#[test]
fn hairline_slivers_leave_art_on_a_locked_artboard_alone() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
s.edit("t", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0);
assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0);
assert!(s.doc().unwrap().doc.node(sliver).is_some());
}
/// A shape too complex to measure is kept, and both commands say how many there were.
#[test]
fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() {
let mut s = session();
let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z");
// A closed zigzag of more anchors than one shape is measured with.
let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1;
let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect();
let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z");
s.edit("t", |d, _| {
if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind {
*path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true));
}
Ok(())
})
.unwrap();
let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap();
assert_eq!(r["count"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true});
let r = s.execute("object.path.cleanUp", &only).unwrap();
assert_eq!(r["removed"], 1);
assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}");
let d = &s.doc().unwrap().doc;
assert!(d.node(sliver).is_none() && d.node(huge).is_some());
}
/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the
/// document, the selection and the undo history stay as they were.
#[test]
fn hairline_slivers_refuse_a_width_out_of_range() {
let mut s = session();
sliver_art(&mut s);
let state = |s: &Session| {
let st = s.doc().unwrap();
(st.doc.clone(), st.selection.objects.clone(), st.history.undo.len())
};
let before = state(&s);
for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] {
for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] {
let mut p = serde_json::Map::new();
p.insert(key.into(), w.clone());
if cmd == "object.path.cleanUp" {
p.insert("hairlineSlivers".into(), json!(true));
}
let r = s.execute(cmd, &Value::Object(p));
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}");
assert!(state(&s) == before, "{cmd} {w} changed the document");
}
}
// Both ends of the range are taken.
for w in [json!(0.001), json!(3), json!("3 pt")] {
assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}");
let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w});
assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}");
}
}
/// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an
/// error naming the param, and leave the document, the selection and the undo history as they were.
/// Null keeps a param's default, and a distance still takes a string with a unit.
+1 -1
View File
@@ -21,7 +21,7 @@ thread_local! {
/// The contour passes made over an arrangement on this thread, each of which walks all of it.
pub(crate) static CONTOUR_PASSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The sweeps [`normalize_bez`] made on this thread.
static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The input curves [`exact_merge`] tested on this thread.
static EXACT_MERGE_CURVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
+2
View File
@@ -15,6 +15,7 @@ mod offset;
mod pathfinder;
mod planar;
mod sweep_axis;
mod thickness;
mod trap;
pub use boolean::{
@@ -35,6 +36,7 @@ pub use planar::{
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
};
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
/// Errors from fallible operations.
+557
View File
@@ -0,0 +1,557 @@
//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its
//! fill (Clean Up's and Select › Object's Hairline Slivers).
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _};
use vectorcraft_geom::{FillRule, PathData};
use crate::boolean::{fill_bezpath, normalize_bez};
/// Most line pieces the outline of one shape is measured with.
pub const MAX_THICKNESS_PIECES: usize = 100_000;
/// Most cells one search for a wide enough spot looks at.
const MAX_CELLS: usize = 500_000;
/// Most distances from a point to a piece of outline one search measures.
const MAX_WORK: usize = 50_000_000;
/// Most distances from a point to a piece of outline the shapes of one document are measured
/// with, all together ([`ThicknessBudget::document`]).
pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000;
/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves.
const FINE_PARTS: f64 = 32.0;
/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`.
const ROUGH_PARTS: f64 = 8.0;
/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than
/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is.
/// A shape within a small fraction of `width` of the limit is taken as thick enough.
///
/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't
/// finite, the fill can't be resolved into outlines, or measuring it would take more than
/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long.
pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option<bool> {
thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK))
}
/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a
/// point to a piece of outline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ThicknessBudget(usize);
impl ThicknessBudget {
pub fn new(work: usize) -> Self {
Self(work)
}
/// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`].
pub fn document() -> Self {
Self(MAX_DOCUMENT_THICKNESS_WORK)
}
/// The work left.
pub fn left(&self) -> usize {
self.0
}
}
/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs
/// more than is left. The quick checks take nothing from it, so they still settle shapes once it
/// runs out.
pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option<bool> {
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
if !(width.is_finite() && width > 0.0)
|| !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out))
{
return None;
}
// Every segment is at least one piece of outline, so a path of more anchors is too long to
// measure before its outline is built.
if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::<usize>() > MAX_THICKNESS_PIECES {
return None;
}
let mut bp = fill_bezpath(path);
if bp.elements().is_empty() {
return Some(true);
}
// Measured from the corner of its bounds, so that a shape far from the origin measures as it
// does near it.
let corner = bp.bounding_box().origin();
bp.apply_affine(Affine::translate(-corner.to_vec2()));
let b = bp.bounding_box();
let (r, fine) = (width / 2.0, width / FINE_PARTS);
// A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the
// width go on to that measure, which keeps them.
if b.width().min(b.height()) < width - 2.0 * fine {
return Some(true);
}
// Every point of a fill lies within the widest circle's radius r of its outline, and the points
// within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds
// a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around
// any point is measured so: the areas of several subpaths add up to more than their fill where
// they overlap, a path that runs around a spot twice counts its area there twice, and an
// even-odd fill of a path that runs around twice is empty.
if path.subpaths.len() == 1
&& rule == FillRule::NonZero
&& winds_at_most_once(&bp)
&& bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r
{
return Some(false);
}
// The circle lies between any two parallel lines that hold the path's points and handles too,
// which settles a long sliver lying on a slant.
if hull_width(&bp) < width - 2.0 * fine {
return Some(true);
}
// A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's
// outline, so a spot this far from every edge (and from the rough pieces' error) is far enough.
let rough = width / ROUGH_PARTS;
let mut edges = vec![];
if !flatten_into(&bp, rough, &mut edges) {
return None;
}
match search(&edges, b, rule, r + rough, rough, budget) {
Search::Found => return Some(false),
// Resolving the outlines takes time of its own, so it isn't started when what is left of
// the budget cut the rough look short. The rough look can run out where the resolved
// outline is much shorter, so one that ran out of its own share goes on.
Search::TooLong if budget.0 < MAX_WORK => return None,
_ => {}
}
// The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the
// fill are no outline of it. A spot within the fine pieces' error of the radius counts as one.
let contours = normalize_bez(&bp, rule).ok()?;
edges.clear();
for c in contours.contours() {
if !flatten_into(&c.path, fine, &mut edges) {
return None;
}
}
if edges.is_empty() {
return Some(true);
}
match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) {
Search::Found | Search::Unsure => Some(false),
Search::Absent => Some(true),
Search::TooLong => None,
}
}
/// The points and handles of `bp`, in order.
fn control_points(bp: &BezPath) -> Vec<Point> {
bp.elements()
.iter()
.flat_map(|el| match *el {
PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p],
PathEl::QuadTo(a, p) => vec![a, p],
PathEl::CurveTo(a, b, p) => vec![a, b, p],
PathEl::ClosePath => vec![],
})
.collect()
}
/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point
/// that a curve winds around twice crosses it at least four times, so such a curve turns through
/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon
/// that turns through less than 4π winds at most once.
fn winds_at_most_once(bp: &BezPath) -> bool {
let mut pts = control_points(bp);
pts.dedup();
while pts.len() > 1 && pts.first() == pts.last() {
pts.pop();
}
if pts.len() < 3 {
return true;
}
let turned: f64 = pts
.iter()
.zip(pts.iter().cycle().skip(1))
.zip(pts.iter().cycle().skip(2))
.map(|((&a, &b), &c)| {
let (u, v) = (b - a, c - b);
u.cross(v).atan2(u.dot(v)).abs()
})
.sum();
turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9)
}
/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded.
const MAX_HULL: usize = 512;
/// The least distance between two parallel lines that hold every point and handle of `bp` (the
/// width of their convex hull, which holds the curves too).
fn hull_width(bp: &BezPath) -> f64 {
let mut pts = control_points(bp);
pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
pts.dedup();
if pts.len() < 3 {
return 0.0;
}
// Andrew's monotone chain: the lower hull, then the upper.
let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o);
let mut hull: Vec<Point> = Vec::with_capacity(pts.len() + 1);
for pass in [false, true] {
let floor = hull.len();
let ordered: Box<dyn Iterator<Item = &Point>> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) };
for &p in ordered {
while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) {
hull.pop();
}
hull.push(p);
}
hull.pop();
}
if hull.len() < 3 {
return 0.0;
}
if hull.len() > MAX_HULL {
return f64::INFINITY;
}
// For each side, the farthest corner from its line; the least of those is the width.
let mut least = f64::INFINITY;
for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) {
let side = b - a;
let len = side.hypot();
if len > 0.0 {
let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max);
least = least.min(far);
}
}
least
}
/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes
/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`]
/// to keep within `tolerance`.
fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool {
let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| {
if from != to {
edges.push((from, to));
}
};
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
for el in bp.iter() {
if edges.len() > MAX_THICKNESS_PIECES {
return false;
}
match el {
// An outline that doesn't end where it starts is closed with a line, as a fill paints it.
PathEl::MoveTo(p) => {
push(last, start, edges);
(start, last) = (p, p);
}
PathEl::ClosePath => {
push(last, start, edges);
last = start;
}
PathEl::LineTo(p) => {
push(last, p, edges);
last = p;
}
PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => {
let length = match el {
PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p),
_ => last.distance(a) + a.distance(p),
};
if length / most > tolerance {
return false;
}
let mut from = last;
vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| {
if let PathEl::LineTo(to) = piece {
push(from, to, edges);
from = to;
}
});
last = p;
}
}
}
push(last, start, edges);
edges.len() <= MAX_THICKNESS_PIECES
}
/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under
/// `rule`.
fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 {
let mut winding = 0i32;
let mut nearest = f64::INFINITY;
for &(a, b) in edges {
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
winding += if b.y > a.y { 1 } else { -1 };
}
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 };
nearest = nearest.min((p - (a + ab * t)).hypot2());
}
let inside = match rule {
FillRule::NonZero => winding != 0,
FillRule::EvenOdd => winding % 2 != 0,
};
let d = nearest.sqrt();
if inside { d } else { -d }
}
/// A square cell of the search: its center, half its side, the signed distance from its center to
/// the outline, and the most that distance can be anywhere in it.
struct Cell {
c: Point,
h: f64,
d: f64,
most: f64,
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.most.total_cmp(&other.most) == Ordering::Equal
}
}
impl Eq for Cell {}
impl PartialOrd for Cell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Cell {
fn cmp(&self, other: &Self) -> Ordering {
self.most.total_cmp(&other.most)
}
}
/// What [`search`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Search {
/// A point at least the distance asked for from the outline.
Found,
/// No such point.
Absent,
/// None found, but cells smaller than the finest size could still hold one.
Unsure,
/// The search needed more cells or distances than it may take.
TooLong,
}
/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal`
/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest
/// point is split first, until a cell's center is `goal` away or no cell could be. The distance
/// changes no faster than the point moves, so a cell holds no point farther than its center's
/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The
/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`.
fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search {
let mut work = 0usize;
let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work);
budget.0 = budget.0.saturating_sub(work);
found
}
/// [`search`], measuring no more than `limit` distances and counting them in `work`.
fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search {
let side = bounds.width().min(bounds.height());
if side.is_nan() || side <= 0.0 {
return Search::Absent;
}
let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil());
if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 {
return Search::TooLong;
}
let cell = |c: Point, h: f64, work: &mut usize| {
*work += edges.len();
let d = signed_distance(edges, rule, c);
Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 }
};
let mut heap = BinaryHeap::new();
let h = side / 2.0;
for i in 0..cols as usize {
for j in 0..rows as usize {
heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work));
}
}
let (mut made, mut unsure) = (heap.len(), false);
while let Some(next) = heap.pop() {
if next.d >= goal {
return Search::Found;
}
if next.most < goal {
break;
}
if next.h < finest / 2.0 {
unsure = true;
continue;
}
if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit {
return Search::TooLong;
}
let h = next.h / 2.0;
for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] {
let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work);
// A cell that can't hold a point `goal` away is left out.
if part.most >= goal {
heap.push(part);
}
}
made += 4;
}
if unsure { Search::Unsure } else { Search::Absent }
}
#[cfg(test)]
mod tests {
use vectorcraft_geom::{Anchor, SubPath};
use super::*;
fn polygon(points: &[(f64, f64)]) -> SubPath {
SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)
}
fn one(points: &[(f64, f64)]) -> PathData {
PathData::single(polygon(points))
}
fn thin(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(true)
}
fn thick(p: &PathData, rule: FillRule, width: f64) -> bool {
thinner_than(p, rule, width) == Some(false)
}
#[test]
fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
assert!(thin(&sliver, FillRule::NonZero, 0.085));
// Long and on a slant at the narrowest width, and far from the origin.
assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001));
let (x, y) = (1_000_000.0, 1_000_000.0);
assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001));
}
#[test]
fn a_bent_sliver_is_found_by_measuring_inside_it() {
// Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are
// wide, and only the measure inside finds it thin.
let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
assert!(thin(&v, FillRule::NonZero, 0.085));
}
#[test]
fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() {
// A diagonal strip 100 pt long.
let strip = |w: f64| {
let (dx, dy) = (0.6 * w, -0.8 * w);
one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)])
};
assert!(thick(&strip(0.2), FillRule::NonZero, 0.085));
assert!(thick(&strip(0.2), FillRule::NonZero, 0.18));
assert!(thin(&strip(0.05), FillRule::NonZero, 0.085));
assert!(thin(&strip(0.2), FillRule::NonZero, 0.24));
}
#[test]
fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() {
// Its inscribed circle is 2 across, centered at (1, 1).
let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]);
assert!(thick(&t, FillRule::NonZero, 1.95));
assert!(thin(&t, FillRule::NonZero, 2.3));
}
#[test]
fn a_tiny_round_dot_is_kept() {
let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3));
assert!(thick(&dot, FillRule::NonZero, 0.085));
assert!(thick(&dot, FillRule::NonZero, 0.29));
assert!(thin(&dot, FillRule::NonZero, 0.4));
}
#[test]
fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() {
let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]);
let mut hole = square(1.01, 98.99);
hole.reverse();
assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085));
// Even-odd: an inner square running the same way still cuts a hole.
assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085));
// Nonzero: it doesn't, and the edges inside the fill are no outline of it.
assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085));
}
#[test]
fn overlapping_strips_are_measured_by_their_union() {
// Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of
// each that run inside the other are no more than 0.1 pt apart.
let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]);
let strips = PathData::new(vec![strip(0.0), strip(0.1)]);
assert!(thick(&strips, FillRule::NonZero, 0.15));
assert!(thin(&strips, FillRule::NonZero, 0.35));
}
#[test]
fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() {
assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085));
assert!(thin(&PathData::default(), FillRule::NonZero, 0.085));
}
/// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled
/// without resolving their outlines, so a document of thousands of them is measured quickly.
#[test]
fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() {
let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get());
for k in 0..2000 {
let x = f64::from(k) * 12.0;
assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085));
assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085));
// Long slivers on a slant are settled by the width of their hull.
assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085));
}
assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before);
}
/// The area measure is used only for an outline that runs around once: one that runs around
/// twice counts its area twice.
#[test]
fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() {
let square = |n: usize| {
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
for _ in 0..n {
for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] {
bp.line_to(p);
}
}
bp.close_path();
bp
};
assert!(winds_at_most_once(&square(1)));
assert!(!winds_at_most_once(&square(2)));
// Measured inside instead, a square run around twice is still as thick as one.
let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
assert!(thick(&twice, FillRule::NonZero, 0.085));
}
/// Shapes that need the search share one budget: once it is spent they can't be measured, and
/// the quick checks still settle the rest.
#[test]
fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() {
let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]);
let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let mut budget = ThicknessBudget::document();
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true));
assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK);
let mut spent = ThicknessBudget::new(0);
assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None);
assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false));
}
#[test]
fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() {
let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]);
for w in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}");
}
let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]);
assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None);
}
}
+14 -1
View File
@@ -21,7 +21,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter");
let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk);
let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k));
form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit());
// Hairline Slivers' widths show in the stroke unit (Preferences › Units › Stroke), or in
// points when that unit's field rounds the narrowest width to 0.
let unit = match command.as_str() {
"object.path.cleanUp" | "select.object.hairlineSlivers" => {
let stroke = app.session.stroke_unit();
if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke }
}
_ => app.session.general_unit(),
};
form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, unit);
if command == crate::addons::packaging::SET_ROLE_SWATCH {
crate::addons::packaging::follow_role(app, d);
}
@@ -154,6 +163,8 @@ fn lengths(command: &str) -> &'static [&'static str] {
crate::addons::cutting::BRIDGES => &["width"],
"object.textWrap.options" => &["offset"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"],
"object.path.cleanUp" => &["sliverWidth"],
"select.object.hairlineSlivers" => &["width"],
_ => &[],
}
}
@@ -168,6 +179,7 @@ pub(super) fn length_range(command: &str, key: &str) -> Option<std::ops::RangeIn
(crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE, "offset") => {
Some(0.0..=vectorcraft_engine::MAX_COORD)
}
("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE),
_ => None,
}
}
@@ -192,6 +204,7 @@ fn order(command: &str) -> &'static [&'static str] {
crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"],
crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"],
crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"],
"object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"],
_ => &[],
}
}
+12 -1
View File
@@ -260,7 +260,17 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
c("Divide Objects Below", "object.path.divideObjectsBelow"),
c("Split Into Grid…", "object.path.splitIntoGrid"),
Sep,
cp("Clean Up…", "object.path.cleanUp", json!({"strayPoints": true, "unpaintedObjects": true, "emptyTextPaths": true})),
cp(
"Clean Up…",
"object.path.cleanUp",
json!({
"strayPoints": true,
"unpaintedObjects": true,
"emptyTextPaths": true,
"hairlineSlivers": false,
"sliverWidth": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH
}),
),
],
),
sub("Shape", vec![c("Convert to Shape", "object.shape.convertToShape"), c("Expand Shape", "object.expandShape")]),
@@ -538,6 +548,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
c("Clipping Masks", "select.object.clippingMasks"),
c("Slices", "select.object.slices"),
c("Stray Points", "select.object.strayPoints"),
cp("Hairline Slivers…", "select.object.hairlineSlivers", json!({"width": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH})),
c("Open Paths", "select.object.openPaths"),
c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"),
Sep,
+18
View File
@@ -7204,6 +7204,24 @@ the dialog on those settings next time.
`"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit
(`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default.
`object.path.cleanUp` with `hairlineSlivers: true` also removes hairline slivers: closed paths and compound paths with
a visible fill, no visible stroke and no effect, so thin that no circle `sliverWidth` across fits inside their fill
(Unpainted Objects covers shapes with no paint). A compound path is measured as one fill, so a compound path with one
sliver member and one real shape stays. `sliverWidth` is a distance from 0.001 to 3 pt; it defaults to 0.03 mm,
VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop app the Clean Up dialog has a Hairline
Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round
0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean
Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command
takes hidden or locked objects, objects in template layers, art on locked artboards, guides, the clipping paths of
groups and layers, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape
that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is
every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were:
```json
{"name":"run_command","arguments":{"command":"object.path.cleanUp","params":{"strayPoints":false,"unpaintedObjects":false,"emptyTextPaths":false,"hairlineSlivers":true,"sliverWidth":"0.03 mm"}}}
{"name":"run_command","arguments":{"command":"select.object.hairlineSlivers","params":{"width":0.1}}}
```
## Smooth
`object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo
+1
View File
@@ -1675,6 +1675,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Geometry and effects:**
- **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged.
- Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635).
Clean Up has a Hairline Slivers option, VectorCraft's own and off by default: it removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle as wide as its Sliver Width (0.03 mm by default) fits inside their fill, and Select › Object › Hairline Slivers… selects them (`crates/engine/src/tests/pathops.rs`, `crates/pathops/src/thickness.rs` tests).
Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow.
Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests).
Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`).