From 80f96d11f9206d893ad141fd513ac47525ec76c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:46:10 -0800 Subject: [PATCH 1/2] Path Precision Tools: Add Inscribed Circle draws the largest circle inside a path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on its pole of inaccessibility. Part of #6966. - The outline is resolved under its fill rule into outer contours and holes, so overlapping subpaths count as the area they fill and holes bound the circle down to 1e-6 pt wide, the path operations' resolution. Square cells are searched best first, and the radius is measured from the center to the curves: within 0.02 pt of the largest, or a thousandth of the narrower side for a shape less than 10 pt across. - The circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside where it touches. - Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors that leave the document unchanged. The first cells are sized to the work limit. - The circles get the current paint, go on top of the current layer or the isolated group, and are one undo step. - Docs: docs/mcp.md, docs/target-app-parity.md, docs/ui-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/pathtools.rs | 6 +- .../src/cmd/addons/pathtools/bounding.rs | 2 +- .../src/cmd/addons/pathtools/inscribed.rs | 88 +++++++ .../cmd/addons/pathtools/inscribed/tests.rs | 203 +++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/pathops/src/addons/pathtools.rs | 7 +- .../pathops/src/addons/pathtools/inscribed.rs | 245 ++++++++++++++++++ .../src/addons/pathtools/inscribed/tests.rs | 140 ++++++++++ crates/ui-egui/src/addons/pathtools.rs | 3 +- docs/mcp.md | 18 ++ docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 13 files changed, 713 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/addons/pathtools/inscribed.rs create mode 100644 crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs create mode 100644 crates/pathops/src/addons/pathtools/inscribed.rs create mode 100644 crates/pathops/src/addons/pathtools/inscribed/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..89eaa755d7 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -158,6 +158,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. +- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 586dc9947e..2c14c3deba 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -4,8 +4,8 @@ //! ([`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`]), Smooth Bridge ([`bridge`]), Common Tangents -//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add -//! Bounding Circle ([`bounding`]). +//! ([`tangents`]), Tangent Circle ([`tangent_circle`]), Add Bounding Rectangle and Add +//! Bounding Circle ([`bounding`]) and Add Inscribed Circle ([`inscribed`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -14,6 +14,7 @@ mod bridge; mod corners; #[cfg(test)] mod effect_tests; +mod inscribed; mod shape; mod shared_edge; mod tangent_circle; @@ -190,6 +191,7 @@ pub fn specs() -> Vec { v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v.extend(bounding::specs()); + v.extend(inscribed::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs index 954a4f829a..b82b67832e 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec { /// Enabled with a selection that is not an object of a symbol instance's art, which /// [`selected_roots_to_transform`] refuses. -fn whole_objects(s: &Session) -> std::result::Result<(), String> { +pub(super) fn whole_objects(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; no_symbol_part(s) } diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..2e016f23a7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -0,0 +1,88 @@ +//! Add Inscribed Circle: the largest live circle inside each selected closed path or compound +//! path. The circle is the pathops crate's +//! ([`inscribed_circle`](vectorcraft_pathops::addons::pathtools::inscribed_circle)). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, FillRule, PathData}; +use vectorcraft_pathops::addons::pathtools::{self as pt, InscribedError}; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::{CommandSpec, bad, cmd}; +use super::bounding::whole_objects; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command. +pub(crate) const COMMAND: &str = "addon.pathtools.inscribedCircle"; +/// The undo step's name. +const LABEL: &str = "Add Inscribed Circle"; +/// How far a live circle's four curves reach past a true circle, as a share of its radius: at +/// most 0.0273%, about 20° from each axis. +const CIRCLE_BULGE: f64 = 3e-4; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.inscribedCircle", + "Add Inscribed Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and its radius is within 0.02 pt of the largest (for a shape at least 10 pt across; a smaller one is measured to a thousandth of its narrower side; a curve whose control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn that much smaller and stays inside where it touches. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 straight pieces once flattened or its search goes past its limit (\"object N is too complex to measure\") → {id: the first circle, ids}", + whole_objects, + inscribed_circle + )] +} + +/// The outline of path or compound path `id` and its fill rule; `None` for anything else, an open +/// path, or a compound path with an open member. +fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> { + let n = d.node(id)?; + let (paths, rule): (Vec<&PathData>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + _ => return None, + }; + let subpaths: Vec<_> = paths.iter().flat_map(|p| p.subpaths.iter()).filter(|sp| !sp.anchors.is_empty()).collect(); + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed) { + return None; + } + Some((PathData::new(subpaths.into_iter().cloned().collect()), rule)) +} + +fn inscribed_circle(s: &mut Session, _p: &Value) -> Result { + let roots = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let mut circles = vec![]; + for id in roots { + let value = id.0; + let Some((path, rule)) = outline(d, id) else { + return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path"))); + }; + let c = pt::inscribed_circle(&path, rule).map_err(|e| match e { + InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")), + InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")), + })?; + circles.push(c); + } + 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 c in &circles { + // Smaller by the curves' bulge, so the drawn circle stays inside where it touches. + let (r, at) = (c.radius / (1.0 + CIRCLE_BULGE), c.center); + let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) }; + 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); + Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::>() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..f19c8fd111 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,203 @@ +//! Add Inscribed Circle: the largest circle in a square, a concave shape and a ring compound path +//! under its fill rule, one circle per object as one undo step, the drawn circle inside where its +//! curves bulge, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, NodeId, NodeKind}; +use vectorcraft_geom::Point; + +use super::COMMAND; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).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 +} + +/// The center and radius of the live circle `id`. +fn circle(s: &Session, id: NodeId) -> (Point, f64) { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(live), .. } => match live.as_ref() { + LiveShape::Ellipse { w, h, xf, .. } => { + assert!((w - h).abs() < 1e-9, "a circle, not an ellipse"); + (*xf * Point::new(w / 2.0, h / 2.0), w / 2.0) + } + other => panic!("not a live ellipse: {other:?}"), + }, + other => panic!("not a live shape: {other:?}"), + } +} + +/// The smallest drawn radius for a largest circle of radius `largest`: smaller by the curves' +/// bulge, and by the search's 0.02 pt. +fn least(largest: f64) -> f64 { + largest / (1.0 + super::CIRCLE_BULGE) - 0.02 +} + +/// The command on the selection fails with a message holding `want`, and the document is as it was. +fn refused(s: &mut Session, want: &str) { + let (undo, objects) = (undo_len(s), object_count(s)); + let e = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + assert_eq!((undo_len(s), object_count(s)), (undo, objects)); +} + +/// The circle in a square sits at its center and touches its sides, gets the current paint, goes +/// on top of the layer and is selected; one undo removes it. +#[test] +fn a_square_gets_the_circle_that_touches_its_sides() { + let mut s = session(); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()); + let (undo, objects) = (undo_len(&s), object_count(&s)); + let out = s.execute(COMMAND, &json!({})).unwrap(); + let id = id_of(&out); + let (center, r) = circle(&s, id); + assert!((center - Point::new(150.0, 150.0)).hypot() < 0.02 && r <= 50.0 + 1e-6 && r > least(50.0), "{center:?} {r}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + let d = &s.doc().unwrap().doc; + let parent = d.parent_of(sq).unwrap(); + assert_eq!(d.parent_of(id), Some(parent)); + assert_eq!(d.node(parent).unwrap().children().unwrap().last().map(|n| n.id), Some(id), "on top of the layer"); + // The current paint, as the rectangle drawn before got it. + let (n, r) = (d.node(id).unwrap(), d.node(sq).unwrap()); + assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint())); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), objects); +} + +/// The circle in an L sits in its corner, inside the shape, where the box's center is outside. +#[test] +fn a_concave_shape_gets_the_circle_in_its_corner() { + let mut s = session(); + let anchors = [(0, 0), (100, 0), (100, 30), (30, 30), (30, 100), (0, 100)].map(|(x, y)| json!({"x": x, "y": y})); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(r <= largest + 1e-6 && r > least(largest), "{r}"); + assert!(center.x < 30.0 && center.y < 30.0, "{center:?}"); +} + +/// A compound path of two concentric circles: under even-odd the inner one is a hole, and the +/// circle lies in the ring beside it. Under nonzero it is a hole while the two circles turn +/// opposite ways, and with both turning the same way the circle fills the outer one. +#[test] +fn a_ring_compound_path_gets_a_circle_by_its_fill_rule() { + let mut s = session(); + let outer = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap()); + let inner = id_of(&s.execute("shape.ellipse", &json!({"x": 160, "y": 160, "width": 80, "height": 80})).unwrap()); + select(&mut s, &[outer, inner]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let ring = Point::new(200.0, 200.0); + let cases = [("evenOdd", false, 70.0, 30.0), ("nonZero", false, 70.0, 30.0), ("nonZero", true, 0.0, 100.0), ("evenOdd", true, 70.0, 30.0)]; + for (rule, same_way, around, largest) in cases { + select(&mut s, &[compound]); + let both = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::>(); + s.execute("path.reverse", &json!({"ids": both, "reversed": true})).unwrap(); + if !same_way { + s.execute("path.reverse", &json!({"ids": [both[1]], "reversed": false})).unwrap(); + } + s.execute("path.setFillRule", &json!({"rule": rule, "ids": [compound.0]})).unwrap(); + select(&mut s, &[compound]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let (center, r) = circle(&s, id); + assert!(r > least(largest) && r < largest + 0.0003 * 140.0, "{rule} {same_way}: {r}"); + assert!(((center - ring).hypot() - around).abs() < 0.1, "{rule} {same_way}: {center:?}"); + } +} + +/// Each selected path gets its own circle, all as one undo step; a path of a compound path +/// selected on its own gets a circle of its own outline. +#[test] +fn each_selected_path_gets_a_circle_in_one_step() { + let mut s = session(); + let a = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap()); + let b = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 40, "height": 80})).unwrap()); + select(&mut s, &[a, b]); + let undo = undo_len(&s); + let ids = ids_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(ids.len(), 2); + assert_eq!(undo_len(&s), undo + 1); + let centers: Vec = ids.iter().map(|id| circle(&s, *id).0).collect(); + assert!(centers.iter().any(|c| c.x < 40.0) && centers.iter().any(|c| c.x > 100.0), "{centers:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + select(&mut s, &[a, b]); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let member = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id; + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let r = circle(&s, id).1; + assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}"); +} + +/// The drawn circle stays inside a large square turned so that it touches the square's sides +/// where its curves bulge most past a true circle, about 20° from each axis. +#[test] +fn the_drawn_circle_stays_inside_where_its_curves_bulge() { + let mut s = session(); + let (center, half) = (Point::new(1200.0, 1200.0), 1000.0); + for degrees in [15.0_f64, 19.4, 25.0] { + let (sin, cos) = degrees.to_radians().sin_cos(); + let corner = |u: f64, v: f64| json!({"x": center.x + u * cos - v * sin, "y": center.y + u * sin + v * cos}); + let anchors = [(-half, -half), (half, -half), (half, half), (-half, half)].map(|(u, v)| corner(u, v)); + s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap(); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { + panic!("not a path"); + }; + for seg in path.to_bezpath().segments() { + for i in 0..=200 { + let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 200.0) - center; + let (u, v) = (p.x * cos + p.y * sin, -p.x * sin + p.y * cos); + assert!(u.abs().max(v.abs()) <= half, "{degrees}°: ({u}, {v}) is outside the square"); + } + } + } +} + +/// An open path, an object that is not a path or compound path, a path that fills no area and an +/// empty selection are errors, and nothing is drawn. +#[test] +fn open_paths_other_objects_and_no_selection_are_refused() { + let mut s = session(); + assert!(s.execute(COMMAND, &json!({})).is_err(), "nothing selected"); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap()); + select(&mut s, &[open]); + refused(&mut s, "is not a closed path or compound path"); + let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()); + select(&mut s, &[sq]); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + select(&mut s, &[group]); + refused(&mut s, "is not a closed path or compound path"); + // One refused object leaves the other selected objects without a circle too. + select(&mut s, &[group, open]); + refused(&mut s, "is not a closed path or compound path"); + let flat = [(0, 300), (100, 300), (50, 300)].map(|(x, y)| json!({"x": x, "y": y})); + let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap()); + select(&mut s, &[flat]); + refused(&mut s, "fills no area"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..fc152f8178 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -60,6 +60,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pathtools.erase", "addon.pathtools.expandDashes", "addon.pathtools.extend", + "addon.pathtools.inscribedCircle", "addon.pathtools.inspect", "addon.pathtools.mergeEdge", "addon.pathtools.removeKeepShape", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index d5fe994bed..58927fbb79 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -6,13 +6,15 @@ //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes //! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles //! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines -//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch -//! two or three shapes ([`tangent_circles`]). +//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]), the circles that touch +//! two or three shapes ([`tangent_circles`]) and the largest circle inside a shape +//! ([`inscribed_circle`]). mod bridge; mod crossings; mod dashes; mod extend; +mod inscribed; pub mod shapes; mod shared_edge; mod slide; @@ -33,6 +35,7 @@ pub use bridge::{ pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; +pub use inscribed::{INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_EDGES, inscribed_circle}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; diff --git a/crates/pathops/src/addons/pathtools/inscribed.rs b/crates/pathops/src/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..285132acba --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed.rs @@ -0,0 +1,245 @@ +//! Add Inscribed Circle: the largest circle inside a filled outline, the center of which is the +//! outline's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). +//! +//! The outline is first resolved under its fill rule into simple contours (outer contours and +//! holes, as [`crate::try_normalize`] resolves them, narrow ones kept), so overlapping and self-crossing subpaths count as the area they fill +//! and only real edges bound the circle. The contours are flattened, and square cells covering +//! their box are searched best first: a cell's center lies some distance inside the outline, and no +//! point of the cell lies more than half the cell's diagonal farther in, so a cell that cannot beat +//! the best center found by more than the precision is not split. The radius is then measured from +//! the center to the curves themselves. + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{ParamCurveNearest, Point, Rect, Shape}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{FillRule, PathData, PathEl}; + +use crate::boolean::{Tidy, fill_bezpath, normalize_bez}; + +#[cfg(test)] +mod tests; + +#[cfg(test)] +thread_local! { + /// The distances from a point to an edge that the last [`search`] on this thread measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How close to the largest circle's radius the search gets, in points, for outlines whose box is +/// at least 10 pt across; a smaller box gets a thousandth of its narrower side. +pub const INSCRIBED_PRECISION: f64 = 0.01; +/// Most straight edges the flattened outline may have. +pub const MAX_INSCRIBED_EDGES: usize = 1 << 18; +/// Most distances from a point to an edge that one search measures. +const MAX_WORK: usize = 1 << 27; +/// Most cells the box is first cut into. +const MAX_FIRST_CELLS: f64 = 4096.0; + +/// The largest circle inside an outline: its center and radius. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Inscribed { + pub center: Point, + pub radius: f64, +} + +/// Why [`inscribed_circle`] found no circle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum InscribedError { + /// The outline fills no area. + NoArea, + /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] edges, or the + /// search would measure more than its limit. + TooComplex, +} + +/// The largest circle inside the area that `path` fills under `rule`, within twice +/// [`INSCRIBED_PRECISION`] of the largest radius: the search's precision and the flattening, at +/// half of it. A curve whose control polygon is longer than 83,886 pt is flattened more coarsely +/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much. Holes and gaps +/// narrower than 1e-6 pt close up, as in the other path operations. Open subpaths count as closed, +/// as when they are filled. +pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result { + let filled = fill_bezpath(path); + let b = filled.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + let precision = INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0); + // Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance + // (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the + // sweep split are rebuilt from the input's own. + let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?; + let tidy = Tidy::keeping(precision, [&filled]); + let mut curves = kurbo::BezPath::new(); + for c in contours.contours() { + curves.extend(tidy.repair(&c.path)); + } + let b = curves.bounding_box(); + if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { + return Err(InscribedError::NoArea); + } + let edges = edges(&curves, precision / 2.0)?; + let center = search(&edges, b, precision, MAX_WORK)?; + // The circle touches the nearest curve, whatever the flattening moved. + let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + if !(radius.is_finite() && radius > 0.0) || !fill_contains(&curves, FillRule::NonZero, center) { + return Err(InscribedError::NoArea); + } + Ok(Inscribed { center, radius }) +} + +/// The straight edges of `curves` flattened to within `tolerance`, each subpath closed. +fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, InscribedError> { + let mut out = vec![]; + let (mut start, mut last) = (None, None); + let close = |out: &mut Vec<(Point, Point)>, start: Option, last: Option| { + if let (Some(a), Some(b)) = (last, start) + && a != b + { + out.push((a, b)); + } + }; + let mut over = false; + vectorcraft_geom::flatten(curves.iter(), tolerance, |el| { + if over { + return; + } + match el { + PathEl::MoveTo(p) => { + close(&mut out, start, last); + (start, last) = (Some(p), Some(p)); + } + PathEl::LineTo(p) => { + if let Some(a) = last { + out.push((a, p)); + } + last = Some(p); + } + PathEl::ClosePath => { + close(&mut out, start, last); + last = start; + } + _ => {} + } + over = out.len() > MAX_INSCRIBED_EDGES; + }); + close(&mut out, start, last); + if over || out.len() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } + Ok(out) +} + +/// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge, +/// negative outside. +fn inside(edges: &[(Point, Point)], p: Point) -> f64 { + let mut winding = 0; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y <= p.y) != (b.y <= p.y) { + let side = (b - a).cross(p - a); + if b.y > a.y && side > 0.0 { + winding += 1; + } else if b.y <= a.y && side < 0.0 { + winding -= 1; + } + } + nearest = nearest.min(distance_sq_to_segment(p, a, b)); + } + let d = nearest.sqrt(); + if winding != 0 { d } else { -d } +} + +fn distance_sq_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)).hypot2() +} + +/// A square cell of the search: its center, half its side, how far its center lies inside the +/// outline, and the most any of its points can. +#[derive(Clone, Copy)] +struct Cell { + center: Point, + half: f64, + inside: f64, + best: f64, +} + +impl Cell { + fn new(edges: &[(Point, Point)], center: Point, half: f64) -> Self { + let inside = inside(edges, center); + Self { center, half, inside, best: inside + half * std::f64::consts::SQRT_2 } + } +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.best.total_cmp(&other.best) + } +} + +/// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`, +/// measuring at most about `limit` distances from a point to an edge. +fn search(edges: &[(Point, Point)], b: Rect, precision: f64, limit: usize) -> Result { + // Square cells as wide as the box's narrower side, or wider when that would make more than + // `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work + // limit, so the first cells take at most about three quarters of it. + let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0); + let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first); + let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize); + let mut work = 0usize; + let measure = |work: &mut usize, center: Point, half: f64| { + *work = work.saturating_add(edges.len()); + #[cfg(test)] + MEASURED.with(|m| m.set(*work)); + Cell::new(edges, center, half) + }; + let mut best = measure(&mut work, b.center(), 0.0); + let mut cells = BinaryHeap::new(); + for row in 0..rows { + for col in 0..cols { + if work > limit { + return Err(InscribedError::TooComplex); + } + let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size); + cells.push(measure(&mut work, at, size / 2.0)); + } + } + while let Some(cell) = cells.pop() { + if cell.inside > best.inside { + best = cell; + } + if cell.best - best.inside <= precision { + break; + } + if work > limit { + return Err(InscribedError::TooComplex); + } + let h = cell.half / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + cells.push(measure(&mut work, cell.center + (dx, dy), h)); + } + } + if best.inside <= 0.0 { + return Err(InscribedError::NoArea); + } + Ok(best.center) +} diff --git a/crates/pathops/src/addons/pathtools/inscribed/tests.rs b/crates/pathops/src/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..50f2d103d3 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/inscribed/tests.rs @@ -0,0 +1,140 @@ +use kurbo::{Point, Rect}; +use vectorcraft_geom::hit::fill_contains; +use vectorcraft_geom::{Anchor, FillRule, PathData, SubPath, shapes}; + +use super::*; + +fn polygon(pts: &[(f64, f64)]) -> PathData { + PathData::new(vec![SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)]) +} + +fn circle(x: f64, y: f64, r: f64) -> SubPath { + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)).subpaths.remove(0) +} + +/// Points around the circle `c`, a little inside its edge. +fn rim(c: Inscribed) -> impl Iterator { + (0..360).map(move |i| { + let a = (i as f64).to_radians(); + c.center + kurbo::Vec2::new(a.cos(), a.sin()) * (c.radius - 1e-6) + }) +} + +/// The circle lies in the filled area and is within twice the precision of `largest`, which may +/// be `slack` too small: a circle of four curves bulges up to 0.03% past a true circle. +fn holds_within(path: &PathData, rule: FillRule, c: Inscribed, largest: f64, slack: f64) { + let bp = path.to_bezpath(); + assert!(rim(c).all(|p| fill_contains(&bp, rule, p)), "{c:?} reaches outside the fill"); + assert!(c.radius <= largest + slack + 1e-6 && c.radius >= largest - 2.0 * INSCRIBED_PRECISION, "{c:?}, largest {largest}"); +} + +fn holds(path: &PathData, rule: FillRule, c: Inscribed, largest: f64) { + holds_within(path, rule, c, largest, 0.0); +} + +#[test] +fn a_square_holds_the_circle_at_its_center() { + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + holds(&sq, FillRule::NonZero, c, 50.0); + assert!((c.center - Point::new(50.0, 50.0)).hypot() < 2.0 * INSCRIBED_PRECISION, "{c:?}"); +} + +#[test] +fn a_concave_shape_holds_the_circle_in_its_corner() { + // An L whose arms are 30 wide: the box's center (50, 50) is outside it. The largest circle + // touches the two outer edges and the inner corner (30, 30): c = √2 (30 − c). + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + holds(&l, FillRule::NonZero, c, largest); +} + +#[test] +fn a_ring_holds_the_circle_beside_its_hole_under_even_odd() { + let ring = PathData::new(vec![circle(0.0, 0.0, 100.0), circle(0.0, 0.0, 40.0)]); + let c = inscribed_circle(&ring, FillRule::EvenOdd).unwrap(); + holds_within(&ring, FillRule::EvenOdd, c, 30.0, 0.0003 * 140.0); + assert!((c.center.to_vec2().hypot() - 70.0).abs() < 0.1, "{c:?}"); + // Both subpaths turn the same way, so under nonzero the inner one fills in and is no hole. + let c = inscribed_circle(&ring, FillRule::NonZero).unwrap(); + holds_within(&ring, FillRule::NonZero, c, 100.0, 0.0003 * 100.0); +} + +#[test] +fn overlapping_subpaths_count_as_the_area_they_fill() { + // Two squares overlapping by half: under nonzero they fill one 150 × 100 rectangle, and the + // edges inside it do not bound the circle. + let a = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let b = polygon(&[(50.0, 0.0), (150.0, 0.0), (150.0, 100.0), (50.0, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + holds(&both, FillRule::NonZero, c, 50.0); +} + +#[test] +fn a_small_shape_is_measured_to_its_own_scale() { + // The L of the concave test, a thousandth of its size. + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0, y / 1000.0))); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); +} + +#[test] +fn a_shape_narrower_than_the_default_precision_gets_a_circle() { + // 0.005 pt square: resolved at 0.01 pt it would be dropped as a sliver. + let sq = polygon(&[(0.0, 0.0), (0.005, 0.0), (0.005, 0.005), (0.0, 0.005)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}"); +} + +#[test] +fn a_hairline_hole_bounds_the_circle() { + // A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let slit = polygon(&[(49.9995, 10.0), (50.0005, 10.0), (50.0005, 90.0), (49.9995, 90.0)]); + let both = PathData::new(sq.subpaths.into_iter().chain(slit.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::EvenOdd).unwrap(); + assert!((c.center.x - 50.0).abs() >= c.radius - 2.0 * INSCRIBED_PRECISION, "{c:?}"); + assert!(c.radius < 30.0, "{c:?}"); +} + +#[test] +fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() { + // A strip 5,000 × 1 whose top edge has 5,000 pieces: cut into cells as wide as it is high, + // the first cells alone would measure 5,000 times every edge. + let n = 5000; + let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect(); + let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 1.0)]).collect(); + let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap(); + let limit = 100 * e.len(); + assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 1.0), 0.01, limit), Err(InscribedError::TooComplex)); + // Past the limit by at most the four cells of one split. + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= limit + 4 * e.len(), "{measured} measured, limit {limit}"); +} + +#[test] +fn an_outline_with_too_many_edges_is_too_complex() { + let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect(); + let bp = polygon(&zigzag).to_bezpath(); + assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex)); + assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000)); +} + +#[test] +fn a_search_past_its_work_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search(&e, b, 0.01, MAX_WORK).is_ok()); + assert_eq!(search(&e, b, 0.01, 20 * e.len()), Err(InscribedError::TooComplex)); +} + +#[test] +fn a_shape_with_no_area_has_no_circle() { + let flat = polygon(&[(0.0, 0.0), (100.0, 0.0), (50.0, 0.0)]); + assert_eq!(inscribed_circle(&flat, FillRule::NonZero), Err(InscribedError::NoArea)); + assert_eq!(inscribed_circle(&PathData::default(), FillRule::NonZero), Err(InscribedError::NoArea)); +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..dd33370568 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding Circle…; the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and @@ -87,6 +87,7 @@ pub fn menu() -> Vec { Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), + Item::Cmd("Add Inscribed Circle", "addon.pathtools.inscribedCircle", json!({})), ] } diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..242821d4bb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14816,6 +14816,24 @@ Commands: ```json {"name":"run_command","arguments":{"command":"addon.pathtools.boundingCircle","params":{"offset":2}}} ``` +- `addon.pathtools.inscribedCircle {}` draws the largest live circle inside each selected closed path or compound + path (Object › Plug-ins › Path Precision Tools › Add Inscribed Circle, #6966). Its center is the shape's + [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). A path of a compound path + selected on its own counts as a path. The circle lies in the area the shape fills under its fill rule: holes and the + overlaps of crossing subpaths count as the fill shows them, and strokes and effects are left out. The command + flattens the outline to within 0.005 pt and searches square cells best first, measuring the radius from the center + to the curves, so its radius is within 0.02 pt of the largest. A shape whose + box is less than 10 pt across on its narrower side is measured to a thousandth of that side instead. A curve whose + control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much. The + drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command draws it that much + smaller, and it stays inside where it touches the shape. Narrow holes count; holes and gaps narrower than 1e-6 pt close up, as + in the other path operations. The circles get the current paint and go on top of the current layer, or of the isolated group, as other new art does. + The new circles are selected, and one undo removes them all. It is an error, with the document unchanged, when a selected + object is not a closed path or compound path ("object N is not a closed path or compound path"; an open path has no + inside), when it fills no area ("object N fills no area"), and when its outline has more than 262,144 straight + pieces once flattened, or the search measures more than 134,217,728 distances from a point to an edge ("object N is + too complex to measure"). + → `{id: the first circle, ids}` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one entry of its object data (`vc-pathtools-shape`, as `document.node` lists `attrs.data`), which SVG export leaves out; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..2bd4e10a02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2989,6 +2989,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle (`addon.pathtools.boundingRectangle`) draws a live rectangle on the selection's geometric bounding box, and Add Bounding Circle (`addon.pathtools.boundingCircle`) draws the [smallest enclosing circle](https://en.wikipedia.org/wiki/Smallest-circle_problem) of the selected outlines, with curves flattened to within 0.01 pt and the radius 0.01 pt larger, so the circle holds the curves. A curve is split into 1,024 pieces at most. One command makes at most 1,048,576 splits at any depth, and with `each` every shape gets an equal share. A shape that has used up its share splits each further curve into at most 8 pieces, with at most 7,340,032 more splits shared the same way (8,388,608 in all), and then counts each further curve whole. A piece that still bends more counts by the hull of its control points cut down to its bounding box, which can make the circle larger than the smallest one. Before the 0.01 pt is added, the circle around a circle of four curves is less than 0.3% larger when each curve is split into 8 pieces, and about 14% larger when each counts whole. Both use the current paint, go on top of the current layer or the isolated group, and are one undo step; shapes with no size are skipped (#6966). The commands take `each` (one shape per object) and `offset`, and the menu items Add Bounding Rectangle… and Add Bounding Circle… open a dialog with Offset, One per Object and Preview. Tests: `shapes::tests` in `vectorcraft-geom` (`enclosing`, `convex_hull`), `cmd::addons::pathtools::bounding::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object`). Commands: `docs/mcp.md` › Path Precision Tools add-on. +## Path Precision Tools add-on: Add Inscribed Circle (2026-11-22) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (a shape less than 10 pt across is measured to a thousandth of its narrower side), and the circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The circles use the current paint, go on top of the current layer or the isolated group, and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, the edge and work limits, a long thin shape, no area) and `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns the dashed stroke of each selected path and compound path into separate open paths, one per dash, for cutters and plotters that need the centre lines rather than Outline Stroke's filled outlines. The dashes are laid out by the renderer's own dash code, so they match what the canvas draws: the dash pattern, its offset and Align Dashes to Corners and Path Ends, a dash running on through the start of a closed path, a dash all the way round staying closed, and under a round or projecting cap each dot (a dash of no length) as a path on its point. Each dash keeps the path's appearance with the top stroke's dashes and arrowheads off; the path's fills stay on it, below its dashes; a compound path's dashes are plain paths. One undo step; the dashes are selected; at most 100000 (more, or a pattern too fine to draw, is refused). Tests: `expand_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (the stroke kept with dashes off, the offset, one undo step, the fill kept below, dashes centred on corners when aligned, dots under round and butt caps, compound paths, refusals and the piece cap), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..1926538a88 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -559,6 +559,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored | From 70a56fb5be73bf73c2d72be4dd04e4e7b9a90532 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:40:39 -0800 Subject: [PATCH 2/2] Path Precision Tools: Add Inscribed Circle bounds its work and memory - The searches for all the selected objects share one limit of 134,217,728 distances from a point to an edge, as Add Bounding Circle shares its splits, and each cell is measured only when the limit has room for it. One search keeps at most 1,048,576 cells waiting. The pathops crate adds inscribed_circle_within for a shared budget. - The search stops once its best center is within the precision of half the box's narrower side, so a long rectangle ends at its first cells, and cells that cannot beat the best center are no longer queued. - A fill much smaller than the precision still gets a circle: the search keeps splitting until it finds a center inside the outline. - The precision also follows the box of the area the fill rule leaves. - Flattening stops at the first curve past the edge limit. An outline that flattening closes up, or whose center lands outside the curves, is flattened up to four times, 16 times finer each time; one it still cannot resolve is too complex to measure, not empty. Areas are summed from each contour's own first point. - An outline with more than 262,144 anchors in its filled subpaths is refused before it is resolved. - A selected layer is refused like any other object that is not a path, and inside an isolated compound path the circles join it, as Tangent Circle's do. - The menu item uses a named constant, and a UI test checks that it runs the command with no dialog and selects a new live circle in each selected shape, as one undo step. - The params text and docs say that the 0.02 pt bound holds before the circle is drawn 0.03% smaller, that a shape under 10 pt across is measured to a five-hundredth of its narrower side, when long curves are flattened more coarsely, and that edges can move by 1e-6 pt as in the other path operations. --- .../src/cmd/addons/pathtools/inscribed.rs | 15 +- .../cmd/addons/pathtools/inscribed/tests.rs | 18 ++ crates/pathops/src/addons/pathtools.rs | 5 +- .../pathops/src/addons/pathtools/inscribed.rs | 210 ++++++++++++++---- .../src/addons/pathtools/inscribed/tests.rs | 180 ++++++++++++++- crates/ui-egui/src/addons/pathtools.rs | 4 +- crates/ui-egui/src/addons/pathtools/tests.rs | 38 ++++ docs/mcp.md | 30 ++- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 10 files changed, 436 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs index 2e016f23a7..e240fdf43d 100644 --- a/crates/engine/src/cmd/addons/pathtools/inscribed.rs +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -29,7 +29,7 @@ pub(super) fn specs() -> Vec { "Add Inscribed Circle", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and its radius is within 0.02 pt of the largest (for a shape at least 10 pt across; a smaller one is measured to a thousandth of its narrower side; a curve whose control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn that much smaller and stays inside where it touches. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 straight pieces once flattened or its search goes past its limit (\"object N is too complex to measure\") → {id: the first circle, ids}", + "{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and before it is drawn its radius is within 0.02 pt of the largest (when the filled area's box is at least 10 pt across on its narrower side; for a smaller one, within a five-hundredth of that side; a curve whose control polygon is longer than 4096² times the flattening tolerance, half the search's precision (83,886 pt at 0.005 pt), is flattened more coarsely, and the circle can be smaller by as much; a curved hole narrower than the flattening tolerance can also make it smaller; a shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 of the tolerance). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn 0.03% smaller and stays inside where it touches. Holes and gaps narrower than 1e-6 pt close up, and edges can move by as much, as in the other path operations. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; inside an isolated compound path they join it and take its appearance; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces once flattened, or the searches of the selected objects together measure more than 134,217,728 distances from a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length that it flattens to no area even at the finest tolerance (\"object N is too complex to measure\") → {id: the first circle, ids}", whole_objects, inscribed_circle )] @@ -52,21 +52,30 @@ fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> { } fn inscribed_circle(s: &mut Session, _p: &Value) -> Result { + // The roots leave out selected layers, which are not paths either. + let st = s.doc()?; + if let Some(layer) = st.selection.objects.iter().find(|id| st.doc.node(**id).is_some_and(Node::is_layer)) { + return Err(bad(COMMAND, format!("object {} is not a closed path or compound path", layer.0))); + } let roots = selected_roots_to_transform(s)?; let d = &s.doc()?.doc; let mut circles = vec![]; + // The searches share one work limit, so the command stays bounded however many objects are + // selected. + let mut work = pt::MAX_INSCRIBED_WORK; for id in roots { let value = id.0; let Some((path, rule)) = outline(d, id) else { return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path"))); }; - let c = pt::inscribed_circle(&path, rule).map_err(|e| match e { + let c = pt::inscribed_circle_within(&path, rule, &mut work).map_err(|e| match e { InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")), InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")), })?; circles.push(c); } - let parent = s.doc()?.target_parent()?; + // Path art: inside an isolated compound path, the circles join it, as Tangent Circle's do. + let parent = s.doc()?.target_parent_for_path()?; 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![]; diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs index f19c8fd111..86f0342ff7 100644 --- a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -152,6 +152,11 @@ fn each_selected_path_gets_a_circle_in_one_step() { let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); let r = circle(&s, id).1; assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}"); + // Inside the isolated compound path, the circle joins it. + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + select(&mut s, &[member]); + let id = id_of(&s.execute(COMMAND, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(compound)); } /// The drawn circle stays inside a large square turned so that it touches the square's sides @@ -200,4 +205,17 @@ fn open_paths_other_objects_and_no_selection_are_refused() { let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap()); select(&mut s, &[flat]); refused(&mut s, "fills no area"); + // A selected layer is refused too, alone or with a path. + let mut layer = None; + s.doc().unwrap().doc.walk(|n| { + if n.is_layer() { + layer.get_or_insert(n.id); + } + }); + let layer = layer.unwrap(); + let path = id_of(&s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap()); + for ids in [vec![layer], vec![layer, path]] { + select(&mut s, &ids); + refused(&mut s, "is not a closed path or compound path"); + } } diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 58927fbb79..032576e605 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -35,7 +35,10 @@ pub use bridge::{ pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; -pub use inscribed::{INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_EDGES, inscribed_circle}; +pub use inscribed::{ + INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_CELLS, MAX_INSCRIBED_EDGES, MAX_INSCRIBED_WORK, inscribed_circle, + inscribed_circle_within, +}; pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; diff --git a/crates/pathops/src/addons/pathtools/inscribed.rs b/crates/pathops/src/addons/pathtools/inscribed.rs index 285132acba..7b021d512e 100644 --- a/crates/pathops/src/addons/pathtools/inscribed.rs +++ b/crates/pathops/src/addons/pathtools/inscribed.rs @@ -32,10 +32,15 @@ thread_local! { pub const INSCRIBED_PRECISION: f64 = 0.01; /// Most straight edges the flattened outline may have. pub const MAX_INSCRIBED_EDGES: usize = 1 << 18; -/// Most distances from a point to an edge that one search measures. -const MAX_WORK: usize = 1 << 27; +/// Most distances from a point to an edge that one search measures, or that the searches of one +/// [`inscribed_circle_within`] budget measure together. +pub const MAX_INSCRIBED_WORK: usize = 1 << 27; /// Most cells the box is first cut into. const MAX_FIRST_CELLS: f64 = 4096.0; +/// Most cells the search keeps waiting to be split. +pub const MAX_INSCRIBED_CELLS: usize = 1 << 20; +/// How many times an outline the flattening does not resolve is flattened 16 times finer. +const FINER_FLATTENINGS: usize = 4; /// The largest circle inside an outline: its center and radius. #[derive(Clone, Copy, Debug, PartialEq)] @@ -49,28 +54,53 @@ pub struct Inscribed { pub enum InscribedError { /// The outline fills no area. NoArea, - /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] edges, or the - /// search would measure more than its limit. + /// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] anchors in its + /// subpaths of two or more or more than as many edges once flattened, or the + /// search would measure more than its limit or keep more than [`MAX_INSCRIBED_CELLS`] cells + /// waiting, or the outline is so thin for its length that it flattens to no area. TooComplex, } -/// The largest circle inside the area that `path` fills under `rule`, within twice -/// [`INSCRIBED_PRECISION`] of the largest radius: the search's precision and the flattening, at -/// half of it. A curve whose control polygon is longer than 83,886 pt is flattened more coarsely -/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much. Holes and gaps -/// narrower than 1e-6 pt close up, as in the other path operations. Open subpaths count as closed, -/// as when they are filled. +/// The largest circle inside the area that `path` fills under `rule`, within twice the precision +/// of the largest radius: the search's precision and the flattening, at half of it. The precision +/// is [`INSCRIBED_PRECISION`], or a thousandth of the narrower side of the filled area's box when +/// that is less than 10 pt. A curve whose control polygon is longer than 4096² times the +/// flattening tolerance (83,886 pt at 0.005 pt) is flattened more coarsely +/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much; so can a curved hole +/// narrower than the flattening tolerance. The bounds hold for the fill as the path operations +/// resolve it: holes and gaps narrower than 1e-6 pt close up, and edges can move by as much. Open +/// subpaths are closed as the other path operations close them, handles included. The searches +/// for one outline measure at most [`MAX_INSCRIBED_WORK`] distances in all, the final distances +/// to the curves included. pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result { + inscribed_circle_within(path, rule, &mut MAX_INSCRIBED_WORK.clone()) +} + +/// [`inscribed_circle`], measuring at most `work` distances from a point to an edge (and never +/// more than [`MAX_INSCRIBED_WORK`]) and taking the ones it measured off `work`, so several +/// searches can share one budget. +pub fn inscribed_circle_within(path: &PathData, rule: FillRule, work: &mut usize) -> Result { + // A path with more anchors than the edge limit, in the subpaths that are filled, is refused + // before it is resolved. + let mut filled_anchors = path.subpaths.iter().map(|sp| sp.anchors.len()).filter(|&n| n >= 2); + if filled_anchors.try_fold(0usize, |total, n| total.checked_add(n).filter(|&t| t <= MAX_INSCRIBED_EDGES)).is_none() { + return Err(InscribedError::TooComplex); + } let filled = fill_bezpath(path); let b = filled.bounding_box(); if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) { return Err(InscribedError::NoArea); } - let precision = INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0); + let precision = precision_for(b); // Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance // (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the // sweep split are rebuilt from the input's own. let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?; + // The resolved boundary can have far more pieces than the input; past the edge limit it is + // refused before it is copied. + if contours.contours().map(|c| c.path.segments().count()).sum::() > MAX_INSCRIBED_EDGES { + return Err(InscribedError::TooComplex); + } let tidy = Tidy::keeping(precision, [&filled]); let mut curves = kurbo::BezPath::new(); for c in contours.contours() { @@ -80,14 +110,61 @@ pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result 0.0 && b.height() > 0.0 && b.is_finite()) { return Err(InscribedError::NoArea); } - let edges = edges(&curves, precision / 2.0)?; - let center = search(&edges, b, precision, MAX_WORK)?; - // The circle touches the nearest curve, whatever the flattening moved. - let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); - if !(radius.is_finite() && radius > 0.0) || !fill_contains(&curves, FillRule::NonZero, center) { - return Err(InscribedError::NoArea); + // The fill rule can leave a much narrower area than the outline's box. + let precision = precision.min(precision_for(b)); + // The attempts for this outline share one allowance, taken off `work` as it is spent. + let start = (*work).min(MAX_INSCRIBED_WORK); + let mut allowance = start; + let found = measure(&curves, b, precision, &mut allowance); + *work = work.saturating_sub(start - allowance); + found +} + +/// The largest circle in the resolved `curves`, whose box is `b`, searched to `precision`, +/// measuring at most `allowance` distances and taking them off it. +fn measure(curves: &kurbo::BezPath, b: Rect, precision: f64, allowance: &mut usize) -> Result { + // Flattening can close up or move an area thinner than its tolerance, so that the flattened + // outline holds nothing or its best center lies outside the curves: the outline is then + // flattened 16 times finer, up to 4 times (down to 1/65,536 of the tolerance). The resolved + // contours have an area, so an outline that is still not measured is past what the + // flattening can resolve (very long curves are flattened more coarsely). + let mut tolerance = precision / 2.0; + // The last edges searched: a finer tolerance can flatten to the same ones (very long curves), + // which would give the same center again. + let mut searched = None; + for attempt in 0..=FINER_FLATTENINGS { + let edges = edges(curves, tolerance)?; + let held = area(&edges); + let last = attempt == FINER_FLATTENINGS; + let fresh = searched.as_ref() != Some(&edges); + if fresh && (held > tolerance * tolerance || (last && held.partial_cmp(&0.0) == Some(Ordering::Greater))) { + match search(&edges, b, precision, allowance) { + Ok(center) => { + // The circle touches the nearest curve, whatever the flattening moved; those + // distances come out of the allowance too. + let pieces = curves.segments().count(); + if *allowance < pieces { + return Err(InscribedError::TooComplex); + } + *allowance -= pieces; + let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt(); + if radius.is_finite() && radius > 0.0 && fill_contains(curves, FillRule::NonZero, center) { + return Ok(Inscribed { center, radius }); + } + } + Err(InscribedError::NoArea) => {} + Err(e) => return Err(e), + } + searched = Some(edges); + } + tolerance /= 16.0; } - Ok(Inscribed { center, radius }) + Err(InscribedError::TooComplex) +} + +/// The search's precision for an area whose box is `b`. +fn precision_for(b: Rect) -> f64 { + INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0) } /// The straight edges of `curves` flattened to within `tolerance`, each subpath closed. @@ -101,9 +178,10 @@ fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, out.push((a, b)); } }; - let mut over = false; - vectorcraft_geom::flatten(curves.iter(), tolerance, |el| { - if over { + // Once past the limit, no further curve is flattened. + let over = std::cell::Cell::new(false); + vectorcraft_geom::flatten(curves.iter().take_while(|_| !over.get()), tolerance, |el| { + if over.get() { return; } match el { @@ -123,15 +201,33 @@ fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result, } _ => {} } - over = out.len() > MAX_INSCRIBED_EDGES; + over.set(out.len() > MAX_INSCRIBED_EDGES); }); close(&mut out, start, last); - if over || out.len() > MAX_INSCRIBED_EDGES { + if over.get() || out.len() > MAX_INSCRIBED_EDGES { return Err(InscribedError::TooComplex); } Ok(out) } +/// The area the closed `edges` hold: their outer contours and holes turn opposite ways. Each +/// contour's points are taken from its first one, so a small area far from the origin is not +/// rounded away. +fn area(edges: &[(Point, Point)]) -> f64 { + let (mut total, mut contour) = (0.0, 0.0); + let (mut o, mut last) = (Point::ZERO, None); + for &(a, b) in edges { + // An edge that does not start where the last one ended starts the next contour. + if last != Some(a) { + total += contour; + (contour, o) = (0.0, a); + } + contour += (a - o).cross(b - o); + last = Some(b); + } + ((total + contour) / 2.0).abs() +} + /// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge, /// negative outside. fn inside(edges: &[(Point, Point)], p: Point) -> f64 { @@ -197,45 +293,77 @@ impl Ord for Cell { } /// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`, -/// measuring at most about `limit` distances from a point to an edge. -fn search(edges: &[(Point, Point)], b: Rect, precision: f64, limit: usize) -> Result { +/// measuring at most `budget` distances from a point to an edge, and never more than +/// [`MAX_INSCRIBED_WORK`], and taking the ones it measured off `budget`. +fn search(edges: &[(Point, Point)], b: Rect, precision: f64, budget: &mut usize) -> Result { + let mut work = 0usize; + let found = search_measuring(edges, b, (precision, (*budget).min(MAX_INSCRIBED_WORK), MAX_INSCRIBED_CELLS), &mut work); + *budget = budget.saturating_sub(work); + found +} + +/// [`search`] with `(precision, limit, max_cells)`, measuring at most `limit` distances (counted +/// in `work`) and keeping at most `max_cells` cells waiting. +fn search_measuring(edges: &[(Point, Point)], b: Rect, limits: (f64, usize, usize), work: &mut usize) -> Result { + let (precision, limit, max_cells) = limits; // Square cells as wide as the box's narrower side, or wider when that would make more than // `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work // limit, so the first cells take at most about three quarters of it. let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0); let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first); let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize); - let mut work = 0usize; + // Each cell is measured only when the limit still has room for it. let measure = |work: &mut usize, center: Point, half: f64| { - *work = work.saturating_add(edges.len()); + let Some(after) = work.checked_add(edges.len()).filter(|&after| after <= limit) else { + return Err(InscribedError::TooComplex); + }; + *work = after; #[cfg(test)] MEASURED.with(|m| m.set(*work)); - Cell::new(edges, center, half) + Ok(Cell::new(edges, center, half)) }; - let mut best = measure(&mut work, b.center(), 0.0); + // No circle in the box is wider than its narrower side. + let ceiling = b.width().min(b.height()) / 2.0; + // Until a center inside the outline is found, every cell that may hold one is split; after + // that, only cells that may beat the best center by more than the precision. + let open = |cell: &Cell, best: &Cell| cell.best > 0.0 && (best.inside <= 0.0 || cell.best - best.inside > precision); + let done = |best: &Cell| best.inside > 0.0 && best.inside >= ceiling - precision; + let mut best = measure(work, b.center(), 0.0)?; let mut cells = BinaryHeap::new(); - for row in 0..rows { - for col in 0..cols { - if work > limit { + let add = |cells: &mut BinaryHeap, best: &mut Cell, cell: Cell| { + if cell.inside > best.inside { + *best = cell; + } + // A best center at the ceiling ends the search, full queue or not. + if !done(best) && open(&cell, best) { + if cells.len() >= max_cells { return Err(InscribedError::TooComplex); } + cells.push(cell); + } + Ok(()) + }; + for row in 0..rows { + for col in 0..cols { + if done(&best) { + return Ok(best.center); + } let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size); - cells.push(measure(&mut work, at, size / 2.0)); + let cell = measure(work, at, size / 2.0)?; + add(&mut cells, &mut best, cell)?; } } while let Some(cell) = cells.pop() { - if cell.inside > best.inside { - best = cell; - } - if cell.best - best.inside <= precision { + if done(&best) || !open(&cell, &best) { break; } - if work > limit { - return Err(InscribedError::TooComplex); - } let h = cell.half / 2.0; for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { - cells.push(measure(&mut work, cell.center + (dx, dy), h)); + if done(&best) { + return Ok(best.center); + } + let child = measure(work, cell.center + (dx, dy), h)?; + add(&mut cells, &mut best, child)?; } } if best.inside <= 0.0 { diff --git a/crates/pathops/src/addons/pathtools/inscribed/tests.rs b/crates/pathops/src/addons/pathtools/inscribed/tests.rs index 50f2d103d3..1731d798a0 100644 --- a/crates/pathops/src/addons/pathtools/inscribed/tests.rs +++ b/crates/pathops/src/addons/pathtools/inscribed/tests.rs @@ -89,6 +89,20 @@ fn a_shape_narrower_than_the_default_precision_gets_a_circle() { assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}"); } +#[test] +fn a_tiny_shape_far_from_the_origin_gets_a_circle() { + let sq = polygon(&[(10_000.0, 10_000.0), (10_000.000_1, 10_000.0), (10_000.000_1, 10_000.000_1), (10_000.0, 10_000.000_1)]); + let c = inscribed_circle(&sq, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); + // With a second tiny square far from the first, each square's area is measured from its own + // corner. + let near = polygon(&[(0.0, 0.0), (0.0001, 0.0), (0.0001, 0.0001), (0.0, 0.0001)]); + let far = polygon(&[(1e6, 1e6), (1e6 + 0.0001, 1e6), (1e6 + 0.0001, 1e6 + 0.0001), (1e6, 1e6 + 0.0001)]); + let both = PathData::new(near.subpaths.into_iter().chain(far.subpaths).collect()); + let a = area(&edges(&both.to_bezpath(), 0.005).unwrap()); + assert!((a - 2e-8).abs() < 1e-10, "{a}"); +} + #[test] fn a_hairline_hole_bounds_the_circle() { // A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side. @@ -102,17 +116,129 @@ fn a_hairline_hole_bounds_the_circle() { #[test] fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() { - // A strip 5,000 × 1 whose top edge has 5,000 pieces: cut into cells as wide as it is high, - // the first cells alone would measure 5,000 times every edge. + // A strip 5,000 long, 1 high at one end and 2 at the other, whose top edge has 5,000 pieces: + // cut into cells as wide as it is high, the first cells alone would measure 2,500 times every + // edge. let n = 5000; let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect(); - let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 1.0)]).collect(); + let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 2.0)]).collect(); let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap(); let limit = 100 * e.len(); - assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 1.0), 0.01, limit), Err(InscribedError::TooComplex)); - // Past the limit by at most the four cells of one split. + assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 2.0), 0.01, &mut limit.clone()), Err(InscribedError::TooComplex)); let measured = MEASURED.with(std::cell::Cell::get); - assert!(measured <= limit + 4 * e.len(), "{measured} measured, limit {limit}"); + assert!(measured <= limit, "{measured} measured, limit {limit}"); +} + +#[test] +fn a_long_rectangle_stops_once_no_wider_circle_fits() { + // Every point of the center line is 50 from the long sides: the box's center is already the + // largest circle's, and the search stops at the first cells. + let r = polygon(&[(0.0, 0.0), (100_000.0, 0.0), (100_000.0, 100.0), (0.0, 100.0)]); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 50.0); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured <= (MAX_FIRST_CELLS as usize + 1) * 4, "{measured} measured"); +} + +#[test] +fn a_fill_far_smaller_than_the_precision_still_gets_a_circle() { + // Two 0.001 pt squares at opposite corners of a 100 pt box, which sets the precision to + // 0.01 pt. + let a = polygon(&[(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.001)]); + let b = polygon(&[(99.999, 99.999), (100.0, 99.999), (100.0, 100.0), (99.999, 100.0)]); + let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect()); + let c = inscribed_circle(&both, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&both.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); +} + +#[test] +fn a_lens_thinner_than_the_flattening_tolerance_gets_a_circle() { + // A straight side and a curve bowed 0.001 pt from it, 141 pt long: flattened to 0.005 pt the + // curve would lie on the straight side. + let lens = |side: f64| { + let n = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt() * (0.001 / 0.75); + let (a, b) = (Point::ZERO, Point::new(side, side)); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, Point::new(side / 3.0, side / 3.0) + n, a), + Anchor::with_handles(b, b, Point::new(side * 2.0 / 3.0, side * 2.0 / 3.0) + n), + ], + true, + )]) + }; + let l = lens(100.0); + let c = inscribed_circle(&l, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + assert!(fill_contains(&l.to_bezpath(), FillRule::NonZero, c.center), "{c:?}"); + // A curve that long is flattened too coarsely to show the bow at all: too complex, not empty. + assert_eq!(inscribed_circle(&lens(1e6), FillRule::NonZero), Err(InscribedError::TooComplex)); +} + +#[test] +fn a_bowed_strip_thinner_than_the_flattening_tolerance_is_not_reported_empty() { + // Two curves 0.001 pt apart, both bowed 0.003 pt the same way: flattened to 0.005 pt they + // become a straight strip that lies outside the bowed one. + let strip = |side: f64| { + let unit = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt(); + let (bow, gap) = (unit * (0.003 / 0.75), unit * 0.001); + let (a, b) = (Point::ZERO, Point::new(side, side)); + let third = (b - a) / 3.0; + let (a1, b1) = (a + gap, b + gap); + PathData::new(vec![SubPath::new( + vec![ + Anchor::with_handles(a, a, a + third + bow), + Anchor::with_handles(b, b - third + bow, b), + Anchor::with_handles(b1, b1, b1 - third + bow), + Anchor::with_handles(a1, a1 + third + bow, a1), + ], + true, + )]) + }; + let inside = |s: &PathData, c: Inscribed| { + assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}"); + // Measured against the curves flattened to 1e-8 pt by kurbo itself, which does not + // coarsen long curves: kurbo's winding can miss a curve a point lies this close to. + let mut polyline = kurbo::BezPath::new(); + kurbo::flatten(s.to_bezpath(), 1e-8, |el| polyline.push(el)); + let fine = edges(&polyline, 1e-8).unwrap(); + assert!(rim(c).all(|p| super::inside(&fine, p) > 1e-8), "{c:?} reaches outside"); + }; + // 28 and 141 pt long: a circle inside it, or too complex to measure; never "no area". + for side in [20.0, 100.0] { + let s = strip(side); + match inscribed_circle(&s, FillRule::NonZero) { + Ok(c) => inside(&s, c), + e => assert_eq!(e, Err(InscribedError::TooComplex), "{side}"), + } + } +} + +#[test] +fn a_thin_turned_rectangle_gets_the_circle_at_its_center() { + // 100 pt long and 0.009998 pt wide, turned 45°: no wider than twice the flattening tolerance. + let (u, v) = (kurbo::Vec2::new(1.0, 1.0) / 2f64.sqrt(), kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt()); + let (along, across) = (u * 100.0, v * 0.009998); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + holds(&r, FillRule::NonZero, c, 0.004999); + assert!(c.radius > 0.004999 * 0.99, "{c:?}"); + // 1,000 pt long and 0.0001 pt wide: also measured at the center. + let (along, across) = (u * 1000.0, v * 0.0001); + let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across]; + let r = polygon(&corners.map(|p| (p.x, p.y))); + let c = inscribed_circle(&r, FillRule::NonZero).unwrap(); + assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}"); +} + +#[test] +fn a_search_past_its_cell_limit_is_too_complex() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let e = edges(&l.to_bezpath(), 0.005).unwrap(); + let b = Rect::new(0.0, 0.0, 100.0, 100.0); + assert!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, MAX_INSCRIBED_CELLS), &mut 0).is_ok()); + assert_eq!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, 10), &mut 0), Err(InscribedError::TooComplex)); } #[test] @@ -120,6 +246,11 @@ fn an_outline_with_too_many_edges_is_too_complex() { let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect(); let bp = polygon(&zigzag).to_bezpath(); assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex)); + // Too many anchors are refused before the outline is resolved, even on a line that would + // otherwise fill no area. + let line: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, 0.0)).collect(); + assert_eq!(inscribed_circle(&polygon(&line), FillRule::NonZero), Err(InscribedError::TooComplex)); + assert_eq!(inscribed_circle(&polygon(&line[..1000]), FillRule::NonZero), Err(InscribedError::NoArea)); assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000)); } @@ -128,8 +259,41 @@ fn a_search_past_its_work_limit_is_too_complex() { let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); let e = edges(&l.to_bezpath(), 0.005).unwrap(); let b = Rect::new(0.0, 0.0, 100.0, 100.0); - assert!(search(&e, b, 0.01, MAX_WORK).is_ok()); - assert_eq!(search(&e, b, 0.01, 20 * e.len()), Err(InscribedError::TooComplex)); + assert!(search(&e, b, 0.01, &mut MAX_INSCRIBED_WORK.clone()).is_ok()); + assert_eq!(search(&e, b, 0.01, &mut (20 * e.len())), Err(InscribedError::TooComplex)); +} + +#[test] +fn searches_that_share_a_budget_stop_when_it_runs_out() { + let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]); + let mut work = MAX_INSCRIBED_WORK; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + let one = MAX_INSCRIBED_WORK - work; + assert!(one > 0); + // Enough for one search and half of another: the first fits, the second runs out. + let mut work = one + one / 2; + assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok()); + assert!(work < one, "{work} left of {one}"); + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + // One distance short of a whole search: refused without measuring past the budget. + let mut work = one - 1; + assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex)); + let measured = MEASURED.with(std::cell::Cell::get); + assert!(measured < one, "{measured} measured, budget {}", one - 1); +} + +#[test] +fn an_area_the_fill_rule_leaves_small_is_measured_to_its_own_scale() { + // Two identical 100 pt squares cancel under even-odd, leaving the small L of the test above: + // the outline's box is 100 pt across, the filled area's 0.1 pt. + let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let l = polygon( + &[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0 + 50.0, y / 1000.0 + 50.0)), + ); + let all = PathData::new(sq.subpaths.iter().cloned().chain(sq.subpaths.iter().cloned()).chain(l.subpaths).collect()); + let c = inscribed_circle(&all, FillRule::EvenOdd).unwrap(); + let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2); + assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}"); } #[test] diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index dd33370568..c71527ab1a 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -41,6 +41,8 @@ pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "exter /// dialog (Offset, One per Object) with a Preview. pub const BOUNDING_RECTANGLE: &str = "addon.pathtools.boundingRectangle"; pub const BOUNDING_CIRCLE: &str = "addon.pathtools.boundingCircle"; +/// Add Inscribed Circle's command, whose menu item runs it with no dialog. +pub const INSCRIBED_CIRCLE: &str = "addon.pathtools.inscribedCircle"; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; const LABEL_W: f32 = 64.0; @@ -87,7 +89,7 @@ pub fn menu() -> Vec { Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), - Item::Cmd("Add Inscribed Circle", "addon.pathtools.inscribedCircle", json!({})), + Item::Cmd("Add Inscribed Circle", INSCRIBED_CIRCLE, json!({})), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..fb9a9c2ac1 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -530,3 +530,41 @@ fn add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_objec } } } + +#[test] +fn add_inscribed_circle_draws_its_circles_without_a_dialog() { + let mut app = app(); + let find = |app: &VectorcraftApp| { + let entries = menus::menu_entries(app); + entries + .into_iter() + .find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Add Inscribed Circle") + .expect("Add Inscribed Circle") + }; + let item = find(&app); + assert_eq!((item.command.as_deref(), &item.params), (Some(super::INSCRIBED_CIRCLE), &json!({}))); + assert!(!item.enabled, "with nothing selected"); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 100, "y": 20, "width": 20, "height": 40})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let (steps, nodes) = (app.session.doc().unwrap().history.undo.len(), app.session.doc().unwrap().doc.node_count()); + let item = find(&app); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert!(app.ui.dialog.is_none(), "no dialog opens"); + let st = app.session.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.doc.node_count()), (steps + 1, nodes + 2), "a circle in each rectangle, one undo step"); + let made = &st.selection.objects; + assert_eq!(made.len(), 2, "the two circles are selected: {made:?}"); + for (id, inside) in made.iter().zip([[10.0, 20.0, 40.0, 60.0], [100.0, 20.0, 120.0, 60.0]]) { + assert!(id.0 != a && id.0 != b, "{id:?} is a new object"); + let live = match &st.doc.node(*id).unwrap().kind { + vectorcraft_doc::NodeKind::Path { live, .. } => live.as_deref(), + _ => None, + }; + assert!(matches!(live, Some(vectorcraft_doc::LiveShape::Ellipse { w, h, .. }) if w == h), "{id:?} is a live circle"); + let r = st.doc.bounds_of(&[*id], false).unwrap(); + assert!(r.x0 >= inside[0] && r.y0 >= inside[1] && r.x1 <= inside[2] && r.y1 <= inside[3], "{r:?} inside {inside:?}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 242821d4bb..17e6ad3d06 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14821,18 +14821,24 @@ Commands: [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). A path of a compound path selected on its own counts as a path. The circle lies in the area the shape fills under its fill rule: holes and the overlaps of crossing subpaths count as the fill shows them, and strokes and effects are left out. The command - flattens the outline to within 0.005 pt and searches square cells best first, measuring the radius from the center - to the curves, so its radius is within 0.02 pt of the largest. A shape whose - box is less than 10 pt across on its narrower side is measured to a thousandth of that side instead. A curve whose - control polygon is longer than 83,886 pt is flattened more coarsely, and the circle can be smaller by as much. The - drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command draws it that much - smaller, and it stays inside where it touches the shape. Narrow holes count; holes and gaps narrower than 1e-6 pt close up, as - in the other path operations. The circles get the current paint and go on top of the current layer, or of the isolated group, as other new art does. - The new circles are selected, and one undo removes them all. It is an error, with the document unchanged, when a selected - object is not a closed path or compound path ("object N is not a closed path or compound path"; an open path has no - inside), when it fills no area ("object N fills no area"), and when its outline has more than 262,144 straight - pieces once flattened, or the search measures more than 134,217,728 distances from a point to an edge ("object N is - too complex to measure"). + flattens the outline to within 0.005 pt and searches square cells best first to within 0.01 pt, then measures the + radius from the center to the curves, so before the circle is drawn its radius is within 0.02 pt of the largest. + When the box of the filled area is less than 10 pt across on its narrower side, the search and the flattening use + a thousandth and a two-thousandth of that side, and the radius is within a five-hundredth of it. A curve whose + control polygon is longer than 4096² times the flattening tolerance (83,886 pt at 0.005 pt) is flattened more + coarsely, and the circle can be smaller by as much. A curved hole narrower than the flattening tolerance can also + make it smaller. A shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 + of the tolerance. The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so the command + draws it 0.03% smaller, and it stays inside where it touches the shape. Holes and gaps narrower than 1e-6 pt close + up, and edges can move by as much, as in the other path operations. The circles get the current paint and go on + top of the current layer, or of the isolated group, as other new art does; inside an isolated compound path they + join it and take its appearance. The new circles are selected, and one undo removes them all. It is an error, + with the document unchanged, when a selected object is not a closed path or compound path ("object N is not a + closed path or compound path"; an open path has no inside), when it fills no area ("object N fills no area"), and + when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces + once flattened, or the searches of all the selected objects together measure more than 134,217,728 distances from + a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length + that it flattens to no area even at the finest tolerance ("object N is too complex to measure"). → `{id: the first circle, ids}` A parametric shape is an ordinary path. It keeps its numbers, with a fingerprint of the outline they drew, in one diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2bd4e10a02..cd3c4c6f23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2991,7 +2991,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Pre ## Path Precision Tools add-on: Add Inscribed Circle (2026-11-22) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (a shape less than 10 pt across is measured to a thousandth of its narrower side), and the circle is drawn up to 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The circles use the current paint, go on top of the current layer or the isolated group, and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 flattened pieces or the search's work limit are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, the edge and work limits, a long thin shape, no area) and `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Add Inscribed Circle (`addon.pathtools.inscribedCircle`) draws the largest live circle inside each selected closed path or compound path, centered on the shape's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility). The rest is VectorCraft's own: the shape is first resolved under its fill rule into outer contours and holes, flattened to within 0.005 pt and searched in square cells best first, and the radius is measured from the center to the curves, within 0.02 pt of the largest (when the filled area's box is less than 10 pt across, within a five-hundredth of its narrower side), and the circle is then drawn 0.03% smaller, by as much as its four curves reach past a true circle, so it stays inside. The searches of one command share one work limit. The circles use the current paint, go on top of the current layer or the isolated group (inside an isolated compound path they join it and take its appearance), and are one undo step (#6966). Open paths, other objects, shapes that fill no area, and outlines past 262,144 anchors or flattened pieces or the search's limits are errors. Tests: `addons::pathtools::inscribed::tests` in `vectorcraft-pathops` (a square, a concave shape, a ring under both fill rules, overlapping subpaths, a small shape, a shape narrower than 0.01 pt, a hairline hole, a small area left by the fill rule, the edge and work limits, a shared work limit, a long thin shape, a long rectangle, a fill far smaller than the precision, a lens and a bowed strip thinner than the flattening tolerance, the cell limit, no area), `cmd::addons::pathtools::inscribed::tests` in `vectorcraft-engine` and `addons::pathtools::tests` in `vectorcraft-ui-egui` (`add_inscribed_circle_draws_its_circles_without_a_dialog`). Commands: `docs/mcp.md` › Path Precision Tools add-on. ## Path Precision Tools add-on: Expand Dashes into Paths (2026-11-01) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1926538a88..7ba71e39bb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -559,7 +559,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, or with Constant Gap that radius plus a gap; Reach; Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, or three or more each to the others within reach, united where the bridges connect, in place of the circles or above them (a pair within reach gets no bridge when its arcs would not reach both circles or would cross, or when its neck would be thinner than the precision its shape is united at; a circle bridged to no other stays as it is); one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… draw a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, from a dialog with Offset, One per Object (a shape around each object instead of one around the whole selection) and Preview; one undo step | done | `addon.pathtools.boundingRectangle` and `addon.pathtools.boundingCircle` (in `crates/engine/src/cmd/addons/pathtools/bounding.rs`, the circle in `crates/geom/src/shapes.rs`, `enclosing_circle`; the dialog is the command dialog, `crates/ui-egui/src/dialogs/command.rs`) and their tests, with the menu items' test `add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | -| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests; a VectorCraft addition, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Add Inscribed Circle draws the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule; one undo step | done | `addon.pathtools.inscribedCircle` (in `crates/engine/src/cmd/addons/pathtools/inscribed.rs`, geometry in `crates/pathops/src/addons/pathtools/inscribed.rs`) and its tests, with the menu item's test `add_inscribed_circle_draws_its_circles_without_a_dialog` in `crates/ui-egui/src/addons/pathtools/tests.rs`; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its six tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape, Corner Tool, Slide Anchor Along Path), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; the Corner Tool cuts editable corners on any path (hover shows the anchor, a click uses its radius and kind, a drag sizes the corner, Shift whole values; a corner's marker selects it and loads its values, drags to resize, to 0 or double-clicked removes it; never past what fits; Alt-marquee cuts every anchor inside) with a Corners section in the Anchor Inspector (radius, kind, selected count, Apply to Selected Anchors); Slide Anchor Along Path drags an anchor along its curve with the segments beside it refitted, Shift snapping where the tangent is a multiple of 45°; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/` and their tests; not a feature of the reference app, so it is not scored |