SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Transform: one box with handles to scale, move and turn what is picked (#6004)
Nathalie Schönwetter6848c7842451
diff --git a/assets/locales/pending/sketch-transform.json b/assets/locales/pending/sketch-transform.jsonnew file mode 100644index 0000000000..4b5a6bd6eb--- /dev/null+++ b/assets/locales/pending/sketch-transform.json@@ -0,0 +1,20 @@+{+ "de": {+ "cmd.sketch_transform": "Transformieren"+ },+ "en": {+ "cmd.sketch_transform": "Transform"+ },+ "ja": {+ "cmd.sketch_transform": "変形"+ },+ "ko": {+ "cmd.sketch_transform": "변환"+ },+ "zh-TW": {+ "cmd.sketch_transform": "變換"+ },+ "zh": {+ "cmd.sketch_transform": "变换"+ }+}diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex 964f019819..482b1cce9e 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -81,6 +81,12 @@ pub static COMMANDS: &[CommandSpec] = &[.icon("sketch_scale").enabled(in_sketch).params("entities: [curve/point ids], base: [x,y] or point ref, factor: number"),+ CommandSpec::new("sketch.transform", "Transform", transform)+ .at("SKETCH", "MODIFY")+ .icon("sketch_move")+ .key("G")+ .enabled(in_sketch)+ .params("entities: [curve/point ids], factor?: number (scale), angle?: degrees (turn), center?: [x,y] or point ref (what scales and turns stay put; default [0,0]), translate?: [dx,dy] (applied last); scales, turns and moves in one step"),CommandSpec::new("sketch.move", "Move/Copy Sketch Entities", move_copy).at("SKETCH", "MODIFY").icon("sketch_move")@@ -2520,6 +2526,30 @@ fn move_copy(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"curves": out, "sketch": info}))}+/// Scale, turn and move the entities in one step: scaled about `center`, then turned about it,+/// then moved by `translate`.+fn transform(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "sketch.transform";+ let k = match p.get("factor") {+ Some(v) => v.as_f64().filter(|k| *k > 1e-9 && *k < 1e6).ok_or_else(|| bad(cmd, "`factor` must be a positive number"))?,+ None => 1.0,+ };+ let ang = match p.get("angle") {+ Some(v) => v.as_f64().filter(|a| a.is_finite()).ok_or_else(|| bad(cmd, "`angle` must be a number (degrees)"))?.to_radians(),+ None => 0.0,+ };+ let t = if p.get("translate").is_some() { req_vec2(cmd, p, "translate")? } else { Vec2::ZERO };+ let (out, info) = edit(s, p, cmd, false, |sk, _| {+ let (cs, ps) = entities(sk, p, cmd)?;+ let c = if p.get("center").is_some() { point_or_ref(sk, p, "center", cmd)? } else { Vec2::ZERO };+ let rot = rotate(c, ang);+ let f = move |q: Vec2| rot(c + (q - c) * k) + t;+ transform_in_place(sk, &cs, &ps, &f, k, cmd)?;+ Ok(ids_of(sk, &cs))+ })?;+ Ok(json!({"curves": out, "sketch": info}))+}+fn scale(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.scale";let k = num(p, "factor").filter(|k| *k > 1e-9 && *k < 1e6).ok_or_else(|| bad(cmd, "`factor` must be a positive number"))?;diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rsindex bd0034ad89..a3e27e6545 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -746,6 +746,32 @@ fn a_circle_drawn_at_the_origin_can_be_moved() {assert!(moved["sketch"]["solved"].as_bool().unwrap_or(false), "the sketch stayed solved: {moved}");}+/// One Transform scales and turns about a centre and moves, in a single undo step, where Scale+/// and Move would be two.+#[test]+fn transform_scales_turns_and_moves_in_one_step() {+ let mut s = new_sketch();+ let line = ids(&run(&mut s, "sketch.line", json!({"points": [[10, 0], [20, 0]], "ids": ["bar"]}))["curves"])[0].clone();+ let disc = ids(&run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 2}))["curves"])[0].clone();+ // Twice as big and a quarter turn about (10, 0), then 5 along x: the line (10..20, 0) runs+ // up to (10, 20) and over to (15, 20); the circle's centre goes from (10, 10) to (-10, 0) + (5, 0).+ run(&mut s, "sketch.transform", json!({"entities": [line, disc], "factor": 2, "angle": 90, "center": [10, 0], "translate": [5, 0]}));+ let sk = sketch(&s);+ let (a, b) = (sk.point(sk.resolve_point("bar.start").unwrap()).unwrap(), sk.point(sk.resolve_point("bar.end").unwrap()).unwrap());+ assert!(a.dist(Vec2::new(15.0, 0.0)) < 1e-7 && b.dist(Vec2::new(15.0, 20.0)) < 1e-7, "{a:?} {b:?}");+ let ci = sk.curve_index(&disc).unwrap();+ assert!(sk.center(ci).unwrap().dist(Vec2::new(-5.0, 0.0)) < 1e-7, "{:?}", sk.center(ci));+ assert!(close(sk.radius(ci).unwrap(), 4.0));+ run(&mut s, "edit.undo", json!({}));+ let sk = sketch(&s);+ assert!(sk.point(sk.resolve_point("bar.start").unwrap()).unwrap().dist(Vec2::new(10.0, 0.0)) < 1e-7, "one undo restores it");+ for bad in [json!({"factor": 0}), json!({"factor": -1}), json!({"angle": "x"})] {+ let mut p = json!({"entities": ["bar"]});+ p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone());+ assert!(s.execute("sketch.transform", &p).is_err(), "{bad}");+ }+}+/// #1485: after a circle is trimmed between two construction lines, clicking the trimmed end/// picks the construction line's end lying there, not the arc's own; the tangent arc still starts/// from the trimmed arc, tangent to it.diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex 2e88ed3c17..bbe2c82e90 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -1022,6 +1022,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {v.extend(explode_text(app));}v.push(cmd(app, "sketch.move", "Move/Copy").key("M"));+ v.push(cmd(app, "sketch.transform", "Transform").key("G"));if !curves.is_empty() {v.push(cmd(app, "sketch.construction", "Normal / Construction").with(json!({ "curves": curves })));}diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rsindex 0123a5d1c6..f28699998d 100644--- a/crates/ui-egui/src/dialogs_sketch_tests.rs+++ b/crates/ui-egui/src/dialogs_sketch_tests.rs@@ -345,3 +345,50 @@ fn sketch_pattern_dialog_preserves_expression_text_when_applying_and_editing() {}}}++/// Transform scales, turns and moves what is picked as one, by handles on its box or by the+/// window's numbers, and OK applies it in a single step.+#[test]+fn transform_handles_and_fields_scale_move_and_turn_the_picks() {+ let mut h = fixture();+ h.step(&json!({"call": "ui.view", "params": {"view": "top"}})).unwrap();+ h.settle();+ let ids: Vec<String> = {+ let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();+ sk.curves.iter().map(|c| c.id.clone()).collect()+ };+ let mut d = Dialog::for_command(&h.app, "sketch.transform").unwrap();+ d.inputs[0].items = ids.iter().map(|id| Sel::SketchCurve { id: id.clone(), sketch: None }).collect();+ h.app.dialog = Some(d);+ h.frames(4);+ let state = |h: &Harness| match h.app.dialog.as_ref().map(|d| d.kind.clone()) {+ Some(Kind::SketchModify(Mod::Transform { x, y, factor, angle, frame })) => (x, y, factor, angle, frame),+ other => panic!("no transform window: {other:?}"),+ };+ // The box is the rectangle's: 30 x 20 around (25, 20).+ assert_eq!(state(&h).4, Some(([25.0, 20.0], [30.0, 20.0])));+ // The corner at (40, 30) dragged to (55, 40): one and a half times the size about the corner at (10, 10).+ h.step(&json!({"drag": [{"handle": "transform:handle:3"}, {"world": [55, 40, 0]}]})).unwrap();+ h.frames(3);+ let (x, y, factor, _, _) = state(&h);+ assert!((factor.parse::<f64>().unwrap() - 1.5).abs() < 0.05, "scaled: {factor}");+ assert!(x.starts_with("7.5") && y.starts_with("5"), "the middle moved to (32.5, 25): {x}, {y}");+ h.step(&json!({"key": "Enter"})).unwrap();+ h.settle();+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone()));+ let state = h.app.session.world_state();+ let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;+ let (mut lo, mut hi) = ((f64::MAX, f64::MAX), (f64::MIN, f64::MIN));+ for p in (0..sk.curves.len()).flat_map(|i| sk.polyline(i)) {+ lo = (lo.0.min(p.x), lo.1.min(p.y));+ hi = (hi.0.max(p.x), hi.1.max(p.y));+ }+ assert!((lo.0 - 10.0).abs() < 0.5 && (lo.1 - 10.0).abs() < 0.5, "the fixed corner stayed: {lo:?}");+ assert!((hi.0 - 55.0).abs() < 1.5 && (hi.1 - 40.0).abs() < 1.5, "the far corner went to (55, 40): {hi:?}");+ h.app.run("edit.undo", json!({})).unwrap();+ h.settle();+ let state = h.app.session.world_state();+ let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;+ let top = (0..sk.curves.len()).flat_map(|i| sk.polyline(i)).fold(f64::MIN, |m, p| m.max(p.x));+ assert!((top - 40.0).abs() < 1e-6, "one undo puts it back: {top}");+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex e4bb6b38be..a3f648b78d 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -248,6 +248,7 @@ pub(crate) mod sketch_text;mod sketch_text_handles;mod sketch_text_move;pub mod sketch_tools;+mod sketch_transform_ui;pub mod smart_extrude;#[cfg(test)]mod smart_extrude_ui_tests;diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rsindex 9e8e8a81a9..0b4d281df3 100644--- a/crates/ui-egui/src/sketch_modify_ui.rs+++ b/crates/ui-egui/src/sketch_modify_ui.rs@@ -48,6 +48,7 @@ pub const MODIFIERS: &[ToolModifiers] = &[ToolModifiers { tool: "sketch.mirror", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp },// Sketch Move: dialog/manipulator inherit only - no invented Alt-copy.ToolModifiers { tool: "sketch.move", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp },+ ToolModifiers { tool: "sketch.transform", scopes: SELECT_MANIP, bindings: &[], audit: Audit::VerifiedNoOp },// Pattern spacing/count live in the dialog - no viewport modifier chords.ToolModifiers { tool: "sketch.pattern.rectangular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp },ToolModifiers { tool: "sketch.pattern.circular", scopes: SELECT_ONLY, bindings: &[], audit: Audit::VerifiedNoOp },@@ -103,6 +104,11 @@ pub enum Mod {/// turn about the centre, and whether the originals stay behind. The command already/// carries the copy flag, so the Create Copy row needs no engine change.Move { x: String, y: String, angle: String, copy: bool },+ /// `sketch.transform`: the picked entities scaled, turned and moved as one, about the middle+ /// of their box. `x` and `y` move that middle, `factor` scales and `angle` turns about it.+ /// `frame` is the box (middle and size in the sketch, kept up to date from the picks by+ /// `sketch_transform_ui`) the window's size rows and the handles work on.+ Transform { x: String, y: String, factor: String, angle: String, frame: Option<([f64; 2], [f64; 2])> },/// `sketch.pattern.rectangular`: how many instances along the picked direction and how far/// apart, then the same along a second picked direction (perpendicular by default).PatternRect {@@ -138,6 +144,7 @@ impl Mod {Mod::Offset { .. } => "OFFSET",Mod::Mirror => "MIRROR",Mod::Move { .. } => "MOVE/COPY",+ Mod::Transform { .. } => "TRANSFORM",Mod::PatternRect { .. } => "RECTANGULAR PATTERN",Mod::PatternCirc { .. } => "CIRCULAR PATTERN",Mod::Corner { chamfer: false, .. } => "FILLET",@@ -151,6 +158,8 @@ impl Mod {Mod::Scale { factor } => Some(("Factor", ValueKind::Unitless, factor)),Mod::Offset { distance, .. } => Some(("Distance", ValueKind::Length, distance)),Mod::Move { x, .. } => Some(("X Distance", ValueKind::Length, x)),+ // The handles in the viewport are its manipulator; the window has the numbers.+ Mod::Transform { .. } => None,Mod::Mirror => None,Mod::PatternRect { spacing, .. } => Some(("Spacing", ValueKind::Length, spacing)),Mod::PatternCirc { angle, .. } => Some(("Angle", ValueKind::Angle, angle)),@@ -167,6 +176,7 @@ fn inputs(k: &Mod) -> Vec<SelInput> {// AXES is the mask that takes a straight sketch curve (`selection::SelInput::accepts`).Mod::Mirror => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true), SelInput::new("Mirror line", AXES, false)],Mod::Move { .. } => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true), SelInput::new("Center", SKETCH_POINTS, false)],+ Mod::Transform { .. } => vec![SelInput::new("Entities", CURVES | SKETCH_POINTS, true)],// The direction is optional: `sketch.pattern.rectangular` documents sketch x as its// default, the way the engine reads it.Mod::PatternRect { .. } => vec![@@ -204,6 +214,13 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {flip: false,},"sketch.mirror" => Mod::Mirror,+ "sketch.transform" => Mod::Transform {+ x: crate::dialogs::length_default(&app.session, "0"),+ y: crate::dialogs::length_default(&app.session, "0"),+ factor: "1".into(),+ angle: "0 deg".into(),+ frame: None,+ },"sketch.move" => Mod::Move {x: crate::dialogs::length_default(&app.session, "0"),y: crate::dialogs::length_default(&app.session, "0"),@@ -332,6 +349,7 @@ pub(crate) fn command(k: &Mod) -> &'static str {Mod::Offset { .. } => "sketch.offset",Mod::Mirror => "sketch.mirror",Mod::Move { .. } => "sketch.move",+ Mod::Transform { .. } => "sketch.transform",Mod::PatternRect { .. } => "sketch.pattern.rectangular",Mod::PatternCirc { .. } => "sketch.pattern.circular",Mod::Corner { chamfer: false, .. } => "sketch.fillet",@@ -416,6 +434,25 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod, doc: &Document) -> bool {enter |= number(ui, "Angle", angle);ui_kit::options(ui, "move_options", &mut [("Create Copy", copy)]);}+ Mod::Transform { x, y, factor, angle, frame } => {+ enter |= ui_kit::value_pair(ui, "Position", [x, y], ["X", "Y"], Some(["X Distance", "Y Distance"]));+ // The size in millimetres follows the factor and the other way round; the aspect is kept.+ if let Some((_, size)) = frame {+ for (label, natural) in [("Width", size[0]), ("Height", size[1])] {+ let k = crate::prefs::parse_number(factor.trim()).filter(|k| *k > 0.0).unwrap_or(1.0);+ let mut shown = format!("{} mm", crate::sketch_transform_ui::plain(natural * k));+ if number(ui, label, &mut shown)+ && let Some(mm) = crate::prefs::parse_number(shown.trim_end_matches("mm").trim())+ && mm > 0.0+ && natural > 1e-9+ {+ *factor = format!("{}", ((mm / natural) * 1e6).round() / 1e6);+ }+ }+ }+ enter |= number(ui, "Scale", factor);+ enter |= number(ui, "Angle", angle);+ }Mod::PatternRect { count, spacing, count2, spacing2, alignment: a, alignment2, reversed, reversed2 } => {let (left1, left2) = (copies_left(doc, count2), copies_left(doc, count));for (key, title, count, spacing, align, reverse, label, distance, align_label, left) in [@@ -574,7 +611,7 @@ fn curve_ids(inputs: &[SelInput], i: usize) -> Vec<String> {/// A typed scale factor as the command wants it: the field evaluated against the document's/// parameters, in the range the command accepts. Checking the range here lets the window say/// so in its own error line instead of the status bar.-fn factor(app: &SolveApp, text: &str) -> Result<f64, String> {+pub(crate) fn factor(app: &SolveApp, text: &str) -> Result<f64, String> {let v = app.session.doc.eval(text.trim(), ValueKind::Unitless).map_err(|e| format!("Factor: {e}"))?;if !(v.is_finite() && v > 1e-9 && v < 1e6) {return Err("Factor must be a positive number".into());@@ -585,7 +622,7 @@ fn factor(app: &SolveApp, text: &str) -> Result<f64, String> {/// A typed field as the command wants it: evaluated against the document's parameters, so an/// expression works, with a bare number read in the design's own units. An empty field is zero,/// the way an untouched row should leave the geometry where it is.-fn value(app: &SolveApp, text: &str, kind: ValueKind, label: &str) -> Result<f64, String> {+pub(crate) fn value(app: &SolveApp, text: &str, kind: ValueKind, label: &str) -> Result<f64, String> {let text = text.trim();if text.is_empty() {return Ok(0.0);@@ -714,6 +751,17 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map<String}("sketch.scale", p)}+ Mod::Transform { x, y, factor: text, angle, frame } => {+ let entities = entity_ids(&app.session, inputs, 0);+ if entities.is_empty() {+ return Err("Select the sketch curves or points to transform first".into());+ }+ let Some((middle, _)) = frame else { return Err("Select the sketch curves or points to transform first".into()) };+ let f = factor(app, text)?;+ let turn = value(app, angle, ValueKind::Angle, "Angle")?.to_degrees();+ let (dx, dy) = (value(app, x, ValueKind::Length, "X")?, value(app, y, ValueKind::Length, "Y")?);+ ("sketch.transform", json!({"entities": entities, "factor": f, "angle": turn, "center": middle, "translate": [dx, dy]}))+ }Mod::Offset { distance, distance2, mode, chain, flip } => {let curves = curve_ids(inputs, 0);if curves.is_empty() {diff --git a/crates/ui-egui/src/sketch_transform_ui.rs b/crates/ui-egui/src/sketch_transform_ui.rsnew file mode 100644index 0000000000..f8f57ba92f--- /dev/null+++ b/crates/ui-egui/src/sketch_transform_ui.rs@@ -0,0 +1,281 @@+//! Transform in the viewport: the picked sketch curves and points get a box with a handle at each+//! corner to scale (the opposite corner stays put, the aspect is kept), the box itself to move,+//! and a knob above it to turn (Shift snaps to 15 degrees). The handles edit the same Position,+//! Scale and Angle the window shows, and the entities are drawn where OK would put them.++use egui::{Pos2, Sense, Stroke, Vec2 as Screen, vec2};+use solidcraft_engine::Sel;+use solidcraft_engine::geom::{Plane, Vec2};++use crate::SolveApp;+use crate::dialogs::Kind;+use crate::sketch_modify_ui::Mod;+use crate::viewport::Proj;++/// Half the side of a corner handle, in screen points.+const HANDLE: f32 = 6.0;+/// How far above the box the turning knob sits, in screen points.+const KNOB_GAP: f32 = 28.0;+const MIN_FACTOR: f64 = 0.0001;+const MAX_FACTOR: f64 = 1e5;++/// A number as the window's fields show it: up to three decimals, none trailing.+pub(crate) fn plain(v: f64) -> String {+ let s = format!("{v:.3}");+ let s = s.trim_end_matches('0').trim_end_matches('.');+ if s == "-0" { "0".into() } else { s.into() }+}++/// What a drag took hold of.+#[derive(Clone, Copy, Debug, PartialEq)]+enum Part {+ Move,+ /// A corner, by its signs in the box's own frame.+ Corner(f64, f64),+ Turn,+}++/// A drag in progress: the part, where the pointer began on the sketch, and the placement then.+#[derive(Clone, Debug)]+pub struct Drag {+ part: Part,+ from: Vec2,+ at: Frame,+}++/// The box as placed: where its middle is, how much it is scaled, how far turned, and its own+/// size before scaling.+#[derive(Clone, Copy, Debug, PartialEq)]+struct Frame {+ x: f64,+ y: f64,+ scale: f64,+ angle: f64,+ natural: (f64, f64),+}++fn turn(v: Vec2, degrees: f64) -> Vec2 {+ let (s, c) = degrees.to_radians().sin_cos();+ Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c)+}++/// A spot of the box in its own frame (`u`, `v` in half sizes) on the sketch.+fn spot(f: &Frame, u: f64, v: f64) -> Vec2 {+ Vec2::new(f.x, f.y) + turn(Vec2::new(u * f.natural.0 * f.scale / 2.0, v * f.natural.1 * f.scale / 2.0), f.angle)+}++fn on_screen(plane: &Plane, proj: &Proj, q: Vec2) -> Option<Pos2> {+ proj.to_screen(plane.to_world(q))+}++fn pointer_on_sketch(plane: &Plane, proj: &Proj, at: Pos2) -> Option<Vec2> {+ let (o, d) = proj.ray(at);+ plane.intersect_ray(o, d).map(|w| plane.to_local(w))+}++/// The picked curves (as polylines on the sketch) and the box around them and the picked points:+/// its middle and its size. None when nothing usable is picked or the box has no extent.+fn picked_box(app: &SolveApp, d: &crate::dialogs::Dialog) -> Option<(Vec<Vec<Vec2>>, [f64; 2], [f64; 2])> {+ let state = app.session.world_state();+ let sk = &state.sketch(app.session.active_sketch?)?.sketch;+ let mut lines: Vec<Vec<Vec2>> = Vec::new();+ let mut points: Vec<Vec2> = Vec::new();+ for sel in &d.inputs.first()?.items {+ match sel {+ Sel::SketchCurve { id, .. } => {+ if let Some(i) = sk.curve_index(id) {+ lines.push(sk.polyline(i));+ }+ }+ Sel::SketchPoint { .. } => {+ if let Some(p) = crate::sketch_modify_ui::point_id(&app.session, sel).and_then(|id| sk.resolve_point(id)).and_then(|i| sk.point(i)) {+ points.push(p);+ }+ }+ _ => {}+ }+ }+ let all: Vec<Vec2> = lines.iter().flatten().copied().chain(points).collect();+ let first = *all.first()?;+ let (lo, hi) = all.iter().fold((first, first), |(lo, hi), p| (Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y))));+ let size = [hi.x - lo.x, hi.y - lo.y];+ // A single point or a straight line along an axis has no area to take hold of.+ (size[0] > 1e-9 && size[1] > 1e-9).then(|| (lines, [(lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0], size))+}++/// Keep the Transform window's box up to date with what is picked.+pub fn refresh(app: &mut SolveApp) {+ let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::SketchModify(Mod::Transform { .. }))) else { return };+ let boxed = picked_box(app, d).map(|(_, middle, size)| (middle, size));+ if let Some(Kind::SketchModify(Mod::Transform { frame, .. })) = app.dialog.as_mut().map(|d| &mut d.kind) {+ *frame = boxed;+ }+}++/// The placement the window's fields describe, as a frame.+fn frame_of(app: &SolveApp, k: &Mod) -> Option<(Frame, [f64; 2])> {+ let Mod::Transform { x, y, factor, angle, frame } = k else { return None };+ let (middle, size) = (*frame)?;+ let (dx, dy) =+ (crate::sketch_modify_ui::value(app, x, ValueKind::Length, "X").ok()?, crate::sketch_modify_ui::value(app, y, ValueKind::Length, "Y").ok()?);+ let scale = crate::sketch_modify_ui::factor(app, factor).ok()?;+ let turned = crate::sketch_modify_ui::value(app, angle, ValueKind::Angle, "Angle").ok()?.to_degrees();+ Some((Frame { x: middle[0] + dx, y: middle[1] + dy, scale, angle: turned, natural: (size[0], size[1]) }, middle))+}++use solidcraft_engine::doc::expr::Kind as ValueKind;++/// Write a frame back into the window's fields.+fn store(k: &mut Mod, f: &Frame, middle: [f64; 2]) {+ if let Mod::Transform { x, y, factor, angle, .. } = k {+ *x = format!("{} mm", plain(f.x - middle[0]));+ *y = format!("{} mm", plain(f.y - middle[1]));+ *factor = format!("{}", (f.scale * 1e6).round() / 1e6);+ *angle = format!("{} deg", plain(f.angle));+ }+}++/// The frame after the pointer has moved to `p`, from where `drag` began.+fn apply(drag: &Drag, p: Vec2, snap: bool) -> Frame {+ let start = drag.at;+ let mut now = start;+ match drag.part {+ Part::Move => {+ now.x = start.x + (p.x - drag.from.x);+ now.y = start.y + (p.y - drag.from.y);+ }+ Part::Turn => {+ let to = p - Vec2::new(start.x, start.y);+ if to.len() > 1e-9 {+ let a = to.angle().to_degrees() - 90.0;+ let a = if snap { (a / 15.0).round() * 15.0 } else { a };+ now.angle = (a + 180.0).rem_euclid(360.0) - 180.0;+ }+ }+ Part::Corner(u, v) => {+ let fixed = spot(&start, -u, -v);+ // The pointer in the box's own frame, measured from the corner that stays.+ let local = turn(p - fixed, -start.angle);+ let k = (local.x.abs() / start.natural.0).max(local.y.abs() / start.natural.1).clamp(MIN_FACTOR, MAX_FACTOR);+ if k.is_finite() {+ let reach = turn(Vec2::new(u * k * start.natural.0 / 2.0, v * k * start.natural.1 / 2.0), start.angle);+ now.scale = k;+ now.x = fixed.x + reach.x;+ now.y = fixed.y + reach.y;+ }+ }+ }+ now+}++/// Where a point of the original box goes: scaled and turned about the middle, then moved.+fn moved(f: &Frame, middle: [f64; 2], q: Vec2) -> Vec2 {+ let m = Vec2::new(middle[0], middle[1]);+ Vec2::new(f.x, f.y) + turn((q - m) * f.scale, f.angle)+}++/// The Transform window's picks with their handles; a drag on them edits the window's values.+pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, proj: &Proj) {+ let Some(d) = app.dialog.as_ref().filter(|d| matches!(d.kind, Kind::SketchModify(Mod::Transform { .. }))) else {+ app.viewport.transform_drag = None;+ return;+ };+ let Some((lines, _, _)) = picked_box(app, d) else { return };+ let Kind::SketchModify(k) = &d.kind else { return };+ let Some((frame, middle)) = frame_of(app, k) else { return };+ let Some(plane) = app.session.active_sketch.and_then(|id| crate::canvas::profile_plane(app, id)) else { return };+ let t = crate::theme::Tokens::get();+ let painter = ui.painter().clone();+ let stroke = Stroke::new(1.5, t.accent);+ // The picks where OK would leave them.+ for line in &lines {+ let pts: Vec<Pos2> = line.iter().filter_map(|q| on_screen(&plane, proj, moved(&frame, middle, *q))).collect();+ if pts.len() > 1 {+ painter.add(egui::Shape::line(pts, Stroke::new(2.5, t.preview_sketch)));+ }+ }+ let signs = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)];+ let Some(corners) = signs.iter().map(|(u, v)| on_screen(&plane, proj, spot(&frame, *u, *v))).collect::<Option<Vec<_>>>() else { return };+ let (Some(top), Some(heart)) = (on_screen(&plane, proj, spot(&frame, 0.0, 1.0)), on_screen(&plane, proj, spot(&frame, 0.0, 0.0))) else { return };+ let away = (top - heart).normalized();+ let knob = top + if away.length() > 0.0 { away * KNOB_GAP } else { vec2(0.0, -KNOB_GAP) };+ painter.add(egui::Shape::closed_line(corners.clone(), stroke));+ painter.line_segment([top, knob], stroke);+ painter.circle(knob, HANDLE, t.overlay, stroke);++ // The whole box first, so the corners and the knob above it win where they overlap.+ let mut parts: Vec<(egui::Rect, Part, egui::CursorIcon)> = vec![(egui::Rect::from_points(&corners), Part::Move, egui::CursorIcon::Grab)];+ for (c, (u, v)) in corners.iter().zip(signs) {+ painter.rect(egui::Rect::from_center_size(*c, Screen::splat(HANDLE * 2.0)), 1.0, t.overlay, stroke, egui::StrokeKind::Inside);+ parts.push((egui::Rect::from_center_size(*c, Screen::splat(HANDLE * 3.0)), Part::Corner(u, v), egui::CursorIcon::ResizeNwSe));+ }+ parts.push((egui::Rect::from_center_size(knob, Screen::splat(HANDLE * 3.0)), Part::Turn, egui::CursorIcon::Crosshair));+ for (i, (rect, part, cursor)) in parts.into_iter().enumerate() {+ let response = ui.interact(rect, egui::Id::new(("sc_transform_handle", i)), Sense::drag()).on_hover_cursor(cursor);+ crate::scenario::publish_handle(&format!("transform:handle:{i}"), rect.center());+ if response.drag_started()+ && let Some(from) = response.interact_pointer_pos().and_then(|p| pointer_on_sketch(&plane, proj, p))+ {+ app.viewport.transform_drag = Some(Drag { part, from, at: frame });+ }+ // The release frame carries the last move too: it counts, or a quick drag stops short.+ if (response.dragged() || response.drag_stopped())+ && let Some(drag) = app.viewport.transform_drag.clone()+ && drag.part == part+ && let Some(p) =+ response.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).and_then(|p| pointer_on_sketch(&plane, proj, p))+ {+ let now = apply(&drag, p, ui.input(|i| i.modifiers.shift));+ if let Some(Kind::SketchModify(k)) = app.dialog.as_mut().map(|d| &mut d.kind) {+ store(k, &now, middle);+ }+ }+ if response.drag_stopped() {+ app.viewport.transform_drag = None;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn frame() -> Frame {+ Frame { x: 10.0, y: 5.0, scale: 1.0, angle: 0.0, natural: (20.0, 10.0) }+ }++ fn drag(part: Part, from: Vec2, at: Frame) -> Drag {+ Drag { part, from, at }+ }++ #[test]+ fn a_corner_scales_about_the_opposite_corner_turned_or_not() {+ for angle in [0.0, 30.0] {+ let f = Frame { angle, ..frame() };+ let fixed = spot(&f, -1.0, -1.0);+ let pulled = spot(&f, 1.0, 1.0) + turn(Vec2::new(20.0, 10.0), angle);+ let now = apply(&drag(Part::Corner(1.0, 1.0), spot(&f, 1.0, 1.0), f), pulled, false);+ assert!((now.scale - 2.0).abs() < 1e-9, "{}", now.scale);+ assert!(spot(&now, -1.0, -1.0).dist(fixed) < 1e-9, "the opposite corner stays");+ }+ }++ #[test]+ fn the_box_moves_and_the_knob_turns() {+ let f = frame();+ let now = apply(&drag(Part::Move, Vec2::new(10.0, 5.0), f), Vec2::new(14.0, 1.0), false);+ assert_eq!((now.x, now.y), (14.0, 1.0));+ // The knob is straight above the middle: to the left of it is a quarter turn.+ let turned = apply(&drag(Part::Turn, Vec2::new(14.0, 10.0), now), Vec2::new(4.0, 1.0), false);+ assert!((turned.angle - 90.0).abs() < 1e-9, "{}", turned.angle);+ let snapped = apply(&drag(Part::Turn, Vec2::new(14.0, 10.0), now), Vec2::new(4.0, 3.0), true);+ assert!((snapped.angle % 15.0).abs() < 1e-9, "{}", snapped.angle);+ }++ #[test]+ fn plain_numbers_keep_three_decimals_at_most() {+ assert_eq!(plain(12.0), "12");+ assert_eq!(plain(1.23456), "1.235");+ assert_eq!(plain(-0.0001), "0");+ }+}diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex b176cc1dce..4ed29e673e 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -52,6 +52,8 @@ pub enum NavMode {pub struct ViewportState {/// A drag on the handles of the drawing being placed (Insert SVG / DXF).pub(crate) insert_drag: Option<crate::insert_handles::Drag>,+ /// A drag on the handles of the Transform window's box.+ pub(crate) transform_drag: Option<crate::sketch_transform_ui::Drag>,/// The arrow turning the view that is still down (`navigation::step_key_hold`).pub(crate) key_hold: Option<crate::navigation::KeyHold>,/// A two-point drawing tool's first point was placed by a press (here) that became a drag:@@ -4340,6 +4342,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {crate::inference::show(app, &painter, &proj);crate::drag_snap::show(app, &painter, &proj);crate::insert_handles::show(app, ui, &proj);+ crate::sketch_transform_ui::refresh(app);+ crate::sketch_transform_ui::show(app, ui, &proj);hover_highlight(app, &painter, &proj);crate::drag_extrude::tick(app);crate::drag_extrude::show(app, &painter);diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rsindex 79137d3176..e8ae6cdaa6 100644--- a/crates/ui-egui/src/workspace.rs+++ b/crates/ui-egui/src/workspace.rs@@ -222,7 +222,7 @@ pub const SECTIONS: &[Section] = &[tab: "SKETCH",panel: "MODIFY",promoted: 3,- ids: &["sketch.trim", "sketch.offset", "sketch.fillet", "sketch.copy", "sketch.cut", "sketch.paste"],+ ids: &["sketch.trim", "sketch.offset", "sketch.fillet", "sketch.transform", "sketch.copy", "sketch.cut", "sketch.paste"],},Section { tab: "SKETCH", panel: "PATTERN", promoted: 3, ids: &["sketch.mirror", "sketch.pattern.circular", "sketch.pattern.rectangular"] },Section {