SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch Transform: keep the applied rectangle at the previewed rotation and size (#11617) (#11620)
Colin Faulkingham5e4c52a7cba8
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rsindex 720dde8530..5ce6f355e0 100644--- a/crates/engine/src/cmd/sketch_modify.rs+++ b/crates/engine/src/cmd/sketch_modify.rs@@ -3538,17 +3538,76 @@ fn transform(s: &mut Session, p: &Value) -> Result<Value> {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 (out, info) = edit(s, p, cmd, false, |sk, doc| {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)?;+ let moved = involved_points(sk, &cs, &ps);+ rotate_axis_constraints(sk, doc, &moved, ang)?;+ scale_dimensions(sk, doc, &cs, &moved, k)?;Ok(ids_of(sk, &cs))})?;+ s.doc_mut().prune_model_params();Ok(json!({"curves": out, "sketch": info}))}+/// The driving lengths wholly inside a transformed selection scale with it. Keep formulas+/// tied to their user parameters, and compensate references between scaled dimensions so a+/// dimension such as `d1 / 2` does not get the factor twice.+fn scale_dimensions(sk: &mut Sketch, doc: &mut solidcraft_doc::Document, curves: &[usize], points: &[usize], factor: f64) -> Result<()> {+ if factor == 1.0 {+ return Ok(());+ }+ let selected: Vec<usize> = sk+ .constraints+ .iter()+ .enumerate()+ .filter(|(_, c)| {+ let pts = sk.constraint_points(&c.kind);+ !c.driven+ && c.kind.is_dimension()+ && !c.kind.is_angle()+ && !pts.is_empty()+ && pts.iter().all(|p| points.contains(p))+ // A circle's centre may move with another curve while its radius stays put.+ && c.kind.indices().1.iter().all(|i| {+ curves.contains(i)+ || !matches!(sk.curves.get(*i).map(|c| &c.kind), Some(CurveKind::Circle { .. } | CurveKind::Ellipse { .. }))+ })+ })+ .map(|(i, _)| i)+ .collect();+ let mut expressions = std::collections::BTreeMap::new();+ for i in selected {+ let Some(c) = sk.constraints.get_mut(i) else { continue };+ if let Some(value) = c.kind.value() {+ c.kind.set_value(value * factor);+ }+ if let Some(name) = &c.param+ && let Some(param) = doc.param(name)+ {+ let expression = if solidcraft_doc::expr::references(¶m.expr).is_empty() {+ format!("{} mm", doc.eval(name, solidcraft_doc::expr::Kind::Length)? * factor)+ } else {+ let formula = param.expr.trim().strip_prefix('=').unwrap_or(¶m.expr);+ format!("({formula}) * {factor}")+ };+ expressions.insert(name.clone(), expression);+ }+ }+ for (name, mut expression) in expressions.clone() {+ for reference in solidcraft_doc::expr::references(&expression) {+ if expressions.contains_key(&reference) {+ expression = solidcraft_doc::expr::rename_reference(&expression, &reference, &format!("({reference} / {factor})"));+ }+ }+ doc.set_param(&name, &expression, None, None)?;+ }+ Ok(())+}+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 b38f93fcf3..6b67b68937 100644--- a/crates/engine/src/cmd/sketch_modify_tests.rs+++ b/crates/engine/src/cmd/sketch_modify_tests.rs@@ -1194,6 +1194,65 @@ fn transform_scales_turns_and_moves_in_one_step() {}}+/// Transform must leave a dimensioned rectangle where its preview put it, rather than letting+/// the old horizontal/vertical relations and size dimensions pull it back (#11617).+#[test]+fn transform_turns_and_scales_a_dimensioned_rectangle() {+ for angle in [30.0_f64, 90.0, 180.0] {+ let mut s = new_sketch();+ let drawn = run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [25, 12.5]}));+ let curves = ids(&drawn["curves"]);+ let width = run(&mut s, "sketch.dimension", json!({"entities": [curves[0]], "type": "length", "value": "50 mm"}));+ let height = run(&mut s, "sketch.dimension", json!({"entities": [curves[1]], "type": "length", "value": "25 mm"}));+ let before = sketch(&s);+ let result = run(&mut s, "sketch.transform", json!({"entities": curves, "factor": 2, "angle": angle, "center": [0, 0]}));+ assert_eq!(result["sketch"]["solved"], true);+ let after = sketch(&s);+ let (sin, cos) = angle.to_radians().sin_cos();+ for id in ["p1", "p2", "p3", "p4"] {+ let p = before.point(before.resolve_point(id).unwrap()).unwrap();+ let expected = Vec2::new(p.x * cos - p.y * sin, p.x * sin + p.y * cos) * 2.0;+ let actual = after.point(after.resolve_point(id).unwrap()).unwrap();+ assert!(actual.dist(expected) < 1e-6, "{angle} degrees, {id}: {actual:?}, expected {expected:?}");+ }+ for (dimension, expected) in [(&width, 100.0), (&height, 50.0)] {+ let name = dimension["param"].as_str().unwrap();+ assert!(close(s.doc.eval(name, solidcraft_doc::expr::Kind::Length).unwrap(), expected));+ }+ assert!(close(profiles(&s)[0], 5000.0));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(sketch(&s).constraints, before.constraints);+ assert!(close(profiles(&s)[0], 1250.0));+ run(&mut s, "edit.redo", json!({}));+ assert!(close(profiles(&s)[0], 5000.0));+ }+}++#[test]+fn transform_scales_dimension_formulas_once_and_keeps_unselected_dimensions() {+ let mut s = new_sketch();+ run(&mut s, "parameters.add", json!({"name": "width", "expression": "50 mm"}));+ let rectangle = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 10], "p1": [60, 35]}));+ let curves = ids(&rectangle["curves"]);+ let width = run(&mut s, "sketch.dimension", json!({"entities": [curves[0]], "type": "length", "value": "=width"}));+ let width_param = width["param"].as_str().unwrap();+ let height = run(&mut s, "sketch.dimension", json!({"entities": [curves[1]], "type": "length", "value": format!("{width_param} / 2")}));+ run(&mut s, "sketch.dimension", json!({"entities": [curves[2]], "type": "length", "driven": true}));+ let circle = run(&mut s, "sketch.circle.center", json!({"center": [100, 100], "radius": 5}));+ let radius = run(&mut s, "sketch.dimension", json!({"entities": [circle["curves"][0]], "type": "radius", "value": "5 mm"}));+ let outside = s.doc.param(radius["param"].as_str().unwrap()).unwrap().clone();+ run(&mut s, "sketch.transform", json!({"entities": curves, "factor": 2, "angle": 90, "center": [35, 22.5]}));+ let length = solidcraft_doc::expr::Kind::Length;+ assert!(close(s.doc.eval("width", length).unwrap(), 50.0), "the user parameter stays unchanged");+ assert!(close(s.doc.eval(width_param, length).unwrap(), 100.0));+ assert!(close(s.doc.eval(height["param"].as_str().unwrap(), length).unwrap(), 50.0));+ assert_eq!(s.doc.param(&outside.name).unwrap(), &outside);+ assert!(close(sketch(&s).radius(sketch(&s).curve_index(circle["curves"][0].as_str().unwrap()).unwrap()).unwrap(), 5.0));+ run(&mut s, "parameters.change", json!({"name": "width", "expression": "60 mm"}));+ assert!(close(s.doc.eval(width_param, length).unwrap(), 120.0), "the formula still follows its user parameter");+ assert!(close(s.doc.eval(height["param"].as_str().unwrap(), length).unwrap(), 60.0), "dependent dimensions scale only once");+}+/// #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/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rsindex 4537400735..8e3d17ac10 100644--- a/crates/ui-egui/src/dialogs_sketch_tests.rs+++ b/crates/ui-egui/src/dialogs_sketch_tests.rs@@ -648,3 +648,36 @@ fn transform_handles_and_fields_scale_move_and_turn_the_picks() {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}");}++#[test]+fn transform_applies_the_dimensioned_rectangle_shown_in_its_preview() {+ for profile in [false, true] {+ let mut h = fixture();+ for (line, value) in [("l1", 30), ("l2", 20)] {+ h.app.run("sketch.dimension", json!({"entities": [line], "type": "length", "value": value})).unwrap();+ }+ let mut dialog = Dialog::for_command(&h.app, "sketch.transform").unwrap();+ dialog.inputs[0].items = if profile {+ vec![Sel::Profile { sketch: h.app.session.active_sketch.unwrap(), index: 0 }]+ } else {+ ["l1", "l2", "l3", "l4"].map(|id| Sel::SketchCurve { id: id.into(), sketch: None }).to_vec()+ };+ h.app.dialog = Some(dialog);+ h.frames(4);+ if let Some(Kind::SketchModify(Mod::Transform { factor, angle, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) {+ *factor = "2".into();+ *angle = "30 deg".into();+ }+ h.frames(3);+ h.step(&json!({"click": {"handle": "dialog:ok"}})).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().unwrap();+ let sk = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;+ let a = sk.point(sk.resolve_point("l1.start").unwrap()).unwrap();+ let b = sk.point(sk.resolve_point("l1.end").unwrap()).unwrap();+ let edge = b - a;+ assert!((edge.len() - 60.0).abs() < 1e-6, "the applied width matches Scale 2: {edge:?}");+ assert!((edge.angle().to_degrees() - 30.0).abs() < 1e-6, "the applied rotation matches Angle 30: {edge:?}");+ }+}diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rsindex 8f8a702b01..795f0fb46b 100644--- a/crates/ui-egui/src/sketch_modify_ui.rs+++ b/crates/ui-egui/src/sketch_modify_ui.rs@@ -729,7 +729,7 @@ pub(crate) fn point_id<'a>(session: &solidcraft_engine::Session, sel: &'a Sel) -/// The curves and lone points picked in input `i`, as the engine's `entities` list. A profile/// pick expands to every curve of its boundary and its holes (#8390).-fn entity_ids(session: &solidcraft_engine::Session, inputs: &[SelInput], i: usize) -> Vec<String> {+pub(crate) fn entity_ids(session: &solidcraft_engine::Session, inputs: &[SelInput], i: usize) -> Vec<String> {let mut out = Vec::new();for x in items(inputs, i) {match x {diff --git a/crates/ui-egui/src/sketch_transform_ui.rs b/crates/ui-egui/src/sketch_transform_ui.rsindex 11cb4e3312..acadf7a480 100644--- a/crates/ui-egui/src/sketch_transform_ui.rs+++ b/crates/ui-egui/src/sketch_transform_ui.rs@@ -5,7 +5,6 @@use egui::{Pos2, Sense, Stroke, Vec2 as Screen, vec2};use solidcore_record::{Plane, Vec2};-use solidcraft_engine::Sel;use solidcraft_engine::geom::prelude::*;use crate::SolveApp;@@ -81,19 +80,11 @@ fn picked_box(app: &SolveApp, d: &crate::dialogs::Dialog) -> Option<(Vec<Vec<Veclet 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);- }- }- _ => {}+ for id in crate::sketch_modify_ui::entity_ids(&app.session, &d.inputs, 0) {+ if let Some(i) = sk.curve_index(&id) {+ lines.push(sk.polyline(i));+ } else if let Some(p) = sk.resolve_point(&id).and_then(|i| sk.point(i)) {+ points.push(p);}}let all: Vec<Vec2> = lines.iter().flatten().copied().chain(points).collect();