From 5e265089c74b5237a3099857fc40a6fa5142cb95 Mon Sep 17 00:00:00 2001 From: Thodoris Tsagkogeorgas Date: Sat, 31 Oct 2026 16:03:31 +0000 Subject: [PATCH] Sketch: offset corners trim when they cross and extend when they fall short (#10089) The chain walk follows ends that share a point, a coincident constraint, or the same position. The offset then meets at the intersection. --- crates/engine/src/cmd/sketch_modify.rs | 64 ++++++- crates/engine/src/cmd/sketch_modify_tests.rs | 178 +++++++++++++++++++ 2 files changed, 237 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index d67dd1aa8..846dfddc5 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -46,7 +46,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .key("O") .enabled(in_sketch) .params(concat!( - "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain); ", + "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain, including ends that only coincide). A corner is trimmed back to the crossing when the offset runs past it, and extended until the offset curves intersect when the corner falls short; ", "direction?: one_side|symmetric (default one_side) or symmetric?: bool (the same distance each way; no `side`, whose job it takes over), ", "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions", created_doc!() @@ -1876,13 +1876,40 @@ fn chamfer_dist_angle(s: &mut Session, p: &Value) -> Result { // --------------------------------------------------------------------------------------------- // Offset +/// Ends this close are one corner. Profile finding joins ends at the same distance, so a loop +/// the sketch already treats as one profile offsets as one chain. +const ENDPOINT_JOIN: f64 = 1e-4; + /// Curves of the connected chain through `start` (joined where exactly two curves meet), in /// order, with whether each is walked from its stored start (`a`) to its end (`b`). +/// +/// A corner counts when the curves share the point, when a coincident constraint makes the two +/// ends one point, or when the ends simply lie on each other. The offset then trims a corner +/// that runs past the crossing and extends one that stops short, so the new curves intersect. fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool) { let ends = |c: usize| sk.curves.get(c).and_then(|c| c.kind.ends()); let Some((s0, s1)) = ends(start) else { return (vec![(start, true)], true) }; + let mut parent: Vec = (0..sk.points.len()).collect(); + for constraint in &sk.constraints { + if let ConstraintKind::Coincident { p, q } = constraint.kind { + union_points(&mut parent, p, q); + } + } + let group: Vec = (0..parent.len()).map(|i| find_point(&mut parent, i)).collect(); + let same = |a: usize, b: usize| -> bool { + if a == b { + return true; + } + if group.get(a).zip(group.get(b)).is_some_and(|(x, y)| x == y) { + return true; + } + match (sk.point(a), sk.point(b)) { + (Some(p), Some(q)) if p.is_finite() && q.is_finite() => p.dist(q) <= ENDPOINT_JOIN, + _ => false, + } + }; let next = |from: usize, at: usize, used: &[usize]| -> Option { - let users: Vec = pool.iter().copied().filter(|c| ends(*c).is_some_and(|(a, b)| a == at || b == at)).collect(); + let users: Vec = pool.iter().copied().filter(|c| ends(*c).is_some_and(|(a, b)| same(a, at) || same(b, at))).collect(); if users.len() != 2 { return None; } @@ -1894,7 +1921,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool let mut closed = false; while let Some(n) = next(cur, at, &used) { let Some((a, b)) = ends(n) else { break }; - let forward = a == at; + let forward = same(a, at); fwd.push((n, forward)); used.push(n); cur = n; @@ -1903,7 +1930,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool break; } } - if at == s0 && fwd.len() > 1 { + if fwd.len() > 1 && same(at, s0) { closed = true; } else { // Walk backwards from the start. @@ -1911,7 +1938,7 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool let mut back = Vec::new(); while let Some(n) = next(cur, at, &used) { let Some((a, b)) = ends(n) else { break }; - let forward = b == at; + let forward = same(b, at); back.push((n, forward)); used.push(n); cur = n; @@ -1927,6 +1954,33 @@ fn chain(sk: &Sketch, start: usize, pool: &[usize]) -> (Vec<(usize, bool)>, bool (fwd, closed) } +fn find_point(parent: &mut [usize], mut i: usize) -> usize { + let mut top = i; + while parent.get(top).copied().unwrap_or(top) != top { + top = parent[top]; + } + while i != top { + let next = parent.get(i).copied().unwrap_or(top); + if let Some(slot) = parent.get_mut(i) { + *slot = top; + } + i = next; + } + top +} + +fn union_points(parent: &mut [usize], a: usize, b: usize) { + if a >= parent.len() || b >= parent.len() { + return; + } + let (a, b) = (find_point(parent, a), find_point(parent, b)); + if a != b + && let Some(slot) = parent.get_mut(b) + { + *slot = a; + } +} + /// An offset piece: shape walked in chain direction, offset by `d` to the left. #[derive(Clone)] enum Piece { diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index bdd89943c..e5c8e6ee6 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -3545,3 +3545,181 @@ fn a_tangent_arc_can_end_on_an_existing_point() { assert!(s.execute("sketch.arc.tangent", &json!({"start": format!("{down}.end"), "curve": down, "end": format!("{down}.end")})).is_err()); assert_eq!(s.doc.to_json(), before); } + +/// Where a circle of radius `r1` at the origin meets a circle of radius `r2` at `(-d, 0)`, +/// then the same on the right. `(top-left, bottom-left, top-right, bottom-right)`. +fn lobe_corners(r1: f64, r2: f64, d: f64) -> (Vec2, Vec2, Vec2, Vec2) { + let a = (r1 * r1 - r2 * r2 + d * d) / (2.0 * d); + let h = (r1 * r1 - a * a).sqrt(); + (Vec2::new(-a, h), Vec2::new(-a, -h), Vec2::new(a, h), Vec2::new(a, -h)) +} + +fn arc_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (usize, usize, Vec2, Vec2, Vec2) { + match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Arc { c, a, b } => (a, b, sk.point(c).unwrap(), sk.point(a).unwrap(), sk.point(b).unwrap()), + ref other => panic!("{id} is {other:?}"), + } +} + +fn line_ends(sk: &solidcraft_sketch::Sketch, id: &str) -> (usize, Vec2, usize, Vec2) { + match sk.curves[sk.curve_index(id).unwrap()].kind { + CurveKind::Line { a, b } => (a, sk.point(a).unwrap(), b, sk.point(b).unwrap()), + ref other => panic!("{id} is {other:?}"), + } +} + +/// Midpoint of the counter-clockwise arc from `a` to `b` around `c`. +fn ccw_mid(c: Vec2, a: Vec2, b: Vec2) -> Vec2 { + let start = (a - c).angle(); + let mut sweep = (b - c).angle() - start; + if sweep <= 1e-12 { + sweep += std::f64::consts::TAU; + } + c + Vec2::from_angle(start + sweep * 0.5) * c.dist(a) +} + +/// Corners whose ends are separate points offset as one chain. An offset that runs past the +/// crossing is trimmed back to it; one that stops short is extended until the curves intersect. +#[test] +fn offset_corners_trim_the_overlap_and_extend_the_gap() { + let (big, small, apart) = (27.5, 12.5, 27.95); + let (tl, bl, tr, br) = lobe_corners(big, small, apart); + let mut s = new_sketch(); + let draw = |s: &mut Session, id: &str, center: [f64; 2], start: Vec2, end: Vec2| { + run( + s, + "sketch.arc.center_point", + json!({ + "id": id, "center": center, "start": [start.x, start.y], "end": [end.x, end.y], "connect": false, + }), + ); + }; + draw(&mut s, "top", [0.0, 0.0], tr, tl); + draw(&mut s, "left", [-apart, 0.0], tl, bl); + draw(&mut s, "bottom", [0.0, 0.0], bl, br); + draw(&mut s, "right", [apart, 0.0], br, tr); + let sk = sketch(&s); + let (top_end, left_start) = (sk.resolve_point("top.end").unwrap(), sk.resolve_point("left.start").unwrap()); + assert_ne!(top_end, left_start, "the corner is two points"); + assert!(sk.point(top_end).unwrap().dist(sk.point(left_start).unwrap()) < 1e-9); + assert!(!sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if p == top_end || q == top_end))); + assert_eq!(profiles(&s).len(), 1, "the four arcs are one profile"); + + // Chain off copies the one arc, source angle and all, so the corner stays open. + let alone = run(&mut s, "sketch.offset", json!({"curves": ["top"], "distance": -3, "chain": false})); + assert_eq!(ids(&alone["curves"]).len(), 1); + let radial = tl.normalized().unwrap() * (big + 3.0); + let (_, _, _, _, open_end) = arc_ends(&sketch(&s), &ids(&alone["curves"])[0]); + assert!(open_end.dist(radial) < 1e-4, "untrimmed end {open_end:?}, radial {radial:?}"); + run(&mut s, "edit.undo", json!({})); + + let out = run(&mut s, "sketch.offset", json!({"curves": ["top"], "distance": -3})); + assert_eq!(ids(&out["curves"]).len(), 4, "{out}"); + assert_eq!(out["sides"].as_array().unwrap().len(), 1); + let sk = sketch(&s); + assert_eq!(sk.offsets.len(), 1); + let rec = &sk.offsets[0]; + assert!(rec.closed); + assert_eq!( + rec.sources.iter().map(|(id, forward)| (id.as_str(), *forward)).collect::>(), + vec![("top", true), ("left", true), ("bottom", true), ("right", true)] + ); + let (meet_tl, meet_bl, meet_tr, meet_br) = lobe_corners(big + 3.0, small + 3.0, apart); + let mut prev_end = arc_ends(&sk, rec.outputs.last().unwrap()).1; + for (id, radius, center) in [ + ("top", big + 3.0, Vec2::ZERO), + ("left", small + 3.0, Vec2::new(-apart, 0.0)), + ("bottom", big + 3.0, Vec2::ZERO), + ("right", small + 3.0, Vec2::new(apart, 0.0)), + ] { + let i = rec.sources.iter().position(|(source, _)| source == id).unwrap(); + let (a, b, c, start, _) = arc_ends(&sk, &rec.outputs[i]); + assert_eq!(prev_end, a, "{id} starts where the previous arc ends"); + assert!((c.dist(start) - radius).abs() < 1e-4 && c.dist(center) < 1e-6, "{id} at {c:?} radius {}", c.dist(start)); + prev_end = b; + } + let (_, _, _, _, trimmed) = arc_ends(&sk, &rec.outputs[0]); + assert!(trimmed.dist(meet_tl) < 1e-4, "top-left corner {trimmed:?}, intersection {meet_tl:?}"); + assert!(trimmed.dist(radial) > 1.0, "trimmed back from the untrimmed end {radial:?} to {trimmed:?}"); + let (_, _, c, a, b) = arc_ends(&sk, &rec.outputs[0]); + let mid = ccw_mid(c, a, b); + assert!(mid.dist(Vec2::new(0.0, big + 3.0)) < 1e-3, "the top arc stays the short one, mid {mid:?}"); + let left_i = rec.sources.iter().position(|(source, _)| source == "left").unwrap(); + let (_, _, c, a, b) = arc_ends(&sk, &rec.outputs[left_i]); + let mid = ccw_mid(c, a, b); + assert!(mid.dist(Vec2::new(-apart - (small + 3.0), 0.0)) < 1e-3, "the left arc stays the outer one, mid {mid:?}"); + // The other three crossings, so a closed chain joins the last corner as well. + let corners: Vec = rec + .outputs + .iter() + .map(|id| { + let (_, _, _, _, end) = arc_ends(&sk, id); + end + }) + .collect(); + for want in [meet_tl, meet_bl, meet_tr, meet_br] { + assert!(corners.iter().any(|q| q.dist(want) < 1e-4), "missing {want:?} in {corners:?}"); + } + + // Editing the distance keeps the corners on the new intersection. + let param = out["param"].as_str().unwrap(); + run(&mut s, "parameters.change", json!({"name": param, "expression": "4 mm"})); + let sk = sketch(&s); + assert!((sk.offsets[0].distance + 4.0).abs() < 1e-6, "distance {}", sk.offsets[0].distance); + let (grown, _, _, _) = lobe_corners(big + 4.0, small + 4.0, apart); + let top_i = sk.offsets[0].sources.iter().position(|(source, _)| source == "top").unwrap(); + let top_out = sk.offsets[0].outputs[top_i].clone(); + let (_, _, _, _, trimmed) = arc_ends(&sk, &top_out); + assert!(trimmed.dist(grown) < 1e-4, "after the edit {trimmed:?}, intersection {grown:?}"); + + // An L of two lines. Negative (outward) stops short of the corner and must be extended. + // Positive runs past it and must be trimmed back. The ends only share a position. + let corner_of = |distance: f64| -> Vec2 { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.0, 0.0], [20.0, 20.0]], "connect": false, "infer": false})); + let sk = sketch(&s); + assert_ne!(sk.resolve_point("l1.end").unwrap(), sk.resolve_point("l2.start").unwrap()); + let out = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": distance})); + assert_eq!(ids(&out["curves"]).len(), 2, "distance {distance}: {out}"); + let sk = sketch(&s); + let (first, second) = (&sk.offsets[0].outputs[0], &sk.offsets[0].outputs[1]); + let (_, _, end_i, end) = line_ends(&sk, first); + let (start_i, start, _, _) = line_ends(&sk, second); + assert_eq!(end_i, start_i, "one corner point"); + assert!(end.dist(start) < 1e-9); + end + }; + let extended = corner_of(-3.0); + assert!(extended.dist(Vec2::new(23.0, -3.0)) < 1e-6, "extended to {extended:?}"); + let trimmed = corner_of(3.0); + assert!(trimmed.dist(Vec2::new(17.0, 3.0)) < 1e-6, "trimmed to {trimmed:?}"); + + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.0, 0.0], [20.0, 20.0]], "connect": false, "infer": false})); + let alone = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": -3, "chain": false})); + assert_eq!(ids(&alone["curves"]).len(), 1); + let (_, _, _, end) = line_ends(&sketch(&s), &ids(&alone["curves"])[0]); + assert!(end.dist(Vec2::new(20.0, -3.0)) < 1e-6, "chain off leaves the gap, end {end:?}"); + + // The same L, joined only by a coincident constraint across a gap the tolerance would not. + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [20.0, 0.0]], "connect": false, "infer": false})); + run(&mut s, "sketch.line", json!({"points": [[20.5, 0.5], [20.5, 20.0]], "connect": false, "infer": false})); + let gap = { + let sk = sketch(&s); + sk.point(sk.resolve_point("l1.end").unwrap()).unwrap().dist(sk.point(sk.resolve_point("l2.start").unwrap()).unwrap()) + }; + assert!(gap > 0.4, "the ends start {gap} mm apart"); + run(&mut s, "sketch.constraint.fix", json!({"entity": "l1.start"})); + run(&mut s, "sketch.constraint.fix", json!({"entity": "l2.end"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1", "mode": "horizontal"})); + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l2", "mode": "vertical"})); + run(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": "l2.start"})); + let out = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": -3})); + assert_eq!(ids(&out["curves"]).len(), 2, "{out}"); + let sk = sketch(&s); + let (_, _, _, end) = line_ends(&sk, &sk.offsets[0].outputs[0]); + assert!(end.dist(Vec2::new(23.5, -3.0)) < 1e-4, "coincident corner extended to {end:?}"); +}