SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Two-sided extrudes: through all (or To Object) on either side, a distance on the other (#2700) (#2728)
CamWightd306d6e658dd
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 34bae024eb..ca0479a30e 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -233,7 +233,9 @@ pub struct Extent {pub convention: ExtrudeConvention,#[serde(default)]pub direction: Direction,- /// Optional second side distance (two-sided extrude), along the negative normal.+ /// Optional second side distance (two-sided extrude): the other way from the first side (against+ /// the normal, or along it when the first side goes against it: `direction: negative`, a+ /// negative distance, or a To Object below the sketch).#[serde(default, skip_serializing_if = "Option::is_none")]#[walk(length = "Distance 2")]pub distance2: Option<Expr>,diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 153b2561fb..615dbb2e82 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -4072,9 +4072,17 @@ fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Vec<k/// Where an extrude of distance `d` starts and ends along the sketch normal, before any start/// offset: one side, the other, both (symmetric), or a second distance on the other side.+///+/// A second distance (`distance2`) goes the other way from the first side, wherever that went:+/// against the normal for `direction: negative` (#2700), and back along it when a negative+/// distance or a To Object below the sketch sends the first side down.pub(crate) fn extent_sides(vals: &BTreeMap<String, Value>, extent: &crate::Extent, d: f64, direction: crate::Direction) -> Result<(f64, f64)> {Ok(match (&extent.distance2, direction) {- (Some(d2), _) => (-val(vals, d2, Kind::Length)?, d),+ (Some(d2), _) => {+ let first = if direction == crate::Direction::Negative { -d } else { d };+ let d2 = val(vals, d2, Kind::Length)?;+ (if first < 0.0 { d2 } else { -d2 }, first)+ }(None, crate::Direction::Positive) => (0.0, d),(None, crate::Direction::Negative) => (-d, 0.0),(None, crate::Direction::Symmetric) => {diff --git a/crates/doc/src/format/pending/two-sided-extrude-direction.rs b/crates/doc/src/format/pending/two-sided-extrude-direction.rsnew file mode 100644index 0000000000..4f54c39ee4--- /dev/null+++ b/crates/doc/src/format/pending/two-sided-extrude-direction.rs@@ -0,0 +1,49 @@+//! A two-sided extrude (`distance2`) follows its `direction` (#2700): with `direction: negative`+//! the first distance goes against the sketch normal and `distance2` along it, so either side can+//! be the through-all or To Object one. Older builds ignored `direction` when an extrude had a+//! second distance (the first always went along the normal), so this step makes the two-sided+//! `negative` extrudes of older designs `positive`, which keeps their shape. 0.15.x asks for an+//! update instead of opening a design with a reversed two-sided extrude.+use serde_json::Value;++pub fn step(v: &mut Value) -> crate::Result<()> {+ let Some(Value::Array(features)) = v.get_mut("features") else {+ return Ok(());+ };+ for feature in features {+ if !matches!(feature.get("type").and_then(Value::as_str), Some("extrude" | "surface_extrude")) {+ continue;+ }+ if let Some(extent) = feature.get_mut("extent").and_then(Value::as_object_mut)+ && extent.get("distance2").is_some_and(|d| !d.is_null())+ && extent.get("direction").and_then(Value::as_str) == Some("negative")+ {+ extent.insert("direction".into(), Value::from("positive"));+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ #[test]+ fn older_reversed_two_sided_extrudes_keep_their_shape() {+ let mut v = json!({"features": [+ {"type": "extrude", "extent": {"distance": "10 mm", "direction": "negative", "distance2": "5 mm"}},+ {"type": "surface_extrude", "extent": {"distance": "10 mm", "direction": "negative", "distance2": "5 mm"}},+ {"type": "extrude", "extent": {"distance": "10 mm", "direction": "negative"}},+ {"type": "extrude", "extent": {"distance": "10 mm", "direction": "symmetric", "distance2": "5 mm"}},+ {"type": "revolve", "extent": {"direction": "negative", "distance2": "5 mm"}},+ {"type": "sketch"}+ ]});+ super::step(&mut v).unwrap();+ let dirs: Vec<Option<&str>> = v["features"].as_array().unwrap().iter().map(|f| f["extent"]["direction"].as_str()).collect();+ assert_eq!(dirs, [Some("positive"), Some("positive"), Some("negative"), Some("symmetric"), Some("negative"), None]);+ // A design with no features is left alone.+ let mut empty = json!({"name": "Untitled"});+ super::step(&mut empty).unwrap();+ assert_eq!(empty, json!({"name": "Untitled"}));+ }+}diff --git a/crates/engine/src/cmd/extrude_convention_tests.rs b/crates/engine/src/cmd/extrude_convention_tests.rsindex def4269794..09d2a223ee 100644--- a/crates/engine/src/cmd/extrude_convention_tests.rs+++ b/crates/engine/src/cmd/extrude_convention_tests.rs@@ -141,3 +141,60 @@ fn surface_extrude_shared_extent_retains_its_existing_per_side_semantics() {check_sheet(&s);check_sheet(&Session::new(Document::from_json(&s.doc.to_json()).unwrap()));}++/// A second distance goes the other way from the first side (#2700): along the normal when the+/// first side goes against it, whether by `direction: negative` or by a negative distance.+#[test]+fn a_second_distance_goes_the_other_way_from_the_first_side() {+ for (settings, lo, hi) in [+ (json!({"direction":"positive","distance":"10 mm","distance2":"4 mm"}), -4.0, 10.0),+ (json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"}), -10.0, 4.0),+ (json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, 4.0),+ ] {+ let s = fixture(settings.clone());+ check(&s, lo, hi);+ // Saved and opened again, it keeps its sides.+ check(&Session::new(Document::from_json(&s.doc.to_json()).unwrap()), lo, hi);+ }+}++/// Through all on one side and a distance on the other, either way round (#2700). A 40 mm cube+/// round the origin, and an r5 hole sketched 10 mm above its middle: through all goes 10 mm up+/// or 30 mm down to the cube's faces, and the 5 mm goes the other way.+#[test]+fn through_all_on_either_side_with_a_distance_on_the_other() {+ let hole = std::f64::consts::PI * 25.0;+ for (direction, depth) in [("positive", 15.0), ("negative", 35.0)] {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length":40,"width":40,"height":40,"corner":[-20,-20,-20],"body_name":"Box"}));+ run(&mut s, "construct.plane.offset", json!({"base":"XY","offset":10,"name":"Above"}));+ run(&mut s, "sketch.create", json!({"plane":"Above","name":"Hole"}));+ run(&mut s, "sketch.circle.center", json!({"center":[0,0],"radius":5}));+ run(&mut s, "sketch.finish", json!({}));+ run(+ &mut s,+ "solid.extrude",+ json!({"sketch":"Hole","through_all":true,"distance2":"5 mm","direction":direction,"operation":"cut","targets":["Box"]}),+ );+ assert!(s.model.results.iter().all(|r| r.error.is_none()));+ let st = s.model.state();+ let m = solidcraft_kernel::measure(&st.body("Box").unwrap().body).unwrap();+ // The hole's depth from the volume removed (within the circle's measuring precision).+ let deep = (64000.0 - m.volume) / hole;+ assert!((deep - depth).abs() < 0.05, "{direction}: {deep} deep, want {depth}");+ }+}++/// Designs saved before #2700 ignored `direction` on a two-sided extrude; opening one keeps its+/// shape: its first distance still goes along the normal.+#[test]+fn an_older_reversed_two_sided_extrude_keeps_its_shape() {+ let s = fixture(json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"}));+ let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap();+ saved["format"] = json!("solidcraft/27");+ saved.as_object_mut().unwrap().remove("format_pending");+ let s = Session::new(Document::from_json(&saved.to_string()).unwrap());+ check(&s, -4.0, 10.0);+ let FeatureKind::Extrude { extent, .. } = &s.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") };+ assert_eq!(extent.direction, solidcraft_doc::Direction::Positive);+}diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex 66fd624900..1b517e1a1e 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -18,7 +18,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SOLID", "CREATE").icon("extrude").key("E")- .params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?; start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),+ .params("distance: expr (or through_all: true); taper?: angle expr; sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile); face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (default total_distance; legacy preserves older symmetric extents); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),CommandSpec::new("solid.revolve", "Revolve", revolve).at("SOLID", "CREATE").icon("revolve")diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex c4f8804878..d3cd1bae93 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -378,7 +378,7 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,1.0}}- (_, Kind::Extrude { direction: 1, .. }) => -1.0,+ (_, Kind::Extrude { direction: 1 | crate::dialogs::TWO_SIDES_REVERSED, .. }) => -1.0,_ => 1.0,};let symmetric = to_span.is_none() && matches!(d.kind, Kind::Extrude { direction: 2, .. });@@ -411,11 +411,11 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,}return;}- // Two sides: the second distance gets its own arrow the other way.- if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES, distance2, .. }, Some(n)) = (&mut d.kind, dir)+ // Two sides: the second distance gets its own arrow, the other way from the first side.+ if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES | crate::dialogs::TWO_SIDES_REVERSED, distance2, .. }, Some(n)) = (&mut d.kind, dir)&& let Some(l2) = app.session.doc.eval(distance2, ValueKind::Length).ok().filter(|v| v.is_finite()){- drag_arrow(ui, painter, proj, base, bs, -n, l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2);+ drag_arrow(ui, painter, proj, base, bs, -(n * sign), l2, true, egui::Id::new("sc_manipulator2"), half_height, distance2);}// A rectangular pattern's second direction gets its own arrow for Spacing 2 (#2462), as the// first direction's arrow sets Spacing.diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex f06e5ef3bd..498737b31b 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -69,9 +69,16 @@ pub const MODIFIERS: &[ToolModifiers] = &[pub(crate) const OPS: [&str; 4] = ["new", "join", "cut", "intersect"];pub(crate) const OP_LABELS: [&str; 4] = ["New Body", "Join", "Cut", "Intersect"];-const DIRS: [&str; 4] = ["positive", "negative", "symmetric", "positive"];+const DIRS: [&str; 5] = ["positive", "negative", "symmetric", "positive", "negative"];/// The "Two sides" direction (a second distance the other way).pub const TWO_SIDES: usize = 3;+/// Two sides, reversed: the first side goes against the normal and the second along it (#2700).+pub const TWO_SIDES_REVERSED: usize = 4;++/// An extrude direction with a second side.+pub fn two_sided(direction: usize) -> bool {+ direction == TWO_SIDES || direction == TWO_SIDES_REVERSED+}/// Thin Extrude wall locations, as `solid.extrude` names them, and their labels.const WALL_SIDES: [&str; 4] = ["center", "inside", "outside", "two_sides"];const WALL_LABELS: [&str; 4] = ["Center", "Inside", "Outside", "Two Sides"];@@ -2487,10 +2494,21 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {row_label(ui, "Direction");// One Side, Two Sides, Symmetric (a flip is a negative distance).let order = [0usize, TWO_SIDES, 2];- let mut pos = order.iter().position(|o| o == direction).unwrap_or(0);+ let reversed = *direction == 1 || *direction == TWO_SIDES_REVERSED;+ let shown = match *direction {+ 1 => 0,+ TWO_SIDES_REVERSED => TWO_SIDES,+ d => d,+ };+ let mut pos = order.iter().position(|o| *o == shown).unwrap_or(0);combo(ui, "ex_dir", &["One Side", "Two Sides", "Symmetric"], &mut pos);- if pos != order.iter().position(|o| o == direction).unwrap_or(0) {- *direction = order.get(pos).copied().unwrap_or(0);+ if pos != order.iter().position(|o| *o == shown).unwrap_or(0) {+ // One Side and Two Sides keep Reverse.+ *direction = match (order.get(pos).copied().unwrap_or(0), reversed) {+ (0, true) => 1,+ (TWO_SIDES, true) => TWO_SIDES_REVERSED,+ (d, _) => d,+ };// Selecting Symmetric applies the current total-distance semantics.d.extra.insert("convention".into(), json!(solidcraft_engine::doc::ExtrudeConvention::TotalDistance));// An explicit direction ends the automatic choices (#1257).@@ -2498,11 +2516,15 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {*auto_op = false;}ui.end_row();- if *direction < 2 {+ if *direction < 2 || two_sided(*direction) {row_label(ui, "Reverse");- let mut reverse = *direction == 1;+ let mut reverse = *direction == 1 || *direction == TWO_SIDES_REVERSED;if ui.checkbox(&mut reverse, tr("Reverse Direction")).changed() {- *direction = usize::from(reverse);+ *direction = match (two_sided(*direction), reverse) {+ (true, true) => TWO_SIDES_REVERSED,+ (true, false) => TWO_SIDES,+ (false, r) => usize::from(r),+ };// An explicit direction ends the automatic choices (#1257).smart.manual_dir = true;*auto_op = false;@@ -2520,17 +2542,19 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {row_label(ui, "Distance");enter |= field(ui, distance);ui.end_row();- if *direction == TWO_SIDES {- row_label(ui, "Distance 2");- enter |= field(ui, distance2);- ui.end_row();- }}if ext == 1 {row_label(ui, "To Offset");enter |= field(ui, to_offset);ui.end_row();}+ // The second side is a distance whatever the first side's extent: All one+ // way and a distance the other is a common two-sided cut (#2700).+ if two_sided(*direction) {+ row_label(ui, "Distance 2");+ enter |= field(ui, distance2);+ ui.end_row();+ }if *direction < 2 {row_label(ui, "Taper Angle");let before = taper.clone();@@ -3805,7 +3829,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, Sneed(0, if *thin { "curves or profiles" } else { "profiles or a planar face" })?;let mut common = json!({"distance": distance, "direction": DIRS.get(*direction).copied().unwrap_or("positive"), "operation": OPS.get(*operation).copied().unwrap_or("new")});let tapered = s.doc.eval(taper, ValueKind::Angle).map(|v| v.abs() > 1e-12).unwrap_or(!taper.trim().is_empty());- if *direction == TWO_SIDES {+ if two_sided(*direction) {common["distance2"] = json!(distance2);} else if *direction < 2 && (*taper_present || tapered) {common["taper"] = json!(taper);@@ -4857,6 +4881,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Diad.kind = Kind::Extrude {distance: extent.distance.to_string(),direction: match (extent.direction, &extent.distance2) {+ (Direction::Negative, Some(_)) => TWO_SIDES_REVERSED,(_, Some(_)) => TWO_SIDES,(Direction::Positive, None) => 0,(Direction::Negative, None) => 1,diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rsindex 739631c343..05600cfe60 100644--- a/crates/ui-egui/src/extrude_edit_tests.rs+++ b/crates/ui-egui/src/extrude_edit_tests.rs@@ -48,6 +48,7 @@ fn unchanged_actual_editor_preserves_all_extents_and_parameter_identities() {json!({"direction":"symmetric","distance":"5 mm"}),json!({"direction":"symmetric","distance":"5 mm","convention":"legacy_per_side"}),json!({"distance":"10 mm","distance2":"3 mm"}),+ json!({"direction":"negative","distance":"10 mm","distance2":"3 mm"}),json!({"from":[0,0,5],"start_offset":"0 mm"}),json!({"to":[0,0,10],"to_offset":"3 mm"}),json!({"to":[0,0,-10],"to_offset":"-2 mm"}),@@ -453,3 +454,50 @@ fn a_click_on_the_extrude_arrow_stem_keeps_the_profile() {assert_eq!(picked(&h), before);assert!((dialog_distance(&h) - distance).abs() < 1e-9, "{} for {distance}", dialog_distance(&h));}++/// The volume of the body `name`.+fn volume(h: &Harness, name: &str) -> f64 {+ let state = h.app.session.world_state();+ solidcraft_engine::doc::kernel::measure(&state.body(name).unwrap().body).unwrap().volume+}++/// Two Sides with All (#2700): the editor shows Distance 2 and Reverse for a through-all cut, and+/// Reverse swaps the sides: through all down and 3 mm up instead of through all up and 3 mm down.+#[test]+fn two_sides_with_all_shows_distance_2_and_reverse_swaps_the_sides() {+ let mut h = Harness::new();+ h.app.home.open = false;+ h.app.run("solid.box", json!({"length":20,"width":20,"height":40,"corner":[0,0,-30],"body_name":"Main"})).unwrap();+ h.app.run("sketch.create", json!({"plane":"XY","name":"Hole"})).unwrap();+ h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":2})).unwrap();+ h.app.run("sketch.finish", json!({})).unwrap();+ let cut = json!({"sketch":"Hole","through_all":true,"distance2":"3 mm","operation":"cut","targets":["Main"],"name":"Depth"});+ h.app.run("solid.extrude", cut).unwrap();+ h.frames(4);+ // The box runs 10 mm above the sketch and 30 mm below it.+ let area = std::f64::consts::PI * 4.0;+ let depth = |h: &Harness| (16000.0 - volume(h, "Main")) / area;+ assert!((depth(&h) - 13.0).abs() < 0.05, "{}", depth(&h));+ open(&mut h);+ assert!(h.widget("Distance 2").is_some(), "Two Sides with All shows the second side's distance");+ assert!(h.widget("Reverse Direction").is_some(), "Two Sides offers Reverse");+ // The first side's arrow goes up (through all) and the second's down, either side of the+ // hole's centre on screen; Reverse swaps them.+ let centre = h.at(&json!({"world":[10,10,0]})).unwrap()[1] as f32;+ let tips = || (crate::scenario::handle_at("arrow").unwrap().y - centre, crate::scenario::handle_at("arrow2").unwrap().y - centre);+ let (first, second) = tips();+ assert!(first < 0.0 && second > 0.0, "the first side's arrow is above the sketch, the second's below: {first} {second}");+ h.step(&json!({"widget":"Reverse Direction"})).unwrap();+ h.frames(2);+ let (first, second) = tips();+ assert!(first > 0.0 && second < 0.0, "reversed, the first side's arrow is below, the second's above: {first} {second}");+ h.step(&json!({"widget":"OK"})).unwrap();+ assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log);+ let e = extent(&h);+ assert_eq!((e.direction, e.through_all, e.distance2.as_deref()), (solidcraft_engine::doc::Direction::Negative, true, Some("3 mm")));+ assert!((depth(&h) - 33.0).abs() < 0.05, "{}", depth(&h));+ // And it opens reversed again: OK without changes keeps it.+ open(&mut h);+ h.step(&json!({"widget":"OK"})).unwrap();+ assert_eq!(extent(&h), e);+}