SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Extend: pick two curves to extend both to where they meet (#4750) (#8392)
momysnow1445b5a4f083
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex 06f935b26b..9cecede6f3 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -71,7 +71,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SKETCH", "MODIFY").icon("extend").enabled(in_sketch)- .params("curve: id, at: [x,y] near the end to extend (a line runs on to the nearest curve, or the previewed reach when nothing is in the way; an arc grows along its circle and closes into a whole circle when nothing stops it)"),+ .params("curve: id, at: [x,y] near the end to extend (a line runs on to the nearest curve, or the previewed reach when nothing is in the way; an arc grows along its circle and closes into a whole circle when nothing stops it) | curves: [id, id] (two lines or arcs of this sketch, grown until they meet and joined there), at?: [[x,y],[x,y]] (one point per curve: the end to grow; default the end nearest the meeting point). `curve` and `curves` exclude each other; the two-curve form returns moved: the meeting point's id"),CommandSpec::new("sketch.break", "Break", break_cmd).at("SKETCH", "MODIFY").icon("sketch_break")@@ -115,6 +115,10 @@ const MAX_COPIES: usize = 500;fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result<usize> {let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?;+ curve_by_id(sk, id, cmd)+}++fn curve_by_id(sk: &Sketch, id: &str, cmd: &str) -> Result<usize> {let c = sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?;if sk.is_linked_curve(c) {return Err(bad(cmd, format!("`{id}` is projected geometry: break its link first")));@@ -628,17 +632,25 @@ struct LineAim {stop: Option<usize>,}-/// The first geometry a line meets when it grows past the end of `ci` nearest `at`, or the reach-/// past that end when nothing is in the way. Two curves stopping it equally far are one stop: the-/// first of them is taken.-fn line_aim(sk: &Sketch, ci: usize, at: Vec2) -> Result<Option<LineAim>> {+/// The end of line `ci` a growth starts from: the end nearest `toward`, with the checks that it+/// may move. `None` for an infinite line or a curve that is not a line.+struct LineEnd {+ end: usize,+ at_b: bool,+ end_pt: Vec2,+ dir: Vec2,+ length: f64,+ sh: Shape,+}++fn line_end(sk: &Sketch, ci: usize, toward: Vec2) -> Result<Option<LineEnd>> {let cmd = "sketch.extend";// An infinite line has no end to grow: moving either of its points moves the whole line.let Some(curve) = sk.curves.get(ci).filter(|c| !c.infinite) else { return Ok(None) };let CurveKind::Line { a: pa, b: pb } = curve.kind else { return Ok(None) };let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?;let (qa, qb) = (sk.point(pa).unwrap_or_default(), sk.point(pb).unwrap_or_default());- let at_b = at.dist(qb) <= at.dist(qa);+ let at_b = toward.dist(qb) <= toward.dist(qa);let (end, end_pt) = if at_b { (pb, qb) } else { (pa, qa) };let dir = (end_pt - if at_b { qa } else { qb }).normalized().ok_or_else(|| bad(cmd, "cannot determine extension direction"))?;@@ -656,9 +668,17 @@ fn line_aim(sk: &Sketch, ci: usize, at: Vec2) -> Result<Option<LineAim>> {}}}+ Ok(Some(LineEnd { end, at_b, end_pt, dir, length: qa.dist(qb), sh }))+}++/// The first geometry a line meets when it grows past the end of `ci` nearest `at`, or the reach+/// past that end when nothing is in the way. Two curves stopping it equally far are one stop: the+/// first of them is taken.+fn line_aim(sk: &Sketch, ci: usize, at: Vec2) -> Result<Option<LineAim>> {+ let cmd = "sketch.extend";+ let Some(LineEnd { end, at_b, end_pt, dir, length, sh }) = line_end(sk, ci, at)? else { return Ok(None) };// Candidate stops on the line's unbounded support beyond the chosen end.- let length = qa.dist(qb);let mut best: Option<(f64, Vec2, usize)> = None;let mut budget = 1_000_000usize;let mut segment_count = 0usize;@@ -724,9 +744,10 @@ struct ArcAim {/// The angle the growing end sits at, and how far round the circle the extension travels.end_angle: f64,travel: f64,- /// The point the extension stops at, and the curve that stops it there.+ /// The point the extension stops at, and the curve that stops it there (none when the stop is+ /// a meeting point the caller chose).hit: Vec2,- cutter: usize,+ cutter: Option<usize>,}impl ArcAim {@@ -738,12 +759,24 @@ impl ArcAim {}}-/// The first geometry an arc meets when it grows from the end of `ci` nearest `at`. Both ends-/// grow: past `b` counter-clockwise, past `a` clockwise, and only as far as the nearest curve on-/// that path stops them. With nothing in the way the extension runs on to the arc's own far end,-/// closing the arc into a full circle. Two curves stopping it equally far are one stop: the first-/// is taken.-fn arc_aim(sk: &Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<Option<ArcAim>> {+/// The end of arc `ci` a growth starts from: the end nearest `toward`, the far end the growth must+/// not pass, and the arc's circle. `None` for a whole circle or a curve that is not an arc.+#[derive(Clone, Copy)]+struct ArcEnd {+ end: usize,+ far: usize,+ far_pt: Vec2,+ at_b: bool,+ centre: Vec2,+ r: f64,+ end_angle: f64,+ /// How far round the circle the growth may travel: up to the far end, where the arc begins.+ reach: f64,+ angle_tol: f64,+ far_tol: f64,+}++fn arc_end(sk: &Sketch, ci: usize, toward: Vec2, cmd: &str) -> Result<Option<ArcEnd>> {let Some(CurveKind::Arc { a, b, .. }) = sk.curves.get(ci).map(|c| c.kind.clone()) else { return Ok(None) };let Some(Shape::Round { c: centre, r, start, sweep }) = sk.shape(ci) else { return Ok(None) };if !(r.is_finite() && r > 0.0) || !start.is_finite() || !sweep.is_finite() {@@ -754,13 +787,21 @@ fn arc_aim(sk: &Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<Option<ArcAim>return Ok(None);}let (Some(qa), Some(qb)) = (sk.point(a), sk.point(b)) else { return Ok(None) };- let at_b = at.dist(qb) <= at.dist(qa);- let (end, far, end_angle) = if at_b { (b, a, start + sweep) } else { (a, b, start) };+ let at_b = toward.dist(qb) <= toward.dist(qa);+ let (end, far, far_pt, end_angle) = if at_b { (b, a, qa, start + sweep) } else { (a, b, qb, start) };+ Ok(Some(ArcEnd { end, far, far_pt, at_b, centre, r, end_angle, reach: TAU - sweep, angle_tol: TOL / r, far_tol: TOL * 10.0 / r }))+}++/// The first geometry an arc meets when it grows from the end of `ci` nearest `at`. Both ends+/// grow: past `b` counter-clockwise, past `a` clockwise, and only as far as the nearest curve on+/// that path stops them. With nothing in the way the extension runs on to the arc's own far end,+/// closing the arc into a full circle. Two curves stopping it equally far are one stop: the first+/// is taken.+fn arc_aim(sk: &Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<Option<ArcAim>> {+ let Some(ae) = arc_end(sk, ci, at, cmd)? else { return Ok(None) };// The extension runs from the growing end round to the far end, where the arc itself begins// again: it may stop on it (closing the gap between the two ends) but not pass it.- let reach = TAU - sweep;- let angle_tol = TOL / r;- let far_tol = TOL * 10.0 / r;+ let ArcEnd { end, far, far_pt, at_b, centre, r, end_angle, reach, angle_tol, far_tol } = ae;let circle = Shape::Round { c: centre, r, start: 0.0, sweep: TAU };let mut best: Option<(f64, Vec2, usize)> = None;let mut budget = 1_000_000usize;@@ -816,8 +857,10 @@ fn arc_aim(sk: &Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<Option<ArcAim>}// Nothing stops the arc on its way round: it grows all the way to its own far end, closing// the gap between its ends into a full circle.- let far_pt = if at_b { qa } else { qb };- let (travel, hit, cutter) = best.unwrap_or((reach, far_pt, ci));+ let (travel, hit, cutter) = match best {+ Some((travel, q, oi)) => (travel, q, Some(oi)),+ None => (reach, far_pt, Some(ci)),+ };Ok(Some(ArcAim { end, far, at_b, centre, radius: r, end_angle, travel, hit, cutter }))}@@ -912,6 +955,11 @@ fn extend_arc(sk: &mut Sketch, ci: usize, at: Vec2) -> Result<String> {let Some(aim) = arc_aim(sk, ci, at, cmd)? else {return Err(bad(cmd, "an arc that is already a whole circle has no end to extend"));};+ grow_arc(sk, ci, aim)+}++/// Grow arc `ci` from the end `aim` names, to `aim.hit`, as [`extend_arc`] does for a click.+fn grow_arc(sk: &mut Sketch, ci: usize, aim: ArcAim) -> Result<String> {let stop = arc_stop(sk, ci, &aim);// The arc's own far end is where the arc begins again: moving the end onto it would leave a// whole circle, so the gap is filled by a new arc joining that end.@@ -941,8 +989,8 @@ fn extend_arc(sk: &mut Sketch, ci: usize, at: Vec2) -> Result<String> {if stop != aim.end {add_c(sk, ConstraintKind::Coincident { p: aim.end, q: stop })?;}- } else {- pin(sk, aim.end, aim.cutter)?;+ } else if let Some(cutter) = aim.cutter {+ pin(sk, aim.end, cutter)?;}Ok(sk.points.get(aim.end).map(|x| x.id.clone()).unwrap_or_default())}@@ -957,12 +1005,16 @@ pub fn extend_arc_preview(sk: &solidcraft_sketch::Sketch, ci: usize, hover_pos:fn extend(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.extend";- let at = req_vec2(cmd, p, "at")?;+ let pair = pair_request(p, cmd)?;+ let at = if pair.is_none() { req_vec2(cmd, p, "at")? } else { Vec2::default() };let (out, info) = edit(s, p, cmd, true, |sk, doc| {let rep = solve_current(sk, doc)?;if !rep.keeps_orientation() {return Err(bad(cmd, rep.failure(|_| "solve the existing sketch constraints before extending".into())));}+ if let Some((ids, ats)) = &pair {+ return extend_pair(sk, ids, *ats, cmd);+ }let ci = curve_arg(sk, p, cmd)?;refuse_offset_ends(sk, ci, "extend", cmd)?;// An infinite line already reaches across the view: moving one of its two points would@@ -981,73 +1033,304 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {let Some(aim) = line_aim(sk, ci, at)? else {return Err(bad(cmd, "only lines and arcs can be extended"));};- let end = aim.end;- let (q, cutter, stop) = (aim.hit, aim.cutter, aim.stop);- let neighbors: Vec<_> = sk.curves.iter().enumerate().filter(|(i, c)| *i != ci && uses(c, end)).collect();-- // The end joined to other geometry stays where it is: add a line from it.- if !neighbors.is_empty() {- return add_line_extension(sk, end, q, stop);- }-- // An end held by a constraint, or lying on a circle or arc, stays where it is too: the- // extension is a new line from it.- let end_is_held = sk.constraints.iter().any(|c| {- use solidcraft_sketch::ConstraintKind::*;- match c.kind {- Coincident { p, q } => p == end || q == end,- Fix { p } => p == end,- PointOnCurve { p, .. } => p == end,- Midpoint { p, .. } => p == end,- HorizontalPoints { p, q } | VerticalPoints { p, q } => p == end || q == end,- Symmetric { p, q, .. } => p == end || q == end,- _ => false,+ grow_line(sk, ci, aim)+ })?;+ Ok(json!({"moved": out, "sketch": info}))+}++/// Grow line `ci` past the end `aim` names, to `aim.hit`: a new line when that end is joined to+/// other geometry or held by a constraint, otherwise the end itself moves there if the solver+/// lets it.+fn grow_line(sk: &mut Sketch, ci: usize, aim: LineAim) -> Result<String> {+ let end = aim.end;+ let (q, cutter, stop) = (aim.hit, aim.cutter, aim.stop);+ let neighbors: Vec<_> = sk.curves.iter().enumerate().filter(|(i, c)| *i != ci && uses(c, end)).collect();++ // The end joined to other geometry stays where it is: add a line from it.+ if !neighbors.is_empty() {+ return add_line_extension(sk, end, q, stop);+ }++ // An end held by a constraint, or lying on a circle or arc, stays where it is too: the+ // extension is a new line from it.+ let end_is_held = sk.constraints.iter().any(|c| {+ use solidcraft_sketch::ConstraintKind::*;+ match c.kind {+ Coincident { p, q } => p == end || q == end,+ Fix { p } => p == end,+ PointOnCurve { p, .. } => p == end,+ Midpoint { p, .. } => p == end,+ HorizontalPoints { p, q } | VerticalPoints { p, q } => p == end || q == end,+ Symmetric { p, q, .. } => p == end || q == end,+ _ => false,+ }+ }) || {+ // Geometric check: does the endpoint lie on any circle or arc?+ let ep = sk.point(end).unwrap_or_default();+ sk.curves.iter().any(|curve| match curve.kind {+ CurveKind::Circle { c, r } => (ep - sk.point(c).unwrap_or_default()).len().abs() - r < 1e-6,+ // This is an arc's own start or end: it sits on that arc.+ CurveKind::Arc { a, b, .. } => ep.dist(sk.point(a).unwrap_or_default()) < 1e-6 || ep.dist(sk.point(b).unwrap_or_default()) < 1e-6,+ _ => false,+ })+ };++ if end_is_held {+ return add_line_extension(sk, end, q, stop);+ }++ // A free end moves along instead, if the solver lets it. The attempt is made on a copy,+ // so an end the solver cannot put where it belongs leaves the sketch as it was for the+ // new line below.+ let mut attempt = sk.clone();+ if let Some(pt) = attempt.points.get_mut(end) {+ pt.pos = q;+ }+ // Held to the point that is already there or to what else stopped it, an end stays where+ // the extension put it; an end with nothing to hold it is simply placed there.+ if let Some(stop) = stop {+ if stop != end {+ add_c(&mut attempt, ConstraintKind::Coincident { p: end, q: stop })?;+ }+ } else if let Some(cutter) = cutter {+ pin(&mut attempt, end, cutter)?;+ }+ let before = sk.points.iter().map(|p| p.pos).collect::<Vec<_>>();+ let hold =+ solidcraft_sketch::Hold { points: (0..attempt.points.len()).filter(|i| *i != end).collect(), radii: (0..attempt.curves.len()).collect() };+ let moved = solidcraft_sketch::solve_with(&mut attempt, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()+ && attempt.point(end).is_some_and(|point| point.dist(q) <= TOL)+ && attempt.points.iter().enumerate().all(|(i, point)| i == end || point.pos.dist(before[i]) <= TOL);+ if moved {+ *sk = attempt;+ return Ok(sk.points.get(end).map(|x| x.id.clone()).unwrap_or_default());+ }+ // The solve could not put the end where it belongs: add a new line instead.+ add_line_extension(sk, end, q, stop)+}++/// The two-curve form of `sketch.extend`: `curves` names exactly two curves, `at` optionally one+/// point per curve. `None` when the request is the single-curve form.+fn pair_request(p: &Value, cmd: &str) -> Result<Option<(Vec<String>, Option<[Vec2; 2]>)>> {+ let Some(list) = p.get("curves") else { return Ok(None) };+ if p.get("curve").is_some() {+ return Err(bad(cmd, "give `curve` with `at` (one curve) or `curves` (two curves), not both"));+ }+ let ids =+ list.as_array().filter(|a| a.len() == 2).and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<String>>>());+ let Some(ids) = ids else {+ return Err(bad(cmd, "`curves` must be a list of exactly two curve ids"));+ };+ let ats = match p.get("at") {+ None => None,+ Some(v) => {+ let pts = v.as_array().filter(|a| a.len() == 2).and_then(|a| a.iter().map(vec2).collect::<Option<Vec<Vec2>>>());+ match pts.map(<[Vec2; 2]>::try_from) {+ Some(Ok(two)) => Some(two),+ _ => return Err(bad(cmd, "with `curves`, `at` is one point per curve: [[x,y],[x,y]]")),}- }) || {- // Geometric check: does the endpoint lie on any circle or arc?- let ep = sk.point(end).unwrap_or_default();- sk.curves.iter().any(|curve| match curve.kind {- CurveKind::Circle { c, r } => (ep - sk.point(c).unwrap_or_default()).len().abs() - r < 1e-6,- // This is an arc's own start or end: it sits on that arc.- CurveKind::Arc { a, b, .. } => ep.dist(sk.point(a).unwrap_or_default()) < 1e-6 || ep.dist(sk.point(b).unwrap_or_default()) < 1e-6,- _ => false,- })- };+ }+ };+ Ok(Some((ids, ats)))+}++/// How a line or arc of a two-curve extension reaches the meeting point `q`: the growth to apply+/// and its length. `None` when `q` lies behind the chosen end (the extension would shorten the+/// curve), or when the curve cannot grow at all.+fn reach_to(sk: &Sketch, ci: usize, toward: Vec2, q: Vec2, cmd: &str) -> Result<Option<(Grow, f64)>> {+ match sk.curves.get(ci).map(|c| &c.kind) {+ Some(CurveKind::Line { .. }) => {+ let Some(le) = line_end(sk, ci, toward)? else { return Ok(None) };+ let t = le.sh.param(q);+ let travel = if le.at_b { (t - 1.0) * le.length } else { -t * le.length };+ if travel < -TOL * 10.0 {+ return Ok(None);+ }+ let aim = LineAim { end: le.end, hit: q, cutter: None, stop: stop_point(sk, ci, q) };+ Ok(Some((Grow::Line(aim), travel.max(0.0))))+ }+ Some(CurveKind::Arc { .. }) => {+ let Some(ae) = arc_end(sk, ci, toward, cmd)? else { return Ok(None) };+ let angle = (q - ae.centre).angle();+ let mut travel = if ae.at_b { angle - ae.end_angle } else { ae.end_angle - angle }.rem_euclid(TAU);+ // Just behind the growing end is the end itself, not a whole turn round.+ if travel >= TAU - ae.angle_tol {+ travel = 0.0;+ }+ if travel > ae.reach + ae.far_tol {+ return Ok(None);+ }+ let aim = ArcAim {+ end: ae.end,+ far: ae.far,+ at_b: ae.at_b,+ centre: ae.centre,+ radius: ae.r,+ end_angle: ae.end_angle,+ travel,+ hit: q,+ cutter: None,+ };+ Ok(Some((Grow::Arc(aim), travel * ae.r)))+ }+ _ => Ok(None),+ }+}++/// A grow step ready to apply: a line's or an arc's aim.+enum Grow {+ Line(LineAim),+ Arc(ArcAim),+}++/// The lines and circles the two curves lie on, before their ends are checked.+#[derive(Clone, Copy)]+enum Support {+ Line { p: Vec2, d: Vec2 },+ Circle { c: Vec2, r: f64 },+}++fn support(sk: &Sketch, ci: usize, cmd: &str) -> Result<Support> {+ let growable = sk.curves.get(ci).is_some_and(|c| !c.infinite && matches!(c.kind, CurveKind::Line { .. } | CurveKind::Arc { .. }));+ if !growable {+ return Err(bad(cmd, "only lines and arcs can be extended, and an infinite line has no end"));+ }+ match sk.shape(ci) {+ Some(Shape::Line { a, b }) if (b - a).len() > TOL => Ok(Support::Line { p: a, d: b - a }),+ Some(Shape::Line { .. }) => Err(bad(cmd, "a line with no length has no direction to extend")),+ Some(Shape::Round { c, r, .. }) if r.is_finite() && r > 0.0 => Ok(Support::Circle { c, r }),+ _ => Err(bad(cmd, "the curve's geometry is not usable")),+ }+}- if end_is_held {- return add_line_extension(sk, end, q, stop);+/// Where two supports meet: the crossings of two lines, a line and a circle, or two circles.+fn support_meets(a: Support, b: Support, cmd: &str) -> Result<Vec<Vec2>> {+ let mut out = Vec::new();+ match (a, b) {+ (Support::Line { p: p1, d: d1 }, Support::Line { p: p2, d: d2 }) => {+ let den = d1.cross(d2);+ if den.abs() <= 1e-12 * d1.len() * d2.len() {+ // Distance of the second line's start from the first line: zero when they are collinear.+ if (p2 - p1).cross(d1).abs() / d1.len() <= TOL * 10.0 {+ return Err(bad(cmd, "these lines are collinear: they lie on one line and never meet at a point"));+ }+ return Err(bad(cmd, "these lines are parallel: they never meet"));+ }+ out.push(p1 + d1 * ((p2 - p1).cross(d2) / den));+ }+ (Support::Line { p, d }, Support::Circle { c, r }) | (Support::Circle { c, r }, Support::Line { p, d }) => {+ // |p + s d - c| = r, a quadratic in s.+ let f = p - c;+ let (qa, qb, qc) = (d.dot(d), 2.0 * d.dot(f), f.dot(f) - r * r);+ let disc = qb * qb - 4.0 * qa * qc;+ if disc >= -1e-9 {+ let root = disc.max(0.0).sqrt();+ out.push(p + d * ((-qb - root) / (2.0 * qa)));+ out.push(p + d * ((-qb + root) / (2.0 * qa)));+ }+ }+ (Support::Circle { c: c1, r: r1 }, Support::Circle { c: c2, r: r2 }) => {+ let dv = c2 - c1;+ let d = dv.len();+ if d <= TOL {+ if (r1 - r2).abs() <= TOL * 10.0 {+ return Err(bad(cmd, "these arcs lie on one circle: they do not meet at a point"));+ }+ return Ok(out);+ }+ if d > r1 + r2 + TOL * 10.0 || d < (r1 - r2).abs() - TOL * 10.0 {+ return Ok(out);+ }+ let along = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d);+ let h = (r1 * r1 - along * along).max(0.0).sqrt();+ let u = dv * (1.0 / d);+ let m = c1 + u * along;+ let perp = Vec2::new(-u.y, u.x);+ out.push(m + perp * h);+ out.push(m - perp * h);}+ }+ Ok(out)+}- // A free end moves along instead, if the solver lets it. The attempt is made on a copy,- // so an end the solver cannot put where it belongs leaves the sketch as it was for the- // new line below.- let mut attempt = sk.clone();- if let Some(pt) = attempt.points.get_mut(end) {- pt.pos = q;+/// Extend two lines or arcs of the sketch until they meet, and join their two grown ends there.+/// Each grows from the end `ats` names for it, or from the end nearest the meeting point. Returns+/// the id of the meeting point.+fn extend_pair(sk: &mut Sketch, ids: &[String], ats: Option<[Vec2; 2]>, cmd: &str) -> Result<String> {+ let [id0, id1] = ids else { return Err(bad(cmd, "`curves` must be a list of exactly two curve ids")) };+ let cs = [curve_by_id(sk, id0, cmd)?, curve_by_id(sk, id1, cmd)?];+ if cs[0] == cs[1] {+ return Err(bad(cmd, "`curves` names the same curve twice: give two different curves"));+ }+ for c in cs {+ refuse_offset_ends(sk, c, "extend", cmd)?;+ }+ let sup = [support(sk, cs[0], cmd)?, support(sk, cs[1], cmd)?];+ let cands = support_meets(sup[0], sup[1], cmd)?;+ if cands.is_empty() {+ return Err(bad(cmd, "these curves do not meet: there is no point to extend them to"));+ }+ let toward = |i: usize, q: Vec2| ats.map_or(q, |a| if i == 0 { a[0] } else { a[1] });++ // Each meeting point both curves reach by growing from their chosen ends, with the total length+ // grown. A candidate one curve cannot reach is skipped; its error is kept, and returned only+ // when no candidate works.+ let mut valid: Vec<(Vec2, f64)> = Vec::new();+ let mut first_err = None;+ for q in cands.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()) {+ match (reach_to(sk, cs[0], toward(0, q), q, cmd), reach_to(sk, cs[1], toward(1, q), q, cmd)) {+ (Ok(Some((_, l0))), Ok(Some((_, l1)))) => {+ if valid.iter().all(|(x, _)| x.dist(q) > TOL * 10.0) {+ valid.push((q, l0 + l1));+ }+ }+ (Err(e), _) | (_, Err(e)) => {+ first_err.get_or_insert(e);+ }+ _ => {}+ }+ }+ if valid.is_empty() {+ if let Some(e) = first_err {+ return Err(e);}- // Held to the point that is already there or to what else stopped it, an end stays where- // the extension put it; an end with nothing to hold it is simply placed there.- if let Some(stop) = stop {- if stop != end {- add_c(&mut attempt, ConstraintKind::Coincident { p: end, q: stop })?;+ return Err(bad(+ cmd,+ "the curves meet only where growing one would shorten it: the meeting point lies on a curve's body or behind its chosen end; pick the other end with `at`, or extend one curve to the point by hand",+ ));+ }+ // The least total growth wins. Two meeting points with the same growth leave no reason to+ // choose one, so that is refused.+ let least = valid.iter().map(|v| v.1).fold(f64::INFINITY, f64::min);+ let best: Vec<Vec2> = valid.iter().filter(|v| v.1 - least <= TOL * 10.0).map(|v| v.0).collect();+ let [q] = best.as_slice() else {+ return Err(bad(cmd, "the curves meet at two points that take the same growth: extend one of them by hand"));+ };+ let q = *q;+ if least <= TOL * 10.0 {+ return Err(bad(cmd, "the two curves already meet there: nothing to extend"));+ }+ // The first grown end becomes the stop of the second, so the second joins it. Each curve's+ // reach is taken again from the sketch as it is by then. The id returned is the joined end.+ let mut joined = String::new();+ for (i, ci) in cs.into_iter().enumerate() {+ let Some((grow, len)) = reach_to(sk, ci, toward(i, q), q, cmd)? else {+ return Err(bad(cmd, "the curves do not meet beyond their ends"));+ };+ let end = match &grow {+ Grow::Line(aim) => aim.end,+ Grow::Arc(aim) => aim.end,+ };+ joined = if len <= TOL * 10.0 {+ sk.points.get(end).map(|p| p.id.clone()).unwrap_or_default()+ } else {+ match grow {+ Grow::Line(aim) => grow_line(sk, ci, aim)?,+ Grow::Arc(aim) => grow_arc(sk, ci, aim)?,}- } else if let Some(cutter) = cutter {- pin(&mut attempt, end, cutter)?;- }- let before = sk.points.iter().map(|p| p.pos).collect::<Vec<_>>();- let hold =- solidcraft_sketch::Hold { points: (0..attempt.points.len()).filter(|i| *i != end).collect(), radii: (0..attempt.curves.len()).collect() };- let moved = solidcraft_sketch::solve_with(&mut attempt, &hold, None, solidcraft_sketch::Analysis::StatusOnly, None).ok()- && attempt.point(end).is_some_and(|point| point.dist(q) <= TOL)- && attempt.points.iter().enumerate().all(|(i, point)| i == end || point.pos.dist(before[i]) <= TOL);- if moved {- *sk = attempt;- return Ok(sk.points.get(end).map(|x| x.id.clone()).unwrap_or_default());- }- // The solve could not put the end where it belongs: add a new line instead.- add_line_extension(sk, end, q, stop)- })?;- Ok(json!({"moved": out, "sketch": info}))+ };+ }+ Ok(joined)}fn uses(c: &Curve, p: usize) -> bool {diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex eb0decb57c..6158375b24 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -2858,3 +2858,275 @@ fn a_fillet_stays_a_quarter_arc_when_its_corner_is_pinned_or_dragged_to_the_otheassert_eq!(curve(&si, "l1")["end_at"], json!([45.0, 10.0]), "{}", curve(&si, "l1"));assert_eq!(curve(&si, "l2")["start_at"], json!([40.0, 5.0]), "{}", curve(&si, "l2"));}++// ---------------------------------------------------------------------------------------------+// `sketch.extend` with two curves (#4750): each grows to where the two meet, and they are joined.++fn coincident_count(sk: &solidcraft_sketch::Sketch) -> usize {+ sk.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Coincident { .. })).count()+}++fn point_at(sk: &solidcraft_sketch::Sketch, id: &str) -> Vec2 {+ sk.point(sk.resolve_point(id).expect("a point")).expect("its position")+}++#[test]+fn extend_two_lines_meet_in_an_open_l_and_close_into_one_profile() {+ // A runs right along y=0 and stops at (8,0); B comes down x=12 from (12,6) to (12,2). Their+ // lines meet at (12,0): A grows 4 (8 to 12), B grows 2 (2 to 0). One Coincident joins them.+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false}))["curves"])[0].clone();+ let before = sketch(&s);+ let (curves, points, coincident) = (before.curves.len(), before.points.len(), coincident_count(&before));++ let out = run(&mut s, "sketch.extend", json!({"curves": [a, b]}));++ let sk = sketch(&s);+ assert_eq!((sk.curves.len(), sk.points.len()), (curves, points), "no curve or point is added");+ assert_eq!(coincident_count(&sk), coincident + 1, "one Coincident joins the two ends");+ assert!(point_at(&sk, &format!("{a}.end")).dist(Vec2::new(12.0, 0.0)) < 1e-6, "{a} ends at the meeting point");+ assert!(point_at(&sk, &format!("{b}.end")).dist(Vec2::new(12.0, 0.0)) < 1e-6, "{b} ends at the meeting point");+ let meet = out["moved"].as_str().expect("the meeting point id");+ assert!(point_at(&sk, meet).dist(Vec2::new(12.0, 0.0)) < 1e-6, "{meet}");++ // A closing line (12,6) to (0,0) makes the L a triangle of area 12 * 6 / 2 = 36.+ run(&mut s, "sketch.line", json!({"points":[[12,6],[0,0]],"closed":false}));+ assert!(profiles(&s).iter().any(|area| (area - 36.0).abs() < 1e-6), "{:?}", profiles(&s));+}++#[test]+fn extend_a_line_and_an_arc_meet_at_the_point_both_reach() {+ // Arc: centre (0,0), radius 5, from (0,5) round to (-5,0). Line: x=-3 from (-3,-1) to (-3,-2).+ // They meet at (-3,-4), a 3-4-5 point: the arc grows from (-5,0) through 53.13 degrees+ // (atan2(-4,-3) is 233.13 degrees), and the line grows 2 (from (-3,-2) to (-3,-4)).+ let mut s = new_sketch();+ let arc = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[0,5],"end":[-5,0],"connect":false}))["curves"])[0].clone();+ let line = ids(&run(&mut s, "sketch.line", json!({"points":[[-3,-1],[-3,-2]],"connect":false,"infer":false}))["curves"])[0].clone();++ run(&mut s, "sketch.extend", json!({"curves": [arc, line], "at": [[-5, 0], [-3, -2]]}));++ let sk = sketch(&s);+ assert!(point_at(&sk, &format!("{arc}.end")).dist(Vec2::new(-3.0, -4.0)) < 1e-6, "the arc reaches the meeting point");+ assert!(point_at(&sk, &format!("{line}.end")).dist(Vec2::new(-3.0, -4.0)) < 1e-6, "the line reaches it");+ assert_eq!(coincident_count(&sk), 1, "one Coincident joins them");+ let ci = sk.curve_index(&arc).expect("the arc");+ assert!(sk.shape(ci).is_some_and(|sh| sh.dist(Vec2::new(-3.0, -4.0)) < 1e-6), "the arc stays on its circle");+}++#[test]+fn extend_two_lines_grows_only_the_one_that_does_not_reach() {+ // A already ends at (12,0), where B meets it: only B grows (2 to 0), and A keeps its end.+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[12,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false}))["curves"])[0].clone();+ let before = sketch(&s);+ let a_end = before.resolve_point(&format!("{a}.end")).expect("a's end");++ run(&mut s, "sketch.extend", json!({"curves": [a, b]}));++ let sk = sketch(&s);+ assert_eq!(sk.resolve_point(&format!("{a}.end")), Some(a_end), "the line that already reaches keeps its end");+ assert!(point_at(&sk, &format!("{b}.end")).dist(Vec2::new(12.0, 0.0)) < 1e-6, "only {b} grows");+ assert_eq!(sk.points.len(), before.points.len(), "its end joins the point that is there");+ assert_eq!(coincident_count(&sk), coincident_count(&before) + 1);+}++#[test]+fn extend_two_lines_adds_a_line_when_an_end_is_held_by_other_geometry() {+ // B's end (12,2) is joined to C (to (14,2)): it does not move, so B's growth is a new line from+ // that end to the point A reaches, (12,0).+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let bc = ids(&run(&mut s, "sketch.line", json!({"points":[[12,6],[12,2],[14,2]],"connect":false,"infer":false}))["curves"]);+ let b = bc[0].clone();+ let before = sketch(&s);+ let (curves, points) = (before.curves.len(), before.points.len());++ run(&mut s, "sketch.extend", json!({"curves": [a, b]}));++ let sk = sketch(&s);+ assert_eq!(sk.curves.len(), curves + 1, "the held end gets a new line");+ assert_eq!(sk.points.len(), points, "the new line joins the point A reaches");+ assert!(point_at(&sk, &format!("{b}.end")).dist(Vec2::new(12.0, 2.0)) < 1e-9, "the held end does not move");+ let last = sk.curves.len() - 1;+ let b_end = sk.resolve_point(&format!("{b}.end"));+ let a_end = sk.resolve_point(&format!("{a}.end"));+ assert!(+ matches!(sk.curves[last].kind, CurveKind::Line { a: from, b: to } if Some(from) == b_end && Some(to) == a_end),+ "the new line runs from the held end to the point A reaches"+ );+}++#[test]+fn extend_two_curves_refuses_what_cannot_meet_and_changes_nothing() {+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false}))["curves"])[0].clone();+ let p = ids(&run(&mut s, "sketch.line", json!({"points":[[0,5],[8,5]],"connect":false,"infer":false}))["curves"])[0].clone();+ let before = serde_json::to_value(sketch(&s)).unwrap();+ let cases = [+ (json!({"curves": [a, p]}), "parallel"),+ (json!({"curves": [a, a]}), "twice"),+ (json!({"curves": [a, "l99"]}), "unknown curve"),+ (json!({"curve": a, "at": [8, 0], "curves": [a, b]}), "not both"),+ (json!({"curves": [a]}), "exactly two"),+ (json!({"curves": [a, b], "at": [[0, 0], [12, 6]]}), "shorten"),+ (json!({"curves": [a, b], "at": [8, 0]}), "one point per curve"),+ ];+ for (params, expected) in cases {+ let e = s.execute("sketch.extend", ¶ms).unwrap_err().to_string();+ assert!(e.contains(expected), "{params}: {e}");+ }+ assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "a refused extension changes nothing");+}++#[test]+fn extend_two_curves_is_one_undo_step() {+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false}))["curves"])[0].clone();+ let before = serde_json::to_value(sketch(&s)).unwrap();++ run(&mut s, "sketch.extend", json!({"curves": [a, b]}));+ assert_ne!(serde_json::to_value(sketch(&s)).unwrap(), before);+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "one undo restores the sketch");+}++#[test]+fn extend_two_curves_meeting_at_the_origin_returns_the_joined_end() {+ // A runs right along y=0 from (-8,0) to (-4,0); B comes down x=0 from (0,4) to (0,2). They meet+ // at the origin. `moved` is the joined end (one of their ends), not whichever point sits there.+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[-8,0],[-4,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let b = ids(&run(&mut s, "sketch.line", json!({"points":[[0,4],[0,2]],"connect":false,"infer":false}))["curves"])[0].clone();++ let out = run(&mut s, "sketch.extend", json!({"curves": [a, b]}));++ let sk = sketch(&s);+ let moved = out["moved"].as_str().expect("the joined end's id");+ assert_ne!(moved, "origin", "the joined end is not the origin point");+ let joined = sk.point_index(moved).expect("the returned point");+ assert!([format!("{a}.end"), format!("{b}.end")].iter().any(|r| sk.resolve_point(r) == Some(joined)), "{moved} is an end of {a} or {b}");+ assert!(point_at(&sk, moved).dist(Vec2::new(0.0, 0.0)) < 1e-6);+}++#[test]+fn extend_two_arcs_meet_at_the_one_point_both_reach() {+ // Arc 1: centre (0,0), radius 5, from (5,0) to (0,5). Arc 2: centre (6,0), radius 5, from (11,0)+ // to (6,5). The circles cross at (3,4) and (3,-4). From (3,4) arc 1 would run back past its own+ // far end, so only (3,-4) is reached: arc 1 grows clockwise from (5,0) by 53.13 degrees (its+ // circle angle goes from 0 to -53.13), arc 2 grows clockwise from (11,0) by 126.87 degrees.+ let mut s = new_sketch();+ let a1 = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[5,0],"end":[0,5],"connect":false}))["curves"])[0].clone();+ let a2 = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[6,0],"start":[11,0],"end":[6,5],"connect":false}))["curves"])[0].clone();++ run(&mut s, "sketch.extend", json!({"curves": [a1, a2]}));++ let sk = sketch(&s);+ assert!(point_at(&sk, &format!("{a1}.start")).dist(Vec2::new(3.0, -4.0)) < 1e-6, "arc 1 reaches (3,-4)");+ assert!(point_at(&sk, &format!("{a2}.start")).dist(Vec2::new(3.0, -4.0)) < 1e-6, "arc 2 reaches (3,-4)");+ assert_eq!(coincident_count(&sk), 1, "one Coincident joins them");+ let ci = sk.curve_index(&a1).expect("arc 1");+ assert!(sk.shape(ci).is_some_and(|sh| sh.dist(Vec2::new(3.0, -4.0)) < 1e-6), "arc 1 stays on its circle");+}++#[test]+fn extend_two_arcs_take_the_meeting_point_with_the_least_growth() {+ // Arc 1: centre (0,0), radius 5, angles -30 to 20. Arc 2: centre (6,0), radius 5, angles 150 to+ // 210. Both crossings (3,4) and (3,-4) are reachable. At (3,4) arc 1 grows its end 20 -> 53.13+ // (33.13 degrees) and arc 2 its start 150 -> 126.87 (23.13): 56.26 in all. At (3,-4) arc 1 grows+ // its start -30 -> -53.13 (23.13) and arc 2 its end 210 -> 233.13 (23.13): 46.26. (3,-4) wins.+ let mut s = new_sketch();+ let a1 = ids(+ &run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[4.330127,-2.5],"end":[4.698463,1.710101],"connect":false}))["curves"]+ )[0]+ .clone();+ let a2 =+ ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[6,0],"start":[1.669873,2.5],"end":[1.669873,-2.5],"connect":false}))["curves"])+ [0]+ .clone();+ let a1_end = point_at(&sketch(&s), &format!("{a1}.end"));++ run(&mut s, "sketch.extend", json!({"curves": [a1, a2]}));++ let sk = sketch(&s);+ assert!(point_at(&sk, &format!("{a1}.start")).dist(Vec2::new(3.0, -4.0)) < 1e-5, "arc 1 grows its start to (3,-4)");+ assert!(point_at(&sk, &format!("{a2}.end")).dist(Vec2::new(3.0, -4.0)) < 1e-5, "arc 2 grows its end to (3,-4)");+ assert!(point_at(&sk, &format!("{a1}.end")).dist(a1_end) < 1e-9, "arc 1's other end stays");+ assert_eq!(coincident_count(&sk), 1, "one Coincident joins them");+}++#[test]+fn extend_two_arcs_with_two_equal_meeting_points_is_refused() {+ // Both arcs are symmetric about the x-axis: arc 1 from (4.330127,-2.5) to (4.330127,2.5) (circle+ // angles -30 to 30), arc 2 centre (6,0) from (1.669873,2.5) to (1.669873,-2.5) (angles 150 to 210).+ // Their circles cross at (3,4) and (3,-4), and each point takes 23.13 degrees from each arc: the+ // same growth both ways, so there is no reason to choose, and the extension is refused.+ let mut s = new_sketch();+ let a1 =+ ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[4.330127,-2.5],"end":[4.330127,2.5],"connect":false}))["curves"])+ [0]+ .clone();+ let a2 =+ ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[6,0],"start":[1.669873,2.5],"end":[1.669873,-2.5],"connect":false}))["curves"])+ [0]+ .clone();+ let before = serde_json::to_value(sketch(&s)).unwrap();++ let e = s.execute("sketch.extend", &json!({"curves": [a1, a2]})).unwrap_err().to_string();++ assert!(e.contains("same growth"), "{e}");+ assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "a refused extension changes nothing");+}++#[test]+fn extend_a_held_arc_end_adds_a_new_arc_and_the_line_joins_it() {+ // The arc's end (-5,0) carries a line running down from it, so the arc does not move: its growth+ // is a new arc from (-5,0), 53.13 degrees round the circle, to (-3,-4). The line x=-3 grows to+ // (-3,-4) and joins that new arc's end with one Coincident.+ let mut s = new_sketch();+ let arc = ids(&run(&mut s, "sketch.arc.center_point", json!({"center":[0,0],"start":[0,5],"end":[-5,0],"connect":false}))["curves"])[0].clone();+ run(&mut s, "sketch.line", json!({"points":[[-5,0],[-5,-3]],"connect":true,"infer":false}));+ let line = ids(&run(&mut s, "sketch.line", json!({"points":[[-3,-1],[-3,-2]],"connect":false,"infer":false}))["curves"])[0].clone();+ let before = sketch(&s);+ let (curves, coincident) = (before.curves.len(), coincident_count(&before));++ run(&mut s, "sketch.extend", json!({"curves": [arc, line], "at": [[-5, 0], [-3, -2]]}));++ let sk = sketch(&s);+ assert_eq!(sk.curves.len(), curves + 1, "the held end gets a new arc");+ assert!(point_at(&sk, &format!("{arc}.end")).dist(Vec2::new(-5.0, 0.0)) < 1e-9, "the held arc end does not move");+ assert!(point_at(&sk, &format!("{line}.end")).dist(Vec2::new(-3.0, -4.0)) < 1e-6, "the line reaches the meeting point");+ assert_eq!(coincident_count(&sk), coincident + 1, "one Coincident joins the line to the new arc");+ let new = sk.curves.len() - 1;+ assert!(matches!(sk.curves[new].kind, CurveKind::Arc { .. }), "the extension is an arc");+ assert!(sk.shape(new).is_some_and(|sh| sh.dist(Vec2::new(-3.0, -4.0)) < 1e-6), "the new arc ends on the meeting point");+}++#[test]+fn extend_two_curves_refuses_a_spline_and_an_infinite_line() {+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let spline = ids(&run(&mut s, "sketch.spline.fit_point", json!({"points":[[12,-6],[14,-2],[16,0]],"connect":false}))["curves"])[0].clone();+ let line = ids(&run(&mut s, "sketch.line", json!({"points":[[0,5],[8,5]],"connect":false,"infer":false}))["curves"])[0].clone();+ run(&mut s, "sketch.infinite", json!({"curves": [line]}));+ let before = serde_json::to_value(sketch(&s)).unwrap();++ let e = s.execute("sketch.extend", &json!({"curves": [a, spline]})).unwrap_err().to_string();+ assert!(e.contains("only lines and arcs"), "{e}");+ let e = s.execute("sketch.extend", &json!({"curves": [a, line]})).unwrap_err().to_string();+ assert!(e.contains("infinite"), "{e}");+ assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before, "refused curves change nothing");+}++#[test]+fn extend_two_collinear_lines_are_refused_as_collinear() {+ // Two lines on y=0 with a gap between them: they lie on one line and never meet at a point.+ let mut s = new_sketch();+ let a = ids(&run(&mut s, "sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let c = ids(&run(&mut s, "sketch.line", json!({"points":[[12,0],[16,0]],"connect":false,"infer":false}))["curves"])[0].clone();+ let e = s.execute("sketch.extend", &json!({"curves": [a, c]})).unwrap_err().to_string();+ assert!(e.contains("collinear"), "{e}");+}diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rsindex 245c369f6d..03e4e746ea 100644--- a/crates/ui-egui/src/sketch_corner_ui_tests.rs+++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs@@ -202,6 +202,75 @@ fn derived_offset_context_action_releases_geometry_and_undo_restores() {assert_eq!(h.app.session.model.state().sketch(sid).unwrap().sketch.freeform_offsets.len(), 1);}+#[test]+fn shift_clicks_on_two_curves_extend_both_to_where_they_meet() {+ // A runs right along y=0 to (8,0); B comes down x=12 from (12,6) to (12,2). With Shift, the+ // first click remembers A and the second (on B) extends both to (12,0). Without Shift a click+ // is still the single-curve extend.+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false})).unwrap();+ h.app.run("sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false})).unwrap();+ h.call("ui.view", json!({"view": "top"}));+ h.app.cam.distance = 60.0;+ h.frames(3);+ h.call("ui.start", json!({"command": "sketch.extend"}));+ h.frames(2);+ let undo = h.app.session.undo.len();++ shift_click(&mut h, &json!({"sketch": [6, 0]}));+ assert_eq!(h.app.session.undo.len(), undo, "the first Shift click only remembers its curve");+ shift_click(&mut h, &json!({"sketch": [12, 3]}));+ assert_eq!(h.app.session.undo.len(), undo + 1, "the second runs the two-curve extend, in one step");++ let st = h.app.session.world_state();+ let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap();+ for end in ["l1.end", "l2.end"] {+ let p = ss.sketch.point(ss.sketch.resolve_point(end).unwrap()).unwrap();+ assert!(p.dist(Vec2::new(12.0, 0.0)) < 1e-6, "{end} at the meeting point: {p:?}, {:?}", h.app.status);+ }+}++#[test]+fn escape_drops_a_pending_pair_pick() {+ // The first Shift click waits for a second curve. Escape cancels the tool, so a later Shift+ // click on the other curve, with the tool started again, starts afresh and runs nothing.+ let mut h = crate::scenario::Harness::new();+ h.app.home.open = false;+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();+ h.app.run("sketch.line", json!({"points":[[0,0],[8,0]],"connect":false,"infer":false})).unwrap();+ h.app.run("sketch.line", json!({"points":[[12,6],[12,2]],"connect":false,"infer":false})).unwrap();+ h.call("ui.view", json!({"view": "top"}));+ h.app.cam.distance = 60.0;+ h.frames(3);+ h.call("ui.start", json!({"command": "sketch.extend"}));+ h.frames(2);+ shift_click(&mut h, &json!({"sketch": [6, 0]}));+ h.step(&json!({"key": "Escape"})).unwrap();+ h.call("ui.start", json!({"command": "sketch.extend"}));+ h.frames(2);+ let undo = h.app.session.undo.len();++ shift_click(&mut h, &json!({"sketch": [12, 3]}));+ assert_eq!(h.app.session.undo.len(), undo, "the pending first pick went with Escape");+}++/// A click with Shift held at `at`: hover first so the pointer is over the curve, then press and+/// release with the modifier.+fn shift_click(h: &mut crate::scenario::Harness, at: &Value) {+ let [sx, sy] = h.at(at).expect("on screen");+ let p = egui::pos2(sx as f32, sy as f32);+ let shift = egui::Modifiers { shift: true, ..Default::default() };+ h.app.synthetic.push(egui::Event::PointerMoved(p));+ h.app.synthetic.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: shift });+ h.app.synthetic.push(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: shift });+ while !h.app.synthetic.is_empty() {+ h.frame();+ }+ h.frames(2);+}+/// The size fields of the open Fillet or Chamfer window, as if they had been typed.fn set_size(app: &mut SolveApp, text: &str) {match app.dialog.as_mut().map(|d| &mut d.kind) {diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rsindex 48531ad3a2..d9194147bd 100644--- a/crates/ui-egui/src/sketch_tools.rs+++ b/crates/ui-egui/src/sketch_tools.rs@@ -27,6 +27,14 @@ const ISOCURVE_ALT: &[Binding] = &[Binding {rebindable: true,}];+/// Extend: Shift picks the second curve of the two-curve form (`ExtendPair`). Shift does not snap+/// the clicked point to a midpoint here (an empty binding overrides the sketch scopes' one), so the+/// end nearest the click stays where it was clicked.+const EXTEND_BINDINGS: &[Binding] = &[+ Binding { action: ModAction::ExtendPair, defaults: &[ModifierCombo::SHIFT], matching: Match::AtLeast, trigger: Trigger::Press, rebindable: true },+ Binding { action: ModAction::TargetMidpoint, defaults: &[], matching: Match::AtLeast, trigger: Trigger::Live, rebindable: true },+];+/// Per-tool modifier descriptors owned by this host file.pub const MODIFIERS: &[ToolModifiers] = &[ToolModifiers { tool: "sketch.project", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },@@ -41,7 +49,7 @@ pub const MODIFIERS: &[ToolModifiers] = &[ToolModifiers { tool: "canvas.insert", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },ToolModifiers { tool: "canvas.decal", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },ToolModifiers { tool: "sketch.trim", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },- ToolModifiers { tool: "sketch.extend", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },+ ToolModifiers { tool: "sketch.extend", scopes: NONE, bindings: EXTEND_BINDINGS, audit: Audit::Implemented },ToolModifiers { tool: "sketch.break", scopes: NONE, bindings: &[], audit: Audit::VerifiedNoOp },ToolModifiers { tool: "sketch.line.midpoint", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },ToolModifiers { tool: "sketch.arc.tangent", scopes: DRAW_SCOPES, bindings: &[], audit: Audit::Implemented },@@ -70,6 +78,8 @@ pub const MODIFIERS: &[ToolModifiers] = &[thread_local! {/// Shift held this frame.static SHIFT: Cell<bool> = const { Cell::new(false) };+ /// Extend's two-curve chord (`ModAction::ExtendPair`) held this frame.+ static EXTEND_PAIR: Cell<bool> = const { Cell::new(false) };/// Glyphs drawn this frame (constraint id, screen centre) and the selected one.static GLYPHS: RefCell<Vec<(String, Pos2)>> = const { RefCell::new(Vec::new()) };static PICKED: RefCell<Option<String>> = const { RefCell::new(None) };@@ -643,7 +653,7 @@ pub fn hint(id: &str) -> Option<String> {"canvas.insert" => "Canvas: click a plane or a planar face where the image's centre goes","canvas.decal" => "Decal: click a planar face where the image's centre goes","sketch.trim" => "Trim: click the piece of a curve to remove, or drag across the pieces to remove",- "sketch.extend" => "Extend: click a curve near the end to extend",+ "sketch.extend" => "Extend: click a curve near the end to extend (Shift: click two curves to extend both to where they meet)","sketch.break" => "Break: click a curve where it should split","sketch.line.midpoint" => "Midpoint line: click the middle, then an end","sketch.arc.tangent" => "Tangent arc: click the end of a line or arc, then the arc's end",@@ -943,7 +953,34 @@ pub fn on_click(app: &mut SolveApp, tool: &mut Tool, proj: &Proj, pos: Pos2) {})});if let (Some(id), Some((p, _))) = (curve, at) {- let _ = app.run(cmd, json!({"curve": id, "at": xy(p)}));+ if cmd == "sketch.extend" && EXTEND_PAIR.with(Cell::get) {+ // The pair chord picks the two curves to extend to where they meet: the first+ // click remembers its curve and point (in point_picks, which nothing draws for+ // Extend), the second runs the command with both, each growing from the end+ // nearest the point clicked on it.+ match tool.picks.first().cloned() {+ None => {+ tool.picks.push(id);+ tool.point_picks.push(xy(p));+ app.set_status("Extend: Shift-click the second curve", false);+ }+ Some(first) if first != id => {+ let first_pt = tool.point_picks.first().cloned();+ tool.picks.clear();+ tool.point_picks.clear();+ let mut params = json!({"curves": [first, id]});+ if let Some(first_pt) = first_pt {+ params["at"] = json!([first_pt, xy(p)]);+ }+ let _ = app.run(cmd, params);+ }+ Some(_) => {}+ }+ } else {+ tool.picks.clear();+ tool.point_picks.clear();+ let _ = app.run(cmd, json!({"curve": id, "at": xy(p)}));+ }}}Mode::Points(_) => {@@ -1192,7 +1229,8 @@ pub(crate) fn trim_hover_piece(app: &SolveApp, sketch: u64, id: &str) -> Option</// of `sketch`. Returns None when extend is not active or the geometry does not support a/// preview. An arc grows along its own circle, in either direction, as a new arc.fn extend_preview_piece(app: &SolveApp, sketch: u64, id: &str) -> Option<Vec<Vec2>> {- let tool = app.tool.as_ref().filter(|t| t.cmd == "sketch.extend")?;+ // A pending pair pick (the first curve of the two-curve form) hides the single-curve preview.+ let tool = app.tool.as_ref().filter(|t| t.cmd == "sketch.extend" && t.picks.is_empty())?;let hover = tool.hover.as_ref()?;if active_sketch(app) != Some(sketch) {return None;@@ -1543,6 +1581,8 @@ pub fn show(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, proj: &Plet held = crate::tool_modifiers::Held::from_modifiers(ui.input(|i| i.modifiers));let iso = crate::tool_modifiers::resolve(&[], crate::tool_modifiers::descriptor("sketch.isoparametric_curve"), held, Trigger::Press);SHIFT.with(|c| c.set(iso.contains(ModAction::IsoCurveAlternate)));+ let pair = crate::tool_modifiers::resolve(&[], crate::tool_modifiers::descriptor("sketch.extend"), held, Trigger::Press);+ EXTEND_PAIR.with(|c| c.set(pair.contains(ModAction::ExtendPair)));glyphs(app, painter, proj, ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(proj.rect)));snap_hint(app, painter, proj);combs(app, painter, proj);diff --git a/crates/ui-egui/src/tool_modifiers.rs b/crates/ui-egui/src/tool_modifiers.rsindex 4dbac0152c..4c8f8ff39f 100644--- a/crates/ui-egui/src/tool_modifiers.rs+++ b/crates/ui-egui/src/tool_modifiers.rs@@ -227,6 +227,7 @@ pub enum ModAction {TextSingleLetter = 7,TextHandleConstrain = 8,IsoCurveAlternate = 9,+ ExtendPair = 10,}impl ModAction {@@ -241,6 +242,7 @@ impl ModAction {Self::TextSingleLetter,Self::TextHandleConstrain,Self::IsoCurveAlternate,+ Self::ExtendPair,];pub const fn id(self) -> &'static str {@@ -255,6 +257,7 @@ impl ModAction {Self::TextSingleLetter => "text_single_letter",Self::TextHandleConstrain => "text_handle_constrain",Self::IsoCurveAlternate => "isocurve_alternate",+ Self::ExtendPair => "extend_pair",}}@@ -625,6 +628,20 @@ mod tests {assert!(!bare.contains(ModAction::IsoCurveAlternate));}+ #[test]+ fn extend_shift_is_the_pair_action_and_not_a_midpoint_snap() {+ let held = Held { shift: true, ..Default::default() };+ let press = resolve(&[], descriptor("sketch.extend"), held, Trigger::Press);+ assert!(press.contains(ModAction::ExtendPair));+ let plain = resolve(&[], descriptor("sketch.extend"), Held::default(), Trigger::Press);+ assert!(!plain.contains(ModAction::ExtendPair));+ // Sketch scopes give Shift the midpoint snap while drawing; Extend's own entry turns it off.+ let live = resolve(&[Scope::SketchDraw, Scope::SketchDrag], descriptor("sketch.extend"), held, Trigger::Live);+ assert!(!live.contains(ModAction::TargetMidpoint));+ let drawing = resolve(&[Scope::SketchDraw, Scope::SketchDrag], descriptor("sketch.line"), held, Trigger::Live);+ assert!(drawing.contains(ModAction::TargetMidpoint));+ }+#[test]fn action_ids_are_unique() {let mut seen = std::collections::BTreeSet::new();diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.mdindex 29146f17f8..4cc0b7b1c7 100644--- a/docs/book/src/guide/sketching.md+++ b/docs/book/src/guide/sketching.md@@ -140,6 +140,7 @@ geometry right away.Extend finds intersections with exact ellipses, rational conics and spline spans. It keeps theoriginal line or circular support and extends only beyond the selected endpoint; conflictingconstraints or an ambiguous overlap leave the sketch unchanged.+To extend two lines or arcs until they meet, hold Shift and click the first curve, then Shift-click the second: both grow to where they cross and are joined there, in one undo step.Closed convex chains of tangent lines and circular arcs support inward offsets that consumea rounded corner. When the offset passes the corner radius, the neighbouring straight