diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index d2488b8b5f..f0b8a5609f 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -23,8 +23,9 @@ pub struct Selection { /// `objects` with no entry here is fully selected; `segments` distinguishes segment picks. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub anchors: BTreeMap>, - /// Explicitly selected segments. Their endpoints in `anchors` move with them, but are not - /// selected anchor points: Delete cuts connections and their anchor squares stay hollow. + /// Explicitly selected segments. Their endpoints in `anchors` move with them (the arrow keys + /// bend a curved one instead), but are not selected anchor points: Delete cuts connections and + /// their anchor squares stay hollow. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub segments: BTreeMap>, /// Key object for Align, one object of a selection of two or more. [`Selection::prune`] clears diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 9082850dff..8ce478ad97 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors (a selected curved segment bends instead: its anchors stay and its handles keep their directions while its middle moves by the step), else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 536dcf9c98..1ccd74d57f 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -347,7 +347,10 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); + return crate::cmd::path::nudge_anchors( + s, + &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }), + ); } if objects && s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 0338c6903a..b7df3dc467 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, SegmentRef, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -244,19 +244,48 @@ fn close(s: &mut Session, p: &Value) -> Result { } pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { - let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; + move_selected(s, p, false) +} + +/// The arrow keys with direct-selected anchors or segments: as `path.moveAnchors`, except that a +/// selected curved segment bends ([`SubPath::nudge_segment`]). +pub(crate) fn nudge_anchors(s: &mut Session, p: &Value) -> Result { + move_selected(s, p, true) +} + +/// Move the selection by `(dx, dy)`: its direct-selected anchors with their handles, and the +/// objects selected whole. With `bend`, each selected curved segment bends instead and its anchors +/// stay, except an anchor that also ends a selected straight segment, which moves with it. +fn move_selected(s: &mut Session, p: &Value, bend: bool) -> Result { + const C: &str = "path.moveAnchors"; + let d = Vec2::new(number_or(p, "dx", 0.0, C)?, number_or(p, "dy", 0.0, C)?); + check_switches(p, &["patterns", "interpolate"], C)?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let mut sel = st.selection.clone(); + let (held, bends) = if bend { held_segments(&st.doc, &mut sel, d) } else { (false, vec![]) }; + // Segments that hold their anchors and don't bend, with nothing else to move, change nothing. + if held && bends.is_empty() && sel.whole().is_empty() && sel.guides.is_empty() && sel.anchors.values().all(BTreeSet::is_empty) { + return ok(); + } // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. - let whole = s.doc()?.selection.whole(); - let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; - // Transform Again repeats a move that moved something; a drag records it when it commits. + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &sel.whole())?, ..Scaling::default() }; + let interpolate = interpolates_handles(s, p, C)?; + s.edit(if bends.is_empty() { "Move" } else { "Reshape" }, |doc, _| { + transform_selected(doc, &sel, vectorcraft_geom::Affine::translate(d), sc, interpolate)?; + for &(id, si, seg) in &bends { + if let Some(sp) = path_mut(doc, id)?.subpaths.get_mut(si) { + sp.nudge_segment(seg, d); + } + } + Ok(()) + })?; + // Transform Again repeats a move that moved something; a drag records it when it commits. A + // move that held segments' anchors is not one move of the selection. let st = s.doc_mut()?; - if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { + if !held && st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; @@ -264,6 +293,29 @@ pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { ok() } +/// Take the anchors of `sel`'s selected curved segments out of its `anchors`, except those that +/// also end a selected straight segment, and list the segments that a bend by `d` changes. Also +/// whether any curved segment is selected. +fn held_segments(doc: &Document, sel: &mut Selection, d: Vec2) -> (bool, Vec<(NodeId, usize, usize)>) { + let (mut held, mut bends) = (false, vec![]); + for (&id, refs) in &sel.segments { + let (Some(path), Some(set)) = (doc.node(id).and_then(Node::path_data), sel.anchors.get_mut(&id)) else { continue }; + let ends = |(si, seg): SegmentRef| path.subpaths.get(si).map(|sp| [(si, seg), (si, (seg + 1) % sp.anchors.len())]); + let curved = |&(si, seg): &SegmentRef| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count() && !sp.segment_is_line(seg)); + let moved: BTreeSet = refs.iter().filter(|r| !curved(r)).filter_map(|&r| ends(r)).flatten().collect(); + for &(si, seg) in refs.iter().filter(|r| curved(r)) { + held = true; + for end in ends((si, seg)).into_iter().flatten().filter(|e| !moved.contains(e)) { + set.remove(&end); + } + if path.subpaths.get(si).is_some_and(|sp| sp.nudged_handles(seg, d).is_some()) { + bends.push((id, si, seg)); + } + } + } + (held, bends) +} + /// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the /// segments beside them (`interpolate` param, else General › Interpolate Control Points When /// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference @@ -276,56 +328,59 @@ pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Res Ok(on) } +/// [`transform_selected`] on the active document's selection, as one undo step `label`. +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { + let sel = s.doc()?.selection.clone(); + s.edit(label, |doc, _| transform_selected(doc, &sel, xf, sc, interpolate)) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the -/// objects selected whole (those with no entry in the selection's `anchors`). An object inside +/// objects selected whole (those with no entry in `sel`'s `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. /// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end /// are re-mapped ([`move_interpolating_handles`]). -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { - let sel = s.doc()?.selection.clone(); - let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); +fn transform_selected(doc: &mut Document, sel: &Selection, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { + let ids = super::edit::outermost(doc, sel.objects.clone()); let c = xf.as_coeffs(); let is_translation = (c[0] - 1.0).abs() < 1e-9 && c[1].abs() < 1e-9 && c[2].abs() < 1e-9 && (c[3] - 1.0).abs() < 1e-9; let delta = vectorcraft_geom::Vec2::new(c[4], c[5]); - s.edit(label, |doc, _| { - for id in &ids { - match sel.anchors.get(id) { - Some(set) => { - let path = path_mut(doc, *id)?; - // Only an exact move takes the interpolating path: a near-identity scale or - // turn still transforms the anchors as asked. - if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { - move_interpolating_handles(path, set, delta); - } else { - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); - } + for id in &ids { + match sel.anchors.get(id) { + Some(set) => { + let path = path_mut(doc, *id)?; + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); } } - // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps - // to the pixel grid again after its anchors move. - let top = compound_or_self(doc, *id); - if let Some(n) = doc.node_mut(top) { - super::object::snap_if_aligned(n); - } } - None => { - if let Some(n) = doc.node_mut(*id) { - n.transform(xf, sc); - super::object::keep_pixel_aligned(n, sc); - } - super::object::keep_compound_aligned(doc, *id, sc); + // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps + // to the pixel grid again after its anchors move. + let top = compound_or_self(doc, *id); + if let Some(n) = doc.node_mut(top) { + super::object::snap_if_aligned(n); } } - } - if is_translation && (delta.x != 0.0 || delta.y != 0.0) { - for &i in &sel.guides { - doc.edit_ruler_guide(i, |g| *g = g.moved(delta)); + None => { + if let Some(n) = doc.node_mut(*id) { + n.transform(xf, sc); + super::object::keep_pixel_aligned(n, sc); + } + super::object::keep_compound_aligned(doc, *id, sc); } } - Ok(()) - }) + } + if is_translation && (delta.x != 0.0 || delta.y != 0.0) { + for &i in &sel.guides { + doc.edit_ruler_guide(i, |g| *g = g.moved(delta)); + } + } + Ok(()) } /// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ac4f237cd8..cd3ff27d5d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -182,6 +182,7 @@ mod script_include; mod script_io; mod script_run; mod scripts; +mod segment_nudge; mod select_effects; mod select_ids_first; mod shaper; diff --git a/crates/engine/src/tests/segment_nudge.rs b/crates/engine/src/tests/segment_nudge.rs new file mode 100644 index 0000000000..9a6e4c7523 --- /dev/null +++ b/crates/engine/src/tests/segment_nudge.rs @@ -0,0 +1,160 @@ +//! The arrow keys with a curved segment selected bend it: its anchors stay, its handles keep their +//! directions, and the middle of the curve moves toward the arrow. + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Anchor, ParamCurve, PathData, Point, SubPath, Vec2}; + +use crate::*; + +/// A session with one open path of one segment from (100, 300) to (400, 300), with the handles +/// `out` at its start and `in` at its end, and that segment selected with Direct Selection. +fn selected_segment(out: Point, h_in: Point) -> (Session, NodeId) { + let (p0, p1) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0)); + let (s, id) = session_with(vec![Anchor::with_handles(p0, p0, out), Anchor::with_handles(p1, h_in, p1)]); + (select(s, id, &[0]), id) +} + +/// A session with one open path through `anchors`. +fn session_with(anchors: Vec) -> (Session, NodeId) { + let mut d = Document::new(1000.0, 1000.0); + let id = d.alloc_id(); + let node = Node::path(id, PathData::single(SubPath::new(anchors, false)), Appearance::default_art()); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.push(Arc::new(node)); + } + let mut s = Session::new(); + s.add_document(d, None); + (s, id) +} + +/// `s` with segments `segments` of path `id` selected with Direct Selection. +fn select(mut s: Session, id: NodeId, segments: &[usize]) -> Session { + let refs: Vec<_> = segments.iter().map(|&seg| [0, seg]).collect(); + s.execute("select.segments", &json!({"id": id.0, "segments": refs})).unwrap(); + s +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn segment(s: &Session, id: NodeId) -> SubPath { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].clone() +} + +/// Each handle as a vector from its anchor: the outgoing one at the start, the incoming one at +/// the end. +fn handles(sp: &SubPath) -> (Vec2, Vec2) { + (sp.anchors[0].h_out - sp.anchors[0].p, sp.anchors[1].h_in - sp.anchors[1].p) +} + +fn middle(sp: &SubPath) -> Point { + sp.segment(0).eval(0.5) +} + +#[test] +fn arrows_bend_a_selected_curved_segment_and_keep_its_anchors() { + // The handle at the start points up, the one at the end left. + let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(300.0, 300.0)); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + let (up, left) = handles(&before); + + // Up: the upward handle grows, the one across the arrow stays. + s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap(); + let after = segment(&s, id); + let (up2, left2) = handles(&after); + assert_eq!((after.anchors[0].p, after.anchors[1].p), (before.anchors[0].p, before.anchors[1].p), "the anchors stay"); + assert!(up2.hypot() > up.hypot() && up2.cross(up).abs() < 1e-9 && up2.dot(up) > 0.0, "the upward handle grows in its direction: {up2:?}"); + assert_eq!(left2, left, "the handle across the arrow stays"); + assert!((middle(&after) - middle(&before) - Vec2::new(0.0, -step)).hypot() < 1e-9, "the middle moves one step up"); + + // Right: the handle pointing left shrinks, the upward one stays. + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + let last = segment(&s, id); + let (up3, left3) = handles(&last); + assert_eq!(up3, up2, "the handle across the arrow stays"); + assert!(left3.hypot() < left2.hypot() && left3.cross(left2).abs() < 1e-9 && left3.dot(left2) > 0.0, "the leftward handle shrinks: {left3:?}"); + assert!((middle(&last) - middle(&after) - Vec2::new(step, 0.0)).hypot() < 1e-9, "the middle moves one step right"); +} + +#[test] +fn arrows_move_a_selected_straight_segment_whole() { + let (mut s, id) = selected_segment(Point::new(100.0, 300.0), Point::new(400.0, 300.0)); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id); + for (a, b) in before.anchors.iter().zip(&after.anchors) { + assert_eq!(b.p - a.p, Vec2::new(0.0, step)); + } +} + +#[test] +fn a_selected_straight_segment_beside_a_curved_one_moves_whole() { + let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(600.0, 300.0)); + let (s, id) = session_with(vec![ + Anchor::with_handles(p0, p0, Point::new(100.0, 150.0)), + Anchor::with_handles(p1, Point::new(300.0, 300.0), p1), + Anchor::corner(p2), + ]); + let mut s = select(s, id, &[0, 1]); + let step = s.prefs.keyboard_increment; + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": -1})).unwrap(); + let after = segment(&s, id); + assert_eq!(after.anchors[0].p, before.anchors[0].p, "the curved segment's other anchor stays"); + for i in [1, 2] { + assert_eq!(after.anchors[i].p - before.anchors[i].p, Vec2::new(0.0, -step), "the straight segment's anchor {i} moves"); + } +} + +#[test] +fn a_segment_whose_handles_lie_across_the_arrow_records_no_undo_step() { + // Both handles point up: ← and → bend nothing. + let (mut s, id) = selected_segment(Point::new(100.0, 150.0), Point::new(400.0, 150.0)); + let (before, steps) = (segment(&s, id), undo_steps(&s)); + s.execute("object.nudge", &json!({"dx": 1, "dy": 0})).unwrap(); + assert_eq!(segment(&s, id), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn a_handle_bent_through_a_smooth_anchor_leaves_the_next_segment_as_it_is() { + // A smooth anchor between the selected segment, whose handle there is short and points up, + // and the next one. + let (p0, p1, p2) = (Point::new(100.0, 300.0), Point::new(400.0, 300.0), Point::new(700.0, 300.0)); + let smooth = Anchor::with_handles(p0, Point::new(100.0, 310.0), Point::new(100.0, 299.5)); + let (s, id) = session_with(vec![ + Anchor::corner(Point::new(-200.0, 300.0)), + smooth, + Anchor::with_handles(p1, Point::new(300.0, 300.0), p1), + Anchor::corner(p2), + ]); + assert_eq!(smooth.kind, vectorcraft_geom::AnchorKind::Smooth); + let mut s = select(s, id, &[1]); + let h_in = segment(&s, id).anchors[1].h_in; + // ↓ shrinks the upward handle through its anchor. + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id).anchors[1]; + assert!(after.h_out.y > p0.y, "the handle comes out pointing down: {:?}", after.h_out); + assert_eq!(after.h_in, h_in, "the next segment's handle stays"); +} + +#[test] +fn a_retracted_handle_the_arrow_leaves_keeps_its_smooth_anchor_smooth() { + // A smooth anchor whose outgoing handle is retracted, so it points toward the other handle's + // end, level with it and across ↓; only the other handle, pointing up, changes. + let (p0, p1) = (Point::new(100.0, 300.0), Point::new(200.0, 400.0)); + let smooth = Anchor { p: p0, h_in: Point::new(0.0, 300.0), h_out: p0, kind: vectorcraft_geom::AnchorKind::Smooth }; + let (s, id) = session_with(vec![Anchor::corner(Point::new(-200.0, 300.0)), smooth, Anchor::with_handles(p1, Point::new(200.0, 300.0), p1)]); + let mut s = select(s, id, &[1]); + let before = segment(&s, id); + s.execute("object.nudge", &json!({"dx": 0, "dy": 1})).unwrap(); + let after = segment(&s, id); + assert_ne!(after.anchors[2].h_in, before.anchors[2].h_in, "the upward handle changes"); + assert_eq!(after.anchors[1], before.anchors[1], "the smooth anchor stays as it was"); +} diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index abd72b255e..5916f6fb21 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -444,6 +444,59 @@ impl SubPath { } true } + /// Bend segment `seg` as the arrow keys do: its anchors stay and its handles go where + /// [`Self::nudged_handles`] puts them. A handle that keeps its direction leaves a smooth anchor + /// smooth; one that flips or grows out of its anchor makes it a corner, so the segment beside + /// it stays as it is. False, with nothing changed, when the bend changes nothing. + pub fn nudge_segment(&mut self, seg: usize, dv: kurbo::Vec2) -> bool { + let Some((h_out, h_in)) = self.nudged_handles(seg, dv) else { return false }; + let n = self.anchors.len(); + // Turned when the new handle doesn't point the way the old one did. + let turned = |a: &Anchor, old: Point, new: Point| (old - a.p).dot(new - a.p) <= 0.0; + if let Some(a) = self.anchors.get_mut(seg % n) + && h_out != a.h_out + { + let independent = turned(a, a.h_out, h_out); + a.set_handle(true, h_out, independent); + } + if let Some(b) = self.anchors.get_mut((seg + 1) % n) + && h_in != b.h_in + { + let independent = turned(b, b.h_in, h_in); + b.set_handle(false, h_in, independent); + } + true + } + /// The outgoing handle at the start and the incoming one at the end that segment `seg` gets + /// from the arrow keys' step `dv`. Each handle keeps its direction and changes length in + /// proportion to `dv` projected onto that direction, so the curve bulges toward `dv`: the + /// middle of the curve moves by `dv`'s length along `dv`, or less when the handles point + /// mostly across it. A handle can shrink through its anchor and come out the other way. A + /// retracted handle takes the direction from its anchor to the other handle's end. `None` when + /// there is no such segment, it is a straight line, or both handles are at right angles to + /// `dv`, so nothing changes. + pub fn nudged_handles(&self, seg: usize, dv: kurbo::Vec2) -> Option<(Point, Point)> { + if seg >= self.segment_count() || self.segment_is_line(seg) { + return None; + } + let c = self.segment(seg); + let direction = |anchor: Point, handle: Point, other: Point| { + let dir = if handle.distance(anchor) > EPS { handle - anchor } else { other - anchor }; + let len = dir.hypot(); + if len > EPS { dir / len } else { kurbo::Vec2::ZERO } + }; + let (u0, u1) = (direction(c.p0, c.p1, c.p2), direction(c.p3, c.p2, c.p1)); + let (d0, d1) = (dv.dot(u0), dv.dot(u1)); + // Handles that change by k·d0 and k·d1 move the middle B(1/2) by 3/8·k·(d0·u0 + d1·u1), + // whose part along dv is 3/8·k·(d0² + d1²)/|dv|: one |dv| for k = 8/3·|dv|²/(d0² + d1²), + // kept to at most 8/3 so that handles nearly across dv don't grow without bound. + let sum = d0 * d0 + d1 * d1; + if sum <= EPS * EPS { + return None; + } + let k = 8.0 / 3.0 * (dv.hypot2() / sum).min(1.0); + Some((c.p1 + u0 * (k * d0), c.p2 + u1 * (k * d1))) + } /// Split segment `seg` at parameter `t`, inserting a new anchor. Returns the new anchor index. pub fn insert_anchor(&mut self, seg: usize, t: f64) -> usize {