SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Fix sketch drag breaking midpoint-constrained line solver (#7635) (#7810)
Dahak Builds64ff25f3804f
diff --git a/crates/engine/src/cmd/sketch_robust_tests.rs b/crates/engine/src/cmd/sketch_robust_tests.rsindex 5869ebf988..65559d89bf 100644--- a/crates/engine/src/cmd/sketch_robust_tests.rs+++ b/crates/engine/src/cmd/sketch_robust_tests.rs@@ -181,3 +181,26 @@ fn offset_cases() {sound(&s);}}++/// #7635: the reporter's design - `l1` with its midpoint pinned at the origin, `l2` perpendicular+/// to it at the origin, and a construction line `l3` at the origin constrained horizontal with a+/// 50-degree angle dimension to `l1`. Dragging a free end of `l1` (whose exact target the pinned+/// inclination makes unreachable) used to leave the failed step placed and break the perpendicular+/// and angle constraints; the sketch must stay solved instead.+#[test]+fn dragging_the_midpoint_line_end_keeps_the_sketch_solved() {+ let mut s = new_sketch();+ add(&mut s, "sketch.line", json!({"points": [[-6.616478376301535, -7.876608451910095], [6.616478376301535, 7.876608451910095]]}));+ add(&mut s, "sketch.constraint.midpoint", json!({"point": "origin", "line": "l1"}));+ add(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [-10.656000978748368, 8.951213010548841]]}));+ add(&mut s, "sketch.constraint.coincident", json!({"a": "l2.start", "b": "origin"}));+ add(&mut s, "sketch.constraint.perpendicular", json!({"a": "l2", "b": "l1"}));+ add(&mut s, "sketch.line", json!({"points": [[0.0, 0.0], [10.0, 0.0]], "construction": true}));+ add(&mut s, "sketch.constraint.coincident", json!({"a": "l3.start", "b": "origin"}));+ add(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l3", "mode": "horizontal"}));+ add(&mut s, "sketch.dimension", json!({"entities": ["l3", "l1"], "type": "angle", "value": "50 deg"}));+ let r = s.execute("sketch.drag", &json!({"entity": "l1.end", "from": [6.616478376301535, 7.876608451910095], "to": [10.0, 4.0]})).unwrap();+ assert_eq!(r["sketch"]["solved"], json!(true), "the drag left the sketch unsolved: {r}");+ s.execute("sketch.drag_end", &json!({})).unwrap();+ sound(&s);+}diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rsindex 19649fa2a4..59e6e2946c 100644--- a/crates/sketch/src/cursor.rs+++ b/crates/sketch/src/cursor.rs@@ -15,11 +15,12 @@ const MAX_VARIABLES: usize = 400;const MAX_STEPS: usize = 96;const CORRECTION_ITERS: usize = 16;const TOTAL_CORRECTION_ITERS: usize = 256;-/// Pivot tolerance of the null space, on rows scaled to a largest entry of 1. Redundant-/// constraints (a parallelogram held both parallel and equal on each pair of sides) are-/// dependent only at an exact solution; a pose corrected to `TOL` leaves their rows independent-/// by about that much, and a tighter tolerance counts that as rank and finds no freedom (#4585).-/// The solver's rank analysis, which reports the sketch's degrees of freedom, uses 1e-7 too.+/// Pivot tolerance of the null space, on the Jacobian equilibrated to unit rows and columns.+/// Redundant constraints (a parallelogram held both parallel and equal on each pair of sides)+/// are dependent only at an exact solution; a pose corrected to `TOL` leaves their rows+/// independent by about that much, and a tighter tolerance counts that as rank and finds no+/// freedom (#4585). The solver's rank analysis, which reports the sketch's degrees of freedom,+/// uses 1e-7 too.const NULL_SPACE_TOL: f64 = 1e-7;/// Move a point toward `target` using freedom left by the design constraints. `max_step`@@ -131,14 +132,22 @@ fn move_cursor_towards(// Held feasibility solves accept up to ACCEPT. A tiny, nearly feasible hard pin can// precede a failed step; refine it before constructing a tangent, rather than losing// the cursor objective just because the previous pose is between TOL and ACCEPT.+ // An ill-conditioned sketch (a near-zero-length construction line makes its angle row+ // unsolvable to TOL, #7635) stalls that refinement between TOL and ACCEPT. The solver+ // itself calls such a pose solved, so the cursor keeps working from it and accepts its+ // corrected trials at the same tolerance the final validation uses.+ let mut trial_tol = TOL;if initial_residual >= TOL {let Some((its, residual)) = lm_capped_with_budget(&problem, &lay, &sub, &vars, &mut x, &col, CORRECTION_ITERS, budget.as_deref_mut()) else {return false;};spent += its.max(1);- if !(residual < TOL) {+ if residual >= ACCEPT {return false;}+ if residual >= TOL {+ trial_tol = ACCEPT;+ }apply(&mut best, &lay, &x);if !in_range(&best) || !valid(&problem, &best) {return false;@@ -214,7 +223,7 @@ fn move_cursor_towards(break 'search;};spent += its.max(1);- if !(residual < TOL) {+ if !(residual < trial_tol) {if budget.as_ref().is_some_and(|b| b.exhausted()) {break 'search;}@@ -263,27 +272,44 @@ fn in_range(sk: &Sketch) -> bool {.all(|c| !matches!(c.kind, CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } if !crate::model::radius_in_range(r)))}-fn null_space(mut j: Mat) -> Vec<Vec<f64>> {- for row in 0..j.rows {- let scale = (0..j.cols).map(|c| j.get(row, c).abs()).fold(0.0_f64, f64::max);+fn null_space(j: Mat) -> Vec<Vec<f64>> {+ // Equilibrate before the rank analysis. A near-zero-length construction line makes its+ // angle row's entries on that line ~1e7 while the same row's entries on the line it+ // measures are ~1: per-row scaling alone hides those (physically meaningful) small+ // entries below the pivot tolerance, and the null space then lets the measured line+ // rotate freely (#7635). Scaling each column by its largest entry first brings the+ // row's entries onto one scale; the null vectors are mapped back afterwards.+ let mut col = vec![0.0_f64; j.cols];+ for (c, m) in col.iter_mut().enumerate() {+ for r in 0..j.rows {+ *m = m.max(j.get(r, c).abs());+ }+ }+ let inv: Vec<f64> = col.iter().map(|m| 1.0 / m.max(1.0)).collect();+ let mut a = Mat::zeros(j.rows, j.cols);+ for r in 0..j.rows {+ let scale = (0..j.cols).map(|c| j.get(r, c).abs() * inv[c]).fold(0.0_f64, f64::max);if scale > 0.0 {- for c in 0..j.cols {- j.set(row, c, j.get(row, c) / scale);+ for (c, &ic) in inv.iter().enumerate() {+ a.set(r, c, j.get(r, c) * ic / scale);}}}- let pivots = rref(&mut j, NULL_SPACE_TOL);+ let pivots = rref(&mut a, NULL_SPACE_TOL);let mut z: Vec<Vec<f64>> = Vec::new();- for free in (0..j.cols).filter(|c| !pivots.contains(c)) {- let mut v = vec![0.0; j.cols];+ for free in (0..a.cols).filter(|c| !pivots.contains(c)) {+ let mut v = vec![0.0; a.cols];if let Some(x) = v.get_mut(free) {*x = 1.0;}for (row, &pivot) in pivots.iter().enumerate() {if let Some(x) = v.get_mut(pivot) {- *x = -j.get(row, free);+ *x = -a.get(row, free);}}+ for (x, &ic) in v.iter_mut().zip(&inv) {+ *x *= ic;+ }for _ in 0..2 {for q in &z {let d: f64 = v.iter().zip(q).map(|(a, b)| a * b).sum();diff --git a/crates/sketch/src/degenerate_line_tests.rs b/crates/sketch/src/degenerate_line_tests.rsnew file mode 100644index 0000000000..4ec991510e--- /dev/null+++ b/crates/sketch/src/degenerate_line_tests.rs@@ -0,0 +1,62 @@+//! Dragging a sketch whose construction line has collapsed to (near) zero length (#7635).+//!+//! The reporter's design: `l1` with its midpoint pinned at the fixed origin, `l2` perpendicular+//! to `l1` at the origin, and a construction line `l3` coincident with the origin, constrained+//! horizontal, with a 50-degree angle dimension between `l3` and `l1`. `l3`'s ends sit on top of+//! each other, so its angle row's entries on `l3` are ~1e7 while the same row's entries on `l1`+//! are ~1. Dragging an endpoint of `l1` must keep the sketch solved: the cursor may not leave the+//! constraint manifold, and the rank analysis may not hide `l1`'s coupling below its tolerance.++use solidcraft_geom::Vec2;++use crate::{Analysis, ConstraintKind, Hold, Sketch, move_point_towards, solve_with};++fn v(x: f64, y: f64) -> Vec2 {+ Vec2::new(x, y)+}++/// The reporter's sketch, at the pose saved in `Sketch bug.solidcraft`: `l3` is a construction+/// line whose ends are ~1e-6 apart at the origin.+fn collapsed_construction_sketch() -> Sketch {+ let mut sk = Sketch::new();+ let s1 = sk.add_point(v(-6.616478376301535, -7.876608451910095), Some("l1.start")).unwrap();+ let e1 = sk.add_point(v(6.616478376301535, 7.876608451910095), Some("l1.end")).unwrap();+ let e2 = sk.add_point(v(-10.656000978748368, 8.951213010548841), Some("l2.end")).unwrap();+ let s3 = sk.add_point(v(2.814486877637019e-13, -1.946249554158009e-16), Some("l3.start")).unwrap();+ let e3 = sk.add_point(v(9.597991615339335e-7, -5.159859446747845e-10), Some("l3.end")).unwrap();+ let l1 = sk.add_line_pts(s1, e1, Some("l1")).unwrap();+ let l2 = sk.add_line_pts(0, e2, Some("l2")).unwrap();+ let l3 = sk.add_line_pts(s3, e3, Some("l3")).unwrap();+ sk.add_constraint(ConstraintKind::PointOnCurve { p: 0, c: l1 }, None).unwrap();+ sk.add_constraint(ConstraintKind::Midpoint { p: 0, l: l1 }, None).unwrap();+ sk.add_constraint(ConstraintKind::Perpendicular { a: l2, b: l1 }, None).unwrap();+ sk.add_constraint(ConstraintKind::Horizontal { l: l3 }, None).unwrap();+ sk.add_constraint(ConstraintKind::Coincident { p: s3, q: 0 }, None).unwrap();+ sk.add_constraint(ConstraintKind::Angle { a: l3, b: l1, value: 50f64.to_radians(), flip: false }, None).unwrap();+ sk+}++/// The pose the reporter saved solves.+#[test]+fn the_saved_pose_solves() {+ let mut sk = collapsed_construction_sketch();+ let rep = solve_with(&mut sk, &Hold::default(), None, Analysis::Full, None);+ assert!(rep.ok(), "the saved pose no longer solves: {:?}", rep.failing);+}++/// Dragging `l1.end` off the 50-degree line: the exact target is unreachable (the midpoint and+/// the angle dimension pin `l1`'s inclination), so the cursor must stay on the manifold: the+/// sketch solves afterwards and `l1.end` keeps the inclination the constraints pin.+#[test]+fn dragging_the_midpoint_line_end_keeps_the_sketch_solved() {+ let mut sk = collapsed_construction_sketch();+ let e1 = 2; // l1.end+ let ok = move_point_towards(&mut sk, e1, v(10.0, 4.0), 2.0, None, |_, _| true);+ assert!(ok, "the cursor gave up on a solved sketch");+ let rep = solve_with(&mut sk, &Hold::default(), None, Analysis::StatusOnly, None);+ assert!(rep.ok(), "the drag broke the sketch: {:?}", rep.failing);+ // `l1.end` stayed on the 50-degree line through the origin: the angle dimension held.+ let at = sk.points[e1].pos;+ let off = (at.y.atan2(at.x) - 50f64.to_radians()).abs();+ assert!(off < 1e-3, "l1.end went to {at:?} (off its line by {off} rad)");+}diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rsindex 18cea9a803..78fdb22386 100644--- a/crates/sketch/src/lib.rs+++ b/crates/sketch/src/lib.rs@@ -88,6 +88,8 @@ mod construct_tests;#[cfg(test)]mod continuation_tests;#[cfg(test)]+mod degenerate_line_tests;+#[cfg(test)]mod ends_tests;#[cfg(test)]mod font_tests;