SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Preserve offset distances when trimming their source line (#10391)
cronosb5d931ff4cc7
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex c6109d9db1..48199cc887 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -60,7 +60,7 @@ pub static COMMANDS: &[CommandSpec] = &[.icon("trim").key("T").enabled(in_sketch)- .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it)", created_doc!())),+ .params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it). Trimming a line source releases its dependent straight offsets' linked extents (offset_released: curve ids), retaining their driving normal-distance dimensions and parallel relations", created_doc!())),CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path).icon("trim").enabled(in_sketch)@@ -409,13 +409,103 @@ 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 (out, _) = remove_piece(sk, ci, at, cmd)?;+ let released = release_source_line_offsets(sk, doc, ci, cmd)?;+ let (mut out, _) = remove_piece(sk, ci, at, cmd)?;+ if !released.is_empty() {+ out["offset_released"] = json!(released);+ }doc.prune_model_params();Ok(out)})?;Ok(json!({"result": out, "sketch": info}))}+/// A source line's endpoints may change independently of its parallel offsets. Materialize+/// the affected line chains before Trim, retaining their original driving distance parameters+/// as point-line dimensions. Directly trimming an associated output remains a separate command policy.+fn release_source_line_offsets(sk: &mut Sketch, doc: &solidcraft_doc::Document, ci: usize, cmd: &str) -> Result<Vec<String>> {+ let Some(curve) = sk.curves.get(ci) else { return Ok(Vec::new()) };+ if curve.infinite || sk.is_linked_curve(ci) || !matches!(curve.kind, CurveKind::Line { .. }) {+ return Ok(Vec::new());+ }+ let id = curve.id.clone();+ let affected: Vec<usize> = sk+ .offsets+ .iter()+ .enumerate()+ .filter_map(|(i, offset)| {+ (offset.topology.is_none()+ && offset.sources.iter().any(|(source, _)| source == &id)+ && offset.sources.len() == offset.outputs.len()+ && offset.sources.iter().zip(&offset.outputs).all(|((source, _), output)| {+ [source, output]+ .iter()+ .all(|id| sk.curve_index(id).and_then(|ci| sk.curves.get(ci)).is_some_and(|c| matches!(c.kind, CurveKind::Line { .. })))+ }))+ .then_some(i)+ })+ .collect();+ if affected.is_empty() {+ return Ok(Vec::new());+ }+ let report = solve_current(sk, doc)?;+ if !report.keeps_orientation() {+ return Err(bad(cmd, report.failure(|_| "cannot trim a source with conflicting offset dimensions".into())));+ }+ let mut released = Vec::new();+ for index in affected.into_iter().rev() {+ let record = sk.offsets.remove(index);+ let dimension = sk+ .constraints+ .iter()+ .find(|c| {+ matches!(&c.kind,+ ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output))+ })+ .cloned()+ .ok_or_else(|| bad(cmd, "missing offset distance dimension"))?;+ let value = match dimension.kind {+ ConstraintKind::OffsetDistance { value, .. } => value,+ _ => record.distance.abs(),+ };+ sk.constraints.retain(|c| !matches!(&c.kind, ConstraintKind::OffsetDistance { output, .. } if record.outputs.contains(output)));+ for output in &record.outputs {+ let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?;+ let points = sk.curves.get(target).map(|c| c.kind.point_ids()).unwrap_or_default();+ for i in points {+ if i != 0+ && sk.curves.iter().all(|c| !c.kind.uses(i) || record.outputs.contains(&c.id))+ && let Some(point) = sk.points.get_mut(i)+ {+ point.fixed = false;+ }+ }+ }+ for (index, ((source, _), output)) in record.sources.iter().zip(&record.outputs).enumerate() {+ let source = sk.curve_index(source).ok_or_else(|| bad(cmd, "missing offset source"))?;+ let target = sk.curve_index(output).ok_or_else(|| bad(cmd, "missing offset line"))?;+ if !sk.constraints.iter().any(|c| {+ matches!(c.kind,+ ConstraintKind::Parallel { a, b } if (a == source && b == target) || (a == target && b == source))+ }) {+ add_c(sk, ConstraintKind::Parallel { a: source, b: target })?;+ }+ let p = sk.curves.get(target).and_then(|c| c.kind.ends()).map(|ends| ends.0).ok_or_else(|| bad(cmd, "missing offset line endpoint"))?;+ let kind = ConstraintKind::PointLineDistance { p, l: source, value };+ let id = sk.add_constraint(kind.clone(), dimension.param.clone())?;+ if let Some(added) = sk.constraints.iter_mut().find(|c| c.id == id) {+ let mut kept = dimension.clone();+ kept.id = if index == 0 { dimension.id.clone() } else { id };+ kept.kind = kind;+ *added = kept;+ }+ }+ released.extend(record.outputs);+ }+ released.sort();+ Ok(released)+}+/// 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.@@ -443,6 +533,21 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valureturn Ok((json!({"deleted": id}), removed));}refuse_offset_ends(sk, ci, "trim", cmd)?;+ // For parallel lines, any point on the output measures the same normal distance.+ // Move an endpoint witness to the surviving piece before removing its old endpoint.+ let witnesses: Vec<String> = sk+ .constraints+ .iter()+ .filter_map(|dimension| {+ let ConstraintKind::PointLineDistance { p, l, .. } = dimension.kind else { return None };+ let ends = sk.curves.get(ci).and_then(|c| c.kind.ends())?;+ let line = matches!(sk.curves.get(ci)?.kind, CurveKind::Line { .. });+ (line+ && (p == ends.0 || p == ends.1)+ && sk.constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Parallel { a, b } if (a == ci && b == l) || (a == l && b == ci))))+ .then(|| dimension.id.clone())+ })+ .collect();release_extent(sk, ci);let ts: Vec<f64> = cuts.iter().map(|c| c.0).collect();let (pieces, pts) = split_at(sk, ci, &ts)?;@@ -477,6 +582,15 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu};let keep: Vec<usize> = pieces.iter().copied().filter(|x| *x != gone).collect();tie(sk, &keep)?;+ if let Some((a, _)) = sk.curves.get(ci).and_then(|c| c.kind.ends()) {+ for dimension in &mut sk.constraints {+ if witnesses.contains(&dimension.id)+ && let ConstraintKind::PointLineDistance { p, .. } = &mut dimension.kind+ {+ *p = a;+ }+ }+ }let removed = sk.polyline(gone);sk.remove_curves(&[gone]);Ok((json!({"trimmed": id}), removed))@@ -575,7 +689,14 @@ fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {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) {+ let cut = release_source_line_offsets(sk, doc, ci, cmd).and_then(|released| {+ let (mut out, gone) = remove_piece(sk, ci, q, cmd)?;+ if !released.is_empty() {+ out["offset_released"] = json!(released);+ }+ Ok((out, gone))+ });+ match cut {Ok((out, gone)) => {trimmed.push(out);removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::<Vec<_>>()));diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex 8ad0a94af3..c28786d8fa 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -4492,3 +4492,148 @@ fn move_copy_drawn_wire_failures_leave_the_design_and_history_unchanged() {assert_eq!(s.doc.to_json(), original);assert_eq!((s.undo.len(), s.redo.len()), history);}++/// A construction line and its two offsets each stop at their own crossing. Trimming one+/// must never shorten the others, whatever order the three curves are picked in.+#[test]+fn trim_source_then_two_offsets_independently_in_either_order() {+ for order in [[0, 1, 2], [0, 2, 1]] {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]}));+ let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false}));+ let mut curves = vec!["source".to_string()];+ curves.extend(ids(&out["curves"]));+ assert_eq!(curves.len(), 3);+ run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false}));+ for picked in order {+ let before = sketch(&s);+ let geometry = |sk: &solidcraft_sketch::Sketch, id: &str| sk.shape(sk.curve_index(id).unwrap()).unwrap();+ let solidcraft_sketch::Shape::Line { a, b } = geometry(&before, &curves[picked]) else { panic!("line") };+ let r = run(&mut s, "sketch.trim", json!({"curve": curves[picked], "at": [a.x + 1.0, a.y + 1.0]}));+ assert_eq!(r["sketch"]["solved"], true, "{order:?}: {r}");+ let after = sketch(&s);+ let solidcraft_sketch::Shape::Line { a: start, b: end } = geometry(&after, &curves[picked]) else { panic!("line") };+ assert!((start.y - 20.0).abs() < 1e-6 && (start.x - (20.0 + a.x - a.y)).abs() < 1e-6, "{order:?}: {start:?}");+ assert!(end.dist(b) < 1e-6, "the far end stays put: {order:?}: {end:?} {b:?}");+ for (i, id) in curves.iter().enumerate().filter(|(i, _)| *i != picked) {+ let solidcraft_sketch::Shape::Line { a: old_a, b: old_b } = geometry(&before, id) else { panic!("line") };+ let solidcraft_sketch::Shape::Line { a: new_a, b: new_b } = geometry(&after, id) else { panic!("line") };+ assert!(new_a.dist(old_a) < 1e-6 && new_b.dist(old_b) < 1e-6, "unpicked {i} changed in {order:?}: {old_a:?} -> {new_a:?}");+ }+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(+ serde_json::to_value(sketch(&s)).unwrap(),+ serde_json::to_value(before).unwrap(),+ "one undo restores the complete association"+ );+ run(&mut s, "edit.redo", json!({}));+ assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), serde_json::to_value(after).unwrap());+ }+ }+}++#[test]+fn trim_path_cuts_source_and_two_offsets_at_their_own_crossings() {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "construction": true, "connect": false, "infer": false, "ids": ["source"]}));+ let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false}));+ let mut curves = vec!["source".to_string()];+ curves.extend(ids(&out["curves"]));+ run(&mut s, "sketch.line", json!({"points": [[-20,20],[60,20]], "connect": false, "infer": false}));+ let before = s.doc.to_json();+ let path = json!({"points": [[4,5],[15,5],[-10,5]], "dry_run": true});+ let preview = run(&mut s, "sketch.trim.path", path);+ assert_eq!(preview["trimmed"].as_array().unwrap().len(), 3, "{preview}");+ assert_eq!(s.doc.to_json(), before, "preview releases no stored associations or parameters");+ let r = run(&mut s, "sketch.trim.path", json!({"points": [[4,5],[15,5],[-10,5]]}));+ assert_eq!(r["trimmed"], preview["trimmed"]);+ assert!(r["skipped"].as_array().unwrap().is_empty(), "{r}");+ let sk = sketch(&s);+ assert!(sk.offsets.is_empty());+ for id in curves {+ let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(&id).unwrap()).unwrap() else { panic!("line") };+ assert!((a.y - 20.0).abs() < 1e-6, "{id}: {a:?}");+ }+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), before, "one undo restores all three lines and their associations");+}++#[test]+fn trim_whole_source_keeps_its_offsets_and_unrelated_associations() {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points": [[0,0],[40,40]], "connect": false, "infer": false, "ids": ["source"]}));+ let out = run(&mut s, "sketch.offset", json!({"curves": ["source"], "distance": 2, "symmetric": true, "chain": false}));+ let outputs = ids(&out["curves"]);+ run(&mut s, "sketch.line", json!({"points": [[100,100],[120,100]], "connect": false, "infer": false, "ids": ["unrelated"]}));+ let other = run(&mut s, "sketch.offset", json!({"curves": ["unrelated"], "distance": 3, "chain": false}));+ let before = sketch(&s);+ let doc_before = s.doc.to_json();+ let r = run(&mut s, "sketch.trim", json!({"curve": "source", "at": [10,10]}));+ assert_eq!(r["result"]["deleted"], "source");+ assert_eq!(r["sketch"]["solved"], true);+ let sk = sketch(&s);+ assert!(sk.curve_index("source").is_none());+ assert_eq!(sk.offsets.len(), 1);+ for id in outputs {+ assert_eq!(sk.polyline(sk.curve_index(&id).unwrap()), before.polyline(before.curve_index(&id).unwrap()), "{id}");+ }+ let other_output = other["curves"][0].as_str().unwrap();+ assert_eq!(sk.offset_distance(other_output), Some(3.0));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), doc_before);+}++#[test]+fn trim_keeps_offset_distances_driving_after_trims_drag_and_reopen() {+ let verify = |s: &Session, distance: f64, parameter: &str| {+ let state = s.world_state();+ let sk = &state.sketch(1).unwrap().sketch;+ let solidcraft_sketch::Shape::Line { a, b } = sk.shape(sk.curve_index("source").unwrap()).unwrap() else { panic!("source line") };+ let dir = (b - a).normalized().unwrap();+ for (id, sign) in [("l1", 1.0), ("l2", -1.0)] {+ let solidcraft_sketch::Shape::Line { a: p, b: q } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("offset line") };+ assert!(dir.cross((q - p).normalized().unwrap()).abs() < 1e-6, "{id} is parallel");+ for point in [p, q] {+ assert!((dir.cross(point - a) - sign * distance).abs() < 1e-6, "{id}: {point:?}, distance {distance}");+ }+ }+ assert!(s.doc.param(parameter).is_some(), "the original driving offset parameter remains");+ assert_eq!(sk.constraints.iter().filter(|c| c.param.as_deref() == Some(parameter)).count(), 2, "both sides retain their dimensions");+ assert!(state.sketch(1).unwrap().report.ok());+ };+ for reverse_outputs in [true, false] {+ let mut s = new_sketch();+ run(&mut s, "sketch.line", json!({"points":[[0,0],[40,40]],"construction":true,"connect":false,"infer":false,"ids":["source"]}));+ let out = run(&mut s, "sketch.offset", json!({"curves":["source"],"distance":2,"symmetric":true,"chain":false}));+ let parameter = out["param"].as_str().unwrap().to_string();+ let cutter =+ run(&mut s, "sketch.line", json!({"points":[[-20,20],[60,20]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string();+ let order = if reverse_outputs { ["source", "l2", "l1"] } else { ["source", "l1", "l2"] };+ for id in order {+ let sk = sketch(&s);+ let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") };+ run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]}));+ verify(&s, 2.0, ¶meter);+ }+ // A second end trim must reattach the existing distance witness to the retained line.+ let second_cutter =+ run(&mut s, "sketch.line", json!({"points":[[-20,25],[60,25]],"connect":false,"infer":false}))["curves"][0].as_str().unwrap().to_string();+ for id in order {+ let sk = sketch(&s);+ let solidcraft_sketch::Shape::Line { a, .. } = sk.shape(sk.curve_index(id).unwrap()).unwrap() else { panic!("line") };+ run(&mut s, "sketch.trim", json!({"curve":id,"at":[a.x+1.0,a.y+1.0]}));+ verify(&s, 2.0, ¶meter);+ }+ run(&mut s, "sketch.constraint.fix", json!({"entities":["source",cutter,second_cutter]}));+ run(&mut s, "sketch.move_point", json!({"point":"l1.end","to":[55,25]}));+ verify(&s, 2.0, ¶meter);+ run(&mut s, "parameters.change", json!({"name":parameter,"expression":"3 mm"}));+ verify(&s, 3.0, ¶meter);+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ verify(&reopened, 3.0, ¶meter);+ run(&mut reopened, "parameters.change", json!({"name":parameter,"expression":"4 mm"}));+ verify(&reopened, 4.0, ¶meter);+ run(&mut reopened, "edit.undo", json!({}));+ verify(&reopened, 3.0, ¶meter);+ }+}diff --git a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rsindex a0a56c02a0..460e24f6e6 100644--- a/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs+++ b/crates/ui-egui/src/sketch_trim_drag_ui_tests.rs@@ -149,3 +149,63 @@ fn play(h: &mut Harness) {}h.frames(2);}++#[test]+fn trimming_construction_source_and_offsets_by_click_or_drag_is_independent() {+ for drag in [false, true] {+ 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],[40,40]],"construction":true,"infer":false,"connect":false,"ids":["source"]}));+ let out = run(&mut h, "sketch.offset", json!({"curves":["source"],"distance":2,"symmetric":true,"chain":false}));+ let parameter = out["param"].as_str().unwrap().to_string();+ let mut curves = vec!["source".to_string()];+ curves.extend(out["curves"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()));+ run(&mut h, "sketch.line", json!({"points":[[-20,20],[60,20]],"infer":false,"connect":false}));+ h.call("ui.view", json!({"view":"top"}));+ h.app.cam.distance = 100.0;+ h.frames(3);+ h.call("ui.start", json!({"command":"sketch.trim"}));+ h.frames(2);+ let before = h.app.session.doc.to_json();+ let undo = h.app.session.undo.len();+ if drag {+ let a = screen(&mut h, 4.0, 5.0);+ let b = screen(&mut h, 15.0, 5.0);+ let mut path = vec![a];+ path.extend(steps(a, b, 16));+ let c = screen(&mut h, -10.0, 5.0);+ path.extend(steps(b, c, 16));+ path.extend(steps(c, b, 16));+ press_and_move(&mut h, &path);+ assert_eq!(h.app.session.doc.to_json(), before);+ release(&mut h, b);+ } else {+ let points = [[10.0, 10.0], [10.0 - 2f64.sqrt(), 10.0 + 2f64.sqrt()], [10.0 + 2f64.sqrt(), 10.0 - 2f64.sqrt()]];+ for point in points {+ h.step(&json!({"click":{"sketch":point}})).unwrap();+ h.frames(2);+ }+ }+ assert_eq!(h.app.session.undo.len(), undo + if drag { 1 } else { 3 }, "drag {drag}: {:?}", h.app.status);+ let sk = sketch(&h);+ assert_eq!(+ sk.constraints.iter().filter(|c| c.param.as_deref() == Some(¶meter)).count(),+ 2,+ "distance dimensions survive actual Trim gestures"+ );+ let Shape::Line { a: origin, b: end } = sk.shape(sk.curve_index("source").unwrap()).unwrap() else { panic!("source line") };+ let direction = (end - origin).normalized().unwrap();+ for id in curves {+ let Shape::Line { a, .. } = sk.shape(sk.curve_index(&id).unwrap()).unwrap() else { panic!("line") };+ assert!((a.y - 20.0).abs() < 1e-5, "drag {drag}: {id} {a:?}");+ if id != "source" {+ assert!((direction.cross(a - origin).abs() - 2.0).abs() < 1e-6, "drag {drag}: {id} keeps 2 mm");+ }+ }+ for _ in 0..if drag { 1 } else { 3 } {+ run(&mut h, "edit.undo", json!({}));+ }+ assert_eq!(h.app.session.doc.to_json(), before);+ }+}