Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Sketch trim: drag a path across curves to trim every piece it crosses (#3182)

SS-ENfb811fbf21f2
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 77c030df3b..c00d6af87a 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -613,6 +613,7 @@
"cmd.sketch_spline_fit_point": "Fit Point Spline",
"cmd.sketch_spun_profile": "Spun Profile",
"cmd.sketch_toggle_driven": "Toggle Driven Dimension",
+ "cmd.sketch_trim_path": "Trim Along Path",
"cmd.solid_align": "Align",
"cmd.solid_boundary_fill": "Boundary Fill",
"cmd.solid_bounding_solid": "Bounding Solid",
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index d6f0ace302..97bff33869 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -613,6 +613,7 @@
"cmd.sketch_spline_fit_point": "通過点スプライン",
"cmd.sketch_spun_profile": "回転プロファイル",
"cmd.sketch_toggle_driven": "従動寸法の切り替え",
+ "cmd.sketch_trim_path": "パスに沿ってトリム",
"cmd.solid_align": "整列",
"cmd.solid_boundary_fill": "境界フィル",
"cmd.solid_bounding_solid": "バウンディング ソリッド",
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index f236bdb8dd..c31f08a819 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -613,6 +613,7 @@
"cmd.sketch_spline_fit_point": "拟合点样条曲线",
"cmd.sketch_spun_profile": "旋转轮廓",
"cmd.sketch_toggle_driven": "切换被驱动尺寸",
+ "cmd.sketch_trim_path": "沿路径修剪",
"cmd.solid_align": "对齐",
"cmd.solid_boundary_fill": "边界填充",
"cmd.solid_bounding_solid": "包围实体",
diff --git a/crates/engine/src/cmd/sketch_freeform.rs b/crates/engine/src/cmd/sketch_freeform.rs
index cd47682c77..6d8763a33c 100644
--- a/crates/engine/src/cmd/sketch_freeform.rs
+++ b/crates/engine/src/cmd/sketch_freeform.rs
@@ -280,8 +280,13 @@ fn modify(sk: &mut Sketch, ci: usize, at: Vec2, remove: bool, points: Option<&[V
}
}
let ids: Vec<String> = made.iter().filter_map(|c| sk.curves.get(*c).map(|c| c.id.clone())).collect();
+ // The removed piece, for previews (`sketch.trim.path`).
+ let removed: Vec<[f64; 2]> = gone
+ .and_then(|k| intervals.get(k))
+ .map(|(a, b, ..)| span(&segs, *a, *b).iter().flat_map(|s| s.polyline(1e-3)).map(|q| [q.x, q.y]).collect())
+ .unwrap_or_default();
sk.remove_curves(&[ci]);
let unused: Vec<usize> = cut_pt.iter().map(|x| x.1).filter(|pi| !sk.curves.iter().any(|c| c.kind.uses(*pi))).collect();
sk.remove_points(&unused);
- Ok(json!({"curves": ids}))
+ Ok(json!({"curves": ids, "removed": removed}))
}
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs
index 1561ed31f8..bf74a90d7b 100644
--- a/crates/engine/src/cmd/sketch_modify.rs
+++ b/crates/engine/src/cmd/sketch_modify.rs
@@ -59,6 +59,13 @@ pub static COMMANDS: &[CommandSpec] = &[
.key("T")
.enabled(in_sketch)
.params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it)", created_doc!())),
+ CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path)
+ .icon("trim")
+ .enabled(in_sketch)
+ .params(concat!(
+ "points: [[x,y]…] (2…2000 positions: a path drawn across the sketch). Every piece the path crosses is removed as `sketch.trim` removes the piece at that crossing, in the order the path crosses them; a piece crossed again after it is gone is not trimmed twice; projected geometry, infinite lines, offset outputs and pieces trim refuses are passed over (why in `skipped`). dry_run?: bool (report without changing the design). One undo step → trimmed: [each trim's result], removed: [[[x,y]…]] (each removed piece as a polyline)",
+ created_doc!()
+ )),
CommandSpec::new("sketch.extend", "Extend", extend)
.at("SKETCH", "MODIFY")
.icon("extend")
@@ -343,63 +350,192 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
let at = req_vec2(cmd, p, "at")?;
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
let ci = curve_arg(sk, p, cmd)?;
- let id = sk.curves.get(ci).map(|c| c.id.clone()).unwrap_or_default();
- if sk.curves.get(ci).is_some_and(|c| c.infinite) {
- return Err(bad(cmd, "an infinite line has no ends to trim back to: make it a normal line first"));
+ let (out, _) = remove_piece(sk, ci, at, cmd)?;
+ doc.prune_model_params();
+ Ok(out)
+ })?;
+ Ok(json!({"result": out, "sketch": info}))
+}
+
+/// Remove the piece of curve `ci` around `at`: between the nearest intersections on either
+/// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the
+/// removed piece as a polyline.
+fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Value, Vec<Vec2>)> {
+ let id = sk.curves.get(ci).map(|c| c.id.clone()).unwrap_or_default();
+ if sk.curves.get(ci).is_some_and(|c| c.infinite) {
+ return Err(bad(cmd, "an infinite line has no ends to trim back to: make it a normal line first"));
+ }
+ if sk.curves.get(ci).is_some_and(|c| c.kind.is_freeform()) {
+ let whole = sk.polyline(ci);
+ let r = super::sketch_freeform::trim_or_break(sk, ci, at, true, cmd)?;
+ let removed = match r.get("removed").and_then(Value::as_array) {
+ Some(pts) => pts.iter().filter_map(|q| Some(Vec2::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(),
+ None => whole,
+ };
+ return Ok((json!({"trimmed": id, "pieces": r["curves"]}), removed));
+ }
+ let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?;
+ let tq = sh.param(sh.project(at));
+ let (cuts, full) = bracket(sk, ci, tq);
+ if cuts.is_empty() {
+ // Nothing crosses it: the whole curve goes.
+ let removed = sk.polyline(ci);
+ sk.remove_curves(&[ci]);
+ return Ok((json!({"deleted": id}), removed));
+ }
+ release_extent(sk, ci);
+ let ts: Vec<f64> = cuts.iter().map(|c| c.0).collect();
+ let (pieces, pts) = split_at(sk, ci, &ts)?;
+ // The piece containing tq.
+ let k = if full {
+ let (a, b) = (ts[0], ts[1]);
+ if tq > a && tq < b { 0 } else { 1 }
+ } else {
+ ts.iter().filter(|t| **t < tq).count()
+ };
+ for (pi, c) in pts.iter().zip(&cuts) {
+ pin(sk, *pi, c.2)?;
+ }
+ let gone = pieces.get(k).copied().ok_or_else(|| bad(cmd, "piece"))?;
+ let keep: Vec<usize> = pieces.iter().copied().filter(|x| *x != gone).collect();
+ // The original curve keeps its id (and constraints): swap geometry into it if needed.
+ let gone = match keep.first() {
+ Some(&other) if gone == ci => {
+ let ka = sk.curves.get(ci).map(|c| c.kind.clone());
+ let kb = sk.curves.get(other).map(|c| c.kind.clone());
+ if let (Some(ka), Some(kb)) = (ka, kb) {
+ if let Some(c) = sk.curves.get_mut(ci) {
+ c.kind = kb;
+ }
+ if let Some(c) = sk.curves.get_mut(other) {
+ c.kind = ka;
+ }
+ }
+ other
}
- if sk.curves.get(ci).is_some_and(|c| c.kind.is_freeform()) {
- let r = super::sketch_freeform::trim_or_break(sk, ci, at, true, cmd)?;
- doc.prune_model_params();
- return Ok(json!({"trimmed": id, "pieces": r["curves"]}));
+ _ => gone,
+ };
+ let keep: Vec<usize> = pieces.iter().copied().filter(|x| *x != gone).collect();
+ tie(sk, &keep)?;
+ let removed = sk.polyline(gone);
+ sk.remove_curves(&[gone]);
+ Ok((json!({"trimmed": id}), removed))
+}
+
+/// Most crossings one `sketch.trim.path` trims (each one splits a curve, so this also caps the
+/// work a hostile path can ask for).
+const MAX_PATH_TRIMS: usize = 500;
+/// Most positions in a trim path.
+const MAX_PATH_POINTS: usize = 2_000;
+
+/// The first place along `path` after `after` (segment, parameter along it) where the path
+/// crosses a curve that a trim may change: (segment, parameter, curve, the crossing point). Crossings are found on the
+/// curves' display polylines; the trim projects them onto the exact curve.
+fn next_crossing(sk: &Sketch, path: &[Vec2], after: (usize, f64)) -> Option<(usize, f64, usize, Vec2)> {
+ let bounds = |pts: &[Vec2]| {
+ pts.iter().fold((Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), q| {
+ (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y)))
+ })
+ };
+ let trimmable: Vec<(usize, Vec<Vec2>, (Vec2, Vec2))> = (0..sk.curves.len())
+ .filter(|ci| curve_ok(sk, *ci))
+ .map(|ci| {
+ let poly = sk.polyline(ci);
+ let b = bounds(&poly);
+ (ci, poly, b)
+ })
+ .collect();
+ for (si, w) in path.windows(2).enumerate().skip(after.0) {
+ let (a, b) = (w[0], w[1]);
+ let from = if si == after.0 { after.1 } else { f64::NEG_INFINITY };
+ let (lo, hi) = bounds(&[a, b]);
+ let mut best: Option<(f64, usize, Vec2)> = None;
+ for (ci, poly, (plo, phi)) in &trimmable {
+ if plo.x > hi.x || plo.y > hi.y || phi.x < lo.x || phi.y < lo.y {
+ continue;
+ }
+ for e in poly.windows(2) {
+ let Some((t, q)) = seg_cross(a, b, e[0], e[1]) else { continue };
+ if t > from + 1e-9 && best.is_none_or(|x| t < x.0) {
+ best = Some((t, *ci, q));
+ }
+ }
}
- let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?;
- let tq = sh.param(sh.project(at));
- let (cuts, full) = bracket(sk, ci, tq);
- if cuts.is_empty() {
- // Nothing crosses it: the whole curve goes.
- sk.remove_curves(&[ci]);
- doc.prune_model_params();
- return Ok(json!({"deleted": id}));
+ if let Some((t, ci, q)) = best {
+ return Some((si, t, ci, q));
}
- release_extent(sk, ci);
- let ts: Vec<f64> = cuts.iter().map(|c| c.0).collect();
- let (pieces, pts) = split_at(sk, ci, &ts)?;
- // The piece containing tq.
- let k = if full {
- let (a, b) = (ts[0], ts[1]);
- if tq > a && tq < b { 0 } else { 1 }
- } else {
- ts.iter().filter(|t| **t < tq).count()
- };
- for (pi, c) in pts.iter().zip(&cuts) {
- pin(sk, *pi, c.2)?;
- }
- let gone = pieces.get(k).copied().ok_or_else(|| bad(cmd, "piece"))?;
- let keep: Vec<usize> = pieces.iter().copied().filter(|x| *x != gone).collect();
- // The original curve keeps its id (and constraints): swap geometry into it if needed.
- let gone = match keep.first() {
- Some(&other) if gone == ci => {
- let ka = sk.curves.get(ci).map(|c| c.kind.clone());
- let kb = sk.curves.get(other).map(|c| c.kind.clone());
- if let (Some(ka), Some(kb)) = (ka, kb) {
- if let Some(c) = sk.curves.get_mut(ci) {
- c.kind = kb;
- }
- if let Some(c) = sk.curves.get_mut(other) {
- c.kind = ka;
+ }
+ None
+}
+
+/// Whether trim may change curve `ci` (what [`curve_arg`] accepts, and not an infinite line).
+fn curve_ok(sk: &Sketch, ci: usize) -> bool {
+ let Some(c) = sk.curves.get(ci) else { return false };
+ !c.infinite
+ && !sk.is_linked_curve(ci)
+ && !sk.freeform_offsets.iter().any(|offset| offset.output == c.id)
+ && !sk.offsets.iter().filter_map(|offset| offset.topology.as_ref()).any(|topology| topology.roles.iter().any(|role| role.output == c.id))
+}
+
+/// Where segment `a`–`b` crosses segment `c`–`d`: the parameter along `a`–`b` and the point.
+fn seg_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Option<(f64, Vec2)> {
+ let (r, s) = (b - a, d - c);
+ let den = r.cross(s);
+ if den.abs() <= 1e-15 * r.len2().max(s.len2()).max(1e-30) {
+ return None;
+ }
+ let t = (c - a).cross(s) / den;
+ let u = (c - a).cross(r) / den;
+ ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then(|| (t, a + r * t))
+}
+
+fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {
+ let cmd = "sketch.trim.path";
+ let path = vec2_list(cmd, p, "points", MAX_PATH_POINTS)?;
+ if path.len() < 2 {
+ return Err(bad(cmd, "`points` needs at least two positions"));
+ }
+ if bool_(p, "dry_run").unwrap_or(false) {
+ let mut t = s.scratch();
+ let mut q = p.clone();
+ if let Some(o) = q.as_object_mut() {
+ o.remove("dry_run");
+ }
+ let mut out = trim_path(&mut t, &q)?;
+ out["dry_run"] = json!(true);
+ return Ok(out);
+ }
+ let ((trimmed, removed, skipped), info) = edit(s, p, cmd, false, |sk, doc| {
+ let mut trimmed: Vec<Value> = Vec::new();
+ let mut removed: Vec<Value> = Vec::new();
+ let mut skipped: Vec<String> = Vec::new();
+ let mut after = (0, f64::NEG_INFINITY);
+ for _ in 0..MAX_PATH_TRIMS {
+ let Some((si, t, ci, q)) = next_crossing(sk, &path, after) else { break };
+ after = (si, t);
+ // A piece trim refuses (a closed spline crossed once) stays as it was.
+ let before = sk.clone();
+ match remove_piece(sk, ci, q, cmd) {
+ Ok((out, gone)) => {
+ trimmed.push(out);
+ removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::<Vec<_>>()));
+ }
+ Err(e) => {
+ *sk = before;
+ let why = e.to_string().replace(&format!("{cmd}: "), "");
+ if !skipped.contains(&why) {
+ skipped.push(why);
}
}
- other
}
- _ => gone,
- };
- let keep: Vec<usize> = pieces.iter().copied().filter(|x| *x != gone).collect();
- tie(sk, &keep)?;
- sk.remove_curves(&[gone]);
+ }
+ if trimmed.is_empty() {
+ return Err(bad(cmd, skipped.first().cloned().unwrap_or_else(|| "the path crosses no curve that can be trimmed".into())));
+ }
doc.prune_model_params();
- Ok(json!({"trimmed": id}))
+ Ok((trimmed, removed, skipped))
})?;
- Ok(json!({"result": out, "sketch": info}))
+ Ok(json!({"trimmed": trimmed, "removed": removed, "skipped": skipped, "sketch": info}))
}
fn break_cmd(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1884,3 +2020,7 @@ mod robust_tests;
#[cfg(test)]
#[path = "sketch_corner_tests.rs"]
mod corner_tests;
+
+#[cfg(test)]
+#[path = "sketch_trim_path_tests.rs"]
+mod trim_path_tests;
diff --git a/crates/engine/src/cmd/sketch_trim_path_tests.rs b/crates/engine/src/cmd/sketch_trim_path_tests.rs
new file mode 100644
index 0000000000..91e8b94bd1
--- /dev/null
+++ b/crates/engine/src/cmd/sketch_trim_path_tests.rs
@@ -0,0 +1,192 @@
+//! `sketch.trim.path`: dragging across curves trims each piece the path crosses, as clicking it
+//! with `sketch.trim` would, in one undo step.
+
+use serde_json::{Value, json};
+use solidcraft_geom::Vec2;
+use solidcraft_sketch::Shape;
+
+use crate::Session;
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ match s.execute(id, &p) {
+ Ok(v) => v,
+ Err(e) => panic!("{id} {p}: {e}"),
+ }
+}
+
+fn ids(v: &Value) -> Vec<String> {
+ v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
+}
+
+fn sketch(s: &Session) -> solidcraft_sketch::Sketch {
+ let id = s.active_sketch.unwrap();
+ s.model.state().sketch(id).unwrap().sketch.clone()
+}
+
+fn new_sketch() -> Session {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ s
+}
+
+fn line(s: &mut Session, points: Value) -> Vec<String> {
+ ids(&run(s, "sketch.line", json!({"points": points}))["curves"])
+}
+
+/// A 40 x 40 square with a step cut across its top right corner (as in the single trim's
+/// dimension test), the right side dimensioned.
+fn square_with_step() -> (Session, String, String) {
+ let mut s = new_sketch();
+ let sq = ids(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 40], [0, 40]], "closed": true, "infer": true}))["curves"]);
+ let (right, top) = (sq[1].clone(), sq[2].clone());
+ run(&mut s, "sketch.dimension", json!({"entities": [right]}));
+ let step = ids(&run(&mut s, "sketch.line", json!({"points": [[23, 40], [23, 23], [40, 23]], "infer": true}))["curves"]);
+ run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", step[0]), "b": top}));
+ run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.end", step[1]), "b": right}));
+ (s, right, top)
+}
+
+#[test]
+fn a_path_trims_what_clicking_each_crossed_piece_would() {
+ // Clicks: the right side above the step, then the top side right of it.
+ let (mut clicked, right, top) = square_with_step();
+ run(&mut clicked, "sketch.trim", json!({"curve": right, "at": [40, 30]}));
+ run(&mut clicked, "sketch.trim", json!({"curve": top, "at": [30, 40]}));
+
+ // One drag from outside the right side, across the corner, out through the top.
+ let (mut dragged, ..) = square_with_step();
+ let before = sketch(&dragged);
+ let undo_before = dragged.undo.len();
+ let out = run(&mut dragged, "sketch.trim.path", json!({"points": [[45, 30], [30, 30], [30, 45]]}));
+ assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(2), "{out}");
+ assert_eq!(out["removed"].as_array().map(Vec::len), Some(2), "{out}");
+ assert_eq!(sketch(&dragged), sketch(&clicked), "the drag and the two clicks leave the same sketch");
+
+ // One undo step brings everything back.
+ assert_eq!(dragged.undo.len(), undo_before + 1);
+ run(&mut dragged, "edit.undo", json!({}));
+ assert_eq!(sketch(&dragged), before);
+}
+
+#[test]
+fn a_piece_crossed_twice_is_trimmed_once() {
+ let mut s = new_sketch();
+ line(&mut s, json!([[0, 0], [20, 0]]));
+ line(&mut s, json!([[0, 10], [20, 10]]));
+ let v = line(&mut s, json!([[10, -5], [10, 15]]))[0].clone();
+ // A zigzag across the middle piece of the vertical line, three times.
+ let out = run(&mut s, "sketch.trim.path", json!({"points": [[5, 3], [15, 4], [5, 5], [15, 6]]}));
+ assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(1), "{out}");
+ let removed = out["removed"][0].as_array().unwrap();
+ let ends: Vec<Vec2> =
+ [removed.first().unwrap(), removed.last().unwrap()].iter().map(|q| Vec2::new(q[0].as_f64().unwrap(), q[1].as_f64().unwrap())).collect();
+ assert!(ends.iter().any(|q| q.dist(Vec2::new(10.0, 0.0)) < 1e-6) && ends.iter().any(|q| q.dist(Vec2::new(10.0, 10.0)) < 1e-6), "{ends:?}");
+ // The two outer pieces of the vertical line stay, the original id on the lower one.
+ let sk = sketch(&s);
+ assert_eq!(sk.curves.len(), 4);
+ let lower = sk.shape(sk.curve_index(&v).unwrap()).unwrap();
+ assert!(matches!(lower, Shape::Line { a, b } if a.dist(Vec2::new(10.0, -5.0)) < 1e-6 && b.dist(Vec2::new(10.0, 0.0)) < 1e-6), "{lower:?}");
+}
+
+/// A scene built twice: trimmed once along `path` and once by clicking `clicks` (curve index
+/// in the scene's curves, where) in turn; both must leave the same sketch.
+fn same_as_clicks(build: fn(&mut Session) -> Vec<String>, path: Value, clicks: &[(usize, [f64; 2])]) {
+ let mut clicked = new_sketch();
+ let curves = build(&mut clicked);
+ for (k, at) in clicks {
+ run(&mut clicked, "sketch.trim", json!({"curve": curves[*k], "at": at}));
+ }
+ let mut dragged = new_sketch();
+ build(&mut dragged);
+ let out = run(&mut dragged, "sketch.trim.path", json!({"points": path}));
+ assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(clicks.len()), "{out}");
+ assert!(out["removed"].as_array().unwrap().iter().all(|r| r.as_array().is_some_and(|r| r.len() >= 2)), "{out}");
+ assert_eq!(sketch(&dragged), sketch(&clicked), "{path}");
+}
+
+#[test]
+fn circles_arcs_and_splines_trim_along_a_path() {
+ // A circle across a line: the lower half goes, the rest is an arc.
+ same_as_clicks(
+ |s| {
+ let c = ids(&run(s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"]);
+ [c, line(s, json!([[-20, 0], [20, 0]]))].concat()
+ },
+ json!([[0, -15], [0, -5]]),
+ &[(0, [0.0, -10.0])],
+ );
+ // An arc cut by a line through its middle: the left part goes.
+ same_as_clicks(
+ |s| {
+ let a = ids(&run(s, "sketch.arc.three_point", json!({"start": [-10, 0], "through": [0, 10], "end": [10, 0]}))["curves"]);
+ [a, line(s, json!([[0, -5], [0, 15]]))].concat()
+ },
+ json!([[-10, 8], [-3, 8]]),
+ &[(0, [-6.0, 8.0])],
+ );
+ // A spline over a line: its hump goes, then the line's piece under it.
+ same_as_clicks(
+ |s| {
+ let sp =
+ ids(&run(s, "sketch.spline.fit_point", json!({"points": [[-20, -20], [-10, 5], [10, 5], [20, -20]], "connect": false}))["curves"]);
+ [sp, line(s, json!([[-30, 0], [30, 0]]))].concat()
+ },
+ json!([[0, 10], [0, -1]]),
+ &[(0, [0.0, 10.0]), (1, [0.0, 0.0])],
+ );
+}
+
+#[test]
+fn a_dry_run_reports_the_pieces_without_changing_the_design() {
+ let (mut s, ..) = square_with_step();
+ let before = sketch(&s);
+ let (undo, revision) = (s.undo.len(), s.revision);
+ let path = json!([[45, 30], [30, 30], [30, 45]]);
+ let dry = run(&mut s, "sketch.trim.path", json!({"points": path, "dry_run": true}));
+ assert_eq!(dry["dry_run"], true);
+ assert_eq!(sketch(&s), before);
+ assert_eq!((s.undo.len(), s.revision), (undo, revision), "a dry run is no step");
+ let real = run(&mut s, "sketch.trim.path", json!({"points": path}));
+ assert_eq!(dry["removed"], real["removed"]);
+ assert_eq!(dry["trimmed"], real["trimmed"]);
+}
+
+#[test]
+fn curves_trim_cannot_change_are_passed_over() {
+ let mut s = new_sketch();
+ let inf = line(&mut s, json!([[0, -10], [0, 10]]))[0].clone();
+ run(&mut s, "sketch.infinite", json!({"curves": [inf]}));
+ let h = line(&mut s, json!([[-20, 0], [20, 0]]))[0].clone();
+ // Crossing the infinite line leaves it alone; the horizontal line's right part goes.
+ let out = run(&mut s, "sketch.trim.path", json!({"points": [[-5, 5], [10, 5], [10, -5]]}));
+ assert_eq!(out["trimmed"].as_array().map(Vec::len), Some(1), "{out}");
+ let sk = sketch(&s);
+ assert!(sk.curves[sk.curve_index(&inf).unwrap()].infinite);
+ let rest = sk.shape(sk.curve_index(&h).unwrap()).unwrap();
+ assert!(matches!(rest, Shape::Line { a, b } if a.dist(Vec2::new(-20.0, 0.0)) < 1e-6 && b.dist(Vec2::new(0.0, 0.0)) < 1e-6), "{rest:?}");
+}
+
+#[test]
+fn hostile_paths_fail_cleanly() {
+ let mut s = new_sketch();
+ line(&mut s, json!([[0, 0], [10, 0]]));
+ let before = sketch(&s);
+ let long: Vec<[f64; 2]> = (0..2_001).map(|i| [i as f64, 1.0]).collect();
+ for p in [
+ json!({}),
+ json!({"points": []}),
+ json!({"points": [[0, 1]]}),
+ json!({"points": "x"}),
+ json!({"points": [[0, 1], ["a", 2]]}),
+ json!({"points": long}),
+ json!({"points": [[50, 50], [60, 60]]}),
+ json!({"points": [[1e308, -1e308], [-1e308, 1e308]]}),
+ json!({"points": [[5, 1], [5, 1]]}),
+ ] {
+ assert!(s.execute("sketch.trim.path", &p).is_err(), "{p}");
+ assert_eq!(sketch(&s), before, "{p}");
+ }
+ // Outside a sketch.
+ let mut none = Session::default();
+ assert!(none.execute("sketch.trim.path", &json!({"points": [[0, -1], [0, 1]]})).is_err());
+}
diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs
index bedd33883b..2e702599b0 100644
--- a/crates/ui-egui/src/sketch_tools.rs
+++ b/crates/ui-egui/src/sketch_tools.rs
@@ -86,6 +86,78 @@ thread_local! {
static ISO: RefCell<Vec<Vec<[Vec3; 2]>>> = const { RefCell::new(Vec::new()) };
/// Center of Mass has just started: measure everything on the next frame.
static DEFERRED: Cell<bool> = const { Cell::new(false) };
+ /// A Trim drag: the pieces its path would remove (sketch polylines), and where the path's
+ /// last point is on screen.
+ static TRIM_REMOVED: RefCell<Vec<Vec<Vec2>>> = const { RefCell::new(Vec::new()) };
+ static TRIM_LAST: Cell<Option<Pos2>> = const { Cell::new(None) };
+}
+
+/// Screen distance the pointer moves before a Trim drag's path takes another point.
+const TRIM_STEP_PX: f32 = 4.0;
+
+/// The sketch-plane position under screen position `pos`.
+fn on_sketch_plane(app: &SolveApp, proj: &Proj, pos: Pos2) -> Option<Vec2> {
+ let st = app.session.world_state();
+ let ss = st.sketch(active_sketch(app)?)?;
+ let (o, d) = proj.ray(pos);
+ ss.plane.intersect_ray(o, d).map(|w| ss.plane.to_local(w))
+}
+
+/// A press and drag with Trim draws a path from `press`; true when it started one. Each piece
+/// the path crosses is trimmed when it is let go (`sketch.trim.path`).
+pub fn trim_drag_start(app: &mut SolveApp, proj: &Proj, press: Pos2) -> bool {
+ let Some(q) = on_sketch_plane(app, proj, press) else { return false };
+ let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim") else { return false };
+ tool.pts = vec![(q, None)];
+ TRIM_LAST.with(|c| c.set(Some(press)));
+ TRIM_REMOVED.with(|r| r.borrow_mut().clear());
+ true
+}
+
+/// The Trim drag's path reaches `pos`: the pieces it would remove light up (a dry run of the
+/// command the release runs).
+pub fn trim_drag_to(app: &mut SolveApp, proj: &Proj, pos: Pos2) {
+ if TRIM_LAST.with(Cell::get).is_some_and(|last| last.distance(pos) < TRIM_STEP_PX) {
+ return;
+ }
+ let Some(q) = on_sketch_plane(app, proj, pos) else { return };
+ let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim" && !t.pts.is_empty()) else { return };
+ if tool.pts.len() >= TRIM_PATH_MAX {
+ return;
+ }
+ tool.pts.push((q, None));
+ TRIM_LAST.with(|c| c.set(Some(pos)));
+ let points: Vec<[f64; 2]> = tool.pts.iter().map(|p| [p.0.x, p.0.y]).collect();
+ let removed = app
+ .session
+ .execute("sketch.trim.path", &json!({"points": points, "dry_run": true}))
+ .map(|v| {
+ v["removed"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|piece| piece.as_array().into_iter().flatten().filter_map(solidcraft_engine::params::vec2).collect())
+ .collect()
+ })
+ .unwrap_or_default();
+ TRIM_REMOVED.with(|r| *r.borrow_mut() = removed);
+}
+
+/// Most points a Trim drag's path keeps (the command's limit).
+const TRIM_PATH_MAX: usize = 2_000;
+
+/// The Trim drag is let go: trim every piece its path crossed, in one undo step. False when the
+/// path crossed nothing (the caller takes the release as a click).
+pub fn trim_drag_end(app: &mut SolveApp) -> bool {
+ TRIM_LAST.with(|c| c.set(None));
+ let crossed = TRIM_REMOVED.with(|r| !std::mem::take(&mut *r.borrow_mut()).is_empty());
+ let Some(tool) = app.tool.as_mut().filter(|t| t.cmd == "sketch.trim") else { return false };
+ let points: Vec<[f64; 2]> = std::mem::take(&mut tool.pts).iter().map(|p| [p.0.x, p.0.y]).collect();
+ if !crossed || points.len() < 2 {
+ return false;
+ }
+ let _ = app.run("sketch.trim.path", json!({"points": points}));
+ true
}
/// Commands registered on one panel that another panel also lists: the analyses (sketch
@@ -528,7 +600,7 @@ pub fn hint(id: &str) -> Option<String> {
"inspect.continuity" => "Continuity: click an edge for its numbers (the button again turns the colours off)",
"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",
+ "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.break" => "Break: click a curve where it should split",
"sketch.line.midpoint" => "Midpoint line: click the middle, then an end",
@@ -1042,6 +1114,18 @@ pub fn preview(app: &SolveApp, t: &Tool, painter: &egui::Painter, proj: &Proj) {
crate::tools::paint_sketch_path(&world, 0, painter, proj, Stroke::new(4.5, tk.error));
}
let stroke = Stroke::new(1.5, tk.rubber_band);
+ // A Trim drag: the pieces it will remove, then the path drawn so far.
+ if t.cmd == "sketch.trim" && !t.pts.is_empty() {
+ TRIM_REMOVED.with(|r| {
+ for piece in r.borrow().iter() {
+ let line: Vec<Pos2> = piece.iter().filter_map(|p| to(*p)).collect();
+ painter.add(egui::Shape::line(line, Stroke::new(4.0, tk.error.gamma_multiply(0.8))));
+ }
+ });
+ let path: Vec<Pos2> = t.pts.iter().filter_map(|p| to(p.0)).collect();
+ painter.add(egui::Shape::line(path, stroke));
+ return;
+ }
if let Some((hp, snap)) = &t.hover
&& let Some(sp) = to(*hp)
{
@@ -1320,3 +1404,7 @@ mod corner_ui_tests;
#[cfg(test)]
#[path = "sketch_continuity_tests.rs"]
mod continuity_tests;
+
+#[cfg(test)]
+#[path = "sketch_trim_drag_ui_tests.rs"]
+mod trim_drag_ui_tests;
diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs
new file mode 100644
index 0000000000..a0a56c02a0
--- /dev/null
+++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs
@@ -0,0 +1,151 @@
+//! Trim by dragging: with Trim on, a press and drag draws a path, the pieces it crosses light
+//! up, and letting go trims them all (`sketch.trim.path`) in one undo step. A click still trims
+//! the one piece under it.
+
+use serde_json::{Value, json};
+use solidcraft_engine::geom::Vec2;
+use solidcraft_engine::sketch::Shape;
+
+use crate::scenario::Harness;
+
+/// Two horizontal lines crossed by a vertical one, seen from the top, with Trim on. Returns the
+/// vertical line's id.
+fn ladder() -> (Harness, String) {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ run(&mut h, "sketch.create", json!({"plane": "XY"}));
+ run(&mut h, "sketch.line", json!({"points": [[0, 0], [20, 0]], "connect": false}));
+ run(&mut h, "sketch.line", json!({"points": [[0, 10], [20, 10]], "connect": false}));
+ let v = run(&mut h, "sketch.line", json!({"points": [[10, -5], [10, 15]], "connect": false}))["curves"][0].as_str().unwrap().to_string();
+ h.call("ui.view", json!({"view": "top"}));
+ h.app.cam.distance = 60.0;
+ h.frames(3);
+ h.call("ui.start", json!({"command": "sketch.trim"}));
+ h.frames(2);
+ (h, v)
+}
+
+#[test]
+fn dragging_across_pieces_trims_them_all_in_one_undo_step() {
+ let (mut h, v) = ladder();
+ let before = h.app.session.doc.to_json();
+ let undo = h.app.session.undo.len();
+ // A zigzag across the vertical line's middle piece, three times, then down across the
+ // lower line's right half.
+ let a = screen(&mut h, 5.0, 8.0);
+ let b = screen(&mut h, 15.0, 7.0);
+ let c = screen(&mut h, 5.0, 5.0);
+ let d = screen(&mut h, 15.0, -3.0);
+ let mut path = vec![a];
+ path.extend(steps(a, b, 8));
+ path.extend(steps(b, c, 8));
+ path.extend(steps(c, d, 8));
+ press_and_move(&mut h, &path);
+
+ // While dragging: nothing has changed yet, and the two pieces to go light up (the middle
+ // piece once).
+ assert!(h.app.viewport.trim_drag);
+ assert_eq!(h.app.session.doc.to_json(), before, "a drag changes nothing before it is let go");
+ assert_eq!(h.app.session.undo.len(), undo);
+ let lit = super::TRIM_REMOVED.with(|r| r.borrow().clone());
+ assert_eq!(lit.len(), 2, "{lit:?}");
+
+ release(&mut h, d);
+ assert!(!h.app.viewport.trim_drag);
+ assert!(super::TRIM_REMOVED.with(|r| r.borrow().is_empty()));
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one undo step");
+ // The vertical line keeps its ends; the lower line its left half.
+ let sk = sketch(&h);
+ let rest: Vec<Shape> = (0..sk.curves.len()).filter_map(|ci| sk.shape(ci)).collect();
+ assert_eq!(rest.len(), 4, "{rest:?}");
+ assert!(rest.iter().all(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3 && s.dist(Vec2::new(15.0, 0.0)) > 1e-3), "{rest:?}");
+ let lower = sk.shape(sk.curve_index(&v).unwrap()).unwrap();
+ assert!(matches!(lower, Shape::Line { a, b } if a.dist(Vec2::new(10.0, -5.0)) < 1e-6 && b.dist(Vec2::new(10.0, 0.0)) < 1e-6), "{lower:?}");
+ // Trim stays on for the next piece.
+ assert_eq!(h.app.tool.as_ref().map(|t| t.cmd), Some("sketch.trim"));
+
+ run(&mut h, "edit.undo", json!({}));
+ assert_eq!(h.app.session.doc.to_json(), before);
+}
+
+#[test]
+fn a_click_still_trims_one_piece_and_an_empty_drag_nothing() {
+ let (mut h, v) = ladder();
+ let undo = h.app.session.undo.len();
+ // A drag that crosses nothing leaves the design alone.
+ let a = screen(&mut h, 1.0, 3.0);
+ let b = screen(&mut h, 8.0, 7.0);
+ let mut path = vec![a];
+ path.extend(steps(a, b, 6));
+ press_and_move(&mut h, &path);
+ release(&mut h, b);
+ assert_eq!(h.app.session.undo.len(), undo);
+
+ // A click on the vertical line's middle piece trims just that piece.
+ h.step(&json!({"click": {"sketch": [10, 5]}})).unwrap();
+ assert_eq!(h.app.session.undo.len(), undo + 1);
+ let sk = sketch(&h);
+ assert_eq!(sk.curves.len(), 4);
+ assert!((0..sk.curves.len()).all(|ci| sk.shape(ci).is_some_and(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3)));
+ assert!(sk.curve_index(&v).is_some());
+}
+
+#[test]
+fn a_click_that_moves_along_a_piece_still_trims_it() {
+ // A press that moves on the way (#2448) beside the vertical line's middle piece, crossing
+ // nothing: the release is the click, and trims the piece under it.
+ let (mut h, _) = ladder();
+ let undo = h.app.session.undo.len();
+ let a = screen(&mut h, 10.0, 3.0) + egui::vec2(3.0, 0.0);
+ let b = screen(&mut h, 10.0, 7.0) + egui::vec2(3.0, 0.0);
+ let mut path = vec![a];
+ path.extend(steps(a, b, 6));
+ press_and_move(&mut h, &path);
+ release(&mut h, b);
+ assert_eq!(h.app.session.undo.len(), undo + 1, "one trim");
+ let sk = sketch(&h);
+ assert_eq!(sk.curves.len(), 4);
+ assert!((0..sk.curves.len()).all(|ci| sk.shape(ci).is_some_and(|s| s.dist(Vec2::new(10.0, 5.0)) > 1e-3)));
+}
+
+fn run(h: &mut Harness, id: &str, p: Value) -> Value {
+ match h.app.run(id, p.clone()) {
+ Ok(v) => v,
+ Err(e) => panic!("{id} {p}: {e}"),
+ }
+}
+
+fn sketch(h: &Harness) -> solidcraft_engine::sketch::Sketch {
+ let sid = h.app.session.active_sketch.expect("sketch mode");
+ h.app.session.world_state().sketch(sid).expect("the sketch").sketch.clone()
+}
+
+fn screen(h: &mut Harness, x: f64, y: f64) -> egui::Pos2 {
+ let [sx, sy] = h.at(&json!({"sketch": [x, y]})).expect("on screen");
+ egui::pos2(sx as f32, sy as f32)
+}
+
+fn steps(a: egui::Pos2, b: egui::Pos2, n: usize) -> Vec<egui::Pos2> {
+ (1..=n).map(|i| a + (b - a) * (i as f32 / n as f32)).collect()
+}
+
+/// Press at `path[0]` and move through the rest, one frame per event.
+fn press_and_move(h: &mut Harness, path: &[egui::Pos2]) {
+ let Some(&a) = path.first() else { return };
+ h.app.synthetic.push(egui::Event::PointerMoved(a));
+ h.app.synthetic.push(egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
+ h.app.synthetic.extend(path.iter().skip(1).map(|&p| egui::Event::PointerMoved(p)));
+ play(h);
+}
+
+fn release(h: &mut Harness, at: egui::Pos2) {
+ h.app.synthetic.push(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
+ play(h);
+}
+
+fn play(h: &mut Harness) {
+ while !h.app.synthetic.is_empty() {
+ h.frame();
+ }
+ h.frames(2);
+}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index dc0a5aa12e..61d18726fc 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -48,6 +48,8 @@ pub struct ViewportState {
/// A tool's click moved on the way (#2448): egui takes a press that moves past its
/// click distance, or is held past its click time, as a drag, so its release is the click.
pub(crate) tool_click: bool,
+ /// A Trim drag is drawing its path (`sketch_tools::trim_drag_*`).
+ pub(crate) trim_drag: bool,
/// Per-body boxes of one world state, held (not just its address, which a later state can
/// reuse once the old one is freed, so stale boxes would come back).
pick_bounds: std::sync::Mutex<Option<BodyBounds>>,
@@ -2533,6 +2535,23 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
crate::tools::on_hover(app, &proj, p);
}
}
+ // A Trim drag's path follows the pointer; letting go trims what it crossed. A path that
+ // crossed nothing was a click that moved on the way (#2448): the release clicks.
+ if app.viewport.trim_drag {
+ let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p));
+ if resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down()) {
+ app.viewport.trim_drag = false;
+ if !crate::sketch_tools::trim_drag_end(app)
+ && let Some(p) = at
+ && app.tool.is_some()
+ {
+ crate::tools::on_hover(app, &proj, p);
+ crate::tools::on_click(app, &proj, p);
+ }
+ } else if let Some(p) = at {
+ crate::sketch_tools::trim_drag_to(app, &proj, p);
+ }
+ }
// Selection chords via resolve (add-only Shift is a preference; default both toggle).
let held_mods = crate::tool_modifiers::Held::from_modifiers(mods);
let (add, allow_toggle) = crate::tool_modifiers::selection_click(held_mods, app.preferences.selection_shift_add_only);
@@ -2541,6 +2560,20 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
if app.tool.is_some() {
crate::tools::on_hover(app, &proj, p);
}
+ // Trim also trims by press and drag across the pieces to remove (its own release handling,
+ // so not a click that moved on the way below).
+ if app.tool.as_ref().is_some_and(|t| t.cmd == "sketch.trim")
+ && !held
+ && primary_nav.is_none()
+ && mode.is_none()
+ && resp.drag_started_by(egui::PointerButton::Primary)
+ && let Some(a) = ui.input(|i| i.pointer.press_origin())
+ {
+ app.viewport.trim_drag = crate::sketch_tools::trim_drag_start(app, &proj, a);
+ if app.viewport.trim_drag {
+ crate::sketch_tools::trim_drag_to(app, &proj, p);
+ }
+ }
// Rectangles, circles and polygons also draw by press, drag and release (#1630): the press
// places the first point as a click there would, the release the second.
let two_point_start = app.tool.as_ref().is_some_and(|t| matches!(t.kind, crate::tools::Kind::Draw(2)) && t.pts.is_empty());
@@ -2553,7 +2586,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
{
crate::tools::on_click(app, &proj, a);
app.viewport.draw_drag = app.tool.as_ref().is_some_and(|t| t.pts.len() == 1).then_some(a);
- } else if app.tool.is_some() && !held && primary_nav.is_none() && mode.is_none() && resp.drag_started_by(egui::PointerButton::Primary) {
+ } else if app.tool.is_some()
+ && !app.viewport.trim_drag
+ && !held
+ && primary_nav.is_none()
+ && mode.is_none()
+ && resp.drag_started_by(egui::PointerButton::Primary)
+ {
// Any other press of a tool that turns into a drag is a click that moved on the way
// (#2448): its release clicks.
app.viewport.tool_click = true;
diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md
index c9595d0ce9..c74d2c3011 100644
--- a/docs/book/src/guide/sketching.md
+++ b/docs/book/src/guide/sketching.md
@@ -30,7 +30,9 @@ Lines and polylines (L), rectangles (two-point R, three-point, centre), circles
two-point, three-point, tangent), arcs (three-point, centre, tangent), polygons, slots, ellipses,
fit-point and control-point splines, conics, points and text. **Construction** (X) turns curves
into reference geometry that doesn't form profiles. Modify tools include trim (T), extend, break,
-fillet, chamfer, offset (O), mirror, patterns, move/copy and scale.
+fillet, chamfer, offset (O), mirror, patterns, move/copy and scale. With trim on, click a
+piece to remove it, or press and drag a path across several pieces: the ones it crosses light up
+and all go when you let go, in one undo step (`sketch.trim.path`).
The Sketch Palette's **Construction Geometries** option hides construction curves while you
work. A hidden construction curve cannot be picked by a click or by a box. Nothing invisible