From 0189417e24e45bafd9efdb31d27f6ba504bb5989 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:07:32 -0800 Subject: [PATCH 1/3] Path Precision Tools: Common Tangents draws the lines touching two closed paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two selected convex closed paths as separate open paths: external (both paths on the same side of the line), internal (the lines between them) or all, and with Centerline the line joining the two centers. An ellipse drawn with the Ellipse tool is measured as an exact ellipse at any rotation and scale; any other path must be closed, have one outline and bend the same way all around, with at most 10000 segments. Each line runs between the points where it touches the two paths, or covers a straight side that lies along it. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other none. Paths that touch, from outside or from inside, share one tangent instead: a line centered on the point where they touch and as long as the narrower path is wide along it. When there is no tangent of the kind asked for, nothing changes and the result carries a warning that says why. The lines take the current stroke and no fill, go directly above the upper path and are selected, as one undo step. The dialog has Preview. The geometry is in vectorcraft-pathops: the tangents are the zeros of the difference of the two outlines' support values over the normal's angle, sampled at 720 even steps and at every angle where either path's touching point passes to another segment, then refined, so the work per pair is bounded. Catalog rows for the menu item, the dialog and the messages are in every catalog. Docs: docs/mcp.md (Path Precision Tools add-on), docs/target-app-parity.md and ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/pathtools.rs | 4 +- .../src/cmd/addons/pathtools/tangents.rs | 130 +++ .../cmd/addons/pathtools/tangents/tests.rs | 265 ++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 4 + crates/pathops/src/addons/pathtools.rs | 5 +- .../pathops/src/addons/pathtools/tangents.rs | 853 ++++++++++++++++++ crates/ui-egui/src/addons/pathtools.rs | 5 + crates/ui-egui/src/addons/pathtools/tests.rs | 70 ++ crates/ui-egui/src/dialogs/command.rs | 9 +- crates/ui-egui/src/i18n/bg.tsv | 16 + crates/ui-egui/src/i18n/bs.tsv | 16 + crates/ui-egui/src/i18n/ca.tsv | 16 + crates/ui-egui/src/i18n/cs.tsv | 16 + crates/ui-egui/src/i18n/da.tsv | 16 + crates/ui-egui/src/i18n/de.tsv | 16 + crates/ui-egui/src/i18n/el.tsv | 16 + crates/ui-egui/src/i18n/es.tsv | 16 + crates/ui-egui/src/i18n/fi.tsv | 16 + crates/ui-egui/src/i18n/fr.tsv | 16 + crates/ui-egui/src/i18n/gu.tsv | 16 + crates/ui-egui/src/i18n/hi.tsv | 16 + crates/ui-egui/src/i18n/hu.tsv | 16 + crates/ui-egui/src/i18n/id.tsv | 16 + crates/ui-egui/src/i18n/it.tsv | 16 + crates/ui-egui/src/i18n/ja.tsv | 16 + crates/ui-egui/src/i18n/ka.tsv | 16 + crates/ui-egui/src/i18n/ko.tsv | 16 + crates/ui-egui/src/i18n/nl.tsv | 16 + crates/ui-egui/src/i18n/pl.tsv | 16 + crates/ui-egui/src/i18n/pt-br.tsv | 16 + crates/ui-egui/src/i18n/ru.tsv | 16 + crates/ui-egui/src/i18n/sv.tsv | 16 + crates/ui-egui/src/i18n/tr.tsv | 16 + crates/ui-egui/src/i18n/uk.tsv | 16 + crates/ui-egui/src/i18n/vi.tsv | 16 + crates/ui-egui/src/i18n/zh-hans.tsv | 16 + crates/ui-egui/src/i18n/zh-hant.tsv | 16 + docs/mcp.md | 21 + docs/target-app-parity.md | 4 + 41 files changed, 1815 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/addons/pathtools/tangents.rs create mode 100644 crates/engine/src/cmd/addons/pathtools/tangents/tests.rs create mode 100644 crates/pathops/src/addons/pathtools/tangents.rs diff --git a/ROADMAP.md b/ROADMAP.md index 0270db445e..7ad95b59da 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -145,6 +145,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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. +- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 8a271557a9..f1707fea1d 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,7 +3,7 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths and Trim at Crossings ([`trim`]). +//! into Paths, Trim at Crossings ([`trim`]) and Common Tangents ([`tangents`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. @@ -12,6 +12,7 @@ mod corners; mod effect_tests; mod shape; mod shared_edge; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -180,6 +181,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(tangents::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..4376cbe791 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents.rs @@ -0,0 +1,130 @@ +//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected +//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without +//! crossing into either, added as separate open paths, with the line joining their centers if +//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, Document, LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Affine; +use vectorcraft_geom::{FillRule, PathData, Point, SubPath}; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::object::choice; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use crate::{EngineError, Result, Session}; + +/// The command's id. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The undo step's name. +const LABEL: &str = "Common Tangents"; +/// The kinds of tangent `tangents` picks. +const KINDS: [&str; 3] = ["external", "internal", "all"]; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.commonTangents", + "Common Tangents", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}", + has_selection, + common_tangents + )] +} + +/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse, +/// else the path's one closed convex subpath. +fn outline_of(d: &Document, id: NodeId) -> Result { + const C: &str = COMMON_TANGENTS; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) }; + let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) }; + if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() { + let span = (pie.1 - pie.0).rem_euclid(360.0); + if span < 1e-9 || 360.0 - span < 1e-9 { + let unit = *xf * Affine::new([w / 2.0, 0.0, 0.0, h / 2.0, w / 2.0, h / 2.0]); + return pt::Outline::ellipse(unit).map_err(refusal); + } + } + pt::Outline::convex(sp).map_err(refusal) +} + +fn refusal(e: pt::OutlineError) -> EngineError { + bad( + COMMON_TANGENTS, + match e { + pt::OutlineError::Open => "a selected path is open", + pt::OutlineError::NotConvex => "a selected path is not convex", + pt::OutlineError::Empty => "a selected path has no area", + pt::OutlineError::TooComplex => "a selected path has more than 10000 segments", + }, + ) +} + +fn common_tangents(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMON_TANGENTS; + let kinds = choice(p, C, "tangents", &KINDS)?.unwrap_or("all"); + let centerline = switch_or(p, "centerline", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let d = &s.doc()?.doc; + let ordered = d.paint_order(roots.iter().copied()); + let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) }; + let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?); + let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?; + let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count(); + let keep = |t: &&pt::Tangent| match kinds { + "external" => t.kind == pt::TangentKind::External, + "internal" => t.kind == pt::TangentKind::Internal, + _ => true, + }; + let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect(); + let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count(); + let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal)); + let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect(); + if lines.is_empty() { + // Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one + // external tangent means one path lies inside the other and touches it there; paths that + // overlap without one inside the other have at least two. + let warning = match external { + 0 => EngineError::Other("One path lies inside the other, so they have no common tangents".into()), + 1 => EngineError::Other("One path lies inside the other, so they have no internal tangents".into()), + _ => EngineError::Other("The paths overlap, so they have no internal tangents".into()), + }; + return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() })); + } + let center = (centerline && (a.center() - b.center()).hypot() > 1e-9).then(|| (a.center(), b.center())); + let fill = Paint::None; + let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }; + let mut look = s.new_art_look(fill, stroke, s.paint.stroke_width.max(0.1)); + // The new art's look may carry more fills than the top one: none of them is kept. + look.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + let top = *second; + let (ids, center_id) = s.edit(LABEL, |d, sel| { + let (parent, idx, _) = d.position(top).ok_or(EngineError::NoNode(top))?; + let mut ids = vec![]; + let mut center_id = None; + for (k, (from, to)) in lines.iter().copied().chain(center).enumerate() { + let id = d.alloc_id(); + let path = PathData::single(SubPath::polyline(&[from, to], false)); + let mut n = Node::new(id, NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: false }); + look.apply(d, &mut n); + d.insert(parent, idx + 1 + k, n)?; + if k == lines.len() { + center_id = Some(id); + } + ids.push(id); + } + sel.set(ids.iter().copied()); + Ok((ids, center_id)) + })?; + Ok(json!({ + "ids": ids.iter().map(|i| i.0).collect::>(), + "external": external_kept, + "internal": internal_kept, + "centerline": center_id.map(|i| i.0), + })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs new file mode 100644 index 0000000000..5ed6e2b0d6 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/tangents/tests.rs @@ -0,0 +1,265 @@ +//! Common Tangents: the lines for circles, turned ellipses and convex paths, the centerline, +//! the paint, one undo step, the cases with no tangent, and refused selections and params. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{AppearanceItem, NodeId, NodeKind}; +use vectorcraft_geom::{Point, Vec2}; + +use crate::Session; + +const C: &str = super::COMMON_TANGENTS; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn circle(s: &mut Session, cx: f64, cy: f64, r: f64) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The ends of each new line, as `ids` lists them. +fn lines(s: &Session, r: &Value) -> Vec<(Point, Point)> { + let d = &s.doc().unwrap().doc; + r["ids"] + .as_array() + .unwrap() + .iter() + .map(|v| { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path") }; + assert_eq!(path.subpaths.len(), 1); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.len(), 2); + (sp.anchors[0].p, sp.anchors[1].p) + }) + .collect() +} + +fn near(p: Point, q: Point) -> bool { + p.distance(q) < 1e-6 +} + +fn has_line(found: &[(Point, Point)], p: Point, q: Point) -> bool { + found.iter().any(|(a, b)| (near(*a, p) && near(*b, q)) || (near(*a, q) && near(*b, p))) +} + +#[test] +fn two_circles_get_four_tangents_at_the_exact_points_as_one_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 200.0, 20.0); + let b = circle(&mut s, 300.0, 200.0, 40.0); + select(&mut s, &[a, b]); + let before = steps(&s); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64(), r["centerline"].is_null()), (Some(2), Some(2), true), "{r}"); + assert_eq!(steps(&s), before + 1); + let found = lines(&s, &r); + assert_eq!(found.len(), 4); + let (c1, c2) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0)); + // External: (c1 - c2) · n = r2 - r1, n.x = -0.1; internal: (c1 - c2) · n = -(r1 + r2), n.x = 0.3. + for (nx, external) in [(-0.1f64, true), (0.3, false)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if external { c2 + n * 40.0 } else { c2 - n * 40.0 }; + assert!(has_line(&found, c1 + n * 20.0, far), "{n:?} in {found:?}"); + } + } + // The lines are the selection, above the two circles. + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 4); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + let order = st.doc.paint_order([a, b].into_iter().chain(ids.iter().copied())); + assert_eq!(&order[..2], &[a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(ids.iter().all(|id| s.doc().unwrap().doc.node(*id).is_none()), "one undo step removes them all"); +} + +#[test] +fn turned_ellipses_are_measured_exactly() { + let mut s = session(); + let a = id_of(&s.execute("shape.ellipse", &json!({"x": 60, "y": 170, "width": 80, "height": 30})).unwrap()); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 30, "origin": [100, 185]})).unwrap(); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 330, "y": 120, "width": 50, "height": 120})).unwrap()); + select(&mut s, &[b]); + s.execute("object.rotate", &json!({"angle": -70, "origin": [355, 180]})).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(C, &json!({"tangents": "all"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + // Each end lies on its ellipse, where the ellipse runs along the line: turned back about the + // center, (x/rx)² + (y/ry)² = 1 and the gradient is square to the line. + let on = |p: Point, center: Point, rx: f64, ry: f64, deg: f64, dir: Vec2| { + let turn = vectorcraft_geom::kurbo::Affine::rotate(-deg.to_radians()); + // `object.rotate` turns counter-clockwise on the page (y down): undo it in page terms. + let page = |v: Vec2| Vec2::new(v.x, -v.y); + let q = page((turn * page(p - center).to_point()).to_vec2()); + let d = page((turn * page(dir).to_point()).to_vec2()); + let value = (q.x / rx).powi(2) + (q.y / ry).powi(2); + let grad = Vec2::new(q.x / (rx * rx), q.y / (ry * ry)); + (value - 1.0).abs() < 1e-9 && (grad.dot(d) / (grad.hypot() * d.hypot())).abs() < 1e-7 + }; + for (p, q) in lines(&s, &r) { + let dir = q - p; + assert!(on(p, Point::new(100.0, 185.0), 40.0, 15.0, 30.0, dir), "{p:?} on the first ellipse"); + assert!(on(q, Point::new(355.0, 180.0), 25.0, 60.0, -70.0, dir), "{q:?} on the second ellipse"); + } +} + +#[test] +fn a_convex_bezier_path_and_the_centerline() { + let mut s = session(); + let anchors = json!([ + {"x": 0, "y": 40, "in": [0, 70], "out": [0, 10]}, + {"x": 50, "y": 0, "in": [20, 0], "out": [90, 0]}, + {"x": 110, "y": 50, "in": [110, 20], "out": [110, 90]}, + {"x": 40, "y": 100, "in": [80, 100], "out": [10, 100]} + ]); + let blob = id_of(&s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()); + let round = circle(&mut s, 300.0, 200.0, 30.0); + let r = s.execute(C, &json!({"ids": [blob.0, round.0], "centerline": true})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(2)), "{r}"); + let found = lines(&s, &r); + assert_eq!(found.len(), 5, "four tangents and the centerline"); + // The centerline is the last line and its id is given: from the blob's center of area to the + // circle's center. + assert_eq!(r["centerline"], r["ids"][4]); + let (from, to) = found[4]; + assert!(near(to, Point::new(300.0, 200.0)), "{to:?}"); + assert!(from.x > 30.0 && from.x < 80.0 && from.y > 30.0 && from.y < 70.0, "{from:?}"); + // A tangent touches without crossing: every point of both paths is on one side of it. + let d = &s.doc().unwrap().doc; + let points = |id: NodeId| { + let sp = d.node(id).unwrap().path_data().unwrap().subpaths[0].clone(); + let segments: Vec<_> = (0..sp.segment_count()).map(|k| sp.segment(k)).collect(); + segments.iter().flat_map(|seg| (0..200).map(|j| vectorcraft_geom::kurbo::ParamCurve::eval(seg, j as f64 / 200.0))).collect::>() + }; + let (pa, pb) = (points(blob), points(round)); + for (p, q) in &found[..4] { + let n = Vec2::new(-(q.y - p.y), q.x - p.x).normalize(); + for pts in [&pa, &pb] { + let side: Vec = pts.iter().map(|x| (*x - *p).dot(n)).collect(); + let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + // The circle is measured as an exact circle, which its four curves follow to within + // about 0.03% of the radius. + assert!(lo > -1e-2 || hi < 1e-2, "crosses: {lo} .. {hi}"); + } + } +} + +#[test] +fn the_lines_take_the_current_stroke_and_no_fill() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + let d = &s.doc().unwrap().doc; + for v in r["ids"].as_array().unwrap() { + let n = d.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(n.appearance.fill().is_none_or(|f| f.paint.is_none()), "no fill"); + let st = n.appearance.stroke().expect("stroked"); + assert!(!st.paint.is_none(), "black when the stroke is None"); + } + // A new-art appearance with two fills and a stroke: the lines keep the stroke and neither fill. + let mut look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 2.0); + let fill = look.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap(); + look.items.push(fill); + s.paint.appearance = Some(look); + s.paint.inherited = false; + let r2 = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "external"})).unwrap(); + let d2 = &s.doc().unwrap().doc; + for v in r2["ids"].as_array().unwrap() { + let n = d2.node(NodeId(v.as_u64().unwrap())).unwrap(); + assert!(!n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))), "no fill at all"); + assert!(n.appearance.stroke().is_some()); + } + // Two equal circles: the external tangents run along their tops and bottoms. + assert!(has_line(&lines(&s, &r), Point::new(100.0, 80.0), Point::new(300.0, 80.0))); + assert!(has_line(&lines(&s, &r), Point::new(100.0, 120.0), Point::new(300.0, 120.0))); +} + +#[test] +fn nested_and_overlapping_paths_change_nothing_and_say_why() { + let mut s = session(); + let big = circle(&mut s, 200.0, 200.0, 100.0); + let small = circle(&mut s, 220.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [big.0, small.0]})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + // Overlapping circles have external tangents only. + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 140.0, 100.0, 30.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [a.0, b.0], "tangents": "internal"})).unwrap(); + assert!(r["warning"].as_str().unwrap().contains("overlap"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}"); + // Circles that touch share the tangent where they touch. + let c = circle(&mut s, 100.0, 300.0, 10.0); + let e = circle(&mut s, 130.0, 300.0, 20.0); + let r = s.execute(C, &json!({"ids": [c.0, e.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["internal"].as_u64(), Some(1), "{r}"); + let (p, q) = lines(&s, &r)[0]; + assert!((p.x - 110.0).abs() < 1e-5 && (q.x - 110.0).abs() < 1e-5 && (p.distance(q) - 20.0).abs() < 1e-5, "{p:?} {q:?}"); + // A circle touching the inside of a larger one: no internal tangent, and the message says the + // one lies inside the other rather than that they overlap. + let outer = circle(&mut s, 400.0, 200.0, 50.0); + let inner = circle(&mut s, 430.0, 200.0, 20.0); + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0], "tangents": "internal"})).unwrap(); + assert_eq!(r["ids"], json!([])); + assert!(r["warning"].as_str().unwrap().contains("inside the other, so they have no internal"), "{r}"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before); + let r = s.execute(C, &json!({"ids": [outer.0, inner.0]})).unwrap(); + assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}"); +} + +#[test] +fn bad_selections_and_params_are_refused() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 300.0, 100.0, 20.0); + let star = id_of(&s.execute("shape.star", &json!({"cx": 200, "cy": 300, "radius1": 40, "radius2": 15, "points": 5})).unwrap()); + let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap()); + let group_of = |s: &mut Session, ids: &[NodeId]| { + select(s, ids); + id_of(&s.execute("object.group", &json!({})).unwrap()) + }; + let before = (steps(&s), s.doc().unwrap().doc.node_count()); + let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": "both"})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "tangents": 3})).contains("tangents")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "centerline": "yes"})).contains("centerline")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "which": "all"})).contains("which"), "unknown keys are refused"); + assert!(err(&mut s, json!({"ids": [a.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, star.0]})).contains("select two closed paths")); + assert!(err(&mut s, json!({"ids": [a.0, star.0]})).contains("not convex")); + assert!(err(&mut s, json!({"ids": [a.0, open.0]})).contains("open")); + assert!(s.execute(C, &json!({"ids": [a.0, a.0]})).is_err(), "the same path twice"); + assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes"); + let copy = id_of(&s.execute("shape.ellipse", &json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()); + assert!(err(&mut s, json!({"ids": [a.0, copy.0]})).contains("same outline")); + let g = group_of(&mut s, &[b]); + assert!(err(&mut s, json!({"ids": [a.0, g.0]})).contains("select two closed paths")); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f445237d83..2615adb680 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -45,6 +45,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", "addon.pathtools.close", + "addon.pathtools.commonTangents", "addon.pathtools.corner", "addon.pathtools.cornerRemove", "addon.pathtools.cornerSet", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 30d0dc96cf..8cdac3bc34 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -984,6 +984,10 @@ fn structured_junk() { ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), + ("addon.pathtools.commonTangents", json!({"tangents": "all", "centerline": true})), + ("addon.pathtools.commonTangents", json!({"tangents": "x", "centerline": "y", "ids": [u64::MAX, -1]})), + ("addon.pathtools.commonTangents", json!({"tangents": null, "ids": [1, 2, 3, 4], "centerline": null})), + ("addon.pathtools.commonTangents", json!({"tangents": ["external"], "ids": "all"})), ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index a20a4a5b36..0e5afd9ce7 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,7 +4,8 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]) and the Parametric Shape Tool's shapes ([`shapes`]). +//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]) and the +//! Parametric Shape Tool's shapes ([`shapes`]). mod crossings; mod dashes; @@ -12,6 +13,7 @@ mod extend; pub mod shapes; mod shared_edge; mod slide; +mod tangents; #[cfg(test)] mod tests; mod trim; @@ -28,6 +30,7 @@ pub use shared_edge::{ COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at, }; pub use slide::{MAX_SLIDE, slide_anchor, slide_stops, slide_t_at}; +pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; use crate::fit::{end_tangent, start_tangent}; diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs new file mode 100644 index 0000000000..c0d66e0dc1 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -0,0 +1,853 @@ +//! Common Tangents: the straight lines that touch two convex closed outlines (ellipses at any +//! rotation and scale, and convex Bézier paths) without crossing into either. An external tangent +//! has both outlines on the same side of it; an internal one runs between them. +//! +//! A line with unit normal `n` touches an outline from outside where `p · n` reaches the +//! outline's support value `h(n)`, the largest `p · n` over its points. External tangents are the +//! normals where both outlines have the same support value, internal ones where `h₁(n) = -h₂(-n)`. +//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with +//! sampled minima refined too so that a double root (outlines that touch) or two roots between +//! neighboring samples are kept. + +use std::f64::consts::TAU; + +use kurbo::{Affine, CubicBez, ParamCurve, Point, Vec2}; +use vectorcraft_geom::SubPath; + +/// Most segments one outline may have. +pub const MAX_TANGENT_SEGMENTS: usize = 10_000; +/// Normal directions sampled around the circle before refining. +const SAMPLES: usize = 720; +/// Steps of bisection or golden-section search for each root. +const STEPS: usize = 64; +/// Straight pieces each segment is cut into to check that a path is convex and to find its center. +const FLATTEN: usize = 32; + +/// Which side of a tangent the two outlines lie on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TangentKind { + /// Both on the same side. + External, + /// One on each side. + Internal, +} + +/// One common tangent: the stretch of the line from where it touches the first outline to where +/// it touches the second. Where the outlines touch each other at one point, the stretch is +/// centered on that point and as long as the narrower outline is wide along the line, and `from` +/// is the end with the lower position along the line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tangent { + pub kind: TangentKind, + pub from: Point, + pub to: Point, +} + +/// Why [`Outline::convex`] or [`Outline::ellipse`] cannot take a shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineError { + /// The path is open. + Open, + /// The path bends inward somewhere, or winds around more than once. + NotConvex, + /// No area, or not finite. + Empty, + /// More than [`MAX_TANGENT_SEGMENTS`] segments. + TooComplex, +} + +/// The two outlines are the same, so every line touching one touches the other. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Coincide; + +/// A convex closed outline that [`common_tangents`] takes. +#[derive(Clone, Debug)] +pub enum Outline { + /// The unit circle under an affine map: the center is the map's translation, `m` its linear + /// part (`[a, b, c, d]`, as kurbo orders them). + Ellipse { center: Point, m: [f64; 4] }, + /// A convex closed path's segments, its center of area and the diagonal of its bounds. `ccw` + /// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then + /// comes later in the list as the angle of `n` grows. + Convex { segments: Vec, center: Point, size: f64, ccw: bool }, +} + +impl Outline { + /// The ellipse that `unit` maps the unit circle onto. + pub fn ellipse(unit: Affine) -> Result { + let [a, b, c, d, e, f] = unit.as_coeffs(); + let norm = a.abs().max(b.abs()).max(c.abs()).max(d.abs()); + if !unit.as_coeffs().iter().all(|v| v.is_finite()) || norm <= 0.0 || (a * d - b * c).abs() <= 1e-12 * norm * norm { + return Err(OutlineError::Empty); + } + Ok(Outline::Ellipse { center: Point::new(e, f), m: [a, b, c, d] }) + } + + /// A closed subpath that bends one way all around and winds around once. + pub fn convex(sp: &SubPath) -> Result { + if !sp.closed { + return Err(OutlineError::Open); + } + let n = sp.segment_count(); + if n > MAX_TANGENT_SEGMENTS { + return Err(OutlineError::TooComplex); + } + let segments: Vec = (0..n).map(|k| sp.segment(k)).collect(); + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if segments.iter().any(|s| ![s.p0, s.p1, s.p2, s.p3].into_iter().all(finite)) { + return Err(OutlineError::Empty); + } + let mut pts: Vec = Vec::with_capacity(n * FLATTEN); + for s in &segments { + pts.extend((0..FLATTEN).map(|k| s.eval(k as f64 / FLATTEN as f64))); + } + let (lo, hi) = pts.iter().fold((Point::new(f64::MAX, f64::MAX), Point::new(f64::MIN, f64::MIN)), |(lo, hi), p| { + (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))) + }); + let size = (hi - lo).hypot(); + if !size.is_finite() || size <= 0.0 { + return Err(OutlineError::Empty); + } + // Points closer than this to the one before are dropped: a retracted handle or a segment + // of no length gives no direction. + pts.dedup_by(|b, a| (*b - *a).hypot() <= 1e-9 * size); + while pts.len() > 1 && pts.first().zip(pts.last()).is_some_and(|(f, l)| (*f - *l).hypot() <= 1e-9 * size) { + pts.pop(); + } + let m = pts.len(); + if m < 3 { + return Err(OutlineError::Empty); + } + // Area, center and turns are worked out on the points taken about the first one and + // divided by the size. + let origin = pts[0].to_vec2(); + let unit: Vec = pts.iter().map(|p| (p.to_vec2() - origin) / size).collect(); + let (mut area2, mut cx, mut cy) = (0.0, 0.0, 0.0); + for i in 0..m { + let (p, q) = (unit[i], unit[(i + 1) % m]); + let cross = p.cross(q); + area2 += cross; + cx += (p.x + q.x) * cross; + cy += (p.y + q.y) * cross; + } + if area2.abs() <= 1e-12 { + return Err(OutlineError::Empty); + } + let sign = area2.signum(); + // Every turn the same way (straight runs allowed), and one turn in all. + let mut turning = 0.0; + for i in 0..m { + let (p, q, r) = (unit[(i + m - 1) % m], unit[i], unit[(i + 1) % m]); + let (u, v) = (q - p, r - q); + let cross = u.cross(v) * sign; + if cross < -1e-12 { + return Err(OutlineError::NotConvex); + } + turning += cross.atan2(u.dot(v)); + } + if (turning - TAU).abs() > 1e-6 { + return Err(OutlineError::NotConvex); + } + let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); + if !center.x.is_finite() || !center.y.is_finite() { + return Err(OutlineError::Empty); + } + Ok(Outline::Convex { segments, center, size, ccw: sign > 0.0 }) + } + + /// The outline moved by `d`. + fn shifted(&self, d: Vec2) -> Self { + match self { + Outline::Ellipse { center, m } => Outline::Ellipse { center: *center + d, m: *m }, + Outline::Convex { segments, center, size, ccw } => Outline::Convex { + segments: segments.iter().map(|s| CubicBez::new(s.p0 + d, s.p1 + d, s.p2 + d, s.p3 + d)).collect(), + center: *center + d, + size: *size, + ccw: *ccw, + }, + } + } + + /// Adds to `out` the normal angles where the point of largest `p · n` can pass from one + /// segment to the next: square to each segment's direction at its ends, on both sides. + fn breaks(&self, out: &mut Vec) { + let Outline::Convex { segments, .. } = self else { return }; + let nonzero = |vs: [Vec2; 3]| vs.into_iter().find(|v| v.hypot2() > 0.0); + for s in segments { + let ends = [nonzero([s.p1 - s.p0, s.p2 - s.p0, s.p3 - s.p0]), nonzero([s.p3 - s.p2, s.p3 - s.p1, s.p3 - s.p0])]; + for d in ends.into_iter().flatten() { + let a = d.y.atan2(d.x); + out.extend([a + TAU / 4.0, a - TAU / 4.0]); + } + } + } + + /// The support value at `n` and the segment it is reached on, from every segment. + fn support_scan(&self, n: Vec2) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, .. } => { + let mut best = (f64::MIN, 0); + for (i, s) in segments.iter().enumerate() { + each_extreme(s, n, |_, v| { + if v > best.0 { + best = (v, i); + } + }); + } + best + } + } + } + + /// The support value at `n` and the segment it is reached on, walking on from segment `from`, + /// where the support value was reached at a normal angle a little less than `n`'s. + fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) { + match self { + Outline::Ellipse { .. } => (self.support(n), 0), + Outline::Convex { segments, ccw, .. } => { + let len = segments.len(); + if len == 0 { + return (f64::MIN, 0); + } + let step = if *ccw { 1 } else { len - 1 }; + let value = |i: usize| { + let mut best = f64::MIN; + if let Some(s) = segments.get(i) { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + }; + let mut i = from % len; + let mut v = value(i); + for _ in 0..len { + let j = (i + step) % len; + let w = value(j); + if w < v { + break; + } + (i, v) = (j, w); + } + (v, i) + } + } + } + + /// The center: an ellipse's, or a path's center of area. + pub fn center(&self) -> Point { + match self { + Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center, + } + } + + /// The diagonal of the bounds (an ellipse's: of the box its axes span). + fn size(&self) -> f64 { + match self { + Outline::Ellipse { m, .. } => { + let [a, b, c, d] = *m; + 2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt() + } + Outline::Convex { size, .. } => *size, + } + } + + /// The support value: the largest `p · n` over the outline's points. + fn support(&self, n: Vec2) -> f64 { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => center.to_vec2().dot(n) + Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y).hypot(), + Outline::Convex { segments, .. } => { + let mut best = f64::MIN; + for s in segments { + each_extreme(s, n, |_, v| best = best.max(v)); + } + best + } + } + } + + /// The points of the outline on the line `p · n = h`, its support value: the point where + /// `p · n` is largest, and the ends of any straight side along the line. Another point counts + /// when it lies within `tol` of the line plus `slope` times its distance from that largest + /// point, where `slope` is how far off the normal's angle may be. + fn touching(&self, n: Vec2, h: f64, tol: f64, slope: f64) -> Vec { + match self { + Outline::Ellipse { center, m: [a, b, c, d] } => { + let w = Vec2::new(a * n.x + b * n.y, c * n.x + d * n.y); + let w = w / w.hypot(); + vec![*center + Vec2::new(a * w.x + c * w.y, b * w.x + d * w.y)] + } + Outline::Convex { segments, .. } => { + let mut all = vec![]; + for s in segments { + each_extreme(s, n, |p, v| all.push((p, v))); + } + let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] }; + all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect() + } + } + } +} + +/// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where +/// the curve runs square to `n`) and the value there. +fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { + let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); + f(s.p0, v0); + f(s.p3, v3); + // The derivative of p(t) · n, divided by 3: a quadratic in t. + let (d0, d1, d2) = (v1 - v0, v2 - v1, v3 - v2); + let (qa, qb, qc) = (d0 - 2.0 * d1 + d2, 2.0 * (d1 - d0), d0); + let mut root = |t: f64| { + if t > 0.0 && t < 1.0 { + let p = s.eval(t); + f(p, p.to_vec2().dot(n)); + } + }; + let scale = qa.abs().max(qb.abs()).max(qc.abs()); + if !scale.is_finite() || scale <= 0.0 { + return; + } + if qa.abs() <= 1e-12 * scale { + if qb != 0.0 { + root(-qc / qb); + } + return; + } + let disc = qb * qb - 4.0 * qa * qc; + if disc < 0.0 { + return; + } + // The stable form of the two roots; with `qb` zero the sign is taken as positive, so `q` is + // not zero. + let sign = if qb < 0.0 { -1.0 } else { 1.0 }; + let q = -0.5 * (qb + sign * disc.sqrt()); + root(q / qa); + if q != 0.0 { + root(qc / q); + } +} + +/// The unit vector at `angle` radians. +fn dir(angle: f64) -> Vec2 { + Vec2::new(angle.cos(), angle.sin()) +} + +/// The common tangents of `a` and `b`: the external ones, then the internal ones, each in order of +/// the angle of its normal. Separate outlines have two of each; overlapping ones only external +/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the +/// other none; outlines that touch share one tangent where they touch. +pub fn common_tangents(a: &Outline, b: &Outline) -> Result, Coincide> { + // Worked out about the point between the two centers. + let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0; + let (a, b) = (&a.shifted(-origin), &b.shifted(-origin)); + let size = a.size().max(b.size()).max((a.center() - b.center()).hypot()); + let tol = 1e-9 * size; + // The normal angles sampled: evenly spaced ones, and every angle where the support value of + // either outline passes to another segment. Between two neighboring samples each outline is + // then touched on one segment. + let mut at: Vec = (0..SAMPLES).map(|k| k as f64 * TAU / SAMPLES as f64).collect(); + a.breaks(&mut at); + b.breaks(&mut at); + let mut at: Vec = at.into_iter().map(|t| t.rem_euclid(TAU)).map(|t| if t < TAU { t } else { 0.0 }).collect(); + at.sort_by(f64::total_cmp); + at.dedup_by(|y, x| *y - *x <= 1e-12); + // The segment each outline is touched on at each sample, found by walking around once. + let hints = |o: &Outline, sign: f64| -> Vec { + let mut out = Vec::with_capacity(at.len()); + let mut i = at.first().map_or(0, |t| o.support_scan(dir(*t) * sign).1); + for t in &at { + i = o.support_from(dir(*t) * sign, i).1; + out.push(i); + } + out + }; + let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0)); + let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0); + let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?; + let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?; + let mut out = Vec::with_capacity(external.len() + internal.len()); + for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] { + for root in list { + let t = tangent_at(a, b, kind, dir(root.angle), root.double, size); + out.push(Tangent { from: t.from + origin, to: t.to + origin, ..t }); + } + } + Ok(out) +} + +/// A zero of a support-value difference: the normal's angle, and whether the difference only +/// touches zero there (outlines that touch) rather than crossing it. +#[derive(Clone, Copy, Debug)] +struct Root { + angle: f64, + double: bool, +} + +/// The tangent of `kind` whose normal is `n`: `a` lies where `p · n` is at most the line's value, +/// and `b` on the same side (external) or the other side (internal). `double` when the outlines +/// touch there. +fn tangent_at(a: &Outline, b: &Outline, kind: TangentKind, n: Vec2, double: bool, size: f64) -> Tangent { + // The rounding allowed in `p · n` grows with each outline's own size and its distance from the + // origin. + let rounding = |o: &Outline| 1e-12 * o.size() + 1e-14 * (o.center().to_vec2().hypot() + o.size()); + let (tol_a, tol_b) = (rounding(a), rounding(b)); + // Bisection finds a simple root's angle to about the rounding of the support values; the + // golden-section search finds a double root's to about 1e-8 radians. + let slope = if double { 1e-7 } else { 1e-10 }; + let ha = a.support(n); + let (on_a, on_b) = match kind { + TangentKind::External => (a.touching(n, ha, tol_a, slope), b.touching(n, b.support(n), tol_b, slope)), + TangentKind::Internal => (a.touching(n, ha, tol_a, slope), b.touching(-n, b.support(-n), tol_b, slope)), + }; + // Positions along the line, which runs square to `n` through `n * ha`. + let t = Vec2::new(-n.y, n.x); + let along = |p: &Point| p.to_vec2().dot(t); + let mean = |v: &[Point]| v.iter().map(along).sum::() / v.len().max(1) as f64; + let all = on_a.iter().chain(&on_b).map(along); + let (lo, hi) = all.fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(s), hi.max(s))); + let at = |s: f64| (n * ha + t * s).to_point(); + // A double root's angle is found less exactly than a simple one's, so touching points may + // stand a little apart. + let (from, to) = if double && hi - lo <= 1e-6 * size { + // Touching at one point: the narrower outline's width along the line, centered there. + let width = [a, b].map(|o| o.support(t) + o.support(-t)).into_iter().fold(f64::MAX, f64::min); + let mid = (lo + hi) / 2.0; + (mid - width / 2.0, mid + width / 2.0) + } else if mean(&on_a) <= mean(&on_b) { + (lo, hi) + } else { + (hi, lo) + }; + Tangent { kind, from: at(from), to: at(to) } +} + +/// The angles in `[0, 2π)` where `f` (periodic) is zero, within `tol`. An interval where it stays +/// zero (outlines that meet at a corner or along a shared stretch) gives the angle at its middle, +/// as a double root. +/// +/// `at` holds the sampled angles in increasing order, in `[0, 2π)`; `f(t, k)` is `f` at an angle +/// `t` at or after sample `k` and before the sample two on. +fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result, Coincide> { + let n = at.len(); + if n < 3 { + return Err(Coincide); + } + // The angle of sample `k + j`, counted on from sample `k` past 2π. + let ang = |k: usize, j: usize| at.get((k + j) % n).copied().unwrap_or(0.0) + TAU * ((k + j) / n) as f64; + let v: Vec = (0..n).map(|k| f(ang(k, 0), k)).collect(); + let val = |k: usize| v.get(k % n).copied().unwrap_or(0.0); + let zero = |x: f64| x.abs() <= tol; + let Some(start) = v.iter().position(|x| !zero(*x)) else { return Err(Coincide) }; + let simple = |angle: f64| Root { angle, double: false }; + let mut out = vec![]; + // Between `lo` (sample `k`) and `hi`, where `s * f` is positive at both ends: the least of + // `s * f`, a double root where it reaches zero, two roots where it goes past it, none where it + // stays above. + let dip = |out: &mut Vec, s: f64, k: usize, lo: f64, hi: f64| { + let g = |t: f64| f(t, k); + let (t, least) = golden(&|t| s * g(t), lo, hi); + if least < -tol { + out.push(simple(bisect(&g, lo, t))); + out.push(simple(bisect(&g, t, hi))); + } else if least <= tol { + out.push(Root { angle: t, double: true }); + } + }; + for i in 0..n { + let k = (start + i) % n; + let (prev, next) = ((k + n - 1) % n, k + 1); + let theta = ang(k, 0); + if zero(val(k)) { + continue; + } + if zero(val(next)) { + let len = (1..n).take_while(|j| zero(val(k + j))).count(); + if len == 1 { + // One sample on zero: a crossing when the samples beside it differ in sign, else a + // dip between them. + let (lo, hi) = (theta, ang(k, 2)); + let s = val(k).signum(); + if val(k + 2).signum() == s { + dip(&mut out, s, k, lo, hi); + } else { + out.push(simple(bisect(&|t| f(t, k), lo, hi))); + } + } else { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } + continue; + } + if val(k).signum() != val(next).signum() { + out.push(simple(bisect(&|t| f(t, k), theta, ang(k, 1)))); + continue; + } + // A sampled minimum of |f|: the curve may dip to zero (a double root), or across it and + // back (two roots), between the neighboring samples. + let (vp, vk, vn) = (val(prev), val(k), val(next)); + if !zero(vp) && vp.signum() == vk.signum() && vk.abs() < vp.abs() && vk.abs() <= vn.abs() { + let lo = if k == 0 { ang(prev, 0) - TAU } else { ang(prev, 0) }; + dip(&mut out, vk.signum(), prev, lo, ang(k, 1)); + } + } + let mut out: Vec = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); + out.sort_by(|a, b| a.angle.total_cmp(&b.angle)); + out.dedup_by(|b, a| { + let same = (b.angle - a.angle).abs() < 1e-7; + a.double |= same && b.double; + same + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.angle + TAU - l.angle < 1e-7) + && let Some(last) = out.pop() + && let Some(first) = out.first_mut() + { + first.double |= last.double; + } + Ok(out) +} + +/// A root of `f` between `lo` and `hi`, where it has opposite signs. +fn bisect(f: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> f64 { + let s = f(lo).signum(); + for _ in 0..STEPS { + let mid = (lo + hi) / 2.0; + if f(mid).signum() == s { + lo = mid; + } else { + hi = mid; + } + } + (lo + hi) / 2.0 +} + +/// Where `g` is least between `lo` and `hi` (taken as having one minimum there), and its value. +fn golden(g: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64) -> (f64, f64) { + let r = (5f64.sqrt() - 1.0) / 2.0; + let (mut x1, mut x2) = (hi - r * (hi - lo), lo + r * (hi - lo)); + let (mut g1, mut g2) = (g(x1), g(x2)); + for _ in 0..STEPS { + if g1 < g2 { + hi = x2; + (x2, g2) = (x1, g1); + x1 = hi - r * (hi - lo); + g1 = g(x1); + } else { + lo = x1; + (x1, g1) = (x2, g2); + x2 = lo + r * (hi - lo); + g2 = g(x2); + } + } + let t = (lo + hi) / 2.0; + (t, g(t)) +} + +#[cfg(test)] +mod tests { + use kurbo::Rect; + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(cx: f64, cy: f64, r: f64) -> Outline { + Outline::ellipse(Affine::new([r, 0.0, 0.0, r, cx, cy])).unwrap() + } + + /// An ellipse with semi-axes `rx`, `ry`, turned `deg` degrees, centered at (`cx`, `cy`). + fn ellipse_map(cx: f64, cy: f64, rx: f64, ry: f64, deg: f64) -> Affine { + Affine::translate((cx, cy)) * Affine::rotate(deg.to_radians()) * Affine::scale_non_uniform(rx, ry) + } + + /// Whether `t` has its two ends at `p` and `q`, in either order. + fn ends_at(t: &Tangent, p: Point, q: Point) -> bool { + ends_within(t, p, q, 1e-7) + } + + /// [`ends_at`] within `eps`: the angle of a tangent where outlines touch (a double root) is + /// found to about 1e-8 radians. + fn ends_within(t: &Tangent, p: Point, q: Point, eps: f64) -> bool { + let near = |a: Point, b: Point| (a - b).hypot() < eps; + (near(t.from, p) && near(t.to, q)) || (near(t.from, q) && near(t.to, p)) + } + + /// Checks `t` against dense samples of the two outlines, without support values: each lies on + /// one side of the line (the same side for an external tangent, opposite ones for an internal + /// one) and comes within `eps` of it. + fn check_against_samples(t: &Tangent, a: &[Point], b: &[Point], eps: f64) { + let d = t.to - t.from; + let n = Vec2::new(-d.y, d.x) / d.hypot(); + let side = |pts: &[Point]| { + let dist: Vec = pts.iter().map(|p| (*p - t.from).dot(n)).collect(); + let (lo, hi) = dist.iter().fold((f64::MAX, f64::MIN), |(lo, hi), s| (lo.min(*s), hi.max(*s))); + assert!(lo > -eps || hi < eps, "the line crosses the outline: {lo} .. {hi} ({t:?})"); + assert!(lo.abs() < eps || hi.abs() < eps, "the line misses the outline: {lo} .. {hi} ({t:?})"); + if hi < eps { -1.0 } else { 1.0 } + }; + let (sa, sb) = (side(a), side(b)); + match t.kind { + TangentKind::External => assert_eq!(sa, sb, "{t:?}"), + TangentKind::Internal => assert_ne!(sa, sb, "{t:?}"), + } + } + + fn sample_ellipse(m: Affine, count: usize) -> Vec { + (0..count).map(|k| m * Point::new((TAU * k as f64 / count as f64).cos(), (TAU * k as f64 / count as f64).sin())).collect() + } + + fn sample_path(sp: &SubPath, per_segment: usize) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..per_segment).map(move |j| sp.segment(k).eval(j as f64 / per_segment as f64))).collect() + } + + #[test] + fn two_circles_have_four_tangents_at_the_closed_form_points() { + let (c1, r1, c2, r2) = (Point::new(0.0, 0.0), 10.0, Point::new(100.0, 0.0), 20.0); + let all = common_tangents(&circle(c1.x, c1.y, r1), &circle(c2.x, c2.y, r2)).unwrap(); + assert_eq!(all.len(), 4, "{all:?}"); + // External: (c1 - c2) · n = r2 - r1, so n.x = -0.1; the points are c + r n on each. + // Internal: (c1 - c2) · n = -(r1 + r2), so n.x = 0.3; c1 + r1 n and c2 - r2 n. + for (kind, nx) in [(TangentKind::External, -0.1f64), (TangentKind::Internal, 0.3)] { + for sy in [1.0, -1.0] { + let n = Vec2::new(nx, sy * (1.0 - nx * nx).sqrt()); + let far = if kind == TangentKind::External { c2 + n * r2 } else { c2 - n * r2 }; + let found = all.iter().filter(|t| t.kind == kind && ends_at(t, c1 + n * r1, far)).count(); + assert_eq!(found, 1, "{kind:?} {n:?} in {all:?}"); + } + } + // Each runs from the first outline to the second. + assert!(all.iter().all(|t| (t.from - c1).hypot() < (t.to - c1).hypot())); + } + + #[test] + fn turned_ellipses_match_an_independent_numeric_solution() { + let (ma, mb) = (ellipse_map(0.0, 0.0, 40.0, 15.0, 30.0), ellipse_map(150.0, 60.0, 25.0, 60.0, -70.0)); + let all = common_tangents(&Outline::ellipse(ma).unwrap(), &Outline::ellipse(mb).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_ellipse(ma, 5_000), sample_ellipse(mb, 5_000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // A brute-force scan of the normal's angle with support values read off the samples finds + // the same normals. + let support = |pts: &[Point], n: Vec2| pts.iter().map(|p| p.to_vec2().dot(n)).fold(f64::MIN, f64::max); + let scan = |f: &dyn Fn(Vec2) -> f64| { + let steps = 7_200; + let g = |k: usize| f(dir(TAU * k as f64 / steps as f64)); + (0..steps).filter(|&k| g(k).signum() != g((k + 1) % steps).signum()).map(|k| TAU * (k as f64 + 0.5) / steps as f64).collect::>() + }; + let ext = scan(&|n| support(&sa, n) - support(&sb, n)); + let int = scan(&|n| support(&sa, n) + support(&sb, -n)); + for (kind, expected) in [(TangentKind::External, ext), (TangentKind::Internal, int)] { + assert_eq!(expected.len(), 2); + for angle in expected { + let n = dir(angle); + let hit = all.iter().filter(|t| t.kind == kind).any(|t| { + let d = t.to - t.from; + let m = Vec2::new(d.y, -d.x) / d.hypot(); + m.dot(n).abs() > 1.0 - 1e-6 + }); + assert!(hit, "{kind:?} normal at {angle} in {all:?}"); + } + } + } + + #[test] + fn nested_overlapping_and_touching_circles() { + // One inside the other: none. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(5.0, 0.0, 10.0)).unwrap().is_empty()); + // Overlapping: the two external ones only. + let over = common_tangents(&circle(0.0, 0.0, 30.0), &circle(40.0, 0.0, 30.0)).unwrap(); + assert_eq!(over.len(), 2); + assert!(over.iter().all(|t| t.kind == TangentKind::External)); + assert!(over.iter().any(|t| ends_at(t, Point::new(0.0, 30.0), Point::new(40.0, 30.0)))); + // Touching from outside at (10, 0): two external ones and one shared internal one, square to + // the line of centers, as long as the smaller circle is wide. + let touch = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0, 0.0, 20.0)).unwrap(); + assert_eq!(touch.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{touch:?}"); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(ends_within(shared[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{shared:?}"); + // Touching along a direction between two sampled normals: the sampled minimum is refined + // down to the double root. + let along = dir(0.1234); + let off = common_tangents(&circle(0.0, 0.0, 10.0), &circle(30.0 * along.x, 30.0 * along.y, 20.0)).unwrap(); + assert_eq!(off.iter().filter(|t| t.kind == TangentKind::Internal).count(), 1, "{off:?}"); + // A hair apart: two internal tangents less than a sample apart, both kept. + let d = 30.000_01; + let near_miss = common_tangents(&circle(0.0, 0.0, 10.0), &circle(d * along.x, d * along.y, 20.0)).unwrap(); + assert_eq!(near_miss.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{near_miss:?}"); + // Inside with a clearance of 1e-6: no tangent. + assert!(common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0 - 1e-6, 0.0, 10.0)).unwrap().is_empty()); + // Equal circles a hair apart: the two external tangents run between their real contact + // points, that hair apart, not as a touching tangent. + let hair = common_tangents(&circle(0.0, 0.0, 30.0), &circle(1e-5, 0.0, 30.0)).unwrap(); + assert_eq!(hair.len(), 2, "{hair:?}"); + assert!(hair.iter().all(|t| ((t.to - t.from).hypot() - 1e-5).abs() < 1e-9), "{hair:?}"); + // Touching from inside at (50, 0): the one shared external tangent. + let inside = common_tangents(&circle(0.0, 0.0, 50.0), &circle(40.0, 0.0, 10.0)).unwrap(); + assert_eq!(inside.len(), 1, "{inside:?}"); + assert!(ends_within(&inside[0], Point::new(50.0, -10.0), Point::new(50.0, 10.0), 1e-5), "{inside:?}"); + } + + #[test] + fn a_convex_bezier_blob_and_an_ellipse_path() { + // A lopsided convex blob of four curves. + let a = |x: f64, y: f64, ix: f64, iy: f64, ox: f64, oy: f64| { + vectorcraft_geom::Anchor::with_handles(Point::new(x, y), Point::new(ix, iy), Point::new(ox, oy)) + }; + let blob = SubPath::new( + vec![ + a(0.0, 40.0, 0.0, 70.0, 0.0, 10.0), + a(50.0, 0.0, 20.0, 0.0, 90.0, 0.0), + a(110.0, 50.0, 110.0, 20.0, 110.0, 90.0), + a(40.0, 100.0, 80.0, 100.0, 10.0, 100.0), + ], + true, + ); + let round = shapes::ellipse(Rect::new(200.0, 150.0, 260.0, 230.0)).subpaths[0].clone(); + let (oa, ob) = (Outline::convex(&blob).unwrap(), Outline::convex(&round).unwrap()); + let all = common_tangents(&oa, &ob).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 2, "{all:?}"); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 2, "{all:?}"); + let (sa, sb) = (sample_path(&blob, 4000), sample_path(&round, 4000)); + for t in &all { + check_against_samples(t, &sa, &sb, 1e-3); + } + // The path's center is its center of area: the ellipse path's is its box's center. + assert!((ob.center() - Point::new(230.0, 190.0)).hypot() < 1e-6, "{:?}", ob.center()); + } + + #[test] + fn flat_sides_give_the_whole_stretch_they_touch() { + let square = + |x: f64| SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)], true); + let all = common_tangents(&Outline::convex(&square(0.0)).unwrap(), &Outline::convex(&square(30.0)).unwrap()).unwrap(); + let ext: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{all:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 0.0), Point::new(40.0, 0.0))), "{ext:?}"); + assert!(ext.iter().any(|t| ends_at(t, Point::new(0.0, 10.0), Point::new(40.0, 10.0))), "{ext:?}"); + // Far apart, each diamond is still touched only at its top corner. + let diamond = + |x: f64| SubPath::polyline(&[Point::new(x - 5.0, 0.0), Point::new(x, -5.0), Point::new(x + 5.0, 0.0), Point::new(x, 5.0)], true); + let far = common_tangents(&Outline::convex(&diamond(0.0)).unwrap(), &Outline::convex(&diamond(1e9)).unwrap()).unwrap(); + let top = far.iter().find(|t| t.kind == TangentKind::External && t.from.y > 0.0).unwrap(); + assert!(ends_within(top, Point::new(0.0, 5.0), Point::new(1e9, 5.0), 1e-3), "{far:?}"); + // Far from the origin the center of area and the tangents come out as near it. + let o = 1e9; + let away = |x: f64| SubPath::polyline(&[(x, o), (x + 10.0, o), (x + 10.0, o + 10.0), (x, o + 10.0)].map(Point::from), true); + let (sa, sb) = (Outline::convex(&away(o)).unwrap(), Outline::convex(&away(o + 30.0)).unwrap()); + assert!((sa.center() - Point::new(o + 5.0, o + 5.0)).hypot() < 1e-6, "{:?}", sa.center()); + let shifted = common_tangents(&sa, &sb).unwrap(); + assert!(shifted.iter().any(|t| ends_within(t, Point::new(o, o), Point::new(o + 40.0, o), 1e-6)), "{shifted:?}"); + // The internal ones are the diagonals between the near corners. + let int: Vec<_> = all.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(int.len(), 2, "{all:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 0.0), Point::new(30.0, 10.0))), "{int:?}"); + assert!(int.iter().any(|t| ends_at(t, Point::new(10.0, 10.0), Point::new(30.0, 0.0))), "{int:?}"); + // Squares meeting at the corner (10, 10): every line through the corner between their + // sides touches both, and the one internal line drawn is the one at the middle of those + // directions, as long as a square is wide along it. + let box_at = |x: f64, y: f64| { + SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y), Point::new(x + 10.0, y + 10.0), Point::new(x, y + 10.0)], true) + }; + let corner = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(10.0, 10.0)).unwrap()).unwrap(); + let shared: Vec<_> = corner.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{corner:?}"); + assert!(ends_within(shared[0], Point::new(5.0, 15.0), Point::new(15.0, 5.0), 1e-6), "{shared:?}"); + // Sides 1e-6 off parallel: each line ends at the corners it touches, not at the corners + // of the sides it nearly lies along. + let tilted = common_tangents(&Outline::convex(&box_at(0.0, 0.0)).unwrap(), &Outline::convex(&box_at(30.0, -1e-6)).unwrap()).unwrap(); + let ext: Vec<_> = tilted.iter().filter(|t| t.kind == TangentKind::External).collect(); + assert_eq!(ext.len(), 2, "{tilted:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(10.0, 10.0), Point::new(40.0, 10.0 - 1e-6), 1e-6)), "{ext:?}"); + assert!(ext.iter().any(|t| ends_within(t, Point::new(0.0, 0.0), Point::new(30.0, -1e-6), 1e-6)), "{ext:?}"); + } + + /// A circle path of four curves, radius 100 about the origin, with an anchor at (100, 0). + fn circle_path() -> SubPath { + shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).subpaths[0].clone() + } + + /// The point of `sp` where `p · n` is largest. + fn peak(sp: &SubPath, n: Vec2) -> Point { + let mut best = (Point::ORIGIN, f64::MIN); + for k in 0..sp.segment_count() { + each_extreme(&sp.segment(k), n, |p, v| { + if v > best.1 { + best = (p, v); + } + }); + } + best.0 + } + + #[test] + fn a_curve_is_touched_only_at_its_peak_beside_an_anchor() { + // The line touches the circle path 5e-4 radians from its anchor at (100, 0), where the + // anchor lies about 1.25e-5 inside the line: the line still ends at the peak, not at the + // anchor 0.05 along it. + let path = circle_path(); + let n = dir(5e-4); + let away = Vec2::new(n.y, -n.x) * 300.0; + let a = Outline::convex(&path).unwrap(); + let all = common_tangents(&a, &a.shifted(away)).unwrap(); + let top = all.iter().find(|t| t.kind == TangentKind::External && (t.from.to_vec2().dot(n) - 100.0).abs() < 1e-3).unwrap(); + let p = peak(&path, n); + assert!(ends_within(top, p, p + away, 1e-6), "{top:?} {p:?}"); + // An exact circle touching the path there from outside: one shared internal line, as long + // as that circle is wide, not a stub running to the anchor. + let b = circle(p.x + 20.0 * n.x, p.y + 20.0 * n.y, 20.0); + let touch = common_tangents(&a, &b).unwrap(); + let shared: Vec<_> = touch.iter().filter(|t| t.kind == TangentKind::Internal).collect(); + assert_eq!(shared.len(), 1, "{touch:?}"); + assert!(((shared[0].to - shared[0].from).hypot() - 40.0).abs() < 1e-3, "{shared:?}"); + assert!(((shared[0].from.midpoint(shared[0].to)) - p).hypot() < 1e-3, "{shared:?}"); + } + + #[test] + fn outlines_crossing_more_often_than_the_even_samples_keep_every_tangent() { + // Two regular 400-gons about one center, one turned half a step: their outlines cross 800 + // times, and an external tangent runs across each crossing. + let gon = |turn: f64| { + let pts: Vec = (0..400).map(|k| (dir(turn + TAU * k as f64 / 400.0) * 100.0).to_point()).collect(); + SubPath::polyline(&pts, true) + }; + let all = common_tangents(&Outline::convex(&gon(0.0)).unwrap(), &Outline::convex(&gon(TAU / 800.0)).unwrap()).unwrap(); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::External).count(), 800); + assert_eq!(all.iter().filter(|t| t.kind == TangentKind::Internal).count(), 0); + // Each runs between a corner of one and the next corner of the other, about 0.785 apart. + assert!(all.iter().all(|t| ((t.to - t.from).hypot() - 200.0 * (TAU / 1600.0).sin()).abs() < 1e-6), "{:?}", all.first()); + } + + #[test] + fn a_curve_peaking_inside_a_segment_is_measured_at_its_peak() { + // p(t) · n has the control values 0, 0.25, 0.5, -0.25: its derivative's linear term is + // zero, and the peak, 0.25 at t = 0.5, lies inside the segment. + let s = CubicBez::new((0.0, 0.0), (1.0, 0.25), (2.0, 0.5), (3.0, -0.25)); + let mut best = f64::MIN; + each_extreme(&s, Vec2::new(0.0, 1.0), |_, v| best = best.max(v)); + assert!((best - 0.25).abs() < 1e-12, "{best}"); + } + + #[test] + fn open_concave_empty_and_identical_outlines_are_refused() { + let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); + assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); + let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); + assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A square traced twice around winds around twice. + let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); + let flat = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(20.0, 0.0)], true); + assert_eq!(Outline::convex(&flat).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::scale_non_uniform(10.0, 0.0)).err(), Some(OutlineError::Empty)); + assert_eq!(Outline::ellipse(Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0])).err(), Some(OutlineError::Empty)); + let many: Vec = (0..=MAX_TANGENT_SEGMENTS).map(|k| dir(TAU * k as f64 / (MAX_TANGENT_SEGMENTS + 1) as f64).to_point()).collect(); + assert_eq!(Outline::convex(&SubPath::polyline(&many, true)).err(), Some(OutlineError::TooComplex)); + // A square 1e110 wide has a finite center. + let huge = SubPath::polyline(&[(0.0, 0.0), (1e110, 0.0), (1e110, 1e110), (0.0, 1e110)].map(Point::from), true); + let center = Outline::convex(&huge).unwrap().center(); + assert!((center - Point::new(5e109, 5e109)).hypot() < 1e98, "{center:?}"); + assert_eq!(common_tangents(&circle(1.0, 2.0, 3.0), &circle(1.0, 2.0, 3.0)), Err(Coincide)); + } +} diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index bfbcf0d5b3..41e8f6efed 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -30,6 +30,10 @@ pub const ID: &str = "anchorInspector"; const COUNT: &str = "anchor-inspector-count"; /// The tools' options dialog. pub const KIND: &str = "pathToolOptions"; +/// Common Tangents' command, whose menu item opens the command dialog with a Preview. +pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; +/// The kinds of tangent Common Tangents' `tangents` picks, and their labels. +pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; /// 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; @@ -70,6 +74,7 @@ pub fn menu() -> Vec { Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), + Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), ] } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index db4b39b6fc..de01be5b7d 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -258,3 +258,73 @@ fn effect_path_effects_lists_the_live_effects_and_their_dialogs_pick_from_their_ assert!(options.iter().all(|(_, value)| doc.params.contains(&format!("\"{value}\""))), "{effect} {key}"); } } + +/// Object › Plug-ins › Path Precision Tools › Common Tangents… opens the command dialog on all +/// tangents without the centerline, Preview off. With Preview on the lines show on the canvas; +/// Cancel takes them away with no step of history, and OK keeps them as one step. Nested circles +/// change nothing and say why. +#[test] +fn common_tangents_previews_cancels_and_runs_on_ok() { + let mut app = app(); + let circle = |app: &mut VectorcraftApp, x: f64, r: f64| { + app.run("shape.ellipse", json!({"x": x - r, "y": 150.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (circle(&mut app, 60.0, 20.0), circle(&mut app, 220.0, 40.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::COMMON_TANGENTS.to_string(), "Common Tangents".to_string())); + assert_eq!((d.str("tangents"), d.bool("centerline"), d.bool("preview")), ("all".to_string(), false, false)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Common Tangents", "Tangents", "All", "Centerline", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + // Each kind the list offers is one the command takes. + for (_, kind) in super::TANGENT_KINDS { + assert!(vectorcraft_engine::check_params(super::COMMON_TANGENTS, &json!({"tangents": kind})).is_ok(), "{kind}"); + } + assert_eq!(count(&app), nodes, "no preview without the checkbox"); + + // Preview on: the four lines are on the canvas. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 4, "previewed"); + // External only, with the centerline: two lines and the centerline. + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "tangents".into(), json!("external")); + crate::dialogs::set_field(d, "centerline".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 3, "previewed again"); + + // Cancel: as it was, with no step of history. + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel takes the preview away"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + // OK: one step. + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(steps(&app), n + 1, "one undo step"); + assert_eq!(count(&app), nodes + 4); + + // A circle inside another: nothing changes, and a message says why. + let inner = circle(&mut app, 220.0, 10.0); + app.run("select.set", json!({"ids": [b, inner]})).unwrap(); + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes)); + assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 7afe37ec0b..9e918fe092 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -66,8 +66,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and -/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes. (Cancel rolls a -/// preview back whichever dialog started it.) +/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path +/// Precision Tools › Common Tangents. (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -77,7 +77,8 @@ fn previews(d: &Dialog) -> bool { | crate::addons::image::COLOR_MASK | crate::addons::cutting::WEED | crate::addons::cutting::BANNER - | crate::addons::cutting::NEST => true, + | crate::addons::cutting::NEST + | crate::addons::pathtools::COMMON_TANGENTS => true, _ => false, } } @@ -163,6 +164,7 @@ fn order(command: &str) -> &'static [&'static str] { } crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], + crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], _ => &[], } } @@ -179,6 +181,7 @@ fn choices(command: &str, key: &str) -> Option { ("text.areaOptions", "firstBaseline") => Some(FIRST_BASELINE), ("text.areaOptions", "verticalAlign") => Some(VERTICAL_ALIGN), (crate::addons::cutting::WEED, "direction") => Some(crate::addons::cutting::WEED_DIRECTIONS), + (crate::addons::pathtools::COMMON_TANGENTS, "tangents") => Some(crate::addons::pathtools::TANGENT_KINDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "background") => Some(crate::addons::image::BACKGROUNDS), (crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK, "match") => Some(crate::addons::image::MATCHES), _ => None, diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a6a69d9100..759e7dcfcd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6729,6 +6729,22 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общи допирателни… + Common Tangents Общи допирателни + Tangents Допирателни + Centerline Централна линия + External Външни + Internal Вътрешни +@msg select two closed paths изберете два затворени пътя +@msg a selected path is open избран път е отворен +@msg a selected path is not convex избран път не е изпъкнал +@msg a selected path has no area избран път няма площ +@msg a selected path has more than 10000 segments избран път има повече от 10000 сегмента +@msg the two paths have the same outline двата пътя имат еднакъв контур +@msg One path lies inside the other, so they have no common tangents Единият път е вътре в другия, затова нямат общи допирателни +@msg The paths overlap, so they have no internal tangents Пътищата се припокриват, затова нямат вътрешни допирателни +@msg One path lies inside the other, so they have no internal tangents Единият път е вътре в другия, затова нямат вътрешни допирателни # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разширяване на тиретата в пътища @msg select paths with dashed strokes to expand изберете пътища с прекъснат щрих за разширяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5da48b6cff..eefcdfe51d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6781,6 +6781,22 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Zajedničke tangente… + Common Tangents Zajedničke tangente + Tangents Tangente + Centerline Središnja linija + External Vanjske + Internal Unutrašnje +@msg select two closed paths odaberite dvije zatvorene putanje +@msg a selected path is open odabrana putanja je otvorena +@msg a selected path is not convex odabrana putanja nije konveksna +@msg a selected path has no area odabrana putanja nema površinu +@msg a selected path has more than 10000 segments odabrana putanja ima više od 10000 segmenata +@msg the two paths have the same outline obje putanje imaju isti obris +@msg One path lies inside the other, so they have no common tangents Jedna putanja leži unutar druge, pa nemaju zajedničkih tangenti +@msg The paths overlap, so they have no internal tangents Putanje se preklapaju, pa nemaju unutrašnjih tangenti +@msg One path lies inside the other, so they have no internal tangents Jedna putanja leži unutar druge, pa nemaju unutrašnjih tangenti # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Proširi crtice u putanje @msg select paths with dashed strokes to expand odaberite putanje s isprekidanim potezom za proširivanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e861e61fec..e2d6dd2c59 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7361,6 +7361,22 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangents comunes… + Common Tangents Tangents comunes + Tangents Tangents + Centerline Línia central + External Externes + Internal Internes +@msg select two closed paths seleccioneu dos camins tancats +@msg a selected path is open un camí seleccionat és obert +@msg a selected path is not convex un camí seleccionat no és convex +@msg a selected path has no area un camí seleccionat no té àrea +@msg a selected path has more than 10000 segments un camí seleccionat té més de 10000 segments +@msg the two paths have the same outline els dos camins tenen el mateix contorn +@msg One path lies inside the other, so they have no common tangents Un camí és dins de l’altre, per tant no tenen tangents comunes +@msg The paths overlap, so they have no internal tangents Els camins se superposen, per tant no tenen tangents internes +@msg One path lies inside the other, so they have no internal tangents Un camí és dins de l’altre, per tant no tenen tangents internes # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandeix els guions en camins @msg select paths with dashed strokes to expand seleccioneu camins amb traç discontinu per expandir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1a4d359b93..a45d114226 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7365,6 +7365,22 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Společné tečny… + Common Tangents Společné tečny + Tangents Tečny + Centerline Středová čára + External Vnější + Internal Vnitřní +@msg select two closed paths vyberte dvě uzavřené cesty +@msg a selected path is open vybraná cesta je otevřená +@msg a selected path is not convex vybraná cesta není konvexní +@msg a selected path has no area vybraná cesta nemá žádnou plochu +@msg a selected path has more than 10000 segments vybraná cesta má více než 10000 segmentů +@msg the two paths have the same outline obě cesty mají stejný obrys +@msg One path lies inside the other, so they have no common tangents Jedna cesta leží uvnitř druhé, takže nemají žádné společné tečny +@msg The paths overlap, so they have no internal tangents Cesty se překrývají, takže nemají žádné vnitřní tečny +@msg One path lies inside the other, so they have no internal tangents Jedna cesta leží uvnitř druhé, takže nemají žádné vnitřní tečny # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozložit čárky na cesty @msg select paths with dashed strokes to expand vyberte cesty s čárkovaným tahem k rozložení diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 723766f020..61366b0a61 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7414,6 +7414,22 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Fælles tangenter… + Common Tangents Fælles tangenter + Tangents Tangenter + Centerline Midterlinje + External Ydre + Internal Indre +@msg select two closed paths vælg to lukkede stier +@msg a selected path is open en valgt sti er åben +@msg a selected path is not convex en valgt sti er ikke konveks +@msg a selected path has no area en valgt sti har intet areal +@msg a selected path has more than 10000 segments en valgt sti har mere end 10000 segmenter +@msg the two paths have the same outline de to stier har samme omrids +@msg One path lies inside the other, so they have no common tangents Den ene sti ligger inden i den anden, så de har ingen fælles tangenter +@msg The paths overlap, so they have no internal tangents Stierne overlapper, så de har ingen indre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ene sti ligger inden i den anden, så de har ingen indre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Udvid streger til stier @msg select paths with dashed strokes to expand vælg stier med stiplet streg, der skal udvides diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 21a07e09e5..900e7a9f44 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6956,6 +6956,22 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeinsame Tangenten… + Common Tangents Gemeinsame Tangenten + Tangents Tangenten + Centerline Mittellinie + External Äußere + Internal Innere +@msg select two closed paths wählen Sie zwei geschlossene Pfade aus +@msg a selected path is open ein ausgewählter Pfad ist offen +@msg a selected path is not convex ein ausgewählter Pfad ist nicht konvex +@msg a selected path has no area ein ausgewählter Pfad hat keine Fläche +@msg a selected path has more than 10000 segments ein ausgewählter Pfad hat mehr als 10000 Segmente +@msg the two paths have the same outline die beiden Pfade haben denselben Umriss +@msg One path lies inside the other, so they have no common tangents Ein Pfad liegt im anderen, daher haben sie keine gemeinsamen Tangenten +@msg The paths overlap, so they have no internal tangents Die Pfade überlappen sich, daher haben sie keine inneren Tangenten +@msg One path lies inside the other, so they have no internal tangents Ein Pfad liegt im anderen, daher haben sie keine inneren Tangenten # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Striche in Pfade umwandeln @msg select paths with dashed strokes to expand wählen Sie Pfade mit gestrichelter Kontur zum Umwandeln aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index ebd167f397..473ebd370d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7334,6 +7334,22 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Κοινές εφαπτόμενες… + Common Tangents Κοινές εφαπτόμενες + Tangents Εφαπτόμενες + Centerline Κεντρική γραμμή + External Εξωτερικές + Internal Εσωτερικές +@msg select two closed paths επιλέξτε δύο κλειστές διαδρομές +@msg a selected path is open μια επιλεγμένη διαδρομή είναι ανοιχτή +@msg a selected path is not convex μια επιλεγμένη διαδρομή δεν είναι κυρτή +@msg a selected path has no area μια επιλεγμένη διαδρομή δεν έχει εμβαδόν +@msg a selected path has more than 10000 segments μια επιλεγμένη διαδρομή έχει περισσότερα από 10000 τμήματα +@msg the two paths have the same outline οι δύο διαδρομές έχουν το ίδιο περίγραμμα +@msg One path lies inside the other, so they have no common tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν κοινές εφαπτόμενες +@msg The paths overlap, so they have no internal tangents Οι διαδρομές επικαλύπτονται, επομένως δεν έχουν εσωτερικές εφαπτόμενες +@msg One path lies inside the other, so they have no internal tangents Η μία διαδρομή βρίσκεται μέσα στην άλλη, επομένως δεν έχουν εσωτερικές εφαπτόμενες # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Επέκταση παυλών σε διαδρομές @msg select paths with dashed strokes to expand επιλέξτε διαδρομές με διακεκομμένο περίγραμμα για επέκταση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 27d7d4aaf8..7b8d2ff82c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7322,6 +7322,22 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comunes… + Common Tangents Tangentes comunes + Tangents Tangentes + Centerline Línea central + External Externas + Internal Internas +@msg select two closed paths seleccione dos trazados cerrados +@msg a selected path is open un trazado seleccionado está abierto +@msg a selected path is not convex un trazado seleccionado no es convexo +@msg a selected path has no area un trazado seleccionado no tiene área +@msg a selected path has more than 10000 segments un trazado seleccionado tiene más de 10000 segmentos +@msg the two paths have the same outline los dos trazados tienen el mismo contorno +@msg One path lies inside the other, so they have no common tangents Un trazado está dentro del otro, por lo que no tienen tangentes comunes +@msg The paths overlap, so they have no internal tangents Los trazados se superponen, por lo que no tienen tangentes internas +@msg One path lies inside the other, so they have no internal tangents Un trazado está dentro del otro, por lo que no tienen tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir guiones en trazados @msg select paths with dashed strokes to expand seleccione trazados con trazo discontinuo para expandir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3f29fd7f7a..d5f6177991 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7410,6 +7410,22 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Yhteiset tangentit… + Common Tangents Yhteiset tangentit + Tangents Tangentit + Centerline Keskilinja + External Ulkoiset + Internal Sisäiset +@msg select two closed paths valitse kaksi suljettua polkua +@msg a selected path is open valittu polku on avoin +@msg a selected path is not convex valittu polku ei ole kupera +@msg a selected path has no area valitulla polulla ei ole pinta-alaa +@msg a selected path has more than 10000 segments valitussa polussa on yli 10000 segmenttiä +@msg the two paths have the same outline kahdella polulla on sama ääriviiva +@msg One path lies inside the other, so they have no common tangents Toinen polku on toisen sisällä, joten niillä ei ole yhteisiä tangentteja +@msg The paths overlap, so they have no internal tangents Polut ovat päällekkäin, joten niillä ei ole sisäisiä tangentteja +@msg One path lies inside the other, so they have no internal tangents Toinen polku on toisen sisällä, joten niillä ei ole sisäisiä tangentteja # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Laajenna viivat poluiksi @msg select paths with dashed strokes to expand valitse laajennettavat polut, joissa on katkoviiva diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 20e94749c5..7b94c77225 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7360,6 +7360,22 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes communes… + Common Tangents Tangentes communes + Tangents Tangentes + Centerline Ligne médiane + External Externes + Internal Internes +@msg select two closed paths sélectionnez deux tracés fermés +@msg a selected path is open un tracé sélectionné est ouvert +@msg a selected path is not convex un tracé sélectionné n’est pas convexe +@msg a selected path has no area un tracé sélectionné n’a pas de surface +@msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments +@msg the two paths have the same outline les deux tracés ont le même contour +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ff59a464c5..354922218f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2976,6 +2976,22 @@ Remove Effect ઇફેક્ટ દૂર કરો Remove Effects ઇફેક્ટ્સ દૂર કરો Remove Gaps ગેપ દૂર કરો +# Path Precision Tools add-on: Common Tangents. + Common Tangents… સામાન્ય સ્પર્શરેખાઓ… + Common Tangents સામાન્ય સ્પર્શરેખાઓ + Tangents સ્પર્શરેખાઓ + Centerline કેન્દ્ર રેખા + External બાહ્ય + Internal આંતરિક +@msg select two closed paths બે બંધ પાથ પસંદ કરો +@msg a selected path is open પસંદ કરેલો એક પાથ ખુલ્લો છે +@msg a selected path is not convex પસંદ કરેલો એક પાથ બહિર્ગોળ નથી +@msg a selected path has no area પસંદ કરેલા એક પાથનું કોઈ ક્ષેત્રફળ નથી +@msg a selected path has more than 10000 segments પસંદ કરેલા એક પાથમાં 10000 થી વધુ ખંડ છે +@msg the two paths have the same outline બંને પાથની રૂપરેખા સમાન છે +@msg One path lies inside the other, so they have no common tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ સામાન્ય સ્પર્શરેખા નથી +@msg The paths overlap, so they have no internal tangents પાથ એકબીજા પર ચઢેલા છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી +@msg One path lies inside the other, so they have no internal tangents એક પાથ બીજાની અંદર છે, તેથી તેમની કોઈ આંતરિક સ્પર્શરેખા નથી Remove Guide ગાઇડ દૂર કરો Remove Item આઇટમ દૂર કરો Remove JavaScript File JavaScript ફાઇલ દૂર કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6fe8f254f4..46ea68f4f0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8040,6 +8040,22 @@ antiAlias Sharp शार्प @msg select paths to join जोड़ने के लिए पाथ सिलेक्ट करें @msg select paths with dashed strokes to expand विस्तृत करने के लिए डैश स्ट्रोक के साथ पाथ सिलेक्ट करें @msg select paths, or segments, to divide विभाजित करने के लिए पाथ, या खंड चुनें +# Path Precision Tools add-on: Common Tangents. + Common Tangents… उभयनिष्ठ स्पर्शरेखाएँ… + Common Tangents उभयनिष्ठ स्पर्शरेखाएँ + Tangents स्पर्शरेखाएँ + Centerline केंद्र रेखा + External बाहरी + Internal आंतरिक +@msg select two closed paths दो बंद पाथ चुनें +@msg a selected path is open चुना गया एक पाथ खुला है +@msg a selected path is not convex चुना गया एक पाथ उत्तल नहीं है +@msg a selected path has no area चुने गए एक पाथ का कोई क्षेत्रफल नहीं है +@msg a selected path has more than 10000 segments चुने गए एक पाथ में 10000 से अधिक खंड हैं +@msg the two paths have the same outline दोनों पाथ की रूपरेखा एक जैसी है +@msg One path lies inside the other, so they have no common tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई उभयनिष्ठ स्पर्शरेखा नहीं है +@msg The paths overlap, so they have no internal tangents पाथ एक-दूसरे पर चढ़े हुए हैं, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है +@msg One path lies inside the other, so they have no internal tangents एक पाथ दूसरे के अंदर है, इसलिए उनकी कोई आंतरिक स्पर्शरेखा नहीं है @msg select plain rectangles, ellipses or regular polygons to convert बदलने के लिए सादे आयत, अंडाकार या नियमित बहुभुजों सिलेक्ट करें @msg Select point type पॉइंट टाइप सिलेक्ट करें @msg select rows or objects to collect इकट्ठा करने के लिए पंक्तियों या ऑब्जेक्ट्स सिलेक्ट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a93411b47..a34a41098b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7350,6 +7350,22 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Közös érintők… + Common Tangents Közös érintők + Tangents Érintők + Centerline Középvonal + External Külső + Internal Belső +@msg select two closed paths jelöljön ki két zárt útvonalat +@msg a selected path is open egy kijelölt útvonal nyitott +@msg a selected path is not convex egy kijelölt útvonal nem konvex +@msg a selected path has no area egy kijelölt útvonalnak nincs területe +@msg a selected path has more than 10000 segments egy kijelölt útvonalnak több mint 10000 szakasza van +@msg the two paths have the same outline a két útvonal körvonala azonos +@msg One path lies inside the other, so they have no common tangents Az egyik útvonal a másikon belül van, így nincsenek közös érintőik +@msg The paths overlap, so they have no internal tangents Az útvonalak átfedik egymást, így nincsenek belső érintőik +@msg One path lies inside the other, so they have no internal tangents Az egyik útvonal a másikon belül van, így nincsenek belső érintőik # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Szaggatások kibontása útvonalakká @msg select paths with dashed strokes to expand jelöljön ki szaggatott körvonalú útvonalakat a kibontáshoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bf029526f7..24886713a4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6744,6 +6744,22 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Garis Singgung Persekutuan… + Common Tangents Garis Singgung Persekutuan + Tangents Garis Singgung + Centerline Garis Tengah + External Luar + Internal Dalam +@msg select two closed paths pilih dua jalur tertutup +@msg a selected path is open jalur yang dipilih terbuka +@msg a selected path is not convex jalur yang dipilih tidak cembung +@msg a selected path has no area jalur yang dipilih tidak memiliki luas +@msg a selected path has more than 10000 segments jalur yang dipilih memiliki lebih dari 10000 segmen +@msg the two paths have the same outline kedua jalur memiliki garis luar yang sama +@msg One path lies inside the other, so they have no common tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung persekutuan +@msg The paths overlap, so they have no internal tangents Jalur-jalur saling tumpang tindih, sehingga tidak ada garis singgung dalam +@msg One path lies inside the other, so they have no internal tangents Satu jalur berada di dalam jalur lainnya, sehingga tidak ada garis singgung dalam # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Perluas garis putus menjadi jalur @msg select paths with dashed strokes to expand pilih jalur dengan stroke putus-putus yang akan diperluas diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 360ec1d5ba..db96ad4a85 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6992,6 +6992,22 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangenti comuni… + Common Tangents Tangenti comuni + Tangents Tangenti + Centerline Linea centrale + External Esterne + Internal Interne +@msg select two closed paths seleziona due tracciati chiusi +@msg a selected path is open un tracciato selezionato è aperto +@msg a selected path is not convex un tracciato selezionato non è convesso +@msg a selected path has no area un tracciato selezionato non ha area +@msg a selected path has more than 10000 segments un tracciato selezionato ha più di 10000 segmenti +@msg the two paths have the same outline i due tracciati hanno lo stesso contorno +@msg One path lies inside the other, so they have no common tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti comuni +@msg The paths overlap, so they have no internal tangents I tracciati si sovrappongono, quindi non hanno tangenti interne +@msg One path lies inside the other, so they have no internal tangents Un tracciato si trova dentro l’altro, quindi non hanno tangenti interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Espandi trattini in tracciati @msg select paths with dashed strokes to expand seleziona tracciati con traccia tratteggiata da espandere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 37089bb835..d65f13fbde 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8869,6 +8869,22 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 共通接線… + Common Tangents 共通接線 + Tangents 接線 + Centerline 中心線 + External 外側 + Internal 内側 +@msg select two closed paths 閉じたパスを 2 つ選択してください +@msg a selected path is open 選択したパスが開いています +@msg a selected path is not convex 選択したパスが凸形ではありません +@msg a selected path has no area 選択したパスに面積がありません +@msg a selected path has more than 10000 segments 選択したパスのセグメントが 10000 を超えています +@msg the two paths have the same outline 2 つのパスの輪郭が同じです +@msg One path lies inside the other, so they have no common tangents 一方のパスがもう一方の内側にあるため、共通接線はありません +@msg The paths overlap, so they have no internal tangents パスが重なっているため、内側の接線はありません +@msg One path lies inside the other, so they have no internal tangents 一方のパスがもう一方の内側にあるため、内側の接線はありません # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 破線をパスに拡張 @msg select paths with dashed strokes to expand 拡張する破線のパスを選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 25fb4f87ed..2252de5811 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9481,6 +9481,22 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი ტრაექტორიები ან სეგმენტები +# Path Precision Tools add-on: Common Tangents. + Common Tangents… საერთო მხებები… + Common Tangents საერთო მხებები + Tangents მხებები + Centerline ცენტრალური ხაზი + External გარე + Internal შიდა +@msg select two closed paths აირჩიეთ ორი დახურული ტრაექტორია +@msg a selected path is open არჩეული ტრაექტორია ღიაა +@msg a selected path is not convex არჩეული ტრაექტორია არ არის ამოზნექილი +@msg a selected path has no area არჩეულ ტრაექტორიას ფართობი არ აქვს +@msg a selected path has more than 10000 segments არჩეულ ტრაექტორიას 10000-ზე მეტი სეგმენტი აქვს +@msg the two paths have the same outline ორივე ტრაექტორიას ერთნაირი კონტური აქვს +@msg One path lies inside the other, so they have no common tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ საერთო მხებები არ აქვთ +@msg The paths overlap, so they have no internal tangents ტრაექტორიები ერთმანეთს ფარავს, ამიტომ მათ შიდა მხებები არ აქვთ +@msg One path lies inside the other, so they have no internal tangents ერთი ტრაექტორია მეორის შიგნითაა, ამიტომ მათ შიდა მხებები არ აქვთ # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths ტირეების ტრაექტორიებად გაშლა @msg select paths with dashed strokes to expand აირჩიეთ გასაშლელი ტირეებიანი ხაზის კონტურები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0787180a1c..ed97f43165 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6956,6 +6956,22 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 공통 접선… + Common Tangents 공통 접선 + Tangents 접선 + Centerline 중심선 + External 외부 + Internal 내부 +@msg select two closed paths 닫힌 패스 2개를 선택하십시오 +@msg a selected path is open 선택한 패스가 열려 있습니다 +@msg a selected path is not convex 선택한 패스가 볼록하지 않습니다 +@msg a selected path has no area 선택한 패스에 면적이 없습니다 +@msg a selected path has more than 10000 segments 선택한 패스의 세그먼트가 10000개를 넘습니다 +@msg the two paths have the same outline 두 패스의 윤곽선이 같습니다 +@msg One path lies inside the other, so they have no common tangents 한 패스가 다른 패스 안에 있어 공통 접선이 없습니다 +@msg The paths overlap, so they have no internal tangents 패스가 겹쳐 있어 내부 접선이 없습니다 +@msg One path lies inside the other, so they have no internal tangents 한 패스가 다른 패스 안에 있어 내부 접선이 없습니다 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 대시를 패스로 확장 @msg select paths with dashed strokes to expand 확장할 점선 획의 패스를 선택하십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ab30a3639f..d6a5e4a7d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9239,6 +9239,22 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemeenschappelijke raaklijnen… + Common Tangents Gemeenschappelijke raaklijnen + Tangents Raaklijnen + Centerline Middellijn + External Uitwendige + Internal Inwendige +@msg select two closed paths selecteer twee gesloten paden +@msg a selected path is open een geselecteerd pad is open +@msg a selected path is not convex een geselecteerd pad is niet convex +@msg a selected path has no area een geselecteerd pad heeft geen oppervlak +@msg a selected path has more than 10000 segments een geselecteerd pad heeft meer dan 10000 segmenten +@msg the two paths have the same outline de twee paden hebben dezelfde omtrek +@msg One path lies inside the other, so they have no common tangents Het ene pad ligt binnen het andere, dus ze hebben geen gemeenschappelijke raaklijnen +@msg The paths overlap, so they have no internal tangents De paden overlappen, dus ze hebben geen inwendige raaklijnen +@msg One path lies inside the other, so they have no internal tangents Het ene pad ligt binnen het andere, dus ze hebben geen inwendige raaklijnen # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Streepjes uitbreiden tot paden @msg select paths with dashed strokes to expand selecteer paden met een streepjeslijn om uit te breiden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 085935a9bd..5ab03b8788 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7221,6 +7221,22 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Wspólne styczne… + Common Tangents Wspólne styczne + Tangents Styczne + Centerline Linia środkowa + External Zewnętrzne + Internal Wewnętrzne +@msg select two closed paths zaznacz dwie zamknięte ścieżki +@msg a selected path is open zaznaczona ścieżka jest otwarta +@msg a selected path is not convex zaznaczona ścieżka nie jest wypukła +@msg a selected path has no area zaznaczona ścieżka nie ma pola +@msg a selected path has more than 10000 segments zaznaczona ścieżka ma więcej niż 10000 segmentów +@msg the two paths have the same outline obie ścieżki mają ten sam kontur +@msg One path lies inside the other, so they have no common tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają wspólnych stycznych +@msg The paths overlap, so they have no internal tangents Ścieżki nachodzą na siebie, więc nie mają stycznych wewnętrznych +@msg One path lies inside the other, so they have no internal tangents Jedna ścieżka leży wewnątrz drugiej, więc nie mają stycznych wewnętrznych # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Rozszerz kreski na ścieżki @msg select paths with dashed strokes to expand zaznacz ścieżki z przerywanym konturem do rozszerzenia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0289161fe4..f7902bd28e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7396,6 +7396,22 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tangentes comuns… + Common Tangents Tangentes comuns + Tangents Tangentes + Centerline Linha central + External Externas + Internal Internas +@msg select two closed paths selecione dois demarcadores fechados +@msg a selected path is open um demarcador selecionado está aberto +@msg a selected path is not convex um demarcador selecionado não é convexo +@msg a selected path has no area um demarcador selecionado não tem área +@msg a selected path has more than 10000 segments um demarcador selecionado tem mais de 10000 segmentos +@msg the two paths have the same outline os dois demarcadores têm o mesmo contorno +@msg One path lies inside the other, so they have no common tangents Um demarcador está dentro do outro, então eles não têm tangentes comuns +@msg The paths overlap, so they have no internal tangents Os demarcadores se sobrepõem, então eles não têm tangentes internas +@msg One path lies inside the other, so they have no internal tangents Um demarcador está dentro do outro, então eles não têm tangentes internas # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandir traços em demarcadores @msg select paths with dashed strokes to expand selecione demarcadores com traçado tracejado para expandir diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e45ac9423a..cfc654e280 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7355,6 +7355,22 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Общие касательные… + Common Tangents Общие касательные + Tangents Касательные + Centerline Осевая линия + External Внешние + Internal Внутренние +@msg select two closed paths выделите два замкнутых контура +@msg a selected path is open выделенный контур открыт +@msg a selected path is not convex выделенный контур не выпуклый +@msg a selected path has no area выделенный контур не имеет площади +@msg a selected path has more than 10000 segments выделенный контур содержит более 10000 сегментов +@msg the two paths have the same outline у обоих контуров одинаковая форма +@msg One path lies inside the other, so they have no common tangents Один контур лежит внутри другого, поэтому у них нет общих касательных +@msg The paths overlap, so they have no internal tangents Контуры перекрываются, поэтому у них нет внутренних касательных +@msg One path lies inside the other, so they have no internal tangents Один контур лежит внутри другого, поэтому у них нет внутренних касательных # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Разобрать штрихи на контуры @msg select paths with dashed strokes to expand выделите контуры со штриховой обводкой для разбора diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 95e7c34b47..4bae8c282f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7381,6 +7381,22 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Gemensamma tangenter… + Common Tangents Gemensamma tangenter + Tangents Tangenter + Centerline Mittlinje + External Yttre + Internal Inre +@msg select two closed paths markera två slutna banor +@msg a selected path is open en markerad bana är öppen +@msg a selected path is not convex en markerad bana är inte konvex +@msg a selected path has no area en markerad bana har ingen yta +@msg a selected path has more than 10000 segments en markerad bana har fler än 10000 segment +@msg the two paths have the same outline de två banorna har samma kontur +@msg One path lies inside the other, so they have no common tangents Den ena banan ligger inuti den andra, så de har inga gemensamma tangenter +@msg The paths overlap, so they have no internal tangents Banorna överlappar, så de har inga inre tangenter +@msg One path lies inside the other, so they have no internal tangents Den ena banan ligger inuti den andra, så de har inga inre tangenter # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Expandera streck till banor @msg select paths with dashed strokes to expand markera banor med streckad kontur att expandera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d8249b1c79..105580e29e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9243,6 +9243,22 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Ortak Teğetler… + Common Tangents Ortak Teğetler + Tangents Teğetler + Centerline Merkez Çizgisi + External Dış + Internal İç +@msg select two closed paths iki kapalı yol seçin +@msg a selected path is open seçili bir yol açık +@msg a selected path is not convex seçili bir yol dışbükey değil +@msg a selected path has no area seçili bir yolun alanı yok +@msg a selected path has more than 10000 segments seçili bir yolun 10000'den fazla bölümü var +@msg the two paths have the same outline iki yolun ana hattı aynı +@msg One path lies inside the other, so they have no common tangents Bir yol diğerinin içinde, bu yüzden ortak teğetleri yok +@msg The paths overlap, so they have no internal tangents Yollar örtüşüyor, bu yüzden iç teğetleri yok +@msg One path lies inside the other, so they have no internal tangents Bir yol diğerinin içinde, bu yüzden iç teğetleri yok # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Tireleri Yollara Genişlet @msg select paths with dashed strokes to expand genişletilecek kesikli konturlu yolları seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 8ebb97a5be..e03a5d3d67 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6974,6 +6974,22 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Спільні дотичні… + Common Tangents Спільні дотичні + Tangents Дотичні + Centerline Осьова лінія + External Зовнішні + Internal Внутрішні +@msg select two closed paths виділіть два замкнені контури +@msg a selected path is open виділений контур відкритий +@msg a selected path is not convex виділений контур не опуклий +@msg a selected path has no area виділений контур не має площі +@msg a selected path has more than 10000 segments виділений контур містить понад 10000 сегментів +@msg the two paths have the same outline обидва контури мають однакову форму +@msg One path lies inside the other, so they have no common tangents Один контур лежить усередині іншого, тому вони не мають спільних дотичних +@msg The paths overlap, so they have no internal tangents Контури перекриваються, тому вони не мають внутрішніх дотичних +@msg One path lies inside the other, so they have no internal tangents Один контур лежить усередині іншого, тому вони не мають внутрішніх дотичних # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Розібрати штрихи на контури @msg select paths with dashed strokes to expand виділіть контури зі штриховим обведенням для розбору diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index a9a9cb140a..41c52ef996 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6991,6 +6991,22 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Common Tangents. + Common Tangents… Tiếp tuyến chung… + Common Tangents Tiếp tuyến chung + Tangents Tiếp tuyến + Centerline Đường tâm + External Ngoài + Internal Trong +@msg select two closed paths chọn hai đường dẫn khép kín +@msg a selected path is open một đường dẫn đã chọn đang mở +@msg a selected path is not convex một đường dẫn đã chọn không lồi +@msg a selected path has no area một đường dẫn đã chọn không có diện tích +@msg a selected path has more than 10000 segments một đường dẫn đã chọn có hơn 10000 đoạn +@msg the two paths have the same outline hai đường dẫn có cùng đường viền +@msg One path lies inside the other, so they have no common tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến chung +@msg The paths overlap, so they have no internal tangents Các đường dẫn chồng lên nhau, nên chúng không có tiếp tuyến trong +@msg One path lies inside the other, so they have no internal tangents Một đường dẫn nằm bên trong đường dẫn kia, nên chúng không có tiếp tuyến trong # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Mở rộng nét đứt thành đường dẫn @msg select paths with dashed strokes to expand chọn các đường dẫn có nét đứt để mở rộng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f3a87e6b84..7dd53fdc00 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7206,6 +7206,22 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切线… + Common Tangents 公切线 + Tangents 切线 + Centerline 中心线 + External 外部 + Internal 内部 +@msg select two closed paths 请选择两条闭合路径 +@msg a selected path is open 所选路径是开放的 +@msg a selected path is not convex 所选路径不是凸形 +@msg a selected path has no area 所选路径没有面积 +@msg a selected path has more than 10000 segments 所选路径的线段超过 10000 条 +@msg the two paths have the same outline 两条路径的轮廓相同 +@msg One path lies inside the other, so they have no common tangents 一条路径位于另一条之内,因此它们没有公切线 +@msg The paths overlap, so they have no internal tangents 路径相互重叠,因此它们没有内公切线 +@msg One path lies inside the other, so they have no internal tangents 一条路径位于另一条之内,因此它们没有内公切线 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 将短划线扩展为路径 @msg select paths with dashed strokes to expand 请选择要扩展的虚线描边路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 52715f8360..732301f843 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7015,6 +7015,22 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Common Tangents. + Common Tangents… 公切線… + Common Tangents 公切線 + Tangents 切線 + Centerline 中心線 + External 外部 + Internal 內部 +@msg select two closed paths 請選取兩條封閉路徑 +@msg a selected path is open 所選路徑是開放的 +@msg a selected path is not convex 所選路徑不是凸形 +@msg a selected path has no area 所選路徑沒有面積 +@msg a selected path has more than 10000 segments 所選路徑的線段超過 10000 條 +@msg the two paths have the same outline 兩條路徑的輪廓相同 +@msg One path lies inside the other, so they have no common tangents 一條路徑位於另一條之內,因此它們沒有公切線 +@msg The paths overlap, so they have no internal tangents 路徑互相重疊,因此它們沒有內公切線 +@msg One path lies inside the other, so they have no internal tangents 一條路徑位於另一條之內,因此它們沒有內公切線 # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths 將短破折號展開為路徑 @msg select paths with dashed strokes to expand 請選取要展開的虛線筆畫路徑 diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..fbf67e9c22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11965,6 +11965,26 @@ Commands: - `addon.pathtools.shape.convert {ids?}` makes the selected plain closed paths that are rectangles, ellipses or polygons with equal sides and corners (stretched along their own axes at most) parametric shapes with the same outline. → `{ids}` (those converted). +- `addon.pathtools.commonTangents {tangents?, centerline?, ids?}` adds the common tangent lines of two convex closed + paths (`ids`, or the two selected objects) as separate open paths: lines that touch both paths without crossing into + either. `tangents`: `external` (both paths on the same side of the line), `internal` (lines that run between them) + or `all` (default). With `centerline: true` it also adds the line joining the two centers: an ellipse's center, or + a path's center of area. Each tangent of paths that do not touch runs from where it touches the lower path to + where it touches the upper one; where a straight side of a path lies along the line, the line covers the whole + side. An ellipse drawn with the Ellipse tool, then moved, turned or scaled, is measured as an exact ellipse. Any + other path must be closed, have one outline, bend the same way all around and have at most 10,000 segments; an open + path, a path that bends inward, a path without area, a group, a compound path or type is refused, and so are two + paths whose outlines are the same to within the touching tolerance given below. Two separate paths have two + external and two internal tangents. Overlapping paths have external tangents only. A path inside the other has + none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point + where they touch and as long as the narrower path is wide along it. Paths that meet at a corner or along a shared + stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when + the gap between them is less than the tolerance, a billionth of the larger of their sizes and the distance between + their centers. The lines are stroked with the current stroke color and weight (black when the stroke is None), have + no fill, go directly above the upper of the two paths and are selected; one undo step. When there is no tangent of + the kind asked for, nothing changes, and the result's `warning` says why. Common Tangents… + opens a dialog (Tangents, Centerline) with Preview. → `{ids, external, internal, centerline, warning?}` + (`centerline`: the centerline's id, or null). 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; @@ -11978,6 +11998,7 @@ plain path from then on. {"name":"run_command","arguments":{"command":"addon.pathtools.crossings","params":{"cut":true}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.create","params":{"kind":"star","center":[200,150],"width":120,"height":120,"count":7,"a":0.4}}} {"name":"run_command","arguments":{"command":"addon.pathtools.shape.set","params":{"id":14,"kind":"gear","count":16,"radius":2}}} +{"name":"run_command","arguments":{"command":"addon.pathtools.commonTangents","params":{"ids":[3,4],"tangents":"external","centerline":true}}} ``` ### Path Effects (live) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 10d476361a..c003439bb4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2453,6 +2453,10 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Nest Shapes… (`addon.cutting.nest`) moves the selected objects close together onto a sheet or a roll of material ([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The rest is VectorCraft's own: the sheet is an artboard, or a set width and height from its top-left corner, and a roll is a set width with no end; a margin is kept inside the edges and a spacing between objects. Objects are packed by their bounding boxes, with or without strokes and effects (shadows, glows and blurs included), the tallest first, each where its bottom edge is highest and then furthest left; with Rotate an object may turn 90° where that places it higher or where only the turned object fits. Objects that do not fit go in a column to the right of the sheet, in stacking order. The command is one undo step, and its result gives the length of material used. The dialog has Preview. Tests: `cmd::addons::cutting::nest::tests` in `vectorcraft-engine`, `nest_shapes_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Nest Shapes. +## Path Precision Tools add-on: Common Tangents (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Common Tangents… (`addon.pathtools.commonTangents`) adds the common tangent lines of two convex closed paths ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)) as separate open paths: external, internal or all, with the line joining the two centers if asked. The rest is VectorCraft's own: an ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse, and any other path must be closed, have one outline and bend the same way all around. Each line runs between the points where it touches the two paths. Separate paths have four tangents, overlapping paths only external ones (two for ellipses), and a path inside the other has none, in which case nothing changes and a message says why. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it. The lines take the current stroke and no fill; one undo step. The dialog has Preview. Tests: `addons::pathtools::tangents::tests` in `vectorcraft-pathops` (circles against the closed form, turned ellipses against a brute-force scan, nested, overlapping and touching circles, a convex Bézier path, flat sides, squares meeting at a corner, a curve touched beside an anchor, refused outlines), `cmd::addons::pathtools::tangents::tests` in `vectorcraft-engine`, `common_tangents_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. From 88d94ef78fe84367fca43d265036ddfca05475f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 16:14:50 -0800 Subject: [PATCH 2/3] Path Precision Tools: Common Tangents refuses a path with a short inward bend The convexity check looked at 32 points along each segment, so a cubic that bends the other way for a short stretch between two of those points was taken as convex. Each segment is now also checked whole: the cross product of its first and second derivatives, a quadratic in t, must not turn against the way the outline turns anywhere on the segment. --- .../pathops/src/addons/pathtools/tangents.rs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index c0d66e0dc1..2059932aa2 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -148,6 +148,11 @@ impl Outline { if (turning - TAU).abs() > 1e-6 { return Err(OutlineError::NotConvex); } + // A short bend the other way can lie between two of the points: each segment is checked + // whole. + if segments.iter().any(|s| bends_against(s, sign)) { + return Err(OutlineError::NotConvex); + } let center = (Vec2::new(cx / (3.0 * area2), cy / (3.0 * area2)) * size + origin).to_point(); if !center.x.is_finite() || !center.y.is_finite() { return Err(OutlineError::Empty); @@ -290,6 +295,32 @@ impl Outline { /// Calls `f` with each point of `s` where `p · n` can be largest (its ends and the places where /// the curve runs square to `n`) and the value there. +/// Whether cubic `s` bends against `sign` (the way its outline turns) anywhere. The cross product +/// of its first and second derivatives is a quadratic in t; its lowest value on [0, 1] is compared +/// with the segment's control polygon length squared. +fn bends_against(s: &CubicBez, sign: f64) -> bool { + let (a, b, c) = (s.p1 - s.p0, s.p2 - s.p1, s.p3 - s.p2); + let q = |t: f64| { + let u = 1.0 - t; + let d1 = a * (u * u) + b * (2.0 * u * t) + c * (t * t); + let d2 = (b - a) * u + (c - b) * t; + d1.cross(d2) * sign + }; + let (q0, half, q1) = (q(0.0), q(0.5), q(1.0)); + // q(t) = q0 + k1 t + k2 t². + let k2 = 2.0 * (q0 + q1 - 2.0 * half); + let k1 = q1 - q0 - k2; + let mut low = q0.min(q1); + if k2 > 0.0 { + let t = -k1 / (2.0 * k2); + if t > 0.0 && t < 1.0 { + low = low.min(q(t)); + } + } + let scale = (a.hypot() + b.hypot() + c.hypot()).powi(2); + low < -1e-9 * scale +} + fn each_extreme(s: &CubicBez, n: Vec2, mut f: impl FnMut(Point, f64)) { let [v0, v1, v2, v3] = [s.p0, s.p1, s.p2, s.p3].map(|p| p.to_vec2().dot(n)); f(s.p0, v0); @@ -835,6 +866,17 @@ mod tests { assert_eq!(Outline::convex(&open).err(), Some(OutlineError::Open)); let star = shapes::star(Point::new(0.0, 0.0), 50.0, 20.0, 5, 0.0).subpaths[0].clone(); assert_eq!(Outline::convex(&star).err(), Some(OutlineError::NotConvex)); + // A half disk whose straight side is a cubic with crossed handles: it bends the other way + // for a short stretch between two of the points the outline is checked at. + let mut bp = vectorcraft_geom::BezPath::new(); + let k = 0.5523 * 50.0; + bp.move_to((0.0, 0.0)); + bp.curve_to((62.4, 43.4), (60.3, 44.2), (100.0, 0.0)); + bp.curve_to((100.0, -k), (50.0 + k, -50.0), (50.0, -50.0)); + bp.curve_to((50.0 - k, -50.0), (0.0, -k), (0.0, 0.0)); + bp.close_path(); + let bend = vectorcraft_geom::PathData::from_bezpath(&bp).subpaths[0].clone(); + assert_eq!(Outline::convex(&bend).err(), Some(OutlineError::NotConvex)); // A square traced twice around winds around twice. let twice: Vec = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].repeat(2).into_iter().map(Point::from).collect(); assert_eq!(Outline::convex(&SubPath::polyline(&twice, true)).err(), Some(OutlineError::NotConvex)); From 6c3a092996d400aecae412934c3886f7f3cd2b16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 15:31:14 -0800 Subject: [PATCH 3/3] Line Segment: a line from one curve to another snaps to their common tangent With Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two. Both ends move to where the line touches the paths, the start sliding along the first path. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around that path switches between the outer tangent and the one crossing between the paths. Each end shows the "tangent" label when Anchor/Path Labels is on, and the line is drawn as a guide when Alignment Guides is on. Before this change the start of a Line Segment drag always stayed where it was pressed. It still does when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. The tangents come from the Common Tangents geometry. Each pointer move looks at the 16 nearest closed subpaths within the snapping tolerance and keeps the tangents of up to 64 pairs for the rest of the drag. --- ROADMAP.md | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/tangent_line.rs | 40 ++++ crates/tools/src/context.rs | 6 +- crates/tools/src/guides.rs | 2 + crates/tools/src/guides/bitangent.rs | 271 ++++++++++++++++++++++++ crates/tools/src/guides/snap.rs | 31 ++- crates/tools/src/guides/targets.rs | 6 +- crates/tools/src/shape.rs | 42 +++- crates/tools/src/shape/tests.rs | 253 ++++++++++++++++++++++ docs/target-app-parity.md | 1 + 11 files changed, 643 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/tests/tangent_line.rs create mode 100644 crates/tools/src/guides/bitangent.rs diff --git a/ROADMAP.md b/ROADMAP.md index 7ad95b59da..4336c13037 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,6 +146,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1b420d7805..91aea0b140 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -196,6 +196,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbollib; +mod tangent_line; mod targeting; mod textcombos; mod textedit; diff --git a/crates/engine/src/tests/tangent_line.rs b/crates/engine/src/tests/tangent_line.rs new file mode 100644 index 0000000000..78511d766b --- /dev/null +++ b/crates/engine/src/tests/tangent_line.rs @@ -0,0 +1,40 @@ +//! Snap to Tangent with the Line Segment tool: a line dragged from one circle to another lands on +//! their common tangent, drawn by `shape.line` as one undo step. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::*; + +use PointerKind::{Down, Drag, Up}; + +#[test] +fn a_line_segment_drag_draws_the_common_tangent_as_one_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 500, "height": 500})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 60, "y": 210, "width": 80, "height": 80})).unwrap(); + s.execute("shape.ellipse", &json!({"x": 240, "y": 190, "width": 120, "height": 120})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + assert_eq!(count(&s), 2); + // Circles about (100, 250), radius 40, and (300, 250), radius 60: the outer tangent above them + // has the normal (-0.1, -√0.99) and touches them at center + radius × normal. + let n = Vec2::new(-0.1, -(0.99f64).sqrt()); + let (on_a, on_b) = (Point::new(100.0, 250.0) + n * 40.0, Point::new(300.0, 250.0) + n * 60.0); + s.select_tool("lineSegment", ViewInfo::default()).unwrap(); + let to = on_b + Vec2::new(0.5, 0.7); + for (k, x, y) in [(Down, 100.0, 210.0), (Drag, 200.0, 200.0), (Drag, to.x, to.y), (Up, to.x, to.y)] { + s.pointer(&PointerEvent::new(k, x, y), ViewInfo::default()).unwrap(); + } + assert_eq!(count(&s), 3); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") }; + let ends: Vec = path.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends.len(), 2); + // Within what the drawn circles' 0.03% radius error allows. + assert!((ends[0] - on_a).hypot() < 0.15 && (ends[1] - on_b).hypot() < 0.15, "{ends:?}, want {on_a:?} {on_b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(count(&s), 2, "one undo removes the line"); +} diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 1e8f57ffc9..8bec1ccc54 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -198,9 +198,11 @@ pub struct ToolContext<'a> { /// [`Self::snap_tolerance`]. pub snap_to_point: bool, /// View → Snapping → Snap to Tangent: with Smart Guides on, a line drawn - /// from an anchor lands where it touches a nearby curve. + /// from an anchor lands where it touches a nearby curve, and a Line Segment + /// drag from one convex curved path to another lands on their common tangent. pub snap_tangent: bool, - /// View → Snapping → Snap to Perpendicular: likewise where it meets a nearby segment square. + /// View → Snapping → Snap to Perpendicular: with Smart Guides on, a line drawn from an anchor + /// lands where it meets a nearby segment square. pub snap_perpendicular: bool, /// View → Snap to Glyph: drawn points snap to live-text glyph bounds, and on a single line of type /// to its baseline, x-height, character widths and glyph anchor points (with Smart Guides). diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index 614df68917..e9f7bf7318 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -20,9 +20,11 @@ use vectorcraft_text::{FontDb, layout as layout_text}; use crate::bbox::Handle; use crate::{GlyphSnap, Overlay, ScreenFrame, ToolContext}; +mod bitangent; mod snap; mod targets; +pub(crate) use bitangent::TangentLine; pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, diff --git a/crates/tools/src/guides/bitangent.rs b/crates/tools/src/guides/bitangent.rs new file mode 100644 index 0000000000..9d4f9fa05c --- /dev/null +++ b/crates/tools/src/guides/bitangent.rs @@ -0,0 +1,271 @@ +//! Snap to Tangent for a line drawn from one curve to another (the Line Segment tool): when the +//! press lands on a convex closed path with curves and the pointer comes near another one, both +//! ends of the line move onto a common tangent of the two, the start sliding along the first path. +//! The tangents are [`vectorcraft_pathops::addons::pathtools::common_tangents`]'s. +//! +//! The closed subpaths in the window the line may end on are listed once, at the press, by their +//! bounds, up to as many segments as Smart Guides gather. Each pointer move looks only at the +//! [`MAX_NEAR`] nearest of them whose outline lies within the snapping tolerance of the pointer. +//! The tangents of each pair are worked out once, and the last [`MAX_KEPT`] pairs' are kept for +//! the rest of the drag. + +use std::collections::HashSet; + +use vectorcraft_pathops::addons::pathtools::{Outline, Tangent, common_tangents}; + +use super::snap::visible; +use super::targets::{BUDGET, walk_but}; +use super::{Node, NodeId, NodeKind, Overlay, ParamCurveNearest, Point, Rect, SubPath, ToolContext}; +use crate::PixelOp; + +/// Most subpaths a pointer move takes tangents from: the nearest ones whose outline lies within +/// the snapping tolerance of the pointer. +const MAX_NEAR: usize = 16; +/// Most pairs whose tangents are kept during one drag. +const MAX_KEPT: usize = 64; +/// Most segments a subpath the line starts or ends on may have: the tangents of two paths take +/// time that grows with both paths' segment counts, and they are worked out during the drag. +const MAX_SEGMENTS: usize = 512; + +/// A closed subpath with a curve the line may end on: its path, its index in the path, and the +/// bounds of its control points. +#[derive(Clone, Copy)] +struct Listed { + key: (NodeId, usize), + bounds: Rect, +} + +/// The two-ended tangent snap of one Line Segment drag. +#[derive(Default)] +pub(crate) struct TangentLine { + /// The subpath the press landed on and its outline: none when the press was not on a convex + /// closed path with a curve, or the snap is off. + from: Option<((NodeId, usize), Outline)>, + /// The closed subpaths with a curve, listed at the press (none when it found no subpath to + /// start from). + listed: Vec, + /// The common tangents of the press's subpath and each subpath the pointer came near. + kept: Vec<((NodeId, usize), Vec)>, + /// The line of the last snap. + line: Option<(Point, Point)>, +} + +/// The snap applies: Smart Guides and Snap to Tangent on, and neither pixels nor the grid +/// snapping drawn points instead. +fn applies(cx: &ToolContext) -> bool { + cx.smart_guides && cx.snap_tangent && !cx.snaps_to_pixel(PixelOp::Drawing) && !cx.snap_to_grid +} + +/// The subpath `key` of the document in `cx`. +fn subpath<'a>(cx: &'a ToolContext, key: (NodeId, usize)) -> Option<&'a SubPath> { + match &cx.doc.node(key.0)?.kind { + NodeKind::Path { path, .. } => path.subpaths.get(key.1), + _ => None, + } +} + +/// The subpaths of path `id` a line may start or end on, with their indexes: closed, with at most +/// [`MAX_SEGMENTS`] segments. +fn closed_subpaths<'a>(cx: &'a ToolContext, id: NodeId) -> impl Iterator { + let subpaths = match cx.doc.node(id).map(|n| &n.kind) { + Some(NodeKind::Path { path, .. }) => path.subpaths.as_slice(), + _ => &[], + }; + subpaths.iter().enumerate().filter(|(_, sp)| sp.closed && sp.segment_count() <= MAX_SEGMENTS) +} + +/// How far `p` lies from `sp` (its segments whose control bounds come within `reach` of `p`); none +/// when no segment comes that near. +fn distance(sp: &SubPath, p: Point, reach: f64) -> Option { + let mut best: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + if !b.inflate(reach, reach).contains(p) { + continue; + } + let d = c.nearest(p, 1e-9).distance_sq.sqrt(); + if best.is_none_or(|e| d < e) { + best = Some(d); + } + } + best +} + +/// Whether `sp` has a curved segment. +fn curved(sp: &SubPath) -> bool { + (0..sp.segment_count()).any(|k| !sp.segment_is_line(k)) +} + +impl TangentLine { + /// Start a drag pressed at `start` (where the pointer went down): the subpath under it, when it + /// is a convex closed path with a curve, and then the closed subpaths with a curve in the window + /// the line may end on, by their bounds. The press looks at the segments of the paths whose + /// bounds reach it only, and lists nothing when it lands on no such subpath, or when `held` (an + /// anchor, center or crossing the press snapped to) lies off that subpath. + pub(crate) fn press(&mut self, cx: &ToolContext, start: Point, held: Option) { + *self = Self::default(); + if !applies(cx) || !start.x.is_finite() || !start.y.is_finite() { + return; + } + let tol = cx.snap_tol(); + // The paths with a closed subpath, by their finite bounds. + let closed = |n: &Node| match &n.kind { + NodeKind::Path { path, .. } if path.subpaths.iter().any(|sp| sp.closed) => { + n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + } + _ => None, + }; + // The subpaths under the press: at most as many segments as Smart Guides gather. + let mut on: Option<(f64, (NodeId, usize))> = None; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| b.inflate(tol, tol).contains(start)) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + if let Some(d) = distance(sp, start, tol) + && d <= tol + && curved(sp) + && on.is_none_or(|(e, _)| d < e) + { + on = Some((d, (n.id, si))); + } + } + }); + // A path that bends inward somewhere has no tangent of this kind: the line keeps its start. + let Some(from) = on.and_then(|(_, key)| Some((key, Outline::convex(subpath(cx, key)?).ok()?))) else { return }; + // A press held by an anchor, center or crossing off that path starts the line there. + if let Some(q) = held + && !subpath(cx, from.0).and_then(|sp| distance(sp, q, tol)).is_some_and(|d| d <= 1e-6 * tol.max(1.0)) + { + return; + } + let from_key = from.0; + self.from = Some(from); + // The subpaths the line may end on: closed ones with a curve, of the paths in the window, + // at most as many segments as Smart Guides gather. + let window = visible(cx); + let listed = &mut self.listed; + let mut budget = BUDGET; + walk_but(&cx.doc.layers, &HashSet::new(), &mut |n| { + if budget == 0 || !closed(n).is_some_and(|b| window.is_none_or(|v| b.intersect(v).area() > 0.0 || v.contains(b.center()))) { + return; + } + for (si, sp) in closed_subpaths(cx, n.id) { + let Some(left) = budget.checked_sub(sp.segment_count()) else { return }; + budget = left; + let mut bounds: Option = None; + for k in 0..sp.segment_count() { + let c = sp.segment(k); + let b = Rect::from_points(c.p0, c.p3).union_pt(c.p1).union_pt(c.p2); + bounds = Some(bounds.map_or(b, |r| r.union(b))); + } + if let Some(bounds) = + bounds.filter(|b| curved(sp) && (n.id, si) != from_key && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) + { + listed.push(Listed { key: (n.id, si), bounds }); + } + } + }); + } + + /// The line for the pointer at `p`: on the nearest subpath whose outline lies within the + /// snapping tolerance of `p` and that has a common tangent with the press's subpath, the + /// tangent whose touch point on it is nearest `p`; none when there is none. A subpath farther + /// from `p` than `rival` (an anchor, center or crossing the pointer snaps to otherwise) gives + /// way to it; its own anchors, which lie on its outline, do not. + pub(crate) fn snap(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + let line = self.find(cx, p, rival); + self.line = line; + line + } + + fn find(&mut self, cx: &ToolContext, p: Point, rival: Option) -> Option<(Point, Point)> { + if self.from.is_none() || !applies(cx) || !p.x.is_finite() || !p.y.is_finite() { + return None; + } + let tol = cx.snap_tol(); + let mut near: Vec<(f64, (NodeId, usize))> = vec![]; + for l in self.listed.iter().filter(|l| l.bounds.inflate(tol, tol).contains(p)) { + // The nearest `MAX_NEAR`, in order, kept while scanning. + if let Some(d) = subpath(cx, l.key).and_then(|sp| distance(sp, p, tol)).filter(|d| *d <= tol) { + let at = near.partition_point(|(e, _)| *e <= d); + if at < MAX_NEAR { + near.insert(at, (d, l.key)); + near.truncate(MAX_NEAR); + } + } + } + for (d, key) in near { + if rival.is_some_and(|r| r < d - 1e-6 * tol) { + return None; + } + let Some(sp) = subpath(cx, key) else { continue }; + let mut best: Option<(f64, Point, Point)> = None; + for t in self.tangents(cx, key) { + // Where the paths touch each other, the tangent's ends are not both on the paths. + let on_b = distance(sp, t.to, tol).is_some_and(|e| e <= 1e-6 * tol.max(1.0)); + if !on_b || t.from.distance(t.to) <= tol { + continue; + } + let dist = t.to.distance(p); + // On a tie the line of the last move stays, so it does not flicker. + let same = self.line == Some((t.from, t.to)); + if best.is_none_or(|(e, ..)| dist < e - 1e-9 || (same && dist <= e + 1e-9)) { + best = Some((dist, t.from, t.to)); + } + } + if let Some((_, a, b)) = best { + return Some((a, b)); + } + } + None + } + + /// The common tangents of the press's subpath and subpath `key`, worked out on first use. + fn tangents(&mut self, cx: &ToolContext, key: (NodeId, usize)) -> Vec { + if let Some((_, t)) = self.kept.iter().find(|(k, _)| *k == key) { + return t.clone(); + } + let Some((_, from)) = &self.from else { return vec![] }; + let all = subpath(cx, key).and_then(|sp| Outline::convex(sp).ok()).and_then(|o| common_tangents(from, &o).ok()).unwrap_or_default(); + if self.kept.len() >= MAX_KEPT { + self.kept.remove(0); + } + self.kept.push((key, all.clone())); + all + } + + /// The line of the last snap, if it found one. + pub(crate) fn line(&self) -> Option<(Point, Point)> { + self.line + } + + /// Forget the last snap's line for a move that does not snap this way (a modifier is held), + /// keeping the press's subpath for the moves after it. + pub(crate) fn drop_line(&mut self) { + self.line = None; + } + + /// End the drag. + pub(crate) fn clear(&mut self) { + *self = Self::default(); + } + + /// The guides of the last snap: the line, and the "tangent" label at both ends. + pub(crate) fn guides(&self, cx: &ToolContext) -> Vec { + let Some((a, b)) = self.line else { return vec![] }; + let color = cx.smart_guide_color; + let mut out = vec![]; + if cx.alignment_guides { + out.push(Overlay::Line { a, b, color, dashed: false }); + } + if cx.anchor_path_labels { + out.extend([a, b].map(|p| Overlay::Label { p, text: "tangent".into(), color })); + } + out + } +} diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index d7ee8ecdd8..4c8a0d189a 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -365,7 +365,7 @@ impl SnapKey { } /// The part of the document the window shows (none headless: all of it). -fn visible(cx: &ToolContext) -> Option { +pub(super) fn visible(cx: &ToolContext) -> Option { let s = cx.screen?; let (w, h) = s.size; Some(Rect::from_points(s.at(0.0, 0.0), s.at(w, h)).union_pt(s.at(w, 0.0)).union_pt(s.at(0.0, h))) @@ -429,6 +429,35 @@ impl DrawSnap { self.snap(cx, p, from) } + /// How far from `p` the nearest Smart Guides point (an anchor or a center) or crossing of the + /// targets lies, when one is within the snapping tolerance: none otherwise, and none while + /// pixels or the grid snap instead. + pub(crate) fn point_within_reach(&self, cx: &ToolContext, p: Point) -> Option { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return None }; + if !cx.smart_guides { + return None; + } + let tol = cx.tol(*tol); + let point = t.nearest_point(p, tol).map(|(q, _)| q.distance(p)); + let crossing = t.crossing(p, tol).map(|q| q.distance(p)); + match (point, crossing) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } + } + + /// Whether `q`, where a point at `p` snapped to, is the nearest Smart Guides point (an anchor or + /// a center) or the nearest crossing of the targets within the snapping tolerance of `p`. + pub(crate) fn snapped_to_point(&self, cx: &ToolContext, p: Point, q: Point) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), .. })) = &self.targets else { return false }; + if !cx.smart_guides { + return false; + } + let tol = cx.tol(*tol); + let at = |a: Point| a.distance(q) <= 1e-9 * tol.max(1.0); + t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index e3e6abeef6..c846f1a55a 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -64,7 +64,7 @@ pub struct Targets { } /// How many anchors, and how many segments, the targets gather at most. -const BUDGET: usize = 20_000; +pub(super) const BUDGET: usize = 20_000; /// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds. #[derive(Clone, Copy, PartialEq)] @@ -88,7 +88,7 @@ fn within(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] { /// Visit `nodes` and everything inside them, but the nodes in `skip`, the hidden nodes and /// everything inside those: one pass, however many are skipped. A Shaper Group's original /// shapes, its first child, are not shown and are skipped too. -fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { +pub(super) fn walk_but<'a>(nodes: &'a [Arc], skip: &HashSet, f: &mut impl FnMut(&'a Node)) { for n in nodes.iter().filter(|n| n.visible && !skip.contains(&n.id)) { f(n); if let Some(ch) = n.children() { @@ -898,7 +898,7 @@ impl Targets { /// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing /// nearest `p` within `tol` ("intersect", #1602). - fn crossing(&self, p: Point, tol: f64) -> Option { + pub(super) fn crossing(&self, p: Point, tol: f64) -> Option { self.crossing_with(p, tol, &self.rulers) } diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..67d23be463 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -5,7 +5,9 @@ //! Illustrator). ↑/↓ during a polygon/star drag change the side/point count; during a star drag, //! Ctrl/Cmd keeps the inner radius where it is while the outer one follows the pointer, and Alt //! keeps the star's shoulders straight (#812). The start point and -//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. +//! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. With Snap +//! to Tangent on, a line pressed on one convex curved path and dragged near another lands on a +//! common tangent of the two, both its ends moving to the touch points ([`TangentLine`]). //! Escape cancels the drag and puts back the options its keys and Ctrl/Cmd changed. //! //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, @@ -22,7 +24,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag}; -use crate::guides::{DrawSnap, Leave, PointSnap, Targets, square}; +use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -95,6 +97,8 @@ pub struct ShapeTool { pub line_angle: f64, pub fill_line: bool, snap: DrawSnap, + /// Snap to Tangent for a line from one curve to another: both ends on a common tangent. + tangent_line: TangentLine, /// The options a drag's keys and Ctrl/Cmd change, as they were when the drag began: Escape /// puts them back. before_drag: Option, @@ -150,6 +154,7 @@ impl ShapeTool { star_ratio: 0.5, inner: None, snap: DrawSnap::default(), + tangent_line: TangentLine::default(), line_length: 100.0, line_angle: 0.0, fill_line: false, @@ -547,6 +552,12 @@ impl Tool for ShapeTool { return out; } let p = self.snap.press(cx, ev.pos, &[], None); + if self.id == "lineSegment" { + // The pressed spot finds the curve; a press that snapped to an anchor, center + // or crossing off that curve keeps the line's start there. + let held = self.snap.snapped_to_point(cx, ev.pos, p).then_some(p); + self.tangent_line.press(cx, ev.pos, held); + } self.start = Some(p); self.last = ev.pos; self.began = false; @@ -556,6 +567,7 @@ impl Tool for ShapeTool { } PointerKind::Drag => { let Some(mut s) = self.start else { return vec![] }; + let raw = ev.pos; let pos = self.snap.drag(cx, ev.pos, self.leave(cx, s, ev.mods).as_ref()); let ev = &PointerEvent { pos, ..*ev }; // The inner radius of the star the last drag showed, with the ratio it drew with: @@ -564,6 +576,10 @@ impl Tool for ShapeTool { let ratio = if self.mods.alt { straight_ratio(self.points).unwrap_or(self.star_ratio) } else { self.star_ratio }; let shown = (self.last - s).hypot() * ratio; space_moves(&mut s, &mut self.last, ev, self.began); + if ev.mods.space && self.began { + // The start no longer lies on the pressed path. + self.tangent_line.clear(); + } self.start = Some(s); self.mods = ev.mods; if self.id == "star" { @@ -578,13 +594,25 @@ impl Tool for ShapeTool { self.before_drag = Some(self.drag_options()); out.push(Action::Begin(self.label().into())); } - let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); + // Snap to Tangent: a line pressed on one curve and ending near another moves both + // its ends onto a common tangent of the two, unless Shift, Alt or Space is held or + // an anchor or crossing nearer the pointer pulls it. + let tangent = if self.id == "lineSegment" && !(ev.mods.shift || ev.mods.alt || ev.mods.space) { + let rival = self.snap.point_within_reach(cx, raw); + self.tangent_line.snap(cx, raw, rival) + } else { + self.tangent_line.drop_line(); + None + }; + let (a, b) = tangent.unwrap_or((s, ev.pos)); + let (c, v) = self.command_at(a, b, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); out } PointerKind::Up => { let Some(s) = self.start.take() else { return vec![] }; self.snap.clear(); + self.tangent_line.clear(); self.inner = None; self.before_drag = None; if self.began { @@ -658,6 +686,7 @@ impl Tool for ShapeTool { self.restore_drag_options(o); } self.snap.clear(); + self.tangent_line.clear(); vec![Action::Cancel] } else { vec![] @@ -706,7 +735,9 @@ impl Tool for ShapeTool { Some(WidgetDrag::Pie(d)) => return d.overlays(cx), None => {} } - let mut o = self.snap.guides().to_vec(); + // A line on a common tangent shows that snap's guides, and its length and angle. + let tangent = self.tangent_line.line().filter(|_| self.start.is_some()); + let mut o = if tangent.is_some() { self.tangent_line.guides(cx) } else { self.snap.guides().to_vec() }; o.extend(self.guides.iter().cloned()); if let Some((p, text)) = &self.measure { o.push(Overlay::Measure { p: *p, text: text.clone() }); @@ -714,7 +745,8 @@ impl Tool for ShapeTool { if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); let text = if self.id == "lineSegment" { - cx.segment_measure_label(s, self.last) + let (a, b) = tangent.unwrap_or((s, self.last)); + cx.segment_measure_label(a, b) } else { // A box's size as drawn (from its centre with Alt, square with Shift). match self.id { diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index c76eef404e..1a72a0fbbf 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -430,6 +430,259 @@ fn line_segment_options_and_fill_line() { assert_eq!(t.command(a, b, Mods::default()).1["fill"], json!(true)); } +/// A document holding the closed paths `paths`, unselected. +fn doc_with_paths(paths: Vec) -> vectorcraft_doc::Document { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + for (k, path) in paths.into_iter().enumerate() { + let id = d.alloc_id(); + d.insert(Some(l), k, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + d +} + +/// The circle of radius `r` about `c`, as the Ellipse tool draws it. +fn circle(c: Point, r: f64) -> vectorcraft_geom::PathData { + vectorcraft_geom::shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)) +} + +/// The ends of the line a Line Segment drag from `press` through `drag` to `to` (with `mods`) +/// previews last, and the drag's actions. +fn line_drag(c: &ToolContext, press: Point, drag: Point, to: Point, mods: Mods) -> ((Point, Point), Vec) { + let mut t = ShapeTool::new("lineSegment"); + t.pointer(c, &PointerEvent::new(PointerKind::Down, press.x, press.y).with_mods(mods)); + let mut all = t.pointer(c, &PointerEvent::new(PointerKind::Drag, drag.x, drag.y).with_mods(mods)); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Drag, to.x, to.y).with_mods(mods))); + let Some(Action::Preview(cmd, v)) = all.last().cloned() else { panic!("a preview: {all:?}") }; + assert_eq!(cmd, "shape.line"); + let f = |k: &str| v[k].as_f64().unwrap(); + let line = (Point::new(f("x1"), f("y1")), Point::new(f("x2"), f("y2"))); + all.extend(t.pointer(c, &PointerEvent::new(PointerKind::Up, to.x, to.y).with_mods(mods))); + (line, all) +} + +/// Snap to Tangent: a line pressed on one circle and dragged near another lands on a common +/// tangent of the two, both ends moving to where it touches them. Near the second circle's top it +/// is the outer tangent, near its bottom left the one crossing between them, each against the +/// closed form (the drawn circles are within 0.03% of round). The guides show the line and a +/// "tangent" label at each end, and the length label measures the tangent line. +#[test] +fn a_line_from_one_circle_to_another_lands_on_their_common_tangent() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // A drawn circle's radius is off by up to 0.03%, which moves the touch points along the line by + // up to about 0.1 pt here; the line's distance from each center stays within 0.03 pt. + let near = |a: Point, b: Point| (a - b).hypot() < 0.15; + let off_by = |(a, b): (Point, Point), c: Point| ((b - a).cross(c - a) / (b - a).hypot()).abs(); + let touches = |line: (Point, Point)| (off_by(line, c1) - r1).abs() < 0.03 && (off_by(line, c2) - r2).abs() < 0.03; + // A normal n with n · (c2 - c1) / |c2 - c1| = k: the line touches the first circle at + // c1 + r1 n, and the second at c2 + r2 n (outer, k = (r1 - r2) / d) or c2 - r2 n (crossing, + // k = (r1 + r2) / d). + let normal = |k: f64, up: bool| Vec2::new(k, if up { -1.0 } else { 1.0 } * (1.0 - k * k).sqrt()); + let outer = normal((r1 - r2) / 200.0, true); + let (on_a, on_b) = (c1 + outer * r1, c2 + outer * r2); + let press = Point::new(100.0, 210.0); + let ((a, b), actions) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.5, 0.7), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // One gesture: one undo step. + assert_eq!(actions.iter().filter(|a| matches!(a, Action::Begin(_))).count(), 1, "{actions:?}"); + assert_eq!(actions.last(), Some(&Action::Commit)); + let crossing = normal((r1 + r2) / 200.0, false); + let (on_a, on_b) = (c1 + crossing * r1, c2 - crossing * r2); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 260.0), on_b + Vec2::new(-0.6, 0.4), Mods::default()); + assert!(near(a, on_a) && near(b, on_b) && touches((a, b)), "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + // The guides and the length label while dragging. + let mut t = ShapeTool::new("lineSegment"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, press.x, press.y)); + let to = on_b + Vec2::new(-0.6, 0.4); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let o = t.overlays(&c); + let tangents: Vec = o + .iter() + .filter_map(|o| match o { + Overlay::Label { p, text, .. } if text == "tangent" => Some(*p), + _ => None, + }) + .collect(); + assert_eq!(tangents.len(), 2, "{o:?}"); + assert!(near(tangents[0], on_a) && near(tangents[1], on_b), "{o:?}"); + let (a, b) = t.tangent_line.line().unwrap(); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &c.segment_measure_label(a, b))), "{o:?}"); + // Escape ends it. + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(t.tangent_line.line().is_none() && t.overlays(&c).is_empty()); +} + +/// The tangent of a turned ellipse and a circle, against the ellipse's own closed form: the +/// support value of the ellipse x = c + M u (|u| = 1) along n is c · n + |Mᵀ n|, touched at +/// c + M Mᵀ n / |Mᵀ n|; the outer tangents are the n where it equals the circle's c₂ · n + r. +#[test] +fn a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle() { + let ce = Point::new(100.0, 250.0); + let turn = Affine::rotate_about(30f64.to_radians(), ce); + let ellipse = vectorcraft_geom::shapes::ellipse(Rect::new(40.0, 220.0, 160.0, 280.0)).transformed(turn); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![ellipse, circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + // M maps the unit circle onto the ellipse's axes: 60 and 30 long, turned 30°. + let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin()); + let m = [[60.0 * cos, -30.0 * sin], [60.0 * sin, 30.0 * cos]]; + let mt_n = |n: Vec2| Vec2::new(m[0][0] * n.x + m[1][0] * n.y, m[0][1] * n.x + m[1][1] * n.y); + let g = |a: f64| { + let n = Vec2::new(a.cos(), a.sin()); + ce.to_vec2().dot(n) + mt_n(n).hypot() - c2.to_vec2().dot(n) - r2 + }; + // The roots of g over the angle, by sampling and bisection; the one with n pointing up. + let mut roots = vec![]; + let steps = 3600; + for k in 0..steps { + let (mut lo, mut hi) = (k as f64 * std::f64::consts::TAU / steps as f64, (k + 1) as f64 * std::f64::consts::TAU / steps as f64); + if g(lo).signum() == g(hi).signum() { + continue; + } + for _ in 0..80 { + let mid = (lo + hi) / 2.0; + if g(mid).signum() == g(lo).signum() { lo = mid } else { hi = mid } + } + roots.push(lo); + } + let n = roots.iter().map(|a| Vec2::new(a.cos(), a.sin())).find(|n| n.y < 0.0).unwrap(); + let w = mt_n(n); + let on_a = ce + Vec2::new(m[0][0] * w.x + m[0][1] * w.y, m[1][0] * w.x + m[1][1] * w.y) / w.hypot(); + let on_b = c2 + n * r2; + // The press on the ellipse's turned top anchor. + let press = turn * Point::new(100.0, 220.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), on_b + Vec2::new(0.4, -0.5), Mods::default()); + assert!((a - on_a).hypot() < 0.05 && (b - on_b).hypot() < 0.05, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// The line keeps its start where it was pressed, as before, when Snap to Tangent is off, Smart +/// Guides are off, Shift or Alt is held, or the pressed path bends inward somewhere (it has no +/// tangent of this kind). Where the tangent touches the second circle at one of its anchors, the +/// tangent still wins over that anchor. +#[test] +fn a_line_keeps_its_start_without_a_tangent_snap() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, c2, r) = (Point::new(100.0, 250.0), Point::new(300.0, 250.0), 50.0); + let d = doc_with_paths(vec![circle(c1, r), circle(c2, r)]); + let (s, p) = (Selection::default(), paint()); + let on = cx(&d, &s, &p); + // The pointer next to the second circle's top anchor, where the outer tangent touches it. + let to = Point::new(300.6, 200.4); + // A press on the first circle 30° round from its top, away from its anchors. + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // With Snap to Tangent on, the start moves to the first circle's top. + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - Point::new(100.0, 200.0)).hypot() < 0.05 && (b - Point::new(300.0, 200.0)).hypot() < 0.05, "{a:?} {b:?}"); + let off = [ToolContext { snap_tangent: false, ..cx(&d, &s, &p) }, ToolContext { smart_guides: false, ..cx(&d, &s, &p) }]; + for c in &off { + let ((a, _), _) = line_drag(c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05, "{a:?}"); + } + for mods in [Mods { shift: true, ..Mods::default() }, Mods { alt: true, ..Mods::default() }] { + let ((a, b), _) = line_drag(&on, pressed, Point::new(200.0, 190.0), to, mods); + // Alt draws the line from its middle. + let start = if mods.alt { a.midpoint(b) } else { a }; + assert!((start - pressed).hypot() < 0.05, "{a:?} {b:?}"); + } + // Space moves the line being drawn, its start off the pressed circle: the snap lets go. + let mut t = ShapeTool::new("lineSegment"); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&on, &PointerEvent::new(PointerKind::Down, pressed.x, pressed.y)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 200.0, 170.0)); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 210.0, 160.0).with_mods(space)); + let a = t.pointer(&on, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("a preview: {a:?}") }; + let start = Point::new(v["x1"].as_f64().unwrap(), v["y1"].as_f64().unwrap()); + assert!((start - (pressed + Vec2::new(10.0, -10.0))).hypot() < 1.0, "{start:?}"); + // A crescent: closed and curved, but its lower side bends inward. The press on its top + // keeps its start. + let mut bp = BezPath::new(); + bp.move_to((60.0, 250.0)); + bp.curve_to((60.0, 190.0), (140.0, 190.0), (140.0, 250.0)); + bp.curve_to((120.0, 220.0), (80.0, 220.0), (60.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![PathData::from_bezpath(&bp), circle(c2, r)]); + let c = cx(&d, &s, &p); + let crest = Point::new(100.0, 205.0); + let ((a, _), _) = line_drag(&c, crest, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - crest).hypot() < 1e-6, "{a:?}"); +} + +/// The upper outer common tangent of the circles about `c1` and `c2` with radii `r1` and `r2` +/// (`c2` to the right): where it touches each. +fn upper_outer_tangent(c1: Point, r1: f64, c2: Point, r2: f64) -> (Point, Point) { + let d = c2 - c1; + let u = d / d.hypot(); + let k = (r1 - r2) / d.hypot(); + // n · u = k, with n pointing up (y down). + let n = u * k + Vec2::new(u.y, -u.x) * (1.0 - k * k).sqrt(); + (c1 + n * r1, c2 + n * r2) +} + +/// The pointer only has to come near the second path's outline: anywhere along it, the line takes +/// the tangent whose touch point is nearest the pointer, here one about 30 pt away. A press on a +/// straight side of a convex path with curves (a rounded rectangle's top edge) moves the start +/// onto the corner the tangent touches. +#[test] +fn a_line_near_the_second_path_takes_the_tangent_touching_it_nearest() { + let (c1, r1, c2, r2) = (Point::new(100.0, 250.0), 40.0, Point::new(300.0, 250.0), 60.0); + let d = doc_with_paths(vec![circle(c1, r1), circle(c2, r2)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(c1, r1, c2, r2); + // On the second circle's outline, 25° round from its top. + let to = c2 + Vec2::new(r2 * 25f64.to_radians().sin(), -r2 * 25f64.to_radians().cos()); + assert!((to - on_b).hypot() > 25.0); + let ((a, b), _) = line_drag(&c, Point::new(100.0, 210.0), Point::new(200.0, 200.0), to, Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); + + // A rounded rectangle whose top right corner is a quarter circle of radius 20 about (140, 220). + let rounded = vectorcraft_geom::shapes::rounded_rectangle(Rect::new(40.0, 200.0, 160.0, 300.0), 20.0); + let (c2, r2) = (Point::new(320.0, 260.0), 40.0); + let d = doc_with_paths(vec![rounded, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let (on_a, on_b) = upper_outer_tangent(Point::new(140.0, 220.0), 20.0, c2, r2); + let press = Point::new(90.0, 200.0); + let ((a, b), _) = line_drag(&c, press, Point::new(200.0, 200.0), Point::new(320.0, 220.5), Mods::default()); + assert!((a - on_a).hypot() < 0.15 && (b - on_b).hypot() < 0.15, "{a:?} {b:?}, want {on_a:?} {on_b:?}"); +} + +/// No tangent snap when the second path bends inward somewhere (a crescent), or when the press +/// snapped to an anchor of other art lying beside the first circle: the start stays where the +/// press put it. +#[test] +fn a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start() { + use vectorcraft_geom::{BezPath, PathData}; + let (c1, r) = (Point::new(100.0, 250.0), 50.0); + let mut bp = BezPath::new(); + bp.move_to((260.0, 250.0)); + bp.curve_to((260.0, 190.0), (340.0, 190.0), (340.0, 250.0)); + bp.curve_to((320.0, 220.0), (280.0, 220.0), (260.0, 250.0)); + bp.close_path(); + let d = doc_with_paths(vec![circle(c1, r), PathData::from_bezpath(&bp)]); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let pressed = c1 + Vec2::new(r * 0.5, -r * 3f64.sqrt() / 2.0); + // Beside the crescent's top, which lies at (300, 205). + let to = Point::new(300.4, 205.3); + let ((a, b), _) = line_drag(&c, pressed, Point::new(200.0, 190.0), to, Mods::default()); + assert!((a - pressed).hypot() < 0.05 && (b - to).hypot() < 1.0, "{a:?} {b:?}"); + + // A square whose corner (99, 199) lies about 1 pt outside the first circle's top; a second + // circle to the right. The press snaps to that corner and the line starts there. + let (c2, r2) = (Point::new(300.0, 250.0), 50.0); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(80.0, 180.0, 99.0, 199.0)); + let d = doc_with_paths(vec![circle(c1, r), square, circle(c2, r2)]); + let c = cx(&d, &s, &p); + let corner = Point::new(99.0, 199.0); + let ((a, _), _) = line_drag(&c, Point::new(99.3, 199.3), Point::new(200.0, 190.0), Point::new(300.6, 200.4), Mods::default()); + assert!((a - corner).hypot() < 1e-6, "{a:?}"); +} + /// #5477: with a shape tool, a drag on a selected live rectangle's corner widget rounds its /// corners (one undo step) and a drag on a live ellipse's pie widget sets its pie angle, as with /// the Selection tool; the pointer over a widget is the Selection tool's. A press anywhere else, or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c003439bb4..8499f23a5c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -611,6 +611,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo.