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.