diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index a0caae9b5..9afcc606e 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -3118,6 +3118,9 @@ mod ux_tests; #[path = "sketch_axis_ref_tests.rs"] mod axis_ref_tests; #[cfg(test)] +#[path = "sketch_centre_align_tests.rs"] +mod centre_align_tests; +#[cfg(test)] #[path = "sketch_circle_edge_tests.rs"] mod circle_edge_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/sketch_centre_align_tests.rs b/crates/engine/src/cmd/sketch_centre_align_tests.rs new file mode 100644 index 000000000..c9a1e53f5 --- /dev/null +++ b/crates/engine/src/cmd/sketch_centre_align_tests.rs @@ -0,0 +1,60 @@ +//! #617: a circle inside a square — manual Horizontal/Vertical between the circle's centre and +//! a square edge, and a distance dimension from an edge to the centre. Both must apply: the +//! engine already accepts centre refs (`c1.center`) and midpoint refs, so these pin the +//! acceptance criteria the reporter's manual tool path needed. + +use serde_json::{Value, json}; +use solidcraft_geom::Vec2; + +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 point(s: &Session, id: &str) -> Vec2 { + let sk = s.model.state().sketch(s.active_sketch.unwrap()).unwrap().sketch.clone(); + sk.resolve_point(id).and_then(|p| sk.point(p)).unwrap() +} + +/// A fixed 100x100 square (`l1` bottom, `l2` right edge) with a radius-10 circle `c1` at (40, 60). +fn square_with_circle() -> Session { + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 100]})); + run(&mut s, "sketch.constraint.fix", json!({"entities": ["l1", "l2", "l3", "l4"]})); + run(&mut s, "sketch.circle.center", json!({"center": [40, 60], "radius": 10, "id": "c1"})); + s +} + +#[test] +fn manual_vertical_constraint_aligns_circle_centre_with_a_square_edge() { + let mut s = square_with_circle(); + // `l2` is the square's right edge (x = 100). Align the centre vertically with it. + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", {"midpoint": "l2"}], "mode": "vertical"})); + assert!((point(&s, "c1.center").x - 100.0).abs() < 1e-6, "centre x: {:?}", point(&s, "c1.center")); + // The alignment persists through undo/redo and reopening. + run(&mut s, "edit.undo", json!({})); + assert!((point(&s, "c1.center").x - 40.0).abs() < 1e-6, "undo restores the centre"); + run(&mut s, "edit.redo", json!({})); + assert!((point(&s, "c1.center").x - 100.0).abs() < 1e-6, "redo re-applies the alignment"); +} + +#[test] +fn manual_horizontal_constraint_aligns_circle_centre_with_a_square_edge() { + let mut s = square_with_circle(); + // `l1` is the square's bottom edge (y = 0): align the centre horizontally with its midpoint. + run(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", {"midpoint": "l1"}], "mode": "horizontal"})); + assert!((point(&s, "c1.center").y - 0.0).abs() < 1e-6, "centre y: {:?}", point(&s, "c1.center")); +} + +#[test] +fn a_dimension_from_an_edge_to_the_centre_measures_the_gap() { + let mut s = square_with_circle(); + let d = run(&mut s, "sketch.dimension", json!({"entities": ["l2", "c1.center"]})); + // The centre sits 60 from the right edge (x = 100). + assert!((d["measured"].as_f64().unwrap() - 60.0).abs() < 1e-6, "{d}"); +} diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 32e78fab3..ebadcb1aa 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1037,6 +1037,17 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { c.push(cmd(app, "sketch.constraint.coincident", "Coincident").with(json!({ "a": picked[0], "b": picked[1] }))); if l == 1 { c.push(cmd(app, "sketch.constraint.midpoint", "MidPoint").with(json!({ "point": points[0], "line": lines[0] }))); + // #617: the point can also be aligned with the line (a circle's centre with a square's edge). + if let Some(align) = crate::tools::point_line_points(&ss.sketch, &json!(points[0]), &lines[0]) { + c.push( + act("ui.horizontalConstraint", "Horizontal Constraint", "c_hv") + .with(json!({"points": align, "mode": "horizontal", "if_redundant": "refuse"})), + ); + c.push( + act("ui.verticalConstraint", "Vertical Constraint", "c_hv") + .with(json!({"points": align, "mode": "vertical", "if_redundant": "refuse"})), + ); + } } } if l == 2 && n == 2 { diff --git a/crates/ui-egui/src/sketch_centre_align_ui_tests.rs b/crates/ui-egui/src/sketch_centre_align_ui_tests.rs new file mode 100644 index 000000000..7ec95215f --- /dev/null +++ b/crates/ui-egui/src/sketch_centre_align_ui_tests.rs @@ -0,0 +1,73 @@ +//! #617: manual Horizontal/Vertical involving a circle's centre and a square's edge. Selecting +//! the centre and the edge (or picking both with the tool, or the context menu) must align the +//! centre with the edge; only the auto-constrain inference used to do it, while the manual path +//! silently did nothing. + +use serde_json::json; +use solidcraft_engine::Sel::{SketchCurve, SketchPoint}; +use solidcraft_engine::geom::Vec2; + +use crate::context_menu::{self, Target}; +use crate::scenario::Harness; + +/// A fixed 100x100 square (`l1` bottom, `l2` right edge) with a radius-10 circle `c1` at (40, 60). +fn square_with_circle() -> Harness { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 100]})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entities": ["l1", "l2", "l3", "l4"]})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [40, 60], "radius": 10, "id": "c1"})).unwrap(); + h.app.cam.distance = 320.0; + h.settle(); + h +} + +fn point(h: &Harness, id: &str) -> Vec2 { + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + sk.point(sk.resolve_point(id).unwrap()).unwrap() +} + +#[test] +fn selecting_the_centre_and_an_edge_preselects_the_alignment() { + let h = square_with_circle(); + let state = h.app.session.world_state(); + let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch; + let edge = || SketchCurve { id: "l2".into(), sketch: None }; + let centre = || SketchPoint { id: "c1.center".into() }; + for sel in [vec![centre(), edge()], vec![edge(), centre()]] { + let params = crate::tools::constraint_preselection("sketch.constraint.horizontal_vertical", &sel, Some(sk)).unwrap(); + // The right edge is vertical: the alignment shares x with the line's midpoint. + assert_eq!(params["mode"], "vertical", "{sel:?}"); + assert_eq!(params["points"][0], "c1.center", "{sel:?}"); + assert_eq!(params["points"][1]["midpoint"], "l2", "{sel:?}"); + } + // The bottom edge is horizontal: the mode follows the line's own axis. + let sel = vec![centre(), SketchCurve { id: "l1".into(), sketch: None }]; + let params = crate::tools::constraint_preselection("sketch.constraint.horizontal_vertical", &sel, Some(sk)).unwrap(); + assert_eq!(params["mode"], "horizontal"); + // A circle (not a line) beside the centre is not an alignment. + let sel = vec![centre(), SketchCurve { id: "c1".into(), sketch: None }]; + assert!(crate::tools::constraint_preselection("sketch.constraint.horizontal_vertical", &sel, Some(sk)).is_none()); +} + +#[test] +fn the_hv_tool_aligns_a_picked_centre_with_a_picked_edge() { + let mut h = square_with_circle(); + h.app.start("sketch.constraint.horizontal_vertical"); + // The circle's centre, then the square's right edge. + for xy in [[40, 60], [100, 50]] { + let at = h.call("ui.at", json!({"sketch": xy}))["result"].clone(); + h.step(&json!({"click": at})).unwrap(); + } + assert!((point(&h, "c1.center").x - 100.0).abs() < 1e-6, "centre: {:?}", point(&h, "c1.center")); +} + +#[test] +fn the_context_menu_aligns_the_centre_with_the_edge() { + let mut h = square_with_circle(); + h.app.session.selection = vec![SketchPoint { id: "c1.center".into() }, SketchCurve { id: "l2".into(), sketch: None }]; + let items = context_menu::items(&h.app, &Target::Viewport); + let item = items.iter().find(|i| i.label == "Vertical Constraint").expect("the menu offers Vertical Constraint"); + context_menu::run_item(&mut h.app, item, egui::Pos2::ZERO); + assert!((point(&h, "c1.center").x - 100.0).abs() < 1e-6, "centre: {:?}", point(&h, "c1.center")); +} diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 0673ec1d3..11d1bd58d 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -56,6 +56,10 @@ mod neutral_click_tests; #[path = "symmetry_pick_tests.rs"] mod symmetry_pick_tests; +#[cfg(test)] +#[path = "sketch_centre_align_ui_tests.rs"] +mod centre_align_ui_tests; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { /// Click points; `n` points complete the shape (0 = chain until finished). @@ -150,7 +154,9 @@ pub fn hint(id: &str) -> String { "sketch.dimension" => { "Dimension: pick one or two entities and type the value (or click to place it first); click a dimension to edit it; Enter applies".into() } - "sketch.constraint.horizontal_vertical" => "Horizontal/Vertical: pick a line or two points; hold Shift to pick a line midpoint".into(), + "sketch.constraint.horizontal_vertical" => { + "Horizontal/Vertical: pick a line, two points, or a point and a line; hold Shift to pick a line midpoint".into() + } "sketch.slot.center_to_center" | "sketch.slot.overall" => "Slot: click both ends, then the width".into(), "sketch.constraint.midpoint" => "MidPoint: pick a point and a line, or two lines to centre the second on the first".into(), _ if id.starts_with("sketch.constraint.") => "Constraint: pick the sketch entities".into(), @@ -252,11 +258,23 @@ pub fn on_click(app: &mut SolveApp, proj: &Proj, pos: Pos2, shift: bool) { } else { tool.point_picks.push(point); } - } else if !shift - && tool.point_picks.is_empty() - && let Some(Hit::SketchCurve { id, straight: true, .. }) = hit - { - let _ = app.run(tool.cmd, json!({"line": id})); + } else if !shift && let Some(Hit::SketchCurve { id, straight: true, .. }) = hit { + // A line picked on its own is made horizontal/vertical; a line picked after a + // point aligns that point with the line (a circle's centre with a square's + // edge, #617). + let first = tool.point_picks.first().cloned(); + let params = match first { + None => Some(json!({"line": id})), + Some(point) => { + let state = app.session.world_state(); + app.session.active_sketch.and_then(|sid| state.sketch(sid)).and_then(|ss| point_line_alignment(&ss.sketch, &point, id)) + } + }; + if let Some(params) = params + && app.run(tool.cmd, params).is_ok() + { + tool.point_picks.clear(); + } } } Kind::Pick(n) => { @@ -532,6 +550,28 @@ fn run_shape(app: &mut SolveApp, t: &Tool) -> Result, String> { Ok(result["curves"].as_array().into_iter().flatten().filter_map(|c| c.as_str().map(str::to_string)).collect()) } +/// #617: Aligning a point with a straight line (a circle's centre with a square's edge) aligns +/// the point with the line's midpoint, in the mode the line's dominant axis suggests. None when +/// the curve is not a line. +pub(crate) fn point_line_alignment(sk: &solidcraft_engine::sketch::Sketch, point: &Value, line: &str) -> Option { + let points = point_line_points(sk, point, line)?; + let mode = line_axis_mode(sk, line)?; + Some(json!({"points": points, "mode": mode})) +} + +/// The `points` pair aligning `point` with the midpoint of `line`; None when `line` is not a line. +pub(crate) fn point_line_points(sk: &solidcraft_engine::sketch::Sketch, point: &Value, line: &str) -> Option<[Value; 2]> { + let l = sk.curve_index(line)?; + matches!(sk.shape(l)?, solidcraft_engine::sketch::Shape::Line { .. }).then(|| [point.clone(), json!({"midpoint": line})]) +} + +/// The axis a straight line is closest to: the alignment mode when a point is aligned with it (#617). +fn line_axis_mode(sk: &solidcraft_engine::sketch::Sketch, line: &str) -> Option<&'static str> { + let solidcraft_engine::sketch::Shape::Line { a, b } = sk.shape(sk.curve_index(line)?)? else { return None }; + let d = b - a; + Some(if d.x.abs() >= d.y.abs() { "horizontal" } else { "vertical" }) +} + /// Only consume a complete, unambiguous selection; command validation owns geometry. pub(crate) fn constraint_preselection( command: &str, @@ -561,6 +601,14 @@ pub(crate) fn constraint_preselection( ("sketch.constraint.equal", _) if selection.len() >= 3 => selected_ids(true, 3).map(|ids| json!({"curves":ids})), ("sketch.constraint.curvature", [SketchCurve { id: a, .. }, SketchCurve { id: b, .. }]) if a != b => Some(json!({"a":a,"b":b})), ("sketch.constraint.horizontal_vertical", [SketchCurve { id, .. }]) => Some(json!({"line":id})), + // A point and a straight line (a circle's centre and a square's edge, #617): align the + // point with the line, in the mode the line's own axis suggests. + ("sketch.constraint.horizontal_vertical", [SketchPoint { id }, SketchCurve { id: line, .. }]) => { + point_line_alignment(sketch?, &json!(id), line) + } + ("sketch.constraint.horizontal_vertical", [SketchCurve { id: line, .. }, SketchPoint { id }]) => { + point_line_alignment(sketch?, &json!(id), line) + } ("sketch.constraint.horizontal_vertical", _) => crate::selection::alignment_points(selection).map(|points| json!({"points": points})), ("sketch.constraint.coincident", [a, b]) => { let entity = |s: &solidcraft_engine::Sel| match s {