From 162b3cd4ed1feb30ddcbad3df17c225996c6da07 Mon Sep 17 00:00:00 2001 From: Frank <58932224+plexi32@users.noreply.github.com> Date: Thu, 29 Oct 2026 16:09:18 +0000 Subject: [PATCH] Sketch Intersect: add Faces/Bodies and Projection Link options (#1110) (#7989) * Sketch Intersect: add Faces/Bodies and Projection Link options (#1110) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Sketch Project: add Geometry/Bodies and Projection Link options (#1110) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Sketch Project/Intersect: keep exact lines and arcs of whole bodies, no noisy rebuild warning (#1110) Whole-body silhouettes and sections fit lines and arcs tightly and snap arcs tangent to their neighbours. A rebuilt projection warns only when it removed the user's own constraints or curves. Pending locales cover ar, he and vi, and the preselection tests use the direct-pick workflow. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Select Other: label curves from Intersect as intersected (#1110) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../pending/sketch-intersect-options.json | 66 ++++++ crates/doc/src/project.rs | 142 ++++++++++-- crates/doc/src/project_order.rs | 29 +++ crates/engine/src/cmd/sketch_project.rs | 33 ++- crates/engine/src/cmd/sketch_project_tests.rs | 210 ++++++++++++++++++ crates/sketch/src/profiles.rs | 4 +- crates/sketch/src/tests.rs | 14 +- crates/ui-egui/src/dialogs.rs | 44 ++++ crates/ui-egui/src/dialogs_dense.rs | 26 +++ crates/ui-egui/src/dialogs_sketch_tests.rs | 76 +++++++ crates/ui-egui/src/lib.rs | 13 ++ crates/ui-egui/src/prefs.rs | 2 + crates/ui-egui/src/prefs/sketch.rs | 2 + crates/ui-egui/src/select_other.rs | 7 +- crates/ui-egui/src/select_other_tests.rs | 19 ++ crates/ui-egui/src/sketch_shortcut_tests.rs | 21 +- crates/ui-egui/src/sketch_tools.rs | 9 + .../ui-egui/tests/projection_preselection.rs | 2 + 18 files changed, 681 insertions(+), 38 deletions(-) create mode 100644 assets/locales/pending/sketch-intersect-options.json diff --git a/assets/locales/pending/sketch-intersect-options.json b/assets/locales/pending/sketch-intersect-options.json new file mode 100644 index 000000000..ff28ff5b6 --- /dev/null +++ b/assets/locales/pending/sketch-intersect-options.json @@ -0,0 +1,66 @@ +{ + "en": { + "prefs.project_options_dialog": "Project options dialog", + "prefs.project_options_dialog_note": "On: choose Geometry or Bodies and Projection Link before projecting. Off: keep the previous direct-pick workflow.", + "ui.sketch_intersect_geometry": "Geometry", + "ui.sketch_intersect_selection_filter": "Selection Filter", + "ui.sketch_intersect_projection_link": "Projection Link", + "ui.sketch_project_geometry": "Geometry" + }, + "ja": { + "prefs.project_options_dialog": "Projectのオプションダイアログ", + "prefs.project_options_dialog_note": "オン: 投影前に「ジオメトリ」または「ボディ」と「投影リンク」を選択します。オフ: 従来の直接選択方式を使用します。", + "ui.sketch_intersect_geometry": "ジオメトリ", + "ui.sketch_intersect_selection_filter": "選択フィルター", + "ui.sketch_intersect_projection_link": "投影リンク", + "ui.sketch_project_geometry": "ジオメトリ" + }, + "zh": { + "prefs.project_options_dialog": "Project 选项对话框", + "prefs.project_options_dialog_note": "开启:投影前选择“几何体”或“实体”以及“投影链接”。关闭:保留原有的直接选择工作流。", + "ui.sketch_intersect_geometry": "几何体", + "ui.sketch_intersect_selection_filter": "选择过滤器", + "ui.sketch_intersect_projection_link": "投影链接", + "ui.sketch_project_geometry": "几何体" + }, + "ar": { + "prefs.project_options_dialog": "مربع حوار خيارات Project", + "prefs.project_options_dialog_note": "تشغيل: اختر الهندسة أو الأجسام ورابط الإسقاط قبل الإسقاط. إيقاف: الإبقاء على سير العمل السابق بالاختيار المباشر.", + "ui.sketch_intersect_geometry": "الهندسة", + "ui.sketch_intersect_selection_filter": "مرشح التحديد", + "ui.sketch_intersect_projection_link": "رابط الإسقاط", + "ui.sketch_project_geometry": "الهندسة" + }, + "he": { + "prefs.project_options_dialog": "תיבת האפשרויות של Project", + "prefs.project_options_dialog_note": "פעיל: לבחור גאומטריה או גופים וקישור הטלה לפני ההטלה. כבוי: להשאיר את זרימת העבודה הקודמת של בחירה ישירה.", + "ui.sketch_intersect_geometry": "גאומטריה", + "ui.sketch_intersect_selection_filter": "מסנן בחירה", + "ui.sketch_intersect_projection_link": "קישור הטלה", + "ui.sketch_project_geometry": "גאומטריה" + }, + "vi": { + "prefs.project_options_dialog": "Hộp thoại tùy chọn Project", + "prefs.project_options_dialog_note": "Bật: chọn Hình học hoặc Thân và Liên kết chiếu trước khi chiếu. Tắt: giữ quy trình chọn trực tiếp trước đây.", + "ui.sketch_intersect_geometry": "Hình học", + "ui.sketch_intersect_selection_filter": "Bộ lọc lựa chọn", + "ui.sketch_intersect_projection_link": "Liên kết chiếu", + "ui.sketch_project_geometry": "Hình học" + }, + "de": { + "prefs.project_options_dialog": "Project-Optionendialog", + "prefs.project_options_dialog_note": "Ein: Vor dem Projizieren Geometrie oder Körper und die Projektionsverknüpfung auswählen. Aus: Den bisherigen Direktwahl-Ablauf beibehalten.", + "ui.sketch_intersect_geometry": "Geometrie", + "ui.sketch_intersect_selection_filter": "Auswahlfilter", + "ui.sketch_intersect_projection_link": "Projektionsverknüpfung", + "ui.sketch_project_geometry": "Geometrie" + }, + "ko": { + "prefs.project_options_dialog": "Project 옵션 대화상자", + "prefs.project_options_dialog_note": "켜기: 투영 전에 지오메트리 또는 바디와 투영 링크를 선택합니다. 끄기: 기존 직접 선택 작업 흐름을 유지합니다.", + "ui.sketch_intersect_geometry": "형상", + "ui.sketch_intersect_selection_filter": "선택 필터", + "ui.sketch_intersect_projection_link": "투영 링크", + "ui.sketch_project_geometry": "형상" + } +} diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index e77c24970..088995265 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -729,9 +729,14 @@ fn refresh_links_in( // Words built from text parameters change shape when the parameters do: that // rebuild is the text following them, not a reference that changed under it. let words_follow = matches!(&l.source, LinkSource::Text { exprs, .. } if exprs.text.is_some()); + let others = |sk: &Sketch| (sk.constraints.len(), sk.curves.len().saturating_sub(sk.link_curves(&l.id).len())); + let before = others(sk); match sk.update_link(&l.id, &r.geom) { Ok(true) if words_follow => {} - Ok(true) => warn.push(format!("projected {} changed shape and was rebuilt", l.source.describe())), + // A rebuilt projection is only worth a warning when it took something of + // the user's with it: a constraint, a dimension or a curve drawn on it. + Ok(true) if others(sk) == before => {} + Ok(true) => warn.push(format!("projected {} changed shape and was rebuilt; constraints on it were removed", l.source.describe())), Ok(false) if r.moved => warn.push(format!("projected {} was re-found on the nearest geometry", l.source.describe())), Ok(false) => {} Err(e) => { @@ -1079,7 +1084,7 @@ fn silhouette(plane: &Plane, m: &Mesh) -> Vec { }) .map(|(a, b, _)| (plane.to_local(*a), plane.to_local(*b))) .collect(); - fit_segments(&segs, size) + fit_segments(&segs, size, true) } /// Section of a mesh (or one of its faces) with the sketch plane. @@ -1088,7 +1093,13 @@ pub(crate) fn section(plane: &Plane, m: &Mesh, face: Option) -> Vec = segs.into_iter().map(|(a, b, _)| (a, b)).collect(); let loose = size * 2e-3; - fit_segments(&segs, size).into_iter().map(|g| refine_round(g, &exact, loose)).collect() + let refine = |v: Vec| -> Vec { v.into_iter().map(|g| refine_round(g, &exact, loose)).collect() }; + let lossy = refine(fit_segments(&segs, size, false)); + // Lines and arcs that follow the section closely (the corners of a rounded profile stay + // where they are) are kept when they take no more curves than the loose fit. + let close = refine(fit_segments(&segs, size, true)); + let plain = |v: &[LinkGeom]| v.iter().all(|g| matches!(g, LinkGeom::Line(..) | LinkGeom::Arc { .. } | LinkGeom::Circle(..))); + if plain(&close) && close.len() <= lossy.len() { close } else { lossy } } /// The segments where the plane crosses the mesh's triangles (in plane coordinates, each with @@ -1253,9 +1264,11 @@ fn refine_round(g: LinkGeom, exact: &[Vec2], tol: f64) -> LinkGeom { } /// Chain loose 2D segments into polylines (merging coincident ends) and fit each chain. -fn fit_segments(segs: &[(Vec2, Vec2)], size: f64) -> Vec { +fn fit_segments(segs: &[(Vec2, Vec2)], size: f64, preserve_arcs: bool) -> Vec { // Mesh chords stray from the surface by up to the display tolerance (1/1000 of the size). - let loose = Some(size * 2e-3); + // A silhouette's vertices lie on the surface, so it is fitted tightly: a loose fit lets a line + // swallow the start of a tangent arc, or an arc run on into the straight edge after it. + let loose = Some(if preserve_arcs { size * 1e-5 } else { size * 2e-3 }); let q = size * 1e-7; let key = |p: Vec2| ((p.x / q).round() as i64, (p.y / q).round() as i64); let mut nodes: BTreeMap<(i64, i64), (Vec2, Vec)> = BTreeMap::new(); @@ -1303,19 +1316,96 @@ fn fit_segments(segs: &[(Vec2, Vec2)], size: f64) -> Vec { for s in starts { while nodes.get(&s).is_some_and(|n| n.1.iter().any(|e| !used.get(*e).copied().unwrap_or(true))) { let c = walk(s, &mut used); - fit_chain(&c, loose, &mut out); + fit_chain_with_arcs(&c, loose, &mut out, preserve_arcs); } } let keys: Vec<(i64, i64)> = nodes.keys().copied().collect(); for s in keys { while nodes.get(&s).is_some_and(|n| n.1.iter().any(|e| !used.get(*e).copied().unwrap_or(true))) { let c = walk(s, &mut used); - fit_chain(&c, loose, &mut out); + fit_chain_with_arcs(&c, loose, &mut out, preserve_arcs); } } + if preserve_arcs { + snap_tangent_arcs(&mut out, size * 1e-3); + } out } +/// A fitted arc is only a least-squares circle: make it exactly tangent to the straight edges +/// it runs into, ending on them where they touch it, with one radius. +fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { + for i in 0..out.len() { + let Some(LinkGeom::Arc { c, a, b }) = out.get(i).cloned() else { continue }; + let r = (c.dist(a) + c.dist(b)) / 2.0; + // (arc end, line index, line end index, tangent point, unit normal towards the centre, centre distance) + let mut hits: Vec<(usize, usize, usize, Vec2, Vec2, f64)> = Vec::new(); + for (end, e) in [a, b].into_iter().enumerate() { + for (j, g) in out.iter().enumerate() { + let LinkGeom::Line(p, q) = g else { continue }; + let Some(u) = (*q - *p).normalized() else { continue }; + let foot = *p + u * (c - *p).dot(u); + let d = c.dist(foot); + if (d - r).abs() > tol || foot.dist(e) > 0.5 * r { + continue; + } + let Some(n) = (c - foot).normalized() else { continue }; + // The end of the line nearest the arc, and the tangent point must lie before it. + let (near, far) = if p.dist(e) <= q.dist(e) { (0, *q) } else { (1, *p) }; + let near_pt = if near == 0 { *p } else { *q }; + // The line must itself end next to the arc: not just lie on the same infinite line. + if (foot - far).dot(near_pt - far) <= 0.0 || near_pt.dist(foot) > 0.25 * r { + continue; + } + hits.push((end, j, near, foot, n, d)); + } + } + let mut hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [None, None]; + for (end, j, near, foot, n, d) in hits { + if let Some(slot) = hits_by_end.get_mut(end) + && slot.is_none() + { + *slot = Some((j, near, foot, n, d)); + } + } + let (mut c, mut r) = (c, r); + if let [Some((_, _, _, n1, d1)), Some((_, _, _, n2, d2))] = hits_by_end { + // One circle tangent to both lines: equal distance to each. + let det = n1.cross(n2); + if det.abs() > 1e-6 { + let m = (d1 + d2) / 2.0; + let (r1, r2) = (m - d1, m - d2); + let delta = Vec2::new((r1 * n2.y - r2 * n1.y) / det, (n1.x * r2 - n2.x * r1) / det); + c += delta; + r = m; + } + } else if let [Some((_, _, _, _, d)), None] | [None, Some((_, _, _, _, d))] = hits_by_end { + r = d; + } + let on = |q: Vec2| c + (q - c).normalized().unwrap_or(Vec2::X) * r; + let (mut na, mut nb) = (on(a), on(b)); + for (end, hit) in hits_by_end.into_iter().enumerate() { + let Some((j, near, _, n, _)) = hit else { continue }; + let t = c - n * r; + if let Some(LinkGeom::Line(p, q)) = out.get_mut(j) { + if near == 0 { + *p = t; + } else { + *q = t; + } + } + if end == 0 { + na = t; + } else { + nb = t; + } + } + if let Some(LinkGeom::Arc { c: cc, a: aa, b: bb }) = out.get_mut(i) { + (*cc, *aa, *bb) = (c, na, nb); + } + } +} + // --------------------------------------------------------------------------------------------- // Fitting @@ -1392,9 +1482,9 @@ fn fits_line(p: &[Vec2], tol: f64) -> bool { /// Circle through the chain (centre, radius, signed sweep from the first to the last point). /// `exact`: the points lie on the curve (edge tessellation), else they are approximate /// (mesh sections and silhouettes) and the circle is a least-squares fit. -fn fits_circle(p: &[Vec2], tol: f64, exact: bool) -> Option<(Vec2, f64, f64)> { +fn fits_circle(p: &[Vec2], tol: f64, exact: bool, preserve_arcs: bool) -> Option<(Vec2, f64, f64)> { let n = p.len(); - if n < 3 || (!exact && n < 5) { + if n < 3 || (!exact && !preserve_arcs && n < 5) { return None; } let closed = p.first()?.dist(*p.last()?) <= tol; @@ -1442,6 +1532,10 @@ fn arc_geom(p: &[Vec2], c: Vec2, r: f64, sweep: f64, tol: f64) -> Option, out: &mut Vec) { + fit_chain_with_arcs(raw, loose, out, false); +} + +fn fit_chain_with_arcs(raw: &[Vec2], loose: Option, out: &mut Vec, preserve_arcs: bool) { let mut p: Vec = Vec::with_capacity(raw.len()); let scale = raw.iter().fold(0.0_f64, |m, q| m.max(q.x.abs()).max(q.y.abs())).max(1.0); let ext = match ( @@ -1491,10 +1585,12 @@ pub(crate) fn fit_chain(raw: &[Vec2], loose: Option, out: &mut Vec 0.0, } }; - let corners: Vec = (0..n).filter(|i| turn(*i) > 30f64.to_radians()).collect(); + // A coarsely tessellated round turns up to ~35 degrees per chord; keep those together. + let corner_turn = if preserve_arcs { 50f64 } else { 30f64 }.to_radians(); + let corners: Vec = (0..n).filter(|i| turn(*i) > corner_turn).collect(); let cut = |a: usize, b: usize, out: &mut Vec| { if let Some(s) = p.get(a..=b) { - fit_piece(s, tol, exact, out); + fit_piece(s, tol, exact, preserve_arcs, out); } }; if closed && let Some(&c0) = corners.first() { @@ -1508,7 +1604,7 @@ pub(crate) fn fit_chain(raw: &[Vec2], loose: Option, out: &mut Vec, out: &mut Vec) { +fn fit_piece(p: &[Vec2], tol: f64, exact: bool, preserve_arcs: bool, out: &mut Vec) { if p.len() < 2 { return; } + // A near-straight run is a line, not an arc of huge radius. + let curved = |sw: f64| !preserve_arcs || exact || sw.abs() >= 20f64.to_radians(); + let fitted_arc = || fits_circle(p, tol, exact, preserve_arcs).filter(|(_, _, sw)| curved(*sw)).and_then(|(c, r, sw)| arc_geom(p, c, r, sw, tol)); + if preserve_arcs + && (exact || p.len() >= 4) + && let Some(g) = fitted_arc() + { + out.push(g); + return; + } if fits_line(p, tol) { if let (Some(a), Some(b)) = (p.first(), p.last()) { out.push(LinkGeom::Line(*a, *b)); } return; } - if let Some((c, r, sw)) = fits_circle(p, tol, exact) - && let Some(g) = arc_geom(p, c, r, sw, tol) - { + if !preserve_arcs && let Some(g) = fitted_arc() { out.push(g); return; } @@ -1553,7 +1657,7 @@ fn fit_piece(p: &[Vec2], tol: f64, exact: bool, out: &mut Vec) { let mut jc = i + 1; let mut arc = None; while jc + 1 < n { - match p.get(i..=jc + 1).and_then(|s| fits_circle(s, tol, exact)) { + match p.get(i..=jc + 1).and_then(|s| fits_circle(s, tol, exact, preserve_arcs)) { Some(f) => { arc = Some(f); jc += 1; @@ -1563,7 +1667,7 @@ fn fit_piece(p: &[Vec2], tol: f64, exact: bool, out: &mut Vec) { } if jc >= jl + 2 && jc - i >= 3 - && let Some((c, r, sw)) = arc + && let Some((c, r, sw)) = arc.filter(|(_, _, sw)| curved(*sw)) && let Some(g) = p.get(i..=jc).and_then(|s| arc_geom(s, c, r, sw, tol)) { out.push(g); diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs index d6fdace2a..f59cdfa79 100644 --- a/crates/doc/src/project_order.rs +++ b/crates/doc/src/project_order.rs @@ -206,6 +206,35 @@ mod tests { assert!(family_edges(&mesh, &selected, &Plane::XY).is_err()); } + #[test] + fn coarsely_tessellated_round_silhouette_fits_an_arc() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let on = |deg: f64| Vec2::new(5. + 5. * deg.to_radians().cos(), 5. + 5. * deg.to_radians().sin()); + let mut chain = vec![Vec2::new(0., -20.)]; + chain.extend([180., 169.5, 135., 100.5, 90.].map(on)); + chain.push(Vec2::new(45., 10.)); + let mut out = Vec::new(); + super::super::fit_chain_with_arcs(&chain, Some(0.05), &mut out, true); + assert!(out.iter().any(|g| matches!(g, LinkGeom::Arc { .. })), "{out:?}"); + } + + #[test] + fn tangent_snapping_leaves_unrelated_collinear_lines_alone() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + // A rounded corner of radius 2 meeting the top edge, and an unrelated collinear edge. + let mut out = vec![ + LinkGeom::Line(v(21., 8.), v(25., 8.)), + LinkGeom::Arc { c: v(2.0008, 5.9992), a: v(2.2808, 8.0), b: v(0., 6.0) }, + LinkGeom::Line(v(2.0668, 8.), v(48., 8.)), + ]; + super::super::snap_tangent_arcs(&mut out, 0.05); + assert_eq!(out.first(), Some(&LinkGeom::Line(v(21., 8.), v(25., 8.)))); + let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.get(1), out.get(2)) else { panic!("{out:?}") }; + assert!(a.dist(*p) < 1e-9, "{out:?}"); + } #[test] fn boundaries_touching_at_a_vertex_project() { // Two squares of one face family meet only at the corner (1, 1): four boundary edges meet diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rs index e0603c73e..e7b830e96 100644 --- a/crates/engine/src/cmd/sketch_project.rs +++ b/crates/engine/src/cmd/sketch_project.rs @@ -21,9 +21,11 @@ macro_rules! refs_doc { } pub static COMMANDS: &[CommandSpec] = &[ - CommandSpec::new("sketch.project", "Project", project_cmd).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).params(concat!(refs_doc!(), created_doc!())), + CommandSpec::new("sketch.project", "Project", project_cmd).at("SKETCH", "CREATE").icon("project").key("P").enabled(in_sketch).params( + concat!(refs_doc!(), "; projection_link?: bool (default true)", created_doc!()), + ), CommandSpec::new("sketch.intersect", "Intersect", intersect_cmd).at("SKETCH", "CREATE").icon("intersect").enabled(in_sketch).params( - concat!("refs: [{body}, {face: [x,y,z], body?}, {edge: [x,y,z], body?}, {sketch, curve}]: section curves (or points) with the sketch plane, linked", created_doc!()), + concat!("refs: [{body}, {face: [x,y,z], body?}, {edge: [x,y,z], body?}, {sketch, curve}]: section curves (or points) with the sketch plane; projection_link?: bool (default true)", created_doc!()), ), CommandSpec::new("sketch.include_3d", "Include 3D Geometry", include_cmd) .at("SKETCH", "CREATE") @@ -307,7 +309,7 @@ fn link_json(sk: &Sketch, link: &str) -> Value { json!({"link": link, "curves": curves, "points": points}) } -fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind) -> Result { +fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind, projection_link: bool) -> Result { let refs: Vec = match p.get("refs").or_else(|| p.get("ref")) { Some(Value::Array(a)) => a.iter().take(1000).cloned().collect(), Some(v) => vec![v.clone()], @@ -327,7 +329,14 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind) -> Result out.push(link_json(sk, &l)), + Ok(Some(l)) => { + let mut result = link_json(sk, &l); + if !projection_link { + result["link"] = Value::Null; + sk.break_link(&l)?; + } + out.push(result); + } Ok(None) => present.push(what), Err(e) => return Err(bad(cmd, format!("{what}: {e}"))), } @@ -346,15 +355,25 @@ fn run_links(s: &mut Session, p: &Value, cmd: &str, kind: LinkKind) -> Result Result { - run_links(s, p, "sketch.project", LinkKind::Project) + let projection_link = match p.get("projection_link") { + None => true, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad("sketch.project", "`projection_link` must be a boolean")), + }; + run_links(s, p, "sketch.project", LinkKind::Project, projection_link) } fn intersect_cmd(s: &mut Session, p: &Value) -> Result { - run_links(s, p, "sketch.intersect", LinkKind::Intersect) + let projection_link = match p.get("projection_link") { + None => true, + Some(Value::Bool(value)) => *value, + Some(_) => return Err(bad("sketch.intersect", "`projection_link` must be a boolean")), + }; + run_links(s, p, "sketch.intersect", LinkKind::Intersect, projection_link) } fn include_cmd(s: &mut Session, p: &Value) -> Result { - run_links(s, p, "sketch.include_3d", LinkKind::Include) + run_links(s, p, "sketch.include_3d", LinkKind::Include, true) } /// A constraint's operands may be model geometry (#6348): an `{edge: [x,y,z], body?}` or diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 066c5bc41..7204ee9c4 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -216,6 +216,20 @@ fn project_edges_bodies_sketches_and_origin() { assert!(s.execute("sketch.project", &json!({"refs": [{"plane": "XY"}]})).is_err(), "parallel plane projects to nothing"); } +#[test] +fn project_whole_body_can_create_unlinked_geometry() { + let mut s = Session::default(); + box_part(&mut s); + let sketch = run(&mut s, "sketch.create", json!({"plane":"XY"}))["sketch"].as_u64().unwrap(); + let body = s.model.state().bodies[0].name.clone(); + let r = run(&mut s, "sketch.project", json!({"refs":[{"body":body}],"projection_link":false})); + assert_eq!(r["links"][0]["link"], Value::Null); + let sk = s.doc.sketch(sketch).unwrap(); + assert!(sk.links.is_empty()); + assert_eq!(sk.curves.len(), 4); + assert!(s.execute("sketch.project", &json!({"refs":[{"body":body}],"projection_link":"false"})).is_err()); +} + #[test] fn intersect_cuts_a_body_with_the_sketch_plane() { let mut s = Session::default(); @@ -873,3 +887,199 @@ fn intersect_on_a_top_face_gives_its_outline() { ends.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]]); } + +#[test] +fn intersect_whole_body_can_create_unlinked_section_geometry() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Post"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 10})); + + let result = run(&mut s, "sketch.intersect", json!({"refs": [{"body": "Post"}], "projection_link": false})); + assert_eq!(result["links"][0]["link"], Value::Null, "{result}"); + assert_eq!(result["links"][0]["curves"].as_array().unwrap().len(), 4, "{result}"); + + let sketch = s.doc.sketch(s.active_sketch.unwrap()).unwrap(); + assert!(sketch.links.is_empty(), "projection links were disabled"); + assert_eq!(sketch.curves.len(), 4, "the whole body's section remains as normal sketch geometry"); + assert!(s.execute("sketch.intersect", &json!({"refs": [{"body": "Post"}], "projection_link": "false"})).is_err()); +} + +#[test] +fn whole_body_project_preserves_the_arc_of_a_chamfered_round_edge() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Plate"})); + run(&mut s, "solid.fillet", json!({"edges": [[40, 0, 10]], "radius": 5})); + let sketch = run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 20]}, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate"}]})); + run(&mut s, "sketch.finish", json!({})); + + run(&mut s, "timeline.roll_to", json!({"position": 2})); + run(&mut s, "solid.chamfer", json!({"edges": [[40, 15, 20]], "distance": 1})); + run(&mut s, "timeline.roll_to", json!({})); + + let result = s.model.result(sketch).unwrap(); + let state = s.model.state(); + let solved = state.sketch(sketch).unwrap(); + let sketch = &solved.sketch; + assert!(result.error.is_none(), "{:?}", result.error); + assert!(result.warning.is_none(), "a rebuilt projection nothing depends on needs no warning: {:?}", result.warning); + assert!((solved.plane.origin.z - 20.).abs() < 1e-6); + assert!( + sketch.curves.iter().any(|curve| matches!(curve.kind, solidcraft_sketch::CurveKind::Arc { .. })), + "the rounded chamfer silhouette should contain an arc, not only line segments: {:?}", + sketch.curves + ); +} + +#[test] +fn whole_body_project_stays_on_the_body_outline_after_a_late_chamfer() { + use solidcraft_sketch::CurveKind; + let planes: [([i32; 3], &str); 3] = [([20, 15, 20], "top"), ([20, 0, 10], "front"), ([40, 15, 10], "side")]; + let chamfers: [[i32; 3]; 4] = [[40, 15, 20], [20, 0, 20], [40, 0, 10], [38, 2, 20]]; + for (face, plane) in planes { + for chamfer in chamfers { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Plate"})); + run(&mut s, "solid.fillet", json!({"edges": [[40, 0, 10]], "radius": 5})); + let sketch = run(&mut s, "sketch.create", json!({"plane": {"face": face}, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate"}]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "timeline.roll_to", json!({"position": 2})); + if s.execute("solid.chamfer", &json!({"edges": [chamfer], "distance": 1})).is_err() { + continue; + } + run(&mut s, "timeline.roll_to", json!({})); + let state = s.model.state(); + let solved = state.sketch(sketch).unwrap(); + let sk = &solved.sketch; + let pts: Vec<_> = sk.points.iter().map(|p| p.pos).collect(); + let (x0, x1) = pts.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.x), a.1.max(p.x))); + let (y0, y1) = pts.iter().fold((f64::MAX, f64::MIN), |a, p| (a.0.min(p.y), a.1.max(p.y))); + let mut worst = 0.0_f64; + for curve in &sk.curves { + if let CurveKind::Arc { c, a, b } = curve.kind { + let (c, a, b) = (pts[c], pts[a], pts[b]); + let r = c.dist(a); + let (t0, mut sweep) = ((a - c).angle(), (b - c).angle() - (a - c).angle()); + while sweep < 0.0 { + sweep += std::f64::consts::TAU; + } + for i in 0..=16 { + let t = t0 + sweep * f64::from(i) / 16.0; + let q = solidcraft_geom::Vec2::new(c.x + r * t.cos(), c.y + r * t.sin()); + worst = worst.max((x0 - q.x).max(q.x - x1).max(y0 - q.y).max(q.y - y1)); + } + assert!(sweep < std::f64::consts::PI + 0.01, "{plane} {chamfer:?}: arc sweeps {sweep} rad, not a rounded corner"); + } + } + assert!(worst < 0.01, "{plane} {chamfer:?}: an arc leaves the body outline by {worst}"); + } + } +} + +#[test] +fn whole_body_project_of_a_filleted_plate_keeps_exact_lines_and_arcs() { + use solidcraft_sketch::CurveKind; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 8, "body_name": "Plate"})); + run(&mut s, "solid.fillet", json!({"edges": [[0, 0, 4], [80, 0, 4], [80, 50, 4], [0, 50, 4]], "radius": 6})); + let sketch = run(&mut s, "sketch.create", json!({"plane": "YZ", "offset": 36, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate"}]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "timeline.roll_to", json!({"position": 2})); + let top = [[40., 0.], [1.7574, 1.7574], [78.2426, 1.7574], [80., 25.], [78.2426, 48.2426], [40., 50.], [1.7574, 48.2426], [0., 25.]]; + let edges: Vec<_> = top.iter().map(|p| json!([p[0], p[1], 8])).collect(); + run(&mut s, "solid.fillet", json!({"edges": edges, "radius": 2})); + run(&mut s, "timeline.roll_to", json!({})); + + let state = s.model.state(); + let sk = &state.sketch(sketch).unwrap().sketch; + let pos = |i: usize| sk.points[i].pos; + let mut arcs = Vec::new(); + for curve in &sk.curves { + match curve.kind { + CurveKind::Line { a, b } => { + let d = pos(b) - pos(a); + assert!(d.x.abs() < 1e-3 || d.y.abs() < 1e-3, "slanted line {:?} -> {:?}", pos(a), pos(b)); + } + CurveKind::Arc { c, a, .. } => arcs.push(pos(c).dist(pos(a))), + _ => {} + } + } + assert_eq!(arcs.len(), 2, "{arcs:?}"); + assert!(arcs.iter().all(|r| (r - 2.).abs() < 5e-3), "{arcs:?}"); + // Every arc end is exactly the end of a straight edge, and meets it tangentially. + for curve in &sk.curves { + let CurveKind::Arc { c, a, b } = curve.kind else { continue }; + for end in [a, b] { + let touching = sk + .curves + .iter() + .filter(|o| matches!(o.kind, CurveKind::Line { a: p, b: q } if pos(p).dist(pos(end)) < 1e-6 || pos(q).dist(pos(end)) < 1e-6)) + .count(); + assert!(touching >= 1, "arc end {:?} meets no line end", pos(end)); + let radial = pos(end) - pos(c); + assert!((radial.len() - 2.).abs() < 5e-3); + } + } +} + +#[test] +fn whole_body_intersect_of_a_filleted_plate_keeps_exact_lines_and_arcs() { + use solidcraft_sketch::CurveKind; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 80, "width": 50, "height": 8, "body_name": "Plate"})); + let sketch = run(&mut s, "sketch.create", json!({"plane": "YZ", "offset": 36, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.intersect", json!({"refs": [{"body": "Plate"}]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "timeline.roll_to", json!({"position": 1})); + let top = [[40., 0.], [80., 25.], [40., 50.], [0., 25.]]; + let edges: Vec<_> = top.iter().map(|p| json!([p[0], p[1], 8])).collect(); + run(&mut s, "solid.fillet", json!({"edges": edges, "radius": 2})); + run(&mut s, "timeline.roll_to", json!({})); + + let result = s.model.result(sketch).unwrap().warning.clone(); + assert!(result.is_none(), "{result:?}"); + let state = s.model.state(); + let sk = &state.sketch(sketch).unwrap().sketch; + let pos = |i: usize| sk.points[i].pos; + let mut arcs = Vec::new(); + for curve in &sk.curves { + match curve.kind { + CurveKind::Line { a, b } => { + let d = pos(b) - pos(a); + assert!(d.x.abs() < 1e-3 || d.y.abs() < 1e-3, "slanted line {:?} -> {:?}", pos(a), pos(b)); + } + CurveKind::Arc { c, a, .. } => arcs.push(pos(c).dist(pos(a))), + _ => {} + } + } + assert_eq!(sk.curves.len(), 6, "{} curves", sk.curves.len()); + assert_eq!(arcs.len(), 2, "{arcs:?}"); + assert!(arcs.iter().all(|r| (r - 2.).abs() < 5e-3), "{arcs:?}"); +} +#[test] +fn a_rebuilt_projection_keeps_user_constraints_without_a_warning() { + for dimensioned in [false, true] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "body_name": "Plate"})); + run(&mut s, "solid.fillet", json!({"edges": [[40, 0, 10]], "radius": 5})); + let sketch = run(&mut s, "sketch.create", json!({"plane": {"face": [20, 15, 20]}, "project_edges": false}))["sketch"].as_u64().unwrap(); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Plate"}]})); + if dimensioned { + // A line of the user's, pinned to the projected corner. + let line = ids(&run(&mut s, "sketch.line", json!({"points": [[5, 5], [10, 5]]}))["curves"]); + run(&mut s, "sketch.constraint.coincident", json!({"a": format!("{}.start", line[0]), "b": "p4"})); + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "timeline.roll_to", json!({"position": 2})); + run(&mut s, "solid.chamfer", json!({"edges": [[40, 15, 20]], "distance": 1})); + run(&mut s, "timeline.roll_to", json!({})); + let warning = s.model.result(sketch).unwrap().warning.clone(); + let st = s.model.state(); + let k = &st.sketch(sketch).unwrap().sketch; + // The user's constraint survives the rebuild, so there is nothing to warn about. + assert_eq!(k.constraints.len(), usize::from(dimensioned)); + assert!(warning.is_none(), "{warning:?}"); + } +} diff --git a/crates/sketch/src/profiles.rs b/crates/sketch/src/profiles.rs index 956b8eab1..db843c19c 100644 --- a/crates/sketch/src/profiles.rs +++ b/crates/sketch/src/profiles.rs @@ -608,9 +608,11 @@ pub fn find_drawn_profiles(sk: &Sketch) -> Vec { if sk.links.iter().all(|l| l.kind == crate::LinkKind::Text) { return find_profiles(sk); } + let intersect_links: std::collections::HashSet<&str> = + sk.links.iter().filter(|link| link.kind == crate::LinkKind::Intersect).map(|link| link.id.as_str()).collect(); let mut d = sk.clone(); for (ci, c) in d.curves.iter_mut().enumerate() { - if c.link.is_some() && !sk.is_text_curve(ci) { + if c.link.as_ref().is_some_and(|link| !intersect_links.contains(link.as_str())) && !sk.is_text_curve(ci) { c.construction = true; } } diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index 11b19ab60..3bf233a73 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -831,17 +831,19 @@ fn text_beside_other_curves_is_drawn_geometry() { } assert_areas(&sorted_areas(&find_drawn_profiles(&sk)), vec![13.5557, 600.0]); // Projected reference geometry still doesn't count as drawn. - let square = |s: f64| { + let square = |x: f64, s: f64| { vec![ - LinkGeom::Line(v(100.0, 0.0), v(100.0 + s, 0.0)), - LinkGeom::Line(v(100.0 + s, 0.0), v(100.0 + s, s)), - LinkGeom::Line(v(100.0 + s, s), v(100.0, s)), - LinkGeom::Line(v(100.0, s), v(100.0, 0.0)), + LinkGeom::Line(v(x, 0.0), v(x + s, 0.0)), + LinkGeom::Line(v(x + s, 0.0), v(x + s, s)), + LinkGeom::Line(v(x + s, s), v(x, s)), + LinkGeom::Line(v(x, s), v(x, 0.0)), ] }; - sk.add_link(LinkKind::Project, LinkSource::Origin, &square(5.0)).unwrap(); + sk.add_link(LinkKind::Project, LinkSource::Origin, &square(100.0, 5.0)).unwrap(); assert_eq!(find_profiles(&sk).len(), 3); assert_areas(&sorted_areas(&find_drawn_profiles(&sk)), vec![13.5557, 600.0]); + sk.add_link(LinkKind::Intersect, LinkSource::Origin, &square(110.0, 7.0)).unwrap(); + assert_areas(&sorted_areas(&find_drawn_profiles(&sk)), vec![13.5557, 49.0, 600.0]); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4737b92c1..af5c63b32 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -97,6 +97,8 @@ const WALL_LABELS: [&str; 4] = ["Center", "Inside", "Outside", "Two Sides"]; /// What an extrude's first input picks: profiles or planar faces, or curves too when thin. const EXTRUDE_ACCEPT: Accept = PROFILES | PLANAR_FACES; const THIN_ACCEPT: Accept = PROFILES | CURVES; +const PROJECT_GEOMETRY: Accept = + EDGES | FACES | selection::VERTICES | PLANES | AXES | selection::SKETCH_LINES | selection::EXTERNAL_POINTS | selection::ORIGIN; const HOLE_TYPES: [&str; 3] = ["simple", "counterbore", "countersink"]; const HOLE_LABELS: [&str; 3] = ["Simple", "Counterbore", "Countersink"]; @@ -388,6 +390,14 @@ crate::dialog_descriptor::dialog_descriptors! { /// Sketch-space modify tools: scale and offset, and later fillet, chamfer, the patterns, /// mirror and move (`sketch_modify_ui`). SketchModify(crate::sketch_modify_ui::Mod), + SketchIntersect { + bodies: bool, + projection_link: bool, + }, + SketchProject { + bodies: bool, + projection_link: bool, + }, } } } @@ -797,6 +807,20 @@ impl Dialog { let has_bodies = !s.world_state().bodies.is_empty(); let mut d = match id { "sketch.create" => Dialog::new(Kind::Sketch, vec![SelInput::new("Plane", PLANES | PLANAR_FACES, false)]), + "sketch.intersect" => { + let bodies = s.selection.iter().any(|sel| matches!(sel, Sel::Body { .. })); + Dialog::new( + Kind::SketchIntersect { bodies, projection_link: true }, + vec![SelInput::new("ui.sketch_intersect_geometry", if bodies { BODIES } else { FACES }, true)], + ) + } + "sketch.project" => { + let bodies = s.selection.iter().any(|sel| matches!(sel, Sel::Body { .. })); + Dialog::new( + Kind::SketchProject { bodies, projection_link: true }, + vec![SelInput::new("ui.sketch_project_geometry", if bodies { BODIES } else { PROJECT_GEOMETRY }, true)], + ) + } "solid.extrude" => Dialog::new( Kind::Extrude { distance: length_default(s, "10"), @@ -2122,6 +2146,8 @@ fn publish_check(ui: &egui::Ui, response: &egui::Response, selected: bool) { fn title(k: &Kind) -> &'static str { match k { Kind::Sketch => "CREATE SKETCH", + Kind::SketchIntersect { .. } => "INTERSECT", + Kind::SketchProject { .. } => "PROJECT", Kind::Extrude { .. } => "EXTRUDE", Kind::Revolve { .. } => "REVOLVE", Kind::Fillet { chamfer: false, .. } => "FILLET", @@ -4752,6 +4778,24 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S Kind::EditParam { name, expr } => ("parameters.change", json!({"name": name, "expression": expr})), Kind::Rename { feature, name } => ("timeline.rename", json!({"feature": feature, "name": name})), Kind::ConfirmDelete { features, groups, .. } => ("timeline.delete", crate::timeline::delete_params(features, groups)), + Kind::SketchIntersect { projection_link, .. } => { + need(0, "faces or bodies")?; + let refs = sels(d, 0) + .iter() + .map(|sel| match sel { + Sel::Body { name } => Ok(json!({"body": name})), + Sel::Face { body, point, .. } => Ok(json!({"face": [point.x, point.y, point.z], "body": body})), + _ => Err("select faces or bodies".to_string()), + }) + .collect::, _>>()?; + ("sketch.intersect", json!({"refs": refs, "projection_link": projection_link})) + } + Kind::SketchProject { projection_link, .. } => { + need(0, "geometry or bodies")?; + let refs = + crate::tools::projection_preselection(sels(d, 0)).ok_or_else(|| "select geometry or bodies that can be projected".to_string())?; + ("sketch.project", json!({"refs": refs, "projection_link": projection_link})) + } Kind::Sketch | Kind::Measure { .. } => return Ok(Vec::new()), Kind::Assembly(k) => return crate::dialogs_assembly::commands(app, k, &d.inputs), Kind::Sheet(k) => return crate::dialogs_sheet::commands(app, k, &d.inputs, &d.extra), diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 793933d79..2c0701fb3 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -19,6 +19,8 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> { Kind::ViewDxf { .. } => Some("file.export_view_dxf"), Kind::InsertDrawing(p) => Some(if p.command.ends_with("dxf") { "sketch.insert_dxf" } else { "sketch.insert_svg" }), Kind::Sketch => Some("sketch.create"), + Kind::SketchIntersect { .. } => Some("sketch.intersect"), + Kind::SketchProject { .. } => Some("sketch.project"), Kind::SketchModify(k) => Some(crate::sketch_modify_ui::command(k)), Kind::Text(_) => Some("sketch.edit_text"), Kind::TextMove(_) => Some("sketch.move"), @@ -212,6 +214,30 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: } } } + Kind::SketchIntersect { bodies, projection_link } => { + let mut selected = if *bodies { 1 } else { 0 }; + let changed = ui_kit::row(ui, tr("ui.sketch_intersect_selection_filter"), |ui| { + ui_kit::segmented(ui, &mut selected, &[tr("Faces"), tr("Bodies")], Default::default()) + }); + if changed && let Some(input) = d.inputs.first_mut() { + *bodies = selected == 1; + input.accept = if *bodies { BODIES } else { FACES }; + input.items.clear(); + } + ui_kit::row(ui, tr("ui.sketch_intersect_projection_link"), |ui| ui_kit::checkbox(ui, "", projection_link)); + } + Kind::SketchProject { bodies, projection_link } => { + let mut selected = if *bodies { 1 } else { 0 }; + let changed = ui_kit::row(ui, tr("ui.sketch_intersect_selection_filter"), |ui| { + ui_kit::segmented(ui, &mut selected, &[tr("Geometry"), tr("Bodies")], Default::default()) + }); + if changed && let Some(input) = d.inputs.first_mut() { + *bodies = selected == 1; + input.accept = if *bodies { BODIES } else { super::PROJECT_GEOMETRY }; + input.items.clear(); + } + ui_kit::row(ui, tr("ui.sketch_intersect_projection_link"), |ui| ui_kit::checkbox(ui, "", projection_link)); + } Kind::SketchModify(k) => enter |= crate::sketch_modify_ui::rows(ui, k, &app.session.doc), Kind::Text(k) => enter |= crate::sketch_text::rows(ui, k, &mut d.inputs, &mut d.active), Kind::TextMove(k) => enter |= crate::sketch_text_move::rows(ui, k), diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index f28699998..c58298fc0 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -101,6 +101,82 @@ fn create_sketch_uses_card_and_still_starts_immediately_on_plane_pick() { assert!(h.app.session.active_sketch.is_some()); } +#[test] +fn intersect_dialog_filters_faces_or_whole_bodies_and_controls_projection_link() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Post"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY","offset":10})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Post".into() }]; + h.app.start("sketch.intersect"); + h.frames(4); + + let d = h.app.dialog.as_ref().expect("Intersect opens an options dialog"); + assert!(matches!(d.kind, Kind::SketchIntersect { bodies: true, projection_link: true })); + assert_eq!(d.inputs[0].accept, super::BODIES); + assert_eq!(d.inputs[0].items, vec![Sel::Body { name: "Post".into() }]); + assert!(scenario::rect_of("dialog:row:ui.sketch_intersect_geometry").is_some()); + assert!(scenario::handle_at("dialog:Selection Filter:Faces").is_some()); + assert!(scenario::handle_at("dialog:Selection Filter:Bodies").is_some()); + assert!(scenario::rect_of("dialog:row:Projection Link").is_some()); + + h.step(&json!({"click":{"handle":"dialog:Selection Filter:Faces"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].accept, super::FACES); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); + h.step(&json!({"click":{"handle":"dialog:Selection Filter:Bodies"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].accept, super::BODIES); + h.step(&json!({"click":{"handle":"dialog:Projection Link"}})).unwrap(); + assert!(matches!(h.app.dialog.as_ref().unwrap().kind, Kind::SketchIntersect { projection_link: false, .. })); + + { + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Body { name: "Post".into() }]; + } + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(apply_commands(&h.app, d).unwrap(), vec![("sketch.intersect".into(), json!({"refs":[{"body":"Post"}],"projection_link":false}))]); +} + +#[test] +fn project_dialog_keeps_geometry_targets_and_can_project_whole_bodies_unlinked() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Plate"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY","offset":10})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Plate".into() }]; + h.app.start("sketch.project"); + h.frames(4); + + let d = h.app.dialog.as_ref().expect("Project opens an options dialog"); + assert!(matches!(d.kind, Kind::SketchProject { bodies: true, projection_link: true })); + assert_eq!(d.inputs[0].accept, super::BODIES); + assert_eq!(d.inputs[0].items, vec![Sel::Body { name: "Plate".into() }]); + assert!(scenario::handle_at("dialog:Selection Filter").is_some()); + assert!(scenario::rect_of("dialog:row:Projection Link").is_some()); + + h.step(&json!({"click":{"handle":"dialog:Selection Filter"}})).unwrap(); + assert!(scenario::handle_at("dialog:Selection Filter:Geometry").is_some()); + h.step(&json!({"click":{"handle":"dialog:Selection Filter:Geometry"}})).unwrap(); + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].accept, super::PROJECT_GEOMETRY); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); + h.step(&json!({"click":{"handle":"dialog:Selection Filter"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Selection Filter:Bodies"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Projection Link"}})).unwrap(); + assert!(matches!(h.app.dialog.as_ref().unwrap().kind, Kind::SketchProject { projection_link: false, .. })); + + { + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Body { name: "Plate".into() }]; + } + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(apply_commands(&h.app, d).unwrap(), vec![("sketch.project".into(), json!({"refs":[{"body":"Plate"}],"projection_link":false}))]); + h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap(); + h.settle(); + assert!(h.app.dialog.is_none()); + let sketch = h.app.session.active_sketch.expect("Project leaves the sketch active"); + let state = h.app.session.world_state(); + let sketch = &state.sketch(sketch).unwrap().sketch; + assert!(sketch.links.is_empty()); + assert!(!sketch.curves.is_empty()); +} + #[test] fn apply_commits_once_keeps_values_and_waits_for_new_selection_ok_closes() { for command in ["sketch.offset", "sketch.mirror", "sketch.pattern.rectangular", "sketch.pattern.circular"] { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f4ba4e0a9..886239139 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1704,6 +1704,19 @@ impl SolveApp { { self.last_command = Some((spec.id.to_string(), spec.label.to_string())); } + if id == "sketch.project" + && self.preferences.project_options_dialog + && let Some(mut d) = dialogs::Dialog::for_command(self, id) + { + if let Some(sketch) = finished_sketch { + d.take_sketch_profile(&self.session, sketch); + } + if d.wants_picks() && !self.session.selection.is_empty() { + let _ = self.session.execute("select.clear", &json!({})); + } + self.dialog = Some(d); + return; + } if let Some(mut t) = tools::Tool::for_command(id) { let state = self.session.world_state(); let sketch = self.session.active_sketch.and_then(|s| state.sketch(s)).map(|ss| &ss.sketch); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index a1bc93599..0a8461d19 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1224,6 +1224,8 @@ preference_settings! { suppress_sketch_snap: ModifierCombo = ModifierCombo::CTRL_ALT, PAGE_SKETCH; /// Temporary horizontal/vertical guides from hovered centres and edge midpoints. sketch_tracking_guides: bool = true, PAGE_SKETCH; + /// Open Project's options before picking; off restores its previous direct-pick workflow. + project_options_dialog: bool = true, PAGE_SKETCH; /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). manipulator_free_alt: bool = true, PAGE_SKETCH; /// A sketch's icon in History and the browser takes the colour of its solve state, and its diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index 3ace7d3f1..87facca5e 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -11,6 +11,8 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if ui_kit::checkbox(ui, crate::i18n::tr_label("Project face edges into new sketches"), &mut auto).changed() { let _ = app.run("sketch.auto_project", json!({"value": auto})); } + ui_kit::checkbox(ui, app.tr("prefs.project_options_dialog"), &mut app.preferences.project_options_dialog) + .on_hover_text(app.tr("prefs.project_options_dialog_note")); ui_kit::checkbox(ui, crate::i18n::tr_label("Pressing a tool's shortcut again switches its mode"), &mut app.preferences.shortcut_cycles_modes) .on_hover_text(crate::i18n::tr_label( "Before the first point, pressing a sketch tool's shortcut again steps through its creation modes. Off: it starts the tool again.", diff --git a/crates/ui-egui/src/select_other.rs b/crates/ui-egui/src/select_other.rs index 9afd44cd0..320c8bd6c 100644 --- a/crates/ui-egui/src/select_other.rs +++ b/crates/ui-egui/src/select_other.rs @@ -267,13 +267,14 @@ fn sketch_name(app: &SolveApp, sketch: u64) -> String { } /// "Line 3" (its kind and number), with what kind of geometry it is when that matters. -fn curve_label(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> String { +pub(crate) fn curve_label(sk: &solidcraft_engine::sketch::Sketch, id: &str) -> String { if let Some((i, c)) = sk.curves.iter().enumerate().find(|(_, c)| c.id == id) { let kind = curve_kind_name(&c.kind); let n = id_number(id).unwrap_or_else(|| sk.curves.iter().take(i + 1).filter(|x| curve_kind_name(&x.kind) == kind).count() as u64); let mut s = format!("{kind} {n}"); - if c.link.is_some() { - s.push_str(" (projected)"); + if let Some(link) = &c.link { + let kind = sk.links.iter().find(|l| &l.id == link).map(|l| l.kind); + s.push_str(if kind == Some(solidcraft_engine::sketch::LinkKind::Intersect) { " (intersected)" } else { " (projected)" }); } else if c.construction { s.push_str(" (construction)"); } diff --git a/crates/ui-egui/src/select_other_tests.rs b/crates/ui-egui/src/select_other_tests.rs index 258988f86..28d2759d7 100644 --- a/crates/ui-egui/src/select_other_tests.rs +++ b/crates/ui-egui/src/select_other_tests.rs @@ -615,3 +615,22 @@ fn a_small_body_on_a_large_one_is_not_picked_through() { assert!(point.x > 0.9, "at {distance} mm away the pick is behind the near face: {first:?}"); } } + +#[test] +fn a_curve_from_intersect_is_labelled_intersected_and_one_from_project_projected() { + use solidcraft_engine::sketch::LinkKind; + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":10,"height":10,"body_name":"Block"})).unwrap(); + let label = |h: &Harness, kind: LinkKind| { + let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + let c = sk.curves.iter().find(|c| c.link.as_deref().and_then(|l| sk.link(l)).is_some_and(|l| l.kind == kind)).unwrap(); + crate::select_other::curve_label(sk, &c.id) + }; + h.app.run("sketch.create", json!({"plane":"XY","offset":5,"project_edges":false})).unwrap(); + h.app.run("sketch.intersect", json!({"refs":[{"body":"Block"}]})).unwrap(); + assert!(label(&h, LinkKind::Intersect).ends_with("(intersected)")); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sketch.create", json!({"plane":"XY","offset":20,"project_edges":false})).unwrap(); + h.app.run("sketch.project", json!({"refs":[{"body":"Block"}]})).unwrap(); + assert!(label(&h, LinkKind::Project).ends_with("(projected)")); +} diff --git a/crates/ui-egui/src/sketch_shortcut_tests.rs b/crates/ui-egui/src/sketch_shortcut_tests.rs index 1b9c2557f..2776a6120 100644 --- a/crates/ui-egui/src/sketch_shortcut_tests.rs +++ b/crates/ui-egui/src/sketch_shortcut_tests.rs @@ -81,11 +81,28 @@ fn sketch_keys_outside_a_sketch_sketch_on_the_selected_plane_and_start_their_too assert!(h.app.session.active_sketch.is_some(), "{key}: no sketch opened"); assert_eq!(h.app.session.world_state().sketches.len(), 1, "{key}"); assert!(normal(&h).y.abs() > 0.999, "{key}: not on XZ: {:?}", normal(&h)); - assert_eq!(tool(&h), Some(cmd), "{key}"); - assert!(h.app.dialog.is_none(), "{key}: dialog left open"); + if cmd == "sketch.project" { + assert!(h.app.preferences.project_options_dialog, "{key}: options are enabled by default"); + assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(crate::dialogs::Kind::SketchProject { .. })), "{key}"); + assert!(tool(&h).is_none(), "{key}: Project should open its options dialog"); + } else { + assert_eq!(tool(&h), Some(cmd), "{key}"); + assert!(h.app.dialog.is_none(), "{key}: dialog left open"); + } } } +#[test] +fn project_can_keep_its_previous_direct_pick_workflow() { + let mut h = Harness::new(); + h.app.preferences.project_options_dialog = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.start("sketch.project"); + h.settle(); + assert!(h.app.dialog.is_none()); + assert_eq!(tool(&h), Some("sketch.project")); +} + #[test] fn a_sketch_key_sketches_on_the_selected_planar_face() { let mut h = Harness::new(); diff --git a/crates/ui-egui/src/sketch_tools.rs b/crates/ui-egui/src/sketch_tools.rs index 46b9d4baa..0a8fa3a9f 100644 --- a/crates/ui-egui/src/sketch_tools.rs +++ b/crates/ui-egui/src/sketch_tools.rs @@ -277,6 +277,15 @@ fn marks(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { /// Commands that start with a step of their own: Canvas and Decal ask for the image first, /// Edit Canvas opens the canvas panel. False when the command should not go on. pub fn start_hook(app: &mut SolveApp, id: &str) -> bool { + if id == "sketch.intersect" + && let Some(dialog) = crate::dialogs::Dialog::for_command(app, id) + { + if dialog.wants_picks() && !app.session.selection.is_empty() { + let _ = app.session.execute("select.clear", &json!({})); + } + app.dialog = Some(dialog); + return false; + } if id == "sketch.edit_text" && let Some(dialog) = crate::dialogs::Dialog::for_command(app, id) { diff --git a/crates/ui-egui/tests/projection_preselection.rs b/crates/ui-egui/tests/projection_preselection.rs index 28ffdef42..116b8f3e4 100644 --- a/crates/ui-egui/tests/projection_preselection.rs +++ b/crates/ui-egui/tests/projection_preselection.rs @@ -4,6 +4,8 @@ use solidcraft_ui_egui::scenario::Harness; fn setup() -> (Harness, u64) { let mut h = Harness::new(); + // These cover the direct pick workflow; the options dialog is covered in dialogs_sketch_tests. + h.app.preferences.project_options_dialog = false; let source = h.app.run("sketch.create", json!({"plane":"XY","offset":10})).unwrap()["sketch"].as_u64().unwrap(); h.app.run("sketch.line", json!({"points":[[10,10],[30,10]],"infer":false})).unwrap(); h.app.run("sketch.point", json!({"point":[20,20],"id":"p"})).unwrap();