From 3a9b053f5b054d505b323f90adbdca037d3413f2 Mon Sep 17 00:00:00 2001 From: takuto-NA Date: Mon, 19 Oct 2026 20:24:04 +0900 Subject: [PATCH] Fix constrained point dragging within the shared frame budget (#1976) (#1977) --- crates/engine/src/cmd/sketch.rs | 2 +- crates/engine/src/cmd/sketch_drag.rs | 51 +++- crates/engine/src/cmd/sketch_ux_tests.rs | 19 ++ crates/engine/tests/sketch_drag_target.rs | 107 ++++++++ crates/engine/tests/support/four_bar.rs | 45 ++++ crates/sketch/src/cursor.rs | 296 ++++++++++++++++++++++ crates/sketch/src/decompose.rs | 22 +- crates/sketch/src/lib.rs | 4 +- crates/sketch/src/solver.rs | 76 ++++-- crates/sketch/tests/cursor_target.rs | 160 ++++++++++++ 10 files changed, 751 insertions(+), 31 deletions(-) create mode 100644 crates/engine/tests/sketch_drag_target.rs create mode 100644 crates/engine/tests/support/four_bar.rs create mode 100644 crates/sketch/src/cursor.rs create mode 100644 crates/sketch/tests/cursor_target.rs diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index f97f4575f..34468fcd0 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -179,7 +179,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("entities: [curve, point or constraint ids]"), CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"), CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params( - "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point goes to `to`, a line (spline, conic) slides by to - from, a circle or arc grabbed on its edge takes the radius to `to`; the rest moves as little as it can and keeps its solution branch (a long move is followed in short steps, each solved with the entity held; a step that cannot be solved that way is approached as far as it can be and the next ones tried; when none past it solves, the last one is left to the sketch's ordinary solve, which may pull it back or leave the sketch unsolved; a step that would sweep an arc through its start is undone and the drag ends there). Returns `reached`: how much of the way from `from` to `to` the geometry followed (0..1), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` (each frame of an interactive drag) solves the sketch once and leaves the features after it as they were (stale) until `sketch.drag_end` or any command that reads the model; `dof` is then the one from before the drag", + "entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: a point moves toward `to` within the design constraints; when exact cursor placement is impossible, bounded feasible steps minimize cursor distance while keeping design constraints mandatory. A line (spline, conic) slides by to - from; a circle or arc grabbed on its edge takes the radius to `to`. Long moves use continuation to retain the solution branch, and a step that would sweep an arc through its start is rejected. Returns `reached`: progress along the requested move (0..1; feasible point motion projects its actual displacement onto that move), and `at`: where the grabbed spot went (`from` moved as the dragged points did), the `from` of the next move. `live: true` solves the sketch and leaves later features stale until `sketch.drag_end` or a command that reads the model; `dof` is then the one from before the drag", ), CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params( "constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom", diff --git a/crates/engine/src/cmd/sketch_drag.rs b/crates/engine/src/cmd/sketch_drag.rs index 9e175e9ba..889923032 100644 --- a/crates/engine/src/cmd/sketch_drag.rs +++ b/crates/engine/src/cmd/sketch_drag.rs @@ -104,29 +104,31 @@ impl Path { } } -/// Drag: the grabbed entity follows the cursor exactly (a point goes to it; a line or spline +/// Drag: the grabbed entity follows the cursor where possible (a point moves toward it; a line or spline /// slides by the cursor's move; a circle or arc grabbed on its edge changes radius about its /// centre; a conic grabbed on its curve reads its fullness, `rho`, off the cursor) and the rest /// of the sketch moves as little as it can, staying on the /// solution it started on. Fixed geometry stays. A step that cannot be solved with the entity /// held (the path crosses where the geometry cannot reach) is approached by halving the way to /// it, and the next steps are tried from the last solved state, the last of them being the whole -/// remaining move. When none past it solves, the first failed step stays placed but unsolved: +/// remaining move. A point whose exact pin fails instead minimizes cursor distance in the +/// design's remaining freedom, retaining only corrected, feasible poses. For other entities, +/// when none past it solves, the first failed step stays placed but unsolved: /// the edit's ordinary, non-strict solve that follows (seeded on the last solved state, see /// [`Left::MovedFrom`]) then pulls it back (fully constrained geometry) or leaves the sketch /// unsolved for the user to see. A step that would sweep an arc through its own start is undone /// and the drag ends there. Returns how far it got and what it leaves for the edit's solve /// ([`Left::Solved`]: the held solve of the last step it kept left the sketch solved). /// -/// `live`: one frame of an interactive drag, whose held solves share one frame's decomposition -/// budget ([`Budget::frame`]); otherwise each has a solve's own. +/// `live`: one frame of an interactive drag, whose held solves and cursor correction share +/// one frame's work budget ([`Budget::frame`]); otherwise each has a solve's own. pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: bool) -> (Dragged, Left) { let Some((path, hold, n, short)) = prepare(sk, e, from, to) else { return (Dragged { reached: 0.0, moving: Vec::new() }, Left::Unsolved); }; #[cfg(test)] let (n, short) = (n.min(step_cap::get()), short.min(step_cap::get())); - let moving = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect(); + let moving: Vec<_> = path.points().filter_map(|q| Some((q, sk.point(q)?))).collect(); let mut frame = live.then(frame_budget); // Only success matters to these solves: the degrees of freedom of a sketch with the entity // held are not the sketch's. Each is seeded on the last solved state (`last`), so what the @@ -211,6 +213,41 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: b failed = Some(t); } } + // First retain held continuation across unreachable stretches of an otherwise reachable + // path (for example an arm dragged through the hole around its shoulder). If it cannot + // arrive, optimize the full cursor target without relaxing the design constraints. + if failed.is_some() + && let Ent::Point(q) = e + { + let (points, radii) = sk.coupled(&hold.points, &hold.radii); + let size = smallest_size(sk, &hold, Some(Group { points: &points, radii: &radii })); + let max_step = (size * SHORT_STEP_FRACTION).min(path.length()).max(MIN_STEP); + #[cfg(test)] + let spent = frame.as_ref().map_or(0, Budget::spent); + let followed = solidcraft_sketch::move_point_towards(sk, q, to, max_step, frame.as_mut(), |before, after| { + let mut geometry = Geometry::default(); + geometry.take(before); + !geometry.sweep_wrapped(after) + }); + #[cfg(test)] + if let Some(budget) = &frame { + solves.work += budget.spent() - spent; + solves.cut |= budget.exhausted(); + } + if followed { + #[cfg(test)] + last_drag::set(solves); + let reached = moving + .iter() + .find(|(p, _)| *p == q) + .and_then(|(_, start)| { + let d = to - *start; + sk.point(q).map(|at| if at.dist(to) < 1e-6 || d.dot(d) == 0.0 { 1.0 } else { ((at - *start).dot(d) / d.dot(d)).clamp(0.0, 1.0) }) + }) + .unwrap_or(0.0); + return (Dragged { reached, moving }, Left::Solved); + } + } #[cfg(test)] last_drag::set(solves); let left = match failed { @@ -225,8 +262,8 @@ pub(super) fn drag_entity(sk: &mut Sketch, e: Ent, from: Vec2, to: Vec2, live: b (Dragged { reached: good, moving }, left) } -/// The held solves of one drag: how many, the decomposition work they did, and whether one ran -/// out of budget. +/// The held solves of one drag: how many, their shared work (including cursor correction), +/// and whether it ran out of budget. #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct Solves { pub count: usize, diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rs index 0e1c18301..c637d3bd7 100644 --- a/crates/engine/src/cmd/sketch_ux_tests.rs +++ b/crates/engine/src/cmd/sketch_ux_tests.rs @@ -1524,3 +1524,22 @@ fn the_first_dimension_does_not_scale_a_sketch_that_has_a_size() { let out = run(&mut s, "sketch.dimension", json!({"entities": ["l1", "l2"], "value": "60 deg", "scale_sketch": true})); assert!(out.get("scaled").is_none(), "{out}"); } + +/// The cursor fallback shares the held solves' frame budget; a scripted drag can finish later. +#[test] +fn cursor_fallback_respects_an_exhausted_live_frame_budget() { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [-10, 0]], "ids": ["crank"], "infer": false})); + run(&mut s, "sketch.dimension", json!({"entities": ["crank"], "value": 10})); + let target = v(-10.0, 16.0); + let nearest = target * (10.0 / target.len()); + super::drag::last_drag::with_frame_work(0, || { + run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [-10, 0], "to": [target.x, target.y], "live": true})); + }); + let at = pt(&s, "crank.end"); + assert!(at.dist(nearest) > 1.0, "an exhausted frame must not start unbudgeted cursor work: {at:?}"); + assert!((at.len() - 10.0).abs() < 1e-6); + assert!(s.model.state().sketch(s.active_sketch.unwrap()).unwrap().report.ok()); + run(&mut s, "sketch.drag", json!({"entity": "crank.end", "from": [at.x, at.y], "to": [target.x, target.y], "live": false})); + assert!(pt(&s, "crank.end").dist(nearest) < 1e-4, "scripted motion retains the full cursor objective"); +} diff --git a/crates/engine/tests/sketch_drag_target.rs b/crates/engine/tests/sketch_drag_target.rs new file mode 100644 index 000000000..e7d1a9ca9 --- /dev/null +++ b/crates/engine/tests/sketch_drag_target.rs @@ -0,0 +1,107 @@ +//! Cursor distance is minimized within the design's freedom; lengths stay mandatory. +#[path = "support/four_bar.rs"] +mod four_bar; + +use serde_json::json; +use solidcraft_geom::Vec2; + +fn drag(s: &mut solidcraft_engine::Session, target: Vec2) { + let from = four_bar::point(s, "crank.end").unwrap(); + s.execute("sketch.drag", &json!({"entity":"crank.end","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); +} + +#[test] +fn four_bar_large_off_locus_drag_reaches_the_closest_feasible_point() { + for target in [Vec2::new(-10.0, 8.0), Vec2::new(-10.0, -8.0), Vec2::new(20.0, 20.0), Vec2::new(20.0, 0.0), Vec2::new(1000.0, -1000.0)] { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + drag(&mut s, target); + let actual = four_bar::point(&s, "crank.end").unwrap(); + let nearest = target * (10.0 / target.len()); + assert!(actual.dist(nearest) < 1e-4, "target {target:?}, actual {actual:?}, expected {nearest:?}"); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + let state = s.model.state(); + let report = &state.sketch(s.active_sketch.unwrap()).unwrap().report; + assert!(report.ok()); + assert_eq!(report.dof, 1); + s.execute("sketch.drag_end", &json!({})).unwrap(); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(nearest) < 1e-4); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(Vec2::new(-10.0, 0.0)) < 1e-7); + } +} + +#[test] +fn four_bar_reverse_motion_and_stationary_cursor_do_not_drift() { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + for target in [Vec2::new(-10.0, 16.0), Vec2::new(-10.0, -16.0), Vec2::new(0.0, 25.0), Vec2::new(0.0, -25.0)] { + drag(&mut s, target); + let at = four_bar::point(&s, "crank.end").unwrap(); + assert!( + at.dist(target * (10.0 / target.len())) < 1e-4, + "target {target:?}, actual {at:?}, length error {}", + four_bar::length_error(&s).unwrap() + ); + for _ in 0..8 { + drag(&mut s, target); + assert!(four_bar::point(&s, "crank.end").unwrap().dist(at) < 1e-4); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + } + } +} + +#[test] +fn four_bar_one_event_and_split_moves_agree_and_keep_the_branch() { + let target = Vec2::new(-10.0, 16.0); + let mut single = four_bar::session().unwrap(); + let mut split = four_bar::session().unwrap(); + let start = four_bar::point(&single, "crank.end").unwrap(); + let side = four_bar::branch(&single).unwrap(); + drag(&mut single, target); + for i in 1..=16 { + drag(&mut split, start + (target - start) * (i as f64 / 16.0)); + assert!(four_bar::length_error(&split).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&split).unwrap(), side); + } + assert!(four_bar::point(&single, "crank.end").unwrap().dist(four_bar::point(&split, "crank.end").unwrap()) < 1e-4); +} + +#[test] +fn four_bar_live_cursor_motion_updates_driven_dimensions_before_release() { + let mut s = four_bar::session().unwrap(); + s.execute("sketch.dimension", &json!({"entities": ["crank"], "type": "horizontal", "driven": true})).unwrap(); + let id = s.active_sketch.unwrap(); + let dimension = s.doc.sketch(id).unwrap().constraints.last().unwrap().id.clone(); + drag(&mut s, Vec2::new(-10.0, 8.0)); + let at = four_bar::point(&s, "crank.end").unwrap(); + assert!(at.dist(Vec2::new(-10.0, 8.0) * (10.0 / 164.0_f64.sqrt())) < 1e-4); + let state = s.model.state(); + for sketch in [s.doc.sketch(id).unwrap(), &state.sketch(id).unwrap().sketch] { + let c = sketch.constraints.iter().find(|c| c.id == dimension).unwrap(); + assert!(c.driven); + assert!((c.kind.value().unwrap() - at.x.abs()).abs() < 1e-6, "reference dimension must measure the final live pose: {:?}", c.kind); + } +} + +#[test] +fn four_bar_other_joint_follows_the_rocker_arc_and_its_limits() { + let base = Vec2::new(42.0, 0.0); + let lo = -(-1264.0_f64 / 1680.0).acos(); + let hi = -(0.2_f64).acos(); + for angle in [-2.6_f64, -2.1, -1.5, -1.1] { + let mut s = four_bar::session().unwrap(); + let side = four_bar::branch(&s).unwrap(); + let from = four_bar::point(&s, "coupler.end").unwrap(); + let target = base + Vec2::new(angle.cos(), angle.sin()) * 60.0; + let nearest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * 20.0; + s.execute("sketch.drag", &json!({"entity":"coupler.end","from":[from.x,from.y],"to":[target.x,target.y],"live":true})).unwrap(); + assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4, "angle {angle}"); + assert!(four_bar::length_error(&s).unwrap() < 1e-6); + assert_eq!(four_bar::branch(&s).unwrap(), side); + s.execute("sketch.drag_end", &json!({})).unwrap(); + assert!(four_bar::point(&s, "coupler.end").unwrap().dist(nearest) < 1e-4); + } +} diff --git a/crates/engine/tests/support/four_bar.rs b/crates/engine/tests/support/four_bar.rs new file mode 100644 index 000000000..8ec6366f2 --- /dev/null +++ b/crates/engine/tests/support/four_bar.rs @@ -0,0 +1,45 @@ +//! Public-safe 10/40/20/42 mm linkage, matching the reported one-degree-of-freedom sketch. +use serde_json::json; +use solidcraft_engine::Session; +use solidcraft_geom::Vec2; + +pub type Result = std::result::Result>; + +pub fn session() -> Result { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane":"XZ"}))?; + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let y = -(1600.0_f64 - (x + 10.0) * (x + 10.0)).sqrt(); + s.execute("sketch.line", &json!({"points":[[0,0],[-10,0],[x,y],[42,0]],"ids":["crank","coupler","rocker"],"infer":false}))?; + s.execute("sketch.line", &json!({"points":["crank.start","rocker.end"],"ids":["ground"],"infer":false}))?; + for (line, length) in [("crank", 10.0), ("coupler", 40.0), ("rocker", 20.0), ("ground", 42.0)] { + s.execute("sketch.dimension", &json!({"entities":[line],"value":length}))?; + } + s.execute("sketch.constraint.horizontal_vertical", &json!({"line":"ground"}))?; + Ok(s) +} + +pub fn point(s: &Session, name: &str) -> Result { + let sk = s.doc.sketch(s.active_sketch.ok_or("missing active sketch")?)?; + sk.resolve_point(name).and_then(|p| sk.point(p)).ok_or_else(|| format!("missing point {name}").into()) +} + +pub fn length_error(s: &Session) -> Result { + let mut error = 0.0_f64; + for (a, b, length) in [ + ("crank.start", "crank.end", 10.0), + ("coupler.start", "coupler.end", 40.0), + ("rocker.start", "rocker.end", 20.0), + ("ground.start", "ground.end", 42.0), + ] { + error = error.max((point(s, a)?.dist(point(s, b)?) - length).abs()); + } + error = error.max(point(s, "crank.start")?.len()); + error = error.max(point(s, "ground.end")?.dist(Vec2::new(42.0, 0.0))); + Ok(error) +} + +pub fn branch(s: &Session) -> Result { + let a = point(s, "crank.end")?; + Ok((point(s, "rocker.end")? - a).cross(point(s, "coupler.end")? - a).signum()) +} diff --git a/crates/sketch/src/cursor.rs b/crates/sketch/src/cursor.rs new file mode 100644 index 000000000..36bdf923d --- /dev/null +++ b/crates/sketch/src/cursor.rs @@ -0,0 +1,296 @@ +//! Feasible cursor motion: optimize only within the design Jacobian's null space, then +//! retract to the constraint manifold. Mouse error never competes with design residuals. +use super::{ + ACCEPT, Hold, Layout, State, TOL, build_blocks, columns, initial_x, layout, lm_capped_with_budget, local_system, max_abs, points_on_curves, + residual_work, system, within_budget, +}; +use crate::{ + Budget, CurveKind, Sketch, + linalg::{Mat, rref}, + union_find::{find, union}, +}; +use solidcraft_geom::Vec2; + +const MAX_VARIABLES: usize = 400; +const MAX_STEPS: usize = 96; +const CORRECTION_ITERS: usize = 16; +const TOTAL_CORRECTION_ITERS: usize = 256; + +/// Move a point toward `target` using freedom left by the design constraints. `max_step` +/// bounds the full variable displacement before constraint correction; `valid` can reject +/// a corrected candidate (for example, an arc crossing its own start). Only feasible, +/// cursor-improving candidates are committed. False leaves the sketch unchanged when the +/// input is unsolved, invalid or outside the dense-work limit. Work is bounded; true may +/// retain the best feasible pose when the iteration or optional shared frame-work budget is +/// exhausted. The work budget includes Jacobian, null-space and LM arithmetic, not wall time. +pub fn move_point_towards( + sk: &mut Sketch, + point: usize, + target: Vec2, + max_step: f64, + mut budget: Option<&mut Budget>, + valid: impl Fn(&Sketch, &Sketch) -> bool, +) -> bool { + let setup_work = sk.points.len().saturating_add(sk.curves.len()).saturating_add(sk.constraints.len()).max(1); + if !within_budget(&mut budget, setup_work) { + return false; + } + if !crate::model::in_range(target) || !max_step.is_finite() || max_step <= 0.0 || !in_range(sk) { + return false; + } + let problem = sk.clone(); + let lay = layout(&problem, &Hold::default()); + let Some(px) = lay.pvar.get(point).copied().flatten() else { return false }; + let (blocks, _) = build_blocks(&problem, &lay, &points_on_curves(&problem)); + let mut parent: Vec = (0..lay.n).collect(); + union(&mut parent, px, px + 1); + for (_, vars) in &blocks { + if let Some(&first) = vars.first() { + for &v in vars.iter().skip(1) { + union(&mut parent, first, v); + } + } + } + let root = find(&mut parent, px); + let vars: Vec = (0..lay.n).filter(|v| find(&mut parent, *v) == root).collect(); + if vars.len() > MAX_VARIABLES { + return false; + } + let sub: Vec<_> = + blocks.iter().filter(|(_, v)| v.iter().any(|i| vars.binary_search(i).is_ok())).map(|(b, v)| (super::copy_block(b), v.clone())).collect(); + // Reserve both initial and final all-block validation before starting cursor work. + // An exhausted search can then keep its best feasible pose, including unrelated blocks. + if !within_budget(&mut budget, residual_work(&lay, &blocks).saturating_mul(2)) { + return false; + } + let mut x = initial_x(&problem, &lay); + let initial_residual = max_abs(&system(&problem, &lay, &blocks, &mut x, false).0); + if initial_residual >= ACCEPT { + return false; + } + let mut col = vec![usize::MAX; lay.n]; + columns(&mut col, &vars, &vars); + let (Some(ix), Some(iy)) = (vars.iter().position(|v| *v == px), vars.iter().position(|v| *v == px + 1)) else { return false }; + let mut best = problem.clone(); + let mut spent = 0; + // 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. + 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) { + return false; + } + apply(&mut best, &lay, &x); + if !in_range(&best) || !valid(&problem, &best) { + return false; + } + } + let mut gain = 1.0_f64; + for _ in 0..MAX_STEPS { + let at = State { sk: &problem, lay: &lay, x: &x }.p(point); + let error = target - at; + if error.len() < 1e-7 || spent >= TOTAL_CORRECTION_ITERS { + break; + } + let n = vars.len(); + let jacobian_work = residual_work(&lay, &sub).saturating_mul(n.saturating_mul(2).saturating_add(1)); + if !within_budget(&mut budget, jacobian_work) { + break; + } + let (_, j, _) = local_system(&problem, &lay, &sub, &mut x, &col, n); + let null_work = n.saturating_mul(n).saturating_mul(j.rows.saturating_add(n)); + if !within_budget(&mut budget, null_work) { + break; + } + let z = null_space(j); + if z.is_empty() { + break; + } + let mut direction = target_step(&z, ix, iy, error); + let norm = length(&direction); + // Adapt to curvature of the reachable locus. Inside a circle the Gauss-Newton + // cursor step can be arbitrarily small although useful freedom remains. + let scale = if norm > 0.0 { gain.min(max_step / norm) } else { gain }; + for v in &mut direction { + *v *= scale; + } + let mut directions = vec![(direction, false)]; + // A cursor across a circular locus has (nearly) zero first derivative at the + // farthest point. If line search stalls, probe both tangent directions. Testing + // only an exactly zero gradient would strand reversed drags after rounding. + let influence = |v: &&Vec| v.get(ix).copied().unwrap_or(0.0).hypot(v.get(iy).copied().unwrap_or(0.0)); + let mut probes: Vec<_> = z.iter().collect(); + probes.sort_by(|a, b| influence(b).total_cmp(&influence(a))); + for v in probes.into_iter().take(2) { + directions.push((v.iter().map(|x| x * max_step).collect(), true)); + directions.push((v.iter().map(|x| -x * max_step).collect(), true)); + } + let old_cost = error.dot(error); + let mut accepted = None; + 'search: for (direction, probe) in directions { + if length(&direction) < 1e-12 { + continue; + } + for backtrack in 0..if probe { 1 } else { 8 } { + if spent >= TOTAL_CORRECTION_ITERS { + break 'search; + } + let alpha = 0.5_f64.powi(backtrack); + let mut trial = x.clone(); + for (&v, d) in vars.iter().zip(&direction) { + if let Some(t) = trial.get_mut(v) { + *t += alpha * d; + } + } + let Some((its, residual)) = lm_capped_with_budget( + &problem, + &lay, + &sub, + &vars, + &mut trial, + &col, + CORRECTION_ITERS.min(TOTAL_CORRECTION_ITERS - spent), + budget.as_deref_mut(), + ) else { + break 'search; + }; + spent += its.max(1); + if !(residual < TOL) { + if budget.as_ref().is_some_and(|b| b.exhausted()) { + break 'search; + } + continue; + } + let next = State { sk: &problem, lay: &lay, x: &trial }.p(point); + let cost = (target - next).dot(target - next); + if !cost.is_finite() || cost >= old_cost - 1e-14 * old_cost.max(1.0) { + continue; + } + if !within_budget(&mut budget, setup_work.saturating_mul(4)) { + break 'search; + } + let mut candidate = best.clone(); + apply(&mut candidate, &lay, &trial); + if !in_range(&candidate) || !valid(&best, &candidate) { + continue; + } + accepted = Some((trial, candidate, ((if probe { 1.0 } else { scale }) * alpha * 1.5).clamp(1e-8, 1e8))); + break 'search; + } + } + let Some((next, candidate, next_gain)) = accepted else { break }; + x = next; + best = candidate; + gain = next_gain; + } + // Full constraint validation includes constant blocks and disconnected components. + if max_abs(&system(&best, &lay, &blocks, &mut x, false).0) >= ACCEPT { + return false; + } + super::refresh_driven_dimensions(&mut best); + *sk = best; + true +} + +fn length(v: &[f64]) -> f64 { + v.iter().map(|x| x * x).sum::().sqrt() +} + +fn in_range(sk: &Sketch) -> bool { + sk.points.iter().all(|p| crate::model::in_range(p.pos)) + && sk + .curves + .iter() + .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> { + for row in 0..j.rows { + let scale = (0..j.cols).map(|c| j.get(row, c).abs()).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); + } + } + } + let pivots = rref(&mut j, 1e-9); + let mut z: Vec> = Vec::new(); + for free in (0..j.cols).filter(|c| !pivots.contains(c)) { + let mut v = vec![0.0; j.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); + } + } + for _ in 0..2 { + for q in &z { + let d: f64 = v.iter().zip(q).map(|(a, b)| a * b).sum(); + for (a, b) in v.iter_mut().zip(q) { + *a -= d * b; + } + } + } + let norm = length(&v); + if norm.is_finite() && norm > 1e-10 { + for x in &mut v { + *x /= norm; + } + z.push(v); + } + } + z +} + +fn target_step(z: &[Vec], ix: usize, iy: usize, error: Vec2) -> Vec { + let mut a = 0.0; + let mut b = 0.0; + let mut c = 0.0; + for q in z { + let x = q.get(ix).copied().unwrap_or(0.0); + let y = q.get(iy).copied().unwrap_or(0.0); + a += x * x; + b += x * y; + c += y * y; + } + let high = 0.5 * (a + c + (a - c).hypot(2.0 * b)); + let low = if high > 0.0 { (a * c - b * b).max(0.0) / high } else { 0.0 }; + let axis = if a >= c { Vec2::new(high - c, b) } else { Vec2::new(b, high - a) }.normalized().unwrap_or(if a >= c { Vec2::X } else { Vec2::Y }); + let other = Vec2::new(-axis.y, axis.x); + let mut u = if high > 1e-12 { axis * (axis.dot(error) / high) } else { Vec2::ZERO }; + if low > high * 1e-8 { + u += other * (other.dot(error) / low); + } + let mut step = vec![0.0; z.first().map_or(0, Vec::len)]; + for q in z { + let d = q.get(ix).copied().unwrap_or(0.0) * u.x + q.get(iy).copied().unwrap_or(0.0) * u.y; + for (x, v) in step.iter_mut().zip(q) { + *x += d * v; + } + } + step +} + +fn apply(sk: &mut Sketch, lay: &Layout, x: &[f64]) { + for (i, p) in sk.points.iter_mut().enumerate() { + if let Some(v) = lay.pvar.get(i).copied().flatten() + && let (Some(a), Some(b)) = (x.get(v), x.get(v + 1)) + { + p.pos = Vec2::new(*a, *b); + } + } + for (i, c) in sk.curves.iter_mut().enumerate() { + if let Some(v) = lay.rvar.get(i).copied().flatten() + && let Some(value) = x.get(v) + && let CurveKind::Circle { r, .. } | CurveKind::Ellipse { r, .. } = &mut c.kind + { + *r = *value; + } + } +} diff --git a/crates/sketch/src/decompose.rs b/crates/sketch/src/decompose.rs index a91bb921c..58afd2272 100644 --- a/crates/sketch/src/decompose.rs +++ b/crates/sketch/src/decompose.rs @@ -75,9 +75,9 @@ pub(crate) const MAX_WORK: usize = 20_000_000; /// frame (see [`Budget::exhausted`]). pub(crate) const FRAME_WORK: usize = 1_000_000; -/// Work the seed's cluster decomposition may do, shared by the solves it is passed to (the held -/// solves of one drag frame): each decomposition is bounded by what is left, and charges what it -/// did. +/// Work shared by the held solves and feasible cursor correction of one drag frame. Cluster +/// decomposition charges membership scans; cursor correction reserves estimates of dense +/// arithmetic before starting it. These deterministic units approximate time, not a deadline. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Budget { left: usize, @@ -86,7 +86,7 @@ pub struct Budget { } impl Budget { - /// A budget of `work` units (a unit is one membership scan of the merge search). + /// A budget of `work` units: membership scans or estimated dense arithmetic operations. pub fn new(work: usize) -> Budget { Budget { left: work, spent: 0, cut: false } } @@ -98,8 +98,7 @@ impl Budget { pub fn frame() -> Budget { Budget::new(FRAME_WORK) } - /// Some decomposition stopped because the budget ran out: what it would have placed was - /// left to LM, from where it was. + /// Some decomposition or cursor work stopped because the budget ran out. pub fn exhausted(&self) -> bool { self.cut } @@ -110,6 +109,17 @@ impl Budget { pub(crate) fn left(&self) -> usize { self.left } + /// Reserve estimated dense arithmetic before starting it. Unlike a decomposition scan, + /// a dense operation can be large, so it must not overshoot the remaining work. + pub(crate) fn try_charge(&mut self, work: usize) -> bool { + if work > self.left { + self.cut = true; + return false; + } + self.charge(work, false); + true + } + /// Charge a decomposition's `work`; `cut` when it stopped at the budget. pub(crate) fn charge(&mut self, work: usize, cut: bool) { self.left = self.left.saturating_sub(work); diff --git a/crates/sketch/src/lib.rs b/crates/sketch/src/lib.rs index aa941345d..60ba5da57 100644 --- a/crates/sketch/src/lib.rs +++ b/crates/sketch/src/lib.rs @@ -62,8 +62,8 @@ pub use profiles::{ }; pub use shape::{Shape, intersections}; pub use solver::{ - Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, solve, - solve_after_edit, solve_after_value_edit, solve_holding, solve_with, + Analysis, CONSISTENT, DrivingValues, Hold, SolveReport, SolveStatus, constraint_residual, determined_by, measure_dimension, move_point_towards, + solve, solve_after_edit, solve_after_value_edit, solve_holding, solve_with, }; pub use text::{MAX_TEXT_CHARS, TextAlign, TextStyle, text_geometry, text_geometry_in, text_geometry_styled}; pub use thin::{MAX_THIN_SEGMENTS, thin_wall_regions}; diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index bd8974955..3c1dfa825 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -21,6 +21,10 @@ use crate::linalg::{Mat, determined_vars, solve as lin_solve}; use crate::model::{ConstraintKind, CurveKind, Sketch}; use crate::union_find::{find, union}; +#[path = "cursor.rs"] +mod cursor; +pub use cursor::move_point_towards; + #[path = "redundancy.rs"] mod redundancy; pub use redundancy::{CONSISTENT, constraint_residual, determined_by}; @@ -945,6 +949,26 @@ fn lm_capped( col: &[usize], max_iters: usize, ) -> (usize, f64) { + // Without a work budget the initial residual is always evaluated. + lm_capped_with_budget(sk, lay, blocks, vars, x, col, max_iters, None).unwrap_or((0, f64::INFINITY)) +} + +/// Deterministic work units, shared with the frame's decomposition budget. Estimates bound +/// dense arithmetic; they are not a wall-clock deadline. None means no residual was evaluated. +fn lm_capped_with_budget( + sk: &Sketch, + lay: &Layout, + blocks: &[(Block, Vec)], + vars: &[usize], + x: &mut Vec, + col: &[usize], + max_iters: usize, + mut budget: Option<&mut Budget>, +) -> Option<(usize, f64)> { + let evaluation_work = if budget.is_some() { residual_work(lay, blocks) } else { 0 }; + if !within_budget(&mut budget, evaluation_work) { + return None; + } let n = vars.len(); #[cfg(test)] lm_vars::add(n); @@ -953,7 +977,12 @@ fn lm_capped( let mut f = norm2(&r); for it in 0..max_iters { if max_abs(&r) < TOL { - return (it, max_abs(&r)); + return Some((it, max_abs(&r))); + } + let normal_work = + n.saturating_mul(n).saturating_mul(r.len()).saturating_add(evaluation_work.saturating_mul(n.saturating_mul(2).saturating_add(1))); + if !within_budget(&mut budget, normal_work) { + return Some((it, max_abs(&r))); } let (_, j, _) = local_system(sk, lay, blocks, x, col, n); // Normal equations of this component. @@ -979,7 +1008,11 @@ fn lm_capped( // the point sliding along it.) A point held on a curve is cheaper still, so it slides // rather than the curve's ends moving. let weight: Vec = vars.iter().map(|&v| if lay.slide.get(v).copied().unwrap_or(false) { SLIDE_WEIGHT } else { 1.0 }).collect(); - for _ in 0..30 { + for _attempt in 0..30 { + let linear_work = n.saturating_mul(n).saturating_mul(n).saturating_add(evaluation_work); + if !within_budget(&mut budget, linear_work) { + return Some((it, max_abs(&r))); + } let mut m = a.clone(); for (i, w) in weight.iter().enumerate() { m.add(i, i, lambda * w + 1e-12); @@ -1011,10 +1044,18 @@ fn lm_capped( } } if !improved { - return (it, max_abs(&r)); + return Some((it, max_abs(&r))); } } - (max_iters, max_abs(&r)) + Some((max_iters, max_abs(&r))) +} + +fn within_budget(budget: &mut Option<&mut Budget>, work: usize) -> bool { + budget.as_deref_mut().is_none_or(|b| b.try_charge(work)) +} + +fn residual_work(lay: &Layout, blocks: &[(Block, Vec)]) -> usize { + blocks.iter().fold(lay.n.max(1), |work, (_, vars)| work.saturating_add(vars.len().max(1))) } /// The variables LM was given and its runs on this thread, for tests that count what the @@ -2222,17 +2263,7 @@ fn solve_inner( Some(v) => vdet(Some(v)) && vdet(Some(v + 1)), None => true, }; - // Driven dimensions measure the solved geometry. - let fixed_lay = Layout { pvar: vec![None; sk.points.len()], rvar: vec![None; sk.curves.len()], n: 0, points: 0, slide: Vec::new() }; - let measured: Vec> = - sk.constraints.iter().map(|c| if c.driven { measure(&State { sk, lay: &fixed_lay, x: &[] }, &c.kind) } else { None }).collect(); - for (c, m) in sk.constraints.iter_mut().zip(measured) { - if let Some(v) = m - && v.is_finite() - { - c.kind.set_value(v); - } - } + refresh_driven_dimensions(sk); let (dof, point_determined, curve_determined) = match analysis { Analysis::Full => ( lay.n.saturating_sub(rank), @@ -2255,6 +2286,21 @@ fn solve_inner( } } +/// Geometry can also be finalized by feasible cursor motion, without another solve. +/// Both paths must measure reference dimensions from the pose they publish. +fn refresh_driven_dimensions(sk: &mut Sketch) { + let fixed_lay = Layout { pvar: vec![None; sk.points.len()], rvar: vec![None; sk.curves.len()], n: 0, points: 0, slide: Vec::new() }; + let measured: Vec> = + sk.constraints.iter().map(|c| if c.driven { measure(&State { sk, lay: &fixed_lay, x: &[] }, &c.kind) } else { None }).collect(); + for (c, m) in sk.constraints.iter_mut().zip(measured) { + if let Some(v) = m + && v.is_finite() + { + c.kind.set_value(v); + } + } +} + #[cfg(test)] mod continuation_unit_tests { use super::*; diff --git a/crates/sketch/tests/cursor_target.rs b/crates/sketch/tests/cursor_target.rs new file mode 100644 index 000000000..ae2fc8b44 --- /dev/null +++ b/crates/sketch/tests/cursor_target.rs @@ -0,0 +1,160 @@ +//! Analytic cursor oracle plus feasibility checks on every accepted continuation step. +use solidcraft_geom::Vec2; +use solidcraft_sketch::{ConstraintKind, Sketch, move_point_towards, solve}; + +fn linkage() -> (Sketch, usize, usize) { + let mut sk = Sketch::new(); + let a = sk.add_point(Vec2::new(-10.0, 0.0), None).unwrap(); + let x = -10.0 + (1600.0 - 400.0 + 52.0 * 52.0) / 104.0; + let c = sk.add_point(Vec2::new(x, -(1600.0_f64 - (x + 10.0).powi(2)).sqrt()), None).unwrap(); + let b = sk.add_point(Vec2::new(42.0, 0.0), None).unwrap(); + sk.points[b].fixed = true; + for (p, q, value) in [(0, a, 10.0), (a, c, 40.0), (c, b, 20.0)] { + sk.add_constraint(ConstraintKind::Distance { p, q, value }, None).unwrap(); + } + assert!(solve(&mut sk).ok()); + (sk, a, c) +} + +#[test] +fn circle_oracle_all_directions_and_large_targets() { + for radius in [1.0, 12.8, 28.3, 100.0, 1000.0] { + for i in 0..24 { + let (mut sk, a, c) = linkage(); + let angle = std::f64::consts::TAU * i as f64 / 24.0; + let target = Vec2::new(angle.cos(), angle.sin()) * radius; + let nearest = target * (10.0 / radius); + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |before, after| { + assert!(after.points[a].pos.dist(target) < before.points[a].pos.dist(target)); + assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9); + assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9); + (Vec2::new(42.0, 0.0) - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0 + })); + assert!(sk.points[a].pos.dist(nearest) < 1e-4, "radius {radius}, angle {angle}, actual {:?}, nearest {nearest:?}", sk.points[a].pos); + } + } +} + +#[test] +fn fixed_axis_and_rejected_candidates_keep_design_constraints() { + let mut sk = Sketch::new(); + let a = sk.add_point(Vec2::new(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(0, a, None).unwrap(); + sk.add_constraint(ConstraintKind::Horizontal { l }, None).unwrap(); + assert!(move_point_towards(&mut sk, a, Vec2::new(20.0, 10.0), 2.0, None, |_, _| true)); + assert!(sk.points[a].pos.dist(Vec2::new(20.0, 0.0)) < 1e-5, "{:?}", sk.points[a].pos); + let before = sk.clone(); + assert!(move_point_towards(&mut sk, a, Vec2::new(-20.0, 10.0), 2.0, None, |_, _| false)); + assert_eq!(sk, before); + assert!(!move_point_towards(&mut sk, usize::MAX, Vec2::ZERO, 1.0, None, |_, _| true)); + assert!(!move_point_towards(&mut sk, a, Vec2::new(f64::NAN, 0.0), 1.0, None, |_, _| true)); + assert_eq!(sk, before); + sk.points[a].pos.x = f64::NAN; + assert!(!move_point_towards(&mut sk, a, Vec2::ZERO, 1.0, None, |_, _| true)); + assert!(sk.points[a].pos.x.is_nan()); +} + +#[test] +fn reversing_across_a_nearly_stationary_extremum_keeps_following() { + let (mut sk, a, _) = linkage(); + for target in [Vec2::new(-10.0, 16.0), Vec2::new(-10.0, -16.0), Vec2::new(0.0, 25.0), Vec2::new(0.0, -25.0)] { + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(target * (10.0 / target.len())) < 1e-4, "target {target:?}, actual {:?}", sk.points[a].pos); + } +} + +#[test] +fn accepted_constraint_roundoff_is_refined_before_following_the_cursor() { + let (mut sk, a, _) = linkage(); + sk.points[a].pos.x -= 1e-8; + let target = Vec2::new(-10.0, 8.0); + assert!(move_point_towards(&mut sk, a, target, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(target * (10.0 / target.len())) < 1e-4); + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); +} + +#[test] +fn a_cursor_at_the_pivot_does_not_choose_a_pose_from_roundoff() { + let (mut sk, a, _) = linkage(); + let before = sk.clone(); + assert!(move_point_towards(&mut sk, a, Vec2::ZERO, 1.25, None, |_, _| true)); + assert!(sk.points[a].pos.dist(before.points[a].pos) < 1e-5, "{:?}", sk.points[a].pos); +} + +#[test] +fn cursor_motion_refreshes_driven_dimensions_without_a_followup_solve() { + let (mut sk, a, _) = linkage(); + sk.add_constraint(ConstraintKind::DistanceX { p: 0, q: a, value: 10.0 }, None).unwrap(); + sk.constraints.last_mut().unwrap().driven = true; + assert!(move_point_towards(&mut sk, a, Vec2::new(-10.0, 8.0), 1.25, None, |_, _| true)); + let value = sk.constraints.last().unwrap().kind.value().unwrap(); + assert!((value - sk.points[a].pos.x.abs()).abs() < 1e-6, "reference {value} does not measure {:?}", sk.points[a].pos); +} + +#[test] +fn the_other_moving_joint_reaches_its_rocker_arc_and_motion_limits() { + let base = Vec2::new(42.0, 0.0); + let lo = -(-1264.0_f64 / 1680.0).acos(); // |OC| >= 40 - 10 + let hi = -(0.2_f64).acos(); // |OC| <= 40 + 10 + for angle in [-2.6_f64, -2.1, -1.5, -1.1] { + let (mut sk, a, c) = linkage(); + let target = base + Vec2::new(angle.cos(), angle.sin()) * 60.0; + let nearest = base + Vec2::new(angle.clamp(lo, hi).cos(), angle.clamp(lo, hi).sin()) * 20.0; + assert!(move_point_towards(&mut sk, c, target, 1.25, None, |_, after| { + (base - after.points[a].pos).cross(after.points[c].pos - after.points[a].pos) < 0.0 + })); + assert!(sk.points[c].pos.dist(nearest) < 1e-4, "angle {angle}, actual {:?}, nearest {nearest:?}", sk.points[c].pos); + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((sk.points[a].pos.dist(sk.points[c].pos) - 40.0).abs() < 1e-9); + assert!((sk.points[c].pos.dist(base) - 20.0).abs() < 1e-9); + } +} + +#[test] +fn zero_cursor_budget_does_not_start_optimization() { + let (mut sk, a, _) = linkage(); + let before = sk.clone(); + let mut budget = solidcraft_sketch::Budget::new(0); + assert!(!move_point_towards(&mut sk, a, Vec2::new(-10.0, 16.0), 1.25, Some(&mut budget), |_, _| { + panic!("an exhausted budget must not evaluate candidates") + })); + assert_eq!(sk, before); + assert_eq!(budget.spent(), 0); + assert!(budget.exhausted()); +} + +#[test] +fn a_cursor_budget_stop_keeps_the_best_corrected_pose_and_reference_dimensions() { + let target = Vec2::new(-10.0, 16.0); + let nearest = target * (10.0 / target.len()); + let mut stopped_after_progress = false; + for work in [128, 256, 512, 1024, 2048, 4096, 8192, 16384] { + let (mut sk, a, c) = linkage(); + sk.add_constraint(ConstraintKind::DistanceX { p: 0, q: a, value: 10.0 }, None).unwrap(); + sk.constraints.last_mut().unwrap().driven = true; + let before = sk.clone(); + let mut budget = solidcraft_sketch::Budget::new(work); + // The validation callback is Fn: Cell records whether a corrected step was accepted. + let calls = std::cell::Cell::new(0); + let moved = move_point_towards(&mut sk, a, target, 1.25, Some(&mut budget), |_, after| { + calls.set(calls.get() + 1); + assert!((after.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((after.points[a].pos.dist(after.points[c].pos) - 40.0).abs() < 1e-9); + assert!((after.points[c].pos.dist(Vec2::new(42.0, 0.0)) - 20.0).abs() < 1e-9); + true + }); + assert!(budget.spent() <= work, "{budget:?}"); + if !moved { + assert_eq!(sk, before); + continue; + } + assert!((sk.points[a].pos.len() - 10.0).abs() < 1e-9); + assert!((sk.constraints.last().unwrap().kind.value().unwrap() - sk.points[a].pos.x.abs()).abs() < 1e-6); + if calls.get() > 0 && budget.exhausted() && sk.points[a].pos.dist(nearest) > 1e-4 { + assert!(sk.points[a].pos.dist(target) < before.points[a].pos.dist(target)); + stopped_after_progress = true; + } + } + assert!(stopped_after_progress, "exercise exhaustion after a feasible cursor improvement"); +}