From 4f4b1fc2d2ab2e46e9a87b52c31411120cc1ed99 Mon Sep 17 00:00:00 2001 From: cronos Date: Sat, 24 Oct 2026 16:15:45 +0000 Subject: [PATCH] Sketch: select edge midpoints for horizontal and vertical constraints (#5159) --- apps/solidcraft/src/space_mouse.rs | 15 +- assets/icons/ui/source/markers.rs | 4 +- assets/locales/en.json | 2 + assets/locales/ja.json | 2 + assets/locales/zh.json | 2 + crates/engine/src/cmd/delete.rs | 1 + crates/engine/src/lib.rs | 4 + crates/ui-egui/src/browser.rs | 14 +- crates/ui-egui/src/context_menu.rs | 34 +- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/select_other.rs | 9 +- crates/ui-egui/src/select_other_tests.rs | 28 +- crates/ui-egui/src/selection.rs | 22 + crates/ui-egui/src/sketch_tools.rs | 2 +- crates/ui-egui/src/tools.rs | 4 +- crates/ui-egui/src/viewport.rs | 108 ++++- .../ui-egui/tests/constraint_preselection.rs | 11 +- crates/ui-egui/tests/point_alignment.rs | 427 +++++++++++++++++- .../tests/point_constraint_preselection.rs | 15 +- 19 files changed, 661 insertions(+), 45 deletions(-) diff --git a/apps/solidcraft/src/space_mouse.rs b/apps/solidcraft/src/space_mouse.rs index 7b8514abf..a4c3f9d45 100644 --- a/apps/solidcraft/src/space_mouse.rs +++ b/apps/solidcraft/src/space_mouse.rs @@ -241,6 +241,7 @@ struct Reading { device: Option, /// A source that is connected but has not yet shown a device behind it (spacenavd's socket answers /// with no mouse plugged in; its protocol has no enumeration, so the first record is the evidence). + #[cfg(target_os = "linux")] awaiting: Option, axes: Axes, /// When each of X, Y, Z, Rx, Ry and Rz last arrived. Each ages on its own: a device may send @@ -287,6 +288,7 @@ impl Reading { } /// A record arrived from the source being waited on: there is a device. + #[cfg(target_os = "linux")] fn heard(&mut self) { if self.device.is_none() { self.device = self.awaiting.take(); @@ -296,6 +298,7 @@ impl Reading { fn new(now: Instant) -> Self { Self { device: None, + #[cfg(target_os = "linux")] awaiting: None, axes: Axes::default(), at: [now; 6], @@ -460,12 +463,20 @@ fn connected(ctx: &Context, shared: &Mutex, source: Source) { let now = Instant::now(); let stale = now.checked_sub(STALE_AFTER).unwrap_or(now); // A daemon is not yet a device: it counts once a record comes from it. - let (device, awaiting) = if needs_evidence(source) { (None, Some(source)) } else { (Some(source), None) }; + let waiting = needs_evidence(source); // A HID device reports the state of its buttons, so the first state seen is a baseline; the daemon // and the driver send presses and releases, which start from nothing down. let buttons_known = !matches!(source, Source::Hid(_)); let generation = CONNECTIONS.fetch_add(1, Ordering::Relaxed).wrapping_add(1); - *reading = Reading { device, awaiting, at: [stale; 6], buttons_known, generation, ..Reading::new(now) }; + *reading = Reading { + device: (!waiting).then_some(source), + #[cfg(target_os = "linux")] + awaiting: waiting.then_some(source), + at: [stale; 6], + buttons_known, + generation, + ..Reading::new(now) + }; } ctx.request_repaint(); } diff --git a/assets/icons/ui/source/markers.rs b/assets/icons/ui/source/markers.rs index 42c97ae85..c49869c76 100644 --- a/assets/icons/ui/source/markers.rs +++ b/assets/icons/ui/source/markers.rs @@ -108,8 +108,8 @@ pub(crate) fn glyph_icon(name: &str) -> Option<&'static str> { } pub(crate) fn glyph_letter(name: &str) -> &'static str { match name { - "Horizontal" => "H", - "Vertical" => "V", + "Horizontal" => "-", + "Vertical" => "|", _ => "?", } } diff --git a/assets/locales/en.json b/assets/locales/en.json index 5b7d6d4ee..c81b0adc1 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -2710,6 +2710,7 @@ "ui.hole_type": "Hole Type", "ui.home": "Home", "ui.homeView": "Home View", + "ui.horizontal_constraint": "Horizontal Constraint", "ui.horizontal_vertical": "Horizontal/Vertical", "ui.import_ellipsis": "Import…", "ui.infinite": "Infinite", @@ -2990,6 +2991,7 @@ "ui.untitled": "Untitled", "ui.up_axis_note": "Which axis points up in the views (axis view, Home, Look At). Designs are unchanged.", "ui.updateToCurrentView": "Update to Current View", + "ui.vertical_constraint": "Vertical Constraint", "ui.view_centre": "View centre", "ui.visual_shaded_hidden_edges": "Shaded with hidden edges", "ui.visual_shaded_with_edges": "Shaded with edges", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index b4b287a05..68d865608 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -2710,6 +2710,7 @@ "ui.hole_type": "穴タイプ", "ui.home": "ホーム", "ui.homeView": "ホームビュー", + "ui.horizontal_constraint": "水平拘束", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "インポート…", "ui.infinite": "無限", @@ -2990,6 +2991,7 @@ "ui.untitled": "無題", "ui.up_axis_note": "ビュー(軸ビュー、ホーム、正面視)で上向きにする軸を指定します。デザインデータ自体は変更されません。", "ui.updateToCurrentView": "現在のビューに更新", + "ui.vertical_constraint": "垂直拘束", "ui.view_centre": "ビュー中心", "ui.visual_shaded_hidden_edges": "隠線付きシェーディング", "ui.visual_shaded_with_edges": "エッジ付きシェーディング", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 537fa31ba..6cc8d0bde 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -2710,6 +2710,7 @@ "ui.hole_type": "孔类型", "ui.home": "主页", "ui.homeView": "主视图", + "ui.horizontal_constraint": "水平约束", "ui.horizontal_vertical": "水平/垂直", "ui.import_ellipsis": "导入…", "ui.infinite": "无限", @@ -2990,6 +2991,7 @@ "ui.untitled": "无标题", "ui.up_axis_note": "视图中朝上的轴(轴视图、主视图、注视)。设计本身不变。", "ui.updateToCurrentView": "更新为当前视图", + "ui.vertical_constraint": "垂直约束", "ui.view_centre": "视图中心", "ui.visual_shaded_hidden_edges": "带隐藏边的着色", "ui.visual_shaded_with_edges": "带边着色", diff --git a/crates/engine/src/cmd/delete.rs b/crates/engine/src/cmd/delete.rs index fc148bc16..0d175638c 100644 --- a/crates/engine/src/cmd/delete.rs +++ b/crates/engine/src/cmd/delete.rs @@ -103,6 +103,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(f) if matches!(f.kind, FeatureKind::ConstructionAxis { .. }) => features.push(f.id), _ => skip("the origin axes can't be deleted".into()), }, + Sel::SketchMidpoint { .. } => skip("a midpoint belongs to its sketch edge".into()), Sel::Body { name } => bodies.push(name.clone()), Sel::Face { body, point, .. } => match faces.iter_mut().find(|(b, _)| b == body) { Some((_, ps)) => ps.push(*point), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 607efcd2f..e56dd499a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -117,6 +117,10 @@ pub enum Sel { SketchPoint { id: String, }, + /// The associative midpoint of a line in the active sketch. Selection alone creates no geometry. + SketchMidpoint { + id: String, + }, /// Geometry of a different sketch, retained for projection preselection. ExternalSketchCurve { sketch: u64, diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 468ff7430..827fea036 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -620,10 +620,12 @@ impl Lit { Sel::Profile { sketch, .. } | Sel::ExternalSketchCurve { sketch, .. } | Sel::ExternalSketchPoint { sketch, .. } => { Thing::Sketch(*sketch) } - Sel::SketchCurve { .. } | Sel::SketchPoint { .. } | Sel::SketchConstraint { .. } => match app.session.active_sketch { - Some(id) => Thing::Sketch(id), - None => continue, - }, + Sel::SketchCurve { .. } | Sel::SketchPoint { .. } | Sel::SketchMidpoint { .. } | Sel::SketchConstraint { .. } => { + match app.session.active_sketch { + Some(id) => Thing::Sketch(id), + None => continue, + } + } Sel::Plane { name } => Thing::Plane(name.clone()), Sel::Axis { name } => Thing::Axis(name.clone()), Sel::Occurrence { .. } => continue, @@ -631,7 +633,9 @@ impl Lit { } let hovered = match &app.viewport.hover { Some(Hit::Face { body, .. } | Hit::Edge { body, .. } | Hit::Vertex { body, .. }) => Some(Thing::Body(body.clone())), - Some(Hit::SketchPoint { sketch, .. } | Hit::SketchCurve { sketch, .. } | Hit::Profile { sketch, .. }) => Some(Thing::Sketch(*sketch)), + Some( + Hit::SketchPoint { sketch, .. } | Hit::SketchMidpoint { sketch, .. } | Hit::SketchCurve { sketch, .. } | Hit::Profile { sketch, .. }, + ) => Some(Thing::Sketch(*sketch)), Some(Hit::Plane { name, .. }) => Some(Thing::Plane(name.clone())), Some(Hit::Axis { name }) => Some(Thing::Axis(name.clone())), None => None, diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index c4efbd375..e63938bde 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -859,6 +859,15 @@ fn explode_text(app: &SolveApp) -> Option { Some(cmd(app, "sketch.break_link", "Explode Text").with(json!({ "link": link }))) } +fn alignment_items(selection: &[Sel]) -> Vec { + let Some(points) = crate::selection::alignment_points(selection) else { return Vec::new() }; + vec![ + act("ui.horizontalConstraint", "Horizontal Constraint", "c_hv") + .with(json!({"points": points, "mode": "horizontal", "if_redundant": "refuse"})), + act("ui.verticalConstraint", "Vertical Constraint", "c_hv").with(json!({"points": points, "mode": "vertical", "if_redundant": "refuse"})), + ] +} + /// Sketch entity items: construction, fix, delete, dimension and the constraints the selection /// can take. fn sketch_entity_items(app: &SolveApp) -> Vec { @@ -866,6 +875,9 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { let Some(sid) = app.session.active_sketch else { return Vec::new() }; let st = app.session.world_state(); let Some(ss) = st.sketch(sid) else { return Vec::new() }; + if app.session.selection.iter().any(|sel| matches!(sel, Sel::SketchMidpoint { .. })) { + return alignment_items(&app.session.selection); + } let mut lines = Vec::new(); let mut rounds = Vec::new(); let mut curves = Vec::new(); @@ -951,7 +963,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { } if p == 2 && n == 2 { c.push(cmd(app, "sketch.constraint.coincident", "Coincident").with(json!({ "a": points[0], "b": points[1] }))); - c.push(cmd(app, "sketch.constraint.horizontal_vertical", "Horizontal/Vertical").with(json!({ "points": points }))); + c.extend(alignment_items(&app.session.selection)); } if p == 1 && curves.len() == 1 && n == 2 { c.push(cmd(app, "sketch.constraint.coincident", "Coincident").with(json!({ "a": picked[0], "b": picked[1] }))); @@ -1021,6 +1033,13 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { } "ui.delete" if item.params.is_some() => crate::delete::request(app, p), "ui.delete" => delete(app), + "ui.horizontalConstraint" | "ui.verticalConstraint" => { + let selection = app.session.selection.clone(); + let keep_midpoints = selection.iter().any(|s| matches!(s, Sel::SketchMidpoint { .. })); + if app.run("sketch.constraint.horizontal_vertical", p).is_ok() && keep_midpoints { + let _ = app.run("select.set", json!({"items": selection})); + } + } "ui.finishSketch" => app.finish_sketch(), "ui.cancelSketch" => app.cancel_sketch(), "ui.relinkSource" => { @@ -1494,6 +1513,14 @@ pub(crate) fn commit_rename(app: &mut SolveApp, r: &Rename) { // Opening and showing // --------------------------------------------------------------------------------------------- +/// Right-clicking the MID of an already selected edge keeps that geometry selection. +fn context_target_selected(selection: &[Sel], target: &Sel) -> bool { + selection.iter().any(|selected| { + crate::selection::same_item(selected, target) + || matches!((selected, target), (Sel::SketchCurve { id: a }, Sel::SketchMidpoint { id: b }) if a == b) + }) +} + /// Open the viewport menu at a screen position. A right-click on something not selected /// selects it first, so the menu is about what is under the cursor; a face or edge already in a /// multi-selection keeps the whole selection (#3733). @@ -1516,8 +1543,9 @@ pub fn open(app: &mut SolveApp, at: Pos2) { } else if app.session.active_sketch.is_some() && let Some(h) = app.viewport.hover.clone() && let Some((_, sel)) = crate::viewport::candidate(app, &[h]) - && (matches!(sel, Sel::SketchCurve { .. } | Sel::SketchPoint { .. }) || crate::sketch_text::entity_for_selection(app, &sel).is_some()) - && !selected(app, &sel) + && (matches!(sel, Sel::SketchCurve { .. } | Sel::SketchPoint { .. } | Sel::SketchMidpoint { .. }) + || crate::sketch_text::entity_for_selection(app, &sel).is_some()) + && !context_target_selected(&app.session.selection, &sel) { let _ = app.run("select.set", json!({ "items": [sel] })); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 780405a07..9401da3d9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -601,7 +601,7 @@ fn fits(a: Accept, s: &Sel) -> bool { // Sketch points go into a sketch command's own inputs (Entities, a base point), so a // box selection and a pre-selection reach them the way a click already does. Sel::SketchPoint { .. } => a & (selection::POINTS | selection::SKETCH_POINTS) != 0, - Sel::SketchConstraint { .. } | Sel::Occurrence { .. } | Sel::ExternalSketchPoint { .. } => false, + Sel::SketchMidpoint { .. } | Sel::SketchConstraint { .. } | Sel::Occurrence { .. } | Sel::ExternalSketchPoint { .. } => false, } } diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index 00e310274..939a25822 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -149,7 +149,7 @@ fn shown_as(hit: &Hit, sel: &Sel) -> Sel { /// Sort key: in a sketch its own points and curves come first; then by kind. fn rank(s: &Sel, sketching: bool) -> (u8, u8) { let kind = match s { - Sel::SketchPoint { .. } | Sel::ExternalSketchPoint { .. } => 0, + Sel::SketchPoint { .. } | Sel::SketchMidpoint { .. } | Sel::ExternalSketchPoint { .. } => 0, Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. } => 1, Sel::SketchConstraint { .. } => 2, Sel::Vertex { .. } => 3, @@ -160,7 +160,7 @@ fn rank(s: &Sel, sketching: bool) -> (u8, u8) { Sel::Plane { .. } => 8, Sel::Axis { .. } => 9, }; - let own = matches!(s, Sel::SketchPoint { .. } | Sel::SketchCurve { .. }); + let own = matches!(s, Sel::SketchPoint { .. } | Sel::SketchMidpoint { .. } | Sel::SketchCurve { .. }); (if sketching && !own { 1 } else { 0 }, kind) } @@ -235,6 +235,9 @@ pub fn label(app: &SolveApp, sel: &Sel) -> String { let in_sketch = |sketch: u64, f: &dyn Fn(&solidcraft_engine::sketch::Sketch) -> String| st.sketch(sketch).map(|ss| f(&ss.sketch)).unwrap_or_default(); match sel { + Sel::SketchMidpoint { id } => { + format!("MID · {}", app.session.active_sketch.map(|s| in_sketch(s, &|sk| curve_label(sk, id))).unwrap_or_else(|| id.clone())) + } Sel::SketchPoint { id } => app.session.active_sketch.map(|s| in_sketch(s, &|sk| point_label(sk, id))).unwrap_or_else(|| id.clone()), Sel::SketchCurve { id } => app.session.active_sketch.map(|s| in_sketch(s, &|sk| curve_label(sk, id))).unwrap_or_else(|| id.clone()), Sel::ExternalSketchPoint { sketch, id } => format!("{} · {}", in_sketch(*sketch, &|sk| point_label(sk, id)), sketch_name(app, *sketch)), @@ -267,7 +270,7 @@ fn icon(app: &SolveApp, sel: &Sel) -> &'static str { } }; match sel { - Sel::SketchPoint { .. } | Sel::ExternalSketchPoint { .. } | Sel::Vertex { .. } => "point", + Sel::SketchPoint { .. } | Sel::SketchMidpoint { .. } | Sel::ExternalSketchPoint { .. } | Sel::Vertex { .. } => "point", Sel::SketchCurve { id } => curve(app.session.active_sketch, id), Sel::ExternalSketchCurve { sketch, id } => curve(Some(*sketch), id), Sel::SketchConstraint { .. } => "dimension", diff --git a/crates/ui-egui/src/select_other_tests.rs b/crates/ui-egui/src/select_other_tests.rs index 69366eb25..0aaede69b 100644 --- a/crates/ui-egui/src/select_other_tests.rs +++ b/crates/ui-egui/src/select_other_tests.rs @@ -15,7 +15,8 @@ fn two_lines() -> (Harness, Value) { } h.app.cam.distance = 60.0; h.settle(); - let at = h.call("ui.at", json!({"sketch":[10,10]}))["result"].clone(); + // Curve tests pick away from MID; the centre is a distinct point target. + let at = h.call("ui.at", json!({"sketch":[5,10]}))["result"].clone(); (h, at) } @@ -214,7 +215,7 @@ fn a_dense_spot_is_capped_per_kind_and_reports_the_total() { let mut h = Harness::new(); h.app.ui.show_origin = false; h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); - // Thirty lines drawn on top of each other: one kind of thing, far beyond the per-kind cap. + // Thirty overlapping lines and their MID targets each exceed the per-kind cap. for _ in 0..30 { h.app.run("sketch.line", json!({"points":[[0,10],[20,10]],"infer":false,"connect":false})).unwrap(); } @@ -227,8 +228,27 @@ fn a_dense_spot_is_capped_per_kind_and_reports_the_total() { let rows = d["rows"].as_array().expect("rows"); let lines = rows.iter().filter(|r| r["label"].as_str().is_some_and(|l| l.starts_with("Line "))).count(); assert_eq!(lines, 20, "at most 20 rows of one kind, nearest first: {rows:?}"); - assert_eq!(rows[0]["label"], json!("Line 1"), "the nearest still leads"); + let mids = rows.iter().filter(|r| r["sel"]["type"] == "sketch_midpoint").count(); + assert_eq!(mids, 20, "MID targets have the same per-kind bound"); + assert_eq!(rows[0]["label"], json!("MID · Line 1"), "the nearest point target leads"); let total = d["total"].as_u64().expect("total"); - assert!(total >= 30, "the total counts every candidate, not just the rows: {total}"); + assert!(total >= 60, "the total counts every line and MID candidate, not just the rows: {total}"); assert!((total as usize) < rows.len() + 30, "the list is truncated: {total} total, {} rows", rows.len()); } + +#[test] +fn overlapping_midpoints_can_be_selected_individually_without_creating_points() { + let (mut h, _) = two_lines(); + let at = h.call("ui.at", json!({"sketch":[10,10]}))["result"].clone(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"hold":at})).unwrap(); + assert!(labels(&h).starts_with(&["MID · Line 1".into(), "MID · Line 2".into(), "Line 1".into(), "Line 2".into()])); + h.step(&json!({"click":{"handle":"select_other:1"}})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchMidpoint { id: "l2".into() }]); + h.step(&json!({"hold":at})).unwrap(); + h.step(&json!({"click":{"handle":"select_other:0"},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchMidpoint { id: "l2".into() }, Sel::SketchMidpoint { id: "l1".into() }]); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); +} diff --git a/crates/ui-egui/src/selection.rs b/crates/ui-egui/src/selection.rs index 92dd0dfa8..ff76b99d9 100644 --- a/crates/ui-egui/src/selection.rs +++ b/crates/ui-egui/src/selection.rs @@ -17,6 +17,28 @@ pub(crate) fn same_item(a: &Sel, b: &Sel) -> bool { } } +/// Two distinct point intents for the alignment command, without creating sketch points. +pub(crate) fn alignment_points(selection: &[Sel]) -> Option<[serde_json::Value; 2]> { + let [a, b] = selection else { return None }; + let point = |s: &Sel| match s { + Sel::SketchPoint { id } => Some(serde_json::json!(id)), + Sel::SketchMidpoint { id } => Some(serde_json::json!({"midpoint": id})), + _ => None, + }; + let (a, b) = (point(a)?, point(b)?); + (a != b).then_some([a, b]) +} + +/// The current middle of a finite straight sketch edge. +pub(crate) fn line_midpoint(sk: &solidcraft_engine::sketch::Sketch, line: usize) -> Option { + let curve = sk.curves.get(line)?; + if curve.infinite { + return None; + } + let solidcraft_engine::sketch::CurveKind::Line { a, b } = &curve.kind else { return None }; + Some((sk.point(*a)? + sk.point(*b)?) * 0.5) +} + /// What a selection input accepts (bit set). pub type Accept = u16; pub const PROFILES: Accept = 1; diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 117fd9561..57a869c3b 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -14,7 +14,7 @@ use solidcraft_engine::geom::{Vec2, Vec3}; use crate::SolveApp; use crate::tool_modifiers::{Audit, Binding, Match, ModAction, ModifierCombo, Scope, ToolModifiers, Trigger}; use crate::tools::{Kind, Tool}; -use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +use crate::viewport::{Hit, Proj, pick_for_tool as pick, sketch_point_at}; const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; const NONE: &[Scope] = &[]; diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 10dabc934..64e06586a 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -7,7 +7,7 @@ use solidcraft_engine::geom::Vec2; use crate::SolveApp; use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; -use crate::viewport::{Hit, Proj, pick, sketch_point_at}; +use crate::viewport::{Hit, Proj, pick_for_tool as pick, sketch_point_at}; const DRAW_SCOPES: &[Scope] = &[Scope::SketchDraw, Scope::SketchDrag]; @@ -545,7 +545,7 @@ pub(crate) fn constraint_preselection(command: &str, selection: &[solidcraft_eng ("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})), - ("sketch.constraint.horizontal_vertical", [SketchPoint { id: a }, SketchPoint { id: b }]) if a != b => Some(json!({"points":[a,b]})), + ("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 { SketchPoint { id } | SketchCurve { id } => Some(id.clone()), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b38cc0928..c62c91a7a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -169,6 +169,12 @@ pub enum Hit { id: String, at: Vec2, }, + /// A selectable line midpoint, before any associated helper point has been made. + SketchMidpoint { + sketch: u64, + id: String, + at: Vec2, + }, /// A sketch curve; `straight` for lines (usable as an axis). SketchCurve { sketch: u64, @@ -1387,6 +1393,8 @@ pub(crate) fn pick_cached(app: &mut SolveApp, proj: &Proj, pos: Pos2) -> Vec Vec { pick_with_sketch_points(app, proj, pos, false) } +/// Operand picking excludes idle MID selection, including while a tool is temporarily taken +/// out of `app.tool` to handle its click. +pub(crate) fn pick_for_tool(app: &SolveApp, proj: &Proj, pos: Pos2) -> Vec { + pick_hits(app, proj, pos, false, false, false) +} + /// Like [`pick`], but also returns points of every visible sketch: only for the 3D drawing snap, /// which converts them to world space through their own sketch's plane. pub fn pick_3d(app: &SolveApp, proj: &Proj, pos: Pos2) -> Vec { @@ -1426,11 +1440,11 @@ pub fn pick_3d(app: &SolveApp, proj: &Proj, pos: Pos2) -> Vec { /// vertex, edge, axis and profile near the cursor, and the nearest face of every body along the /// ray, instead of the nearest of each kind. Each kind is nearest first. pub fn pick_all(app: &SolveApp, proj: &Proj, pos: Pos2) -> Vec { - pick_hits(app, proj, pos, false, true) + pick_hits(app, proj, pos, false, true, true) } fn pick_with_sketch_points(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool) -> Vec { - let mut hits = pick_hits(app, proj, pos, other_sketch_points, false); + let mut hits = pick_hits(app, proj, pos, other_sketch_points, false, true); // A Single hole's face place snaps to the face's centre and its round edges' centres. crate::hole_place::snap_hits(app, proj, pos, &mut hits); hits @@ -1439,7 +1453,8 @@ fn pick_with_sketch_points(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_ /// The same thing picked twice (one row per target in [`pick_all`]). pub fn same_target(a: &Hit, b: &Hit) -> bool { match (a, b) { - (Hit::SketchPoint { sketch: s, id: i, .. }, Hit::SketchPoint { sketch: t, id: j, .. }) + (Hit::SketchMidpoint { sketch: s, id: i, .. }, Hit::SketchMidpoint { sketch: t, id: j, .. }) + | (Hit::SketchPoint { sketch: s, id: i, .. }, Hit::SketchPoint { sketch: t, id: j, .. }) | (Hit::SketchCurve { sketch: s, id: i, .. }, Hit::SketchCurve { sketch: t, id: j, .. }) => s == t && i == j, (Hit::Vertex { body: a, point: p }, Hit::Vertex { body: b, point: q }) => a == b && p.dist(*q) < 1e-9, (Hit::Edge { body: a, index: i, .. }, Hit::Edge { body: b, index: j, .. }) @@ -1486,12 +1501,35 @@ impl Near { } } -fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, all: bool) -> Vec { +fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool, all: bool, include_midpoints: bool) -> Vec { let s = &app.session; let st = crate::open_meshing::shown_world(app); let bounds = body_bounds(app, &st); let mut hits = Vec::new(); let (o, d) = proj.ray(pos); + // MID is an idle sketch selection target. Tools and dialogs keep their existing picks. + // Put it before a materialized helper point so later constraints still refer to the edge. + if include_midpoints + && app.tool.is_none() + && app.dialog.is_none() + && let Some(ss) = s.active_sketch.and_then(|sid| st.sketch(sid)) + { + let mut mids = Near::new(all); + for (i, curve) in ss.sketch.curves.iter().enumerate() { + if !solidcraft_engine::view::sketch_curve_visible(&ss.sketch, i) { + continue; + } + if let Some(at) = crate::selection::line_midpoint(&ss.sketch, i) + && let Some(screen) = proj.to_screen(ss.plane.to_world(at)) + { + let distance = screen.distance(pos); + if distance < 8.0 { + mids.offer(distance, Hit::SketchMidpoint { sketch: ss.feature, id: curve.id.clone(), at }); + } + } + } + hits.extend(mids.hits()); + } // Sketch points of the active sketch (of every shown sketch while a command takes points, // while idle or projecting, and while 3D drawing snaps to points on other visible sketches). let wants_points = app.dialog.as_ref().and_then(|d| d.active_input()).is_some_and(|i| i.accept & crate::selection::POINTS != 0); @@ -1841,6 +1879,14 @@ pub fn selection_bounds(app: &SolveApp) -> Option b.add(*point), + Sel::SketchMidpoint { id } => { + if let Some(ss) = app.session.active_sketch.and_then(|sid| st.sketch(sid)) + && let Some(line) = ss.sketch.curve_index(id) + && let Some(at) = crate::selection::line_midpoint(&ss.sketch, line) + { + b.add(ss.plane.to_world(at)); + } + } Sel::ExternalSketchPoint { sketch, id } => { if let Some(ss) = st.sketch(*sketch) && let Some(p) = ss.sketch.resolve_point(id).and_then(|i| ss.sketch.point(i)) @@ -1971,6 +2017,7 @@ const AXIS_LEN: f64 = 1.8; /// The hit as a plain selection (no command filter). pub fn hit_sel(h: &Hit) -> Option { Some(match h { + Hit::SketchMidpoint { id, .. } => Sel::SketchMidpoint { id: id.clone() }, Hit::SketchPoint { id, .. } => Sel::SketchPoint { id: id.clone() }, Hit::SketchCurve { id, .. } => Sel::SketchCurve { id: id.clone() }, Hit::Vertex { body, point } => Sel::Vertex { body: body.clone(), point: *point }, @@ -2014,7 +2061,7 @@ fn pick_allowed(app: &SolveApp, h: &Hit) -> bool { let off = |k: &str| app.ui.pick_off.iter().any(|x| x == k); match h { Hit::SketchCurve { .. } => !off("sketch") && !off("sketch_curves"), - Hit::SketchPoint { .. } => !off("sketch") && !off("sketch_points"), + Hit::SketchPoint { .. } | Hit::SketchMidpoint { .. } => !off("sketch") && !off("sketch_points"), Hit::Profile { .. } => !off("sketch"), Hit::Vertex { .. } => !off("vertices") && !app.ui.pick_bodies, Hit::Edge { .. } => !off("edges") && !app.ui.pick_bodies, @@ -3143,11 +3190,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let sketching = app.session.active_sketch.is_some(); // A dimension's text wins; its lines only where no sketch point or curve is (a // diameter's line runs through the centre point). - let on_geometry = matches!(cand.as_ref().map(|c| &c.0), Some(Hit::SketchPoint { .. } | Hit::SketchCurve { .. })); + let on_geometry = + matches!(cand.as_ref().map(|c| &c.0), Some(Hit::SketchPoint { .. } | Hit::SketchMidpoint { .. } | Hit::SketchCurve { .. })); let on_dim = crate::dim_view::hit_text(p) .or_else(|| if on_geometry { None } else { crate::dim_view::hit(p) }) .filter(|_| sketching && !off("dimensions")); - let on_glyph = crate::sketch_tools::glyph_at(p).filter(|_| sketching && !off("constraints")); + let on_midpoint = matches!(cand.as_ref().map(|c| &c.0), Some(Hit::SketchMidpoint { .. })); + let on_glyph = crate::sketch_tools::glyph_at(p).filter(|_| sketching && !off("constraints") && !on_midpoint); if crate::sketch_text_handles::over(app, &proj, p) { // A text's resize or rotation handle: the text stays selected. } else if !crate::sketch3d::click(app, &proj, p) { @@ -3241,7 +3290,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { && !crate::sketch_text_handles::dragging(app) && let Some(q) = on_plane(app, *a) { - let on_geometry = matches!(hit, Some(Hit::SketchPoint { .. } | Hit::SketchCurve { .. })); + let on_geometry = matches!(hit, Some(Hit::SketchPoint { .. } | Hit::SketchMidpoint { .. } | Hit::SketchCurve { .. })); crate::dim_view::drag_start(app, *a, q, on_geometry); } if crate::sketch3d::dragging() @@ -3276,7 +3325,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let grab = if dragged_with(app, &id).is_empty() { None } else { on_plane(app, a) }; app.viewport.point_drag = Some((id, app.session.undo.len(), grab)) } - Some(Hit::SketchCurve { sketch, id, .. }) if Some(sketch) == active => { + Some(Hit::SketchCurve { sketch, id, .. } | Hit::SketchMidpoint { sketch, id, .. }) if Some(sketch) == active => { app.viewport.point_drag = on_plane(app, a).map(|q| (id, app.session.undo.len(), Some(q))); } _ => {} @@ -4133,6 +4182,13 @@ fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } } + Some(Hit::SketchMidpoint { sketch, at, .. }) => { + if let Some(ss) = st.sketch(*sketch) + && let Some(p) = proj.to_screen(ss.plane.to_world(*at)) + { + midpoint_marker(painter, p, col); + } + } Some(Hit::SketchPoint { sketch, at, .. }) => { if let Some(ss) = st.sketch(*sketch) && let Some(p) = proj.to_screen(ss.plane.to_world(*at)) @@ -4144,6 +4200,13 @@ fn hover_highlight(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } } +/// A midpoint stays attached to its edge; hover and selection share the same marker. +fn midpoint_marker(painter: &egui::Painter, at: Pos2, color: Color32) { + let triangle = vec![at + vec2(0.0, -6.0), at + vec2(6.0, 5.0), at + vec2(-6.0, 5.0)]; + painter.add(Shape::closed_line(triangle, Stroke::new(2.0, color))); + painter.text(at + vec2(10.0, -8.0), Align2::LEFT_BOTTOM, "MID", FontId::proportional(Tokens::get().font_button), color); +} + /// The standalone points of the finished sketches shown (placed with Point, not a curve's /// ends or centres), in world space: they can still be picked (a hole's centre), so they are /// drawn too (#3267). Not the sketch's origin, projected points, or a sketch's points while it @@ -4218,6 +4281,15 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { painter.rect_filled(Rect::from_center_size(sp, vec2(5.0, 5.0)), 0.0, c); } } + for selected in &app.session.selection { + if let Sel::SketchMidpoint { id } = selected + && let Some(line) = sk.curve_index(id) + && let Some(at) = crate::selection::line_midpoint(sk, line) + && let Some(screen) = proj.to_screen(ss.plane.to_world(at)) + { + midpoint_marker(painter, screen, t.sel_edge); + } + } loose_end_markers(sk, &ss.ends, &ss.plane, painter, proj, &t); // Sketch status. if let Some(r) = app.viewport.layout.as_ref().map(|l| l.content) { @@ -6404,6 +6476,24 @@ mod tests { assert!(app.viewport.device_motion.is_none()); } + #[test] + fn midpoint_picking_cache_follows_tool_lifecycle() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[30,10]],"infer":false})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.frames(3); + let proj = projection(&h.app, h.app.viewport.rect.unwrap()); + let at = proj.to_screen(Vec3::new(20.0, 10.0, 0.0)).unwrap(); + let is_mid = |hits: Vec| matches!(hits.first(), Some(Hit::SketchMidpoint { id, .. }) if id == "l1"); + assert!(is_mid(pick_cached(&mut h.app, &proj, at))); + h.app.tool = crate::tools::Tool::for_command("sketch.line"); + assert!(!is_mid(pick_cached(&mut h.app, &proj, at)), "starting a tool invalidates idle hover"); + h.app.tool = None; + assert!(is_mid(pick_cached(&mut h.app, &proj, at)), "ending a tool restores MID at the same pixel"); + assert!(!is_mid(pick_for_tool(&h.app, &proj, at)), "a temporarily taken tool still picks its operands"); + } + #[test] fn device_navigation_keeps_face_hover_current_for_a_stationary_or_moving_pointer() { for gpu in [false, true] { diff --git a/crates/ui-egui/tests/constraint_preselection.rs b/crates/ui-egui/tests/constraint_preselection.rs index d32d85f2e..8a6185322 100644 --- a/crates/ui-egui/tests/constraint_preselection.rs +++ b/crates/ui-egui/tests/constraint_preselection.rs @@ -11,9 +11,10 @@ fn lines() -> Harness { } fn select_lines(h: &mut Harness) { + // These tests select whole edges; the exact centre is now a selectable MID. h.run(&json!([ - {"click":{"sketch":[25,10]}}, - {"click":{"sketch":[25,32.5]},"shift":true} + {"click":{"sketch":[17.5,10]}}, + {"click":{"sketch":[17.5,31.25]},"shift":true} ])) .unwrap(); assert_eq!(h.app.session.selection, vec![Sel::SketchCurve { id: "l1".into() }, Sel::SketchCurve { id: "l2".into() }]); @@ -183,16 +184,16 @@ fn curvature_polygon_and_fix_consume_clicked_operands_atomically() { "curvature" => { h.app.run("sketch.line", json!({"points":[[10,10],[30,10]],"infer":false})).unwrap(); h.app.run("sketch.spline.control_point", json!({"points":["l1.end",[40,12],[50,16],[60,25]]})).unwrap(); - vec![[20., 10.], [45., 14.875]] + vec![[15., 10.], [45., 14.875]] } "polygon" => { h.app.run("sketch.line", json!({"points":[[10,10],[40,10],[40,30],[10,30]],"closed":true,"infer":false})).unwrap(); - vec![[25., 10.], [40., 20.], [25., 30.], [10., 20.]] + vec![[17.5, 10.], [40., 15.], [32.5, 30.], [10., 25.]] } _ => { h.app.run("sketch.line", json!({"points":[[10,10],[40,10]],"infer":false})).unwrap(); h.app.run("sketch.point", json!({"point":[20,25],"id":"p"})).unwrap(); - vec![[25., 10.], [20., 25.]] + vec![[17.5, 10.], [20., 25.]] } }; h.call("ui.view", json!({"view":"top"})); diff --git a/crates/ui-egui/tests/point_alignment.rs b/crates/ui-egui/tests/point_alignment.rs index 3614eef38..2bbe92ff9 100644 --- a/crates/ui-egui/tests/point_alignment.rs +++ b/crates/ui-egui/tests/point_alignment.rs @@ -1,5 +1,8 @@ //! Horizontal/Vertical accepts either one line or two distinct sketch points. +#[path = "support/raster.rs"] +mod raster; + use serde_json::json; use solidcraft_engine::sketch::ConstraintKind; use solidcraft_ui_egui::scenario::Harness; @@ -23,7 +26,7 @@ fn horizontal_vertical_uses_preselected_line_and_preserves_rejection() { if fixed { h.app.session.execute("sketch.constraint.fix", &json!({"entity":"l1"})).unwrap(); } - h.run(&json!([{"click":{"sketch":[25,11.5]}}])).unwrap(); + h.run(&json!([{"click":{"sketch":[17.5,10.75]}}])).unwrap(); assert_eq!(h.app.session.selection.len(), 1); let selection = h.app.session.selection.clone(); let before = serde_json::to_value(&h.app.session.doc).unwrap(); @@ -346,3 +349,425 @@ fn conflicting_midpoint_pick_keeps_pending_preview_without_creating_geometry() { assert!(h.app.tool.is_none()); assert_eq!(h.app.session.doc.to_json(), before); } + +#[test] +fn context_menu_explicitly_aligns_two_points_and_removes_one_freedom() { + use solidcraft_engine::Sel; + use solidcraft_ui_egui::context_menu::{self, Target}; + // Include independent points, a circle centre and line endpoints; choose the direction + // opposite to the automatic H/V guess, in either selection order. + for (first, second) in [("a", "b"), ("l1.start", "c1.center"), ("l1.start", "l1.end")] { + for horizontal in [true, false] { + for reverse in [false, true] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.point", json!({"point":[10,10],"id":"a"})).unwrap(); + h.app.run("sketch.point", json!({"point":[25,30],"id":"b"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[15,12],[35,40]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[45,50],"radius":3})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + let pair = if reverse { [second, first] } else { [first, second] }; + h.app.session.selection = pair.into_iter().map(|id| Sel::SketchPoint { id: id.into() }).collect(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let dof = h.app.session.model.state().sketches[0].report.dof; + let items = context_menu::items(&h.app, &Target::Viewport); + let horizontal_item = items.iter().find(|i| i.id == "ui.horizontalConstraint").unwrap(); + let vertical_item = items.iter().find(|i| i.id == "ui.verticalConstraint").unwrap(); + assert_eq!(horizontal_item.label, "Horizontal Constraint"); + assert_eq!(vertical_item.label, "Vertical Constraint"); + let item = if horizontal { horizontal_item } else { vertical_item }; + assert!(item.enabled); + context_menu::open_for(&mut h.app, egui::pos2(600.0, 400.0), Target::Viewport); + context_menu::pick(&mut h.app, &item.id).unwrap(); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + let state = h.app.session.model.state(); + let ss = &state.sketches[0]; + let a = ss.sketch.point(ss.sketch.resolve_point(first).unwrap()).unwrap(); + let b = ss.sketch.point(ss.sketch.resolve_point(second).unwrap()).unwrap(); + assert!((if horizontal { a.y - b.y } else { a.x - b.x }).abs() < 1e-6); + assert_eq!(ss.report.dof, dof - 1); + assert_eq!(h.app.session.undo.len(), undo + 1); + let constraint = ss + .sketch + .constraints + .iter() + .find(|c| { + if horizontal { + matches!(c.kind, ConstraintKind::HorizontalPoints { .. }) + } else { + matches!(c.kind, ConstraintKind::VerticalPoints { .. }) + } + }) + .unwrap() + .id + .clone(); + h.frames(3); + assert!(solidcraft_ui_egui::sketch_tools::glyph_positions().iter().any(|(id, _)| id == &constraint)); + let after = h.app.session.doc.to_json(); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), after); + // Repeating the same relationship must not stack a redundant constraint. + let undo = h.app.session.undo.len(); + context_menu::run_item(&mut h.app, item, egui::Pos2::ZERO); + assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + assert_eq!(h.app.session.doc.to_json(), after); + assert_eq!(h.app.session.undo.len(), undo); + } + } + } +} + +#[test] +fn context_menu_alignment_requires_exactly_two_points_and_preserves_conflicts() { + use solidcraft_engine::Sel; + use solidcraft_ui_egui::context_menu::{self, Target}; + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[20,30],"radius":3})).unwrap(); + let origin = Sel::SketchPoint { id: "origin".into() }; + let center = Sel::SketchPoint { id: "c1.center".into() }; + let curve = Sel::SketchCurve { id: "c1".into() }; + for selection in [vec![], vec![origin.clone()], vec![origin.clone(), curve.clone()], vec![origin.clone(), center.clone(), curve]] { + h.app.session.selection = selection; + assert!( + !context_menu::items(&h.app, &Target::Viewport) + .iter() + .any(|i| matches!(i.id.as_str(), "ui.horizontalConstraint" | "ui.verticalConstraint")) + ); + } + h.app.run("sketch.constraint.fix", json!({"entity":"c1"})).unwrap(); + h.app.session.selection = vec![origin, center]; + for id in ["ui.horizontalConstraint", "ui.verticalConstraint"] { + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let selection = h.app.session.selection.clone(); + let item = context_menu::items(&h.app, &Target::Viewport).into_iter().find(|i| i.id == id).unwrap(); + context_menu::run_item(&mut h.app, &item, egui::Pos2::ZERO); + assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.selection, selection); + } +} + +/// Reproducible review images of the actual menu and glyphs, using the app's egui meshes. +#[test] +#[ignore = "writes review images; run explicitly for visual verification"] +fn context_menu_alignment_review_images() { + use solidcraft_engine::Sel; + use solidcraft_ui_egui::{ + context_menu::{self, Target}, + fonts, theme, + }; + let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/point-alignment-review"); + std::fs::create_dir_all(&dir).unwrap(); + let previous = theme::is_dark(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.language = "ja".into(); + h.call("ui.resize", json!({"width":1100,"height":1500})); + h.call("ui.set", json!({"dark":dark})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + for (id, point) in [("a", [10, 10]), ("b", [35, 20]), ("c", [55, 10]), ("d", [70, 35])] { + h.app.run("sketch.point", json!({"point":point,"id":id})).unwrap(); + } + h.call("ui.view", json!({"view":"top"})); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(40.0, 22.0, 0.0); + h.app.cam.distance = 180.0; + h.app.cam_anim = None; + h.frames(3); + h.ctx = egui::Context::default(); + fonts::setup_fonts_for(&h.ctx, "ja", ""); + theme::apply(&h.ctx); + let mut textures = std::collections::HashMap::new(); + for _ in 0..8 { + raster::paint(&mut h, &mut textures, vec![]); + } + let mode = if dark { "dark" } else { "light" }; + for (pair, item, shot) in [(["a", "b"], "ui.horizontalConstraint", "horizontal"), (["c", "d"], "ui.verticalConstraint", "vertical")] { + h.app.session.selection = pair.into_iter().map(|id| Sel::SketchPoint { id: id.into() }).collect(); + context_menu::open_for(&mut h.app, egui::pos2(800.0, 950.0), Target::Viewport); + for _ in 0..4 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + raster::raster(&mut h, &textures, output).save(dir.join(format!("{mode}-{shot}-menu.png"))).unwrap(); + context_menu::pick(&mut h.app, item).unwrap(); + for _ in 0..4 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + raster::raster(&mut h, &textures, output).save(dir.join(format!("{mode}-{shot}.png"))).unwrap(); + } + } + theme::set_dark(previous); +} + +#[test] +fn context_menu_alignment_follows_screen_axes_in_principal_sketch_views() { + use solidcraft_engine::Sel; + use solidcraft_ui_egui::{ + context_menu::{self, Target}, + dialogs, viewport, + }; + for plane in ["XY", "XZ", "YZ"] { + for horizontal in [true, false] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":plane})).unwrap(); + h.app.run("sketch.point", json!({"point":[10,10],"id":"a"})).unwrap(); + h.app.run("sketch.point", json!({"point":[30,25],"id":"b"})).unwrap(); + dialogs::look_at_sketch(&mut h.app); + h.settle(); + h.app.session.selection = ["a", "b"].into_iter().map(|id| Sel::SketchPoint { id: id.into() }).collect(); + let id = if horizontal { "ui.horizontalConstraint" } else { "ui.verticalConstraint" }; + let item = context_menu::items(&h.app, &Target::Viewport).into_iter().find(|i| i.id == id).unwrap(); + context_menu::run_item(&mut h.app, &item, egui::Pos2::ZERO); + let state = h.app.session.model.state(); + let ss = &state.sketches[0]; + let proj = viewport::projection(&h.app, h.app.viewport.rect.unwrap()); + let a = proj.to_screen(ss.plane.to_world(ss.sketch.point(ss.sketch.resolve_point("a").unwrap()).unwrap())).unwrap(); + let b = proj.to_screen(ss.plane.to_world(ss.sketch.point(ss.sketch.resolve_point("b").unwrap()).unwrap())).unwrap(); + assert!((if horizontal { a.y - b.y } else { a.x - b.x }).abs() < 0.01, "{plane}: {a:?}, {b:?}"); + } + } +} + +#[test] +fn idle_midpoints_are_selectable_without_modifying_the_sketch() { + use solidcraft_engine::Sel; + use solidcraft_ui_egui::{ + context_menu::{self, Target}, + viewport::Hit, + }; + for (plane, view) in [("XY", "top"), ("XZ", "front"), ("YZ", "right")] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":plane})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[50,20]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.line", json!({"points":[[-10,40],[70,50]],"infer":false,"connect":false})).unwrap(); + h.call("ui.view", json!({"view":view})); + h.app.fit_view(); + h.frames(3); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.step(&json!({"move":{"sketch":[30,15]}})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(Hit::SketchMidpoint { ref id, .. }) if id == "l1")); + h.step(&json!({"click":{"sketch":[30,15]}})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchMidpoint { id: "l1".into() }]); + assert!(!context_menu::items(&h.app, &Target::Viewport).iter().any(|i| i.id == "ui.horizontalConstraint")); + h.step(&json!({"click":{"sketch":[30,45]},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchMidpoint { id: "l1".into() }, Sel::SketchMidpoint { id: "l2".into() }]); + let items = context_menu::items(&h.app, &Target::Viewport); + assert_eq!( + items.iter().find(|i| i.id == "ui.horizontalConstraint").unwrap().params.as_ref().unwrap()["points"], + json!([{"midpoint":"l1"},{"midpoint":"l2"}]) + ); + h.step(&json!({"click":{"sketch":[30,45]},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchMidpoint { id: "l1".into() }]); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + // Ordinary edge and endpoint picks still work away from MID. + h.step(&json!({"click":{"sketch":[20,12.5]}})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::SketchCurve { id: "l1".into() }]); + h.step(&json!({"click":{"sketch":[10,10]}})).unwrap(); + assert!(matches!(h.app.session.selection.as_slice(), [Sel::SketchPoint { .. }])); + h.app.ui.pick_off.push("sketch_points".into()); + h.step(&json!({"move":{"sketch":[30,15]}})).unwrap(); + assert!(!matches!(h.app.viewport.hover, Some(Hit::SketchMidpoint { .. }))); + } +} + +#[test] +fn selected_midpoints_can_take_both_axes_and_reuse_the_same_helpers() { + use solidcraft_engine::{Sel, Session}; + use solidcraft_ui_egui::context_menu::{self, Target}; + for reverse in [false, true] { + for horizontal_first in [false, true] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[10,10],[50,20]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.line", json!({"points":[[25,35],[65,55]],"infer":false,"connect":false})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entity":"l1"})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.app.fit_view(); + h.frames(3); + let (a, b) = if reverse { ([45, 45], [30, 15]) } else { ([30, 15], [45, 45]) }; + h.step(&json!({"click":{"sketch":a}})).unwrap(); + h.step(&json!({"click":{"sketch":b},"shift":true})).unwrap(); + let selected = h.app.session.selection.clone(); + assert_eq!(selected.len(), 2); + assert!(selected.iter().all(|s| matches!(s, Sel::SketchMidpoint { .. }))); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let dof = h.app.session.model.state().sketches[0].report.dof; + let mut after_first = String::new(); + for (i, horizontal) in [horizontal_first, !horizontal_first].into_iter().enumerate() { + context_menu::open_for(&mut h.app, egui::pos2(600.0, 400.0), Target::Viewport); + context_menu::pick(&mut h.app, if horizontal { "ui.horizontalConstraint" } else { "ui.verticalConstraint" }).unwrap(); + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + assert_eq!(h.app.session.selection, selected, "both MID selections remain for the second axis"); + let state = h.app.session.model.state(); + let ss = &state.sketches[0]; + let (m, n) = (line_midpoint(&ss.sketch, "l1"), line_midpoint(&ss.sketch, "l2")); + assert!((if horizontal { m.y - n.y } else { m.x - n.x }).abs() < 1e-6); + assert_eq!(ss.report.dof, dof - i - 1); + assert_eq!(ss.sketch.points.len(), 7, "two helper points are reused on the second axis"); + assert_eq!(ss.sketch.constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::Midpoint { .. })).count(), 2); + assert_eq!(h.app.session.undo.len(), undo + i + 1); + if i == 0 { + after_first = h.app.session.doc.to_json(); + } + } + let after = h.app.session.doc.to_json(); + let sk = &h.app.session.model.state().sketches[0].sketch; + assert!(line_midpoint(sk, "l1").dist(line_midpoint(sk, "l2")) < 1e-6); + // The same references must remain pickable after materializing their helper points. + let mid = line_midpoint(sk, "l2"); + h.step(&json!({"move":{"sketch":[mid.x,mid.y]}})).unwrap(); + assert!(matches!(h.app.viewport.hover, Some(solidcraft_ui_egui::viewport::Hit::SketchMidpoint { .. }))); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), after_first); + h.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), before); + h.app.run("edit.redo", json!({})).unwrap(); + h.app.run("edit.redo", json!({})).unwrap(); + assert_eq!(h.app.session.doc.to_json(), after); + let mut reopened = Session::new(solidcraft_engine::doc::Document::from_json(&after).unwrap()); + reopened.active_sketch = h.app.session.active_sketch; + reopened.execute("sketch.move_point", &json!({"point":"l2.end","to":[60,25]})).unwrap(); + let sk = &reopened.model.state().sketches[0].sketch; + assert!(line_midpoint(sk, "l1").dist(line_midpoint(sk, "l2")) < 1e-6); + let undo = h.app.session.undo.len(); + h.app.run("select.set", json!({"items": selected})).unwrap(); + let item = context_menu::items(&h.app, &Target::Viewport).into_iter().find(|i| i.id == "ui.horizontalConstraint").unwrap(); + context_menu::run_item(&mut h.app, &item, egui::Pos2::ZERO); + assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + assert_eq!(h.app.session.doc.to_json(), after); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.selection, selected); + } + } +} + +#[test] +fn midpoint_menu_aligns_rectangle_sides_and_refuses_conflicts_atomically() { + use solidcraft_ui_egui::context_menu; + for horizontal in [true, false] { + for fixed in [true, false] { + 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":[80,70]})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[15,15],"p1":[50,55]})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entities":["l1","l2","l3","l4"]})).unwrap(); + if fixed { + h.app.run("sketch.constraint.fix", json!({"entities":["l5","l6","l7","l8"]})).unwrap(); + } + h.call("ui.view", json!({"view":"top"})); + h.app.fit_view(); + h.frames(3); + let (a, b) = if horizontal { ([40., 70.], [32.5, 55.]) } else { ([40., 0.], [32.5, 15.]) }; + h.step(&json!({"click":{"sketch":a}})).unwrap(); + h.step(&json!({"click":{"sketch":b},"shift":true})).unwrap(); + assert_eq!(h.app.session.selection.len(), 2); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + let selected = h.app.session.selection.clone(); + let lines: Vec<_> = selected + .iter() + .map(|s| if let solidcraft_engine::Sel::SketchMidpoint { id } = s { id.clone() } else { panic!("expected MID: {s:?}") }) + .collect(); + let dof = h.app.session.model.state().sketches[0].report.dof; + h.step(&json!({"click":{"sketch":if horizontal {[32.5,55.]} else {b}},"button":"right"})).unwrap(); + context_menu::pick(&mut h.app, if horizontal { "ui.horizontalConstraint" } else { "ui.verticalConstraint" }).unwrap(); + if fixed { + assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error)); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); + } else { + assert!(!h.app.status.as_ref().is_some_and(|(_, _, error)| *error), "{:?}", h.app.status); + let ss = &h.app.session.model.state().sketches[0]; + let (m, n) = (line_midpoint(&ss.sketch, &lines[0]), line_midpoint(&ss.sketch, &lines[1])); + assert!((if horizontal { m.y - n.y } else { m.x - n.x }).abs() < 1e-6); + assert_eq!(ss.report.dof, dof - 1); + } + assert_eq!(h.app.session.selection, selected); + } + } +} + +#[test] +#[ignore = "writes MID review images; run explicitly for visual verification"] +fn midpoint_selection_review_images() { + use solidcraft_ui_egui::{ + context_menu::{self, Target}, + fonts, theme, + }; + let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/midpoint-selection-review"); + std::fs::create_dir_all(&dir).unwrap(); + solidcraft_engine::capture::install(std::sync::Arc::new(|scene, cam, w, h| { + let (rgba, renderer) = solidcraft_gpu::capture::headless_rgba(scene, cam, w, h)?; + Ok(solidcraft_engine::capture::Picture { rgba, renderer }) + })); + let previous = theme::is_dark(); + for dark in [false, true] { + for horizontal in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.language = "ja".into(); + h.call("ui.resize", json!({"width":1100,"height":1500})); + h.call("ui.set", json!({"dark":dark})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[80,70]})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[15,18],"p1":[50,58]})).unwrap(); + h.call("ui.view", json!({"view":"top"})); + h.app.cam.target = solidcraft_engine::geom::Vec3::new(40., 35., 0.); + h.app.cam.distance = 180.; + h.app.cam_anim = None; + h.frames(3); + h.ctx = egui::Context::default(); + fonts::setup_fonts_for(&h.ctx, "ja", ""); + theme::apply(&h.ctx); + let mut textures = std::collections::HashMap::new(); + for _ in 0..8 { + raster::paint(&mut h, &mut textures, vec![]); + } + let (a, b) = if horizontal { ([0., 35.], [15., 38.]) } else { ([40., 0.], [32.5, 18.]) }; + h.step(&json!({"move":{"sketch":a}})).unwrap(); + h.step(&json!({"click":{"sketch":a}})).unwrap(); + h.step(&json!({"click":{"sketch":b},"shift":true})).unwrap(); + assert!(h.app.session.selection.iter().all(|s| matches!(s, solidcraft_engine::Sel::SketchMidpoint { .. }))); + assert_eq!(h.app.session.selection.len(), 2); + let prefix = format!("{}-{}", if dark { "dark" } else { "light" }, if horizontal { "horizontal" } else { "vertical" }); + context_menu::open_for(&mut h.app, egui::pos2(880., 800.), Target::Viewport); + for _ in 0..4 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + raster::raster(&mut h, &textures, output).save(dir.join(format!("{prefix}-menu.png"))).unwrap(); + std::fs::write(dir.join(format!("{prefix}-menu-model.png")), solidcraft_ui_egui::control::view_png(&h.app, 1000, 900).unwrap()).unwrap(); + context_menu::pick(&mut h.app, if horizontal { "ui.horizontalConstraint" } else { "ui.verticalConstraint" }).unwrap(); + for _ in 0..4 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + raster::raster(&mut h, &textures, output).save(dir.join(format!("{prefix}-aligned.png"))).unwrap(); + std::fs::write(dir.join(format!("{prefix}-aligned-model.png")), solidcraft_ui_egui::control::view_png(&h.app, 1000, 900).unwrap()) + .unwrap(); + if !horizontal { + context_menu::open_for(&mut h.app, egui::pos2(880., 800.), Target::Viewport); + context_menu::pick(&mut h.app, "ui.horizontalConstraint").unwrap(); + for _ in 0..4 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + raster::raster(&mut h, &textures, output).save(dir.join(format!("{prefix}-both.png"))).unwrap(); + std::fs::write(dir.join(format!("{prefix}-both-model.png")), solidcraft_ui_egui::control::view_png(&h.app, 1000, 900).unwrap()) + .unwrap(); + } + } + } + theme::set_dark(previous); +} diff --git a/crates/ui-egui/tests/point_constraint_preselection.rs b/crates/ui-egui/tests/point_constraint_preselection.rs index 7c0765347..7f569260d 100644 --- a/crates/ui-egui/tests/point_constraint_preselection.rs +++ b/crates/ui-egui/tests/point_constraint_preselection.rs @@ -14,14 +14,15 @@ fn setup() -> Harness { #[test] fn clicked_point_constraint_preselection_applies_and_undoes_once() { + // Pick the edge away from its selectable MID; the point/edge constraint is unchanged. for (command, picks) in [ ("coincident", vec![[20, 20], [25, 30]]), - ("coincident", vec![[20, 20], [20, 10]]), - ("coincident", vec![[20, 10], [20, 20]]), - ("midpoint", vec![[20, 20], [20, 10]]), - ("midpoint", vec![[20, 10], [20, 20]]), - ("symmetry", vec![[20, 10], [20, 20], [25, 30]]), - ("symmetry", vec![[20, 20], [20, 10], [25, 30]]), + ("coincident", vec![[20, 20], [15, 10]]), + ("coincident", vec![[15, 10], [20, 20]]), + ("midpoint", vec![[20, 20], [15, 10]]), + ("midpoint", vec![[15, 10], [20, 20]]), + ("symmetry", vec![[15, 10], [20, 20], [25, 30]]), + ("symmetry", vec![[20, 20], [15, 10], [25, 30]]), ] { let mut h = setup(); for (index, pick) in picks.iter().enumerate() { @@ -54,7 +55,7 @@ fn clicked_point_constraint_preselection_applies_and_undoes_once() { assert!(((a + b) * 0.5 - start).cross(axis).abs() < 1e-6); assert!((b - a).dot(axis).abs() < 1e-6); } - _ if picks.contains(&[20, 10]) => assert!((a - start).cross(axis).abs() < 1e-6), + _ if picks.contains(&[15, 10]) => assert!((a - start).cross(axis).abs() < 1e-6), _ => assert!(a.dist(b) < 1e-6), } let after = h.app.session.doc.to_json();