diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 70a46feec..978d7254b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2240,7 +2240,11 @@ pub enum PatternKind { reversed2: bool, }, Circular { - origin: Position, + /// A point on the axis the copies turn about: numbers, or length expressions it follows + /// as the parameters change (#10852). + #[serde(with = "point_expr")] + #[walk(placement)] + origin: PointExpr, axis: Dir, #[walk(unitless = "Quantity")] count: Expr, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 438f732df..60984be81 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -6541,11 +6541,19 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model } } crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => { - // On an edge or round face: about it as it is now; on a construction axis: where it is. + // On an edge or round face: about it as it is now; on a construction axis: where it is; + // else through its origin, whose expressions follow the parameters (#10852). let (origin, axis) = match (axis_ref, axis_feature) { (Some(g), _) => crate::construct::model_axis(&construction_state(doc, st, component), g)?, (None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?, - (None, None) => (origin.0, axis.0), + (None, None) => { + let [x, y, z] = origin; + let o = Vec3::new(val(vals, x, Kind::Length)?, val(vals, y, Kind::Length)?, val(vals, z, Kind::Length)?); + if ![o.x, o.y, o.z].iter().all(|c| c.is_finite() && c.abs() < 1e9) { + return Err(DocError::Invalid("the pattern's axis origin is out of range".into())); + } + (o, axis.0) + } }; let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index fc766b6a5..81b637362 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -107,7 +107,7 @@ pattern_circular inputs: Quantity = circ.count (Unitless) Total angle = circ.angle (Angle) - expressions: circ.count, circ.angle + expressions: circ.count, circ.angle, 0, 0, 0 pattern_path inputs: Quantity = path.count (Unitless) diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 4196cf133..a7e5ba3bf 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -47,6 +47,7 @@ pattern_rectangular moves: pattern.dir1[0], pattern.dir1[1], pattern.dir2[1], pattern.dir2[2] pattern_circular moves: pattern.axis[0], pattern.axis[2], pattern.origin[0], pattern.origin[1], pattern.origin[2] + placement: 0, 0, 0 pattern_path mirror moves: plane.axis_dir[0], plane.axis_dir[1], plane.axis_origin[0], plane.axis_origin[1], plane.axis_origin[2] diff --git a/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs b/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs new file mode 100644 index 000000000..7919fbe64 --- /dev/null +++ b/crates/doc/src/format/pending/circular-pattern-origin-expressions.rs @@ -0,0 +1,4 @@ +//! A circular pattern's axis `origin` can hold length expressions (strings) as well as numbers, +//! so a pattern about a parameter-driven point follows the parameter (#10852). An origin of +//! plain numbers is saved as before, and older designs need no transformation. The last release +//! refuses this newer format and asks for an update instead of failing to read the origin. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 4f1e70c5f..5a65389ff 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -91,7 +91,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} (origin coordinates may be length expressions; the pattern follows them) | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_path") @@ -2081,16 +2081,32 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { finish_pattern(s, p, features, pattern, bodies) } +/// The line a circular pattern turns about, as [`axis_line`] reads it, except that the origin of +/// `{origin, dir}` may be length expressions, kept so the pattern follows them (#10852). +fn pattern_axis(s: &Session, p: &Value, cmd: &str) -> Result<(PointExpr, Vec3, Option, Option)> { + if let Some(a @ Value::Object(o)) = p.get("axis") + && o.contains_key("origin") + && !super::is_model_axis(a) + { + // Read under its full name, so a refusal says which origin it means. + let origin = point_param(s, &json!({ "axis.origin": o.get("origin") }), "axis.origin", cmd)?; + let dir = a.get("dir").and_then(vec3).and_then(|d| d.normalized()).ok_or_else(|| bad(cmd, "axis needs a non-zero `dir`"))?; + return Ok((origin.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO)), dir, None, None)); + } + let (origin, dir, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + Ok((solidcraft_doc::point_expr(origin), dir, axis_ref, axis_feature)) +} + fn pattern_circ(s: &mut Session, p: &Value) -> Result { let cmd = "solid.pattern.circular"; let (features, bodies) = pattern_sources(s, p, cmd)?; - let (origin, axis, axis_ref, axis_feature) = axis_line(s, p, cmd)?; + let (origin, axis, axis_ref, axis_feature) = pattern_axis(s, p, cmd)?; let count = req_expr(cmd, p, "count")?; check_count(s, &count, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); check_expr(s, &angle, Kind::Angle, cmd, "angle")?; let pattern = solidcraft_doc::PatternKind::Circular { - origin: Position(origin), + origin, axis: Dir(axis), count, angle, diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs index 2ea9aa128..cf34986a8 100644 --- a/crates/engine/src/cmd/patterns_tests.rs +++ b/crates/engine/src/cmd/patterns_tests.rs @@ -240,27 +240,79 @@ fn circular_axis_origin_rejects_invalid_values_atomically() { run(&mut s, "parameters.add", json!({"name":"cy","expression":"25 mm"})); let before = s.doc.to_json(); let undo = s.undo.len(); - for origin in [ - json!(["cx", "cy", 0]), - json!(["50", 25, 0]), - json!([0, 0]), - json!([0, 0, 0, 0]), - json!(null), - json!(false), - json!({"x":0,"y":0}), - json!([1e9, 0, 0]), - json!([0, 1e100, 0]), - ] { - for (cmd, params) in [ - ("solid.pattern.circular", json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4})), - ("construct.plane.at_angle", json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45})), - ] { - let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); - assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); - assert_eq!(s.doc.to_json(), before); - assert_eq!(s.undo.len(), undo); - } + let invalid = [json!([0, 0]), json!([0, 0, 0, 0]), json!(null), json!(false), json!({"x":0,"y":0}), json!([1e9, 0, 0]), json!([0, 1e100, 0])]; + // A circular pattern's origin takes length expressions (#10852); an angled plane's doesn't. + for origin in invalid.iter().chain(&[json!(["nope", 0, 0]), json!(["2 deg", 0, 0])]) { + let params = json!({"features":["Hole1"],"axis":{"origin":origin,"dir":[0,0,1]},"count":4}); + let error = s.execute("solid.pattern.circular", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin"), "{origin}: {error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); } + for origin in invalid.iter().chain(&[json!(["cx", "cy", 0]), json!(["50", 25, 0])]) { + let params = json!({"base":"XY","axis":{"origin":origin,"dir":[1,0,0]},"angle":45}); + let error = s.execute("construct.plane.at_angle", ¶ms).unwrap_err().to_string(); + assert!(error.contains("axis.origin") && error.contains("expressions are not supported"), "{error}"); + assert_eq!(s.doc.to_json(), before); + assert_eq!(s.undo.len(), undo); + } +} + +/// #10852: a circular pattern about `{origin, dir}` with length expressions in the origin turns +/// about the point they give now, so the copies follow the parameters as the seed does. The +/// expressions are saved, renamed with their parameter, and can be set by `timeline.edit`. +#[test] +fn circular_axis_origin_expressions_follow_their_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name":"cx","expression":"50 mm"})); + run(&mut s, "parameters.add", json!({"name":"cy","expression":"40 mm"})); + // A 2 mm cube 20 mm from (cx, cy), turned about the vertical line there. + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":["cx + 20 mm","cy",0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":["cx","cy",0],"dir":[0,0,1]},"count":4})); + // The x and y extent of the four cubes: 22 mm either side of the axis while it is 20 mm away. + let span = |s: &Session| { + let st = s.model.state(); + assert_eq!(st.bodies.len(), 4); + let mut out = [f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY]; + for b in st.bodies.iter().filter_map(|mb| solidcraft_kernel::measure(&mb.body).ok()).map(|m| m.bbox) { + out = [out[0].min(b.min.x), out[1].max(b.max.x), out[2].min(b.min.y), out[3].max(b.max.y)]; + } + out + }; + let about_at = |s: &Session, x: f64, y: f64, half: f64| { + for (got, want) in span(s).into_iter().zip([x - half, x + half, y - half, y + half]) { + assert!((got - want).abs() < 1e-6, "{:?} is not {half} mm either side of ({x}, {y})", span(s)); + } + }; + let about = |s: &Session, x: f64, y: f64| about_at(s, x, y, 22.0); + // The origin as the pattern saves it. + let saved_origin = |s: &Session| match s.doc.features.last().map(|f| &f.kind) { + Some(solidcraft_doc::FeatureKind::Pattern { pattern, .. }) => serde_json::to_value(pattern).unwrap_or_default()["origin"].clone(), + other => panic!("not a pattern: {other:?}"), + }; + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!(["cx", "cy", 0.0]), "the expressions are saved"); + run(&mut s, "parameters.change", json!({"name":"cx","expression":"60 mm"})); + about(&s, 60.0, 40.0); + // Renaming a parameter renames it in the origin, and the pattern still follows it. + run(&mut s, "parameters.rename", json!({"name":"cy","new_name":"py"})); + run(&mut s, "parameters.change", json!({"name":"py","expression":"45 mm"})); + about(&s, 60.0, 45.0); + assert_eq!(saved_origin(&s), json!(["cx", "py", 0.0])); + let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap_or_else(|e| panic!("{e}"))); + about(&reopened, 60.0, 45.0); + // timeline.edit sets the origin as expressions too: 10 mm back, so the cube is 30 mm away. + let pattern = s.doc.features.last().map(|f| f.id).unwrap_or_default(); + run(&mut s, "timeline.edit", json!({"feature":pattern,"set":{"pattern.origin":["cx - 10 mm","py","0 mm"]}})); + about_at(&s, 50.0, 45.0, 32.0); + run(&mut s, "edit.undo", json!({})); + about(&s, 60.0, 45.0); + // Plain numbers are saved as numbers, as before. + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length":2,"width":2,"height":2,"corner":[70,40,0],"body_name":"Cube"})); + run(&mut s, "solid.pattern.circular", json!({"bodies":["Cube"],"axis":{"origin":[50,40,0],"dir":[0,0,1]},"count":4})); + about(&s, 50.0, 40.0); + assert_eq!(saved_origin(&s), json!([50.0, 40.0, 0.0])); } #[test] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 755ae3bd5..baf004a22 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6361,11 +6361,15 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option().is_ok_and(|v| v.abs() < 1e-9)); + let origin: Vec = + origin.iter().map(|e| e.trim().parse::().map_or_else(|_| json!(e.to_string()), |v| json!(v))).collect(); let pick = match (axis_ref, axis_feature) { (Some(g), _) => model_axis_sel(s, g), (None, Some(name)) => Some(Sel::Axis { name: name.to_string() }), - (None, None) => world_axis(axis.0).filter(|_| origin.len() < 1e-9).map(|name| Sel::Axis { name }), + (None, None) => world_axis(axis.0).filter(|_| at_zero).map(|name| Sel::Axis { name }), }; match (pick, axis_ref) { (Some(pick), _) => { @@ -6378,7 +6382,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { - d.extra.insert("axis".into(), json!({"origin": pt3(origin.0), "dir": pt3(axis.0)})); + d.extra.insert("axis".into(), json!({"origin": origin, "dir": pt3(axis.0)})); } } d diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 4cd548cc5..8a9cc9316 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -1251,6 +1251,30 @@ fn ok_on_a_rolled_back_pattern_editor_says_it_is_not_built() { assert!(text.starts_with("Pattern changed, but it is after the history marker"), "{text}"); } +/// #10852: the editor of a circular pattern whose axis origin is length expressions sends them +/// back as they are, so applying it unchanged keeps the pattern following its parameters. +#[test] +fn editing_a_circular_pattern_keeps_its_origin_expressions() { + let mut h = Harness::new(); + h.app.home.open = false; + for (id, params) in [ + ("parameters.add", json!({"name":"cx","expression":"20 mm"})), + ("solid.box", json!({"length":40,"width":30,"height":10,"corner":[0,0,0],"body_name":"Plate"})), + ("solid.cylinder", json!({"radius":2,"height":20,"base":["cx - 10 mm",15,-5],"operation":"cut","targets":["Plate"],"name":"Cut"})), + ("solid.pattern.circular", json!({"features":["Cut"],"axis":{"origin":["cx",15,0],"dir":[0,0,1]},"count":2,"name":"Pattern"})), + ] { + h.app.run(id, params).unwrap(); + } + let pattern = h.app.session.doc.features.last().unwrap().id; + let origin = |h: &Harness| serde_json::to_value(&h.app.session.doc.feature(pattern).unwrap().kind).unwrap()["pattern"]["origin"].clone(); + assert_eq!(origin(&h), json!(["cx", 15.0, 0.0])); + let d = crate::dialogs::for_feature(&h.app, pattern, None).unwrap(); + for (command, params) in crate::dialogs::apply_commands(&h.app, &d).unwrap() { + h.app.run(&command, params).unwrap(); + } + assert_eq!(origin(&h), json!(["cx", 15.0, 0.0]), "the expression is kept, not its value now"); +} + /// The Circular Pattern dialog must show only one field active at a time (#10066): the pick /// field's accent ring yields while a text field holds the keyboard, and clicking a pick field /// takes the keyboard back. diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index b2f877472..ce581d136 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -82,7 +82,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face or a fillet between curved faces (see Order in `SKILL.md`). Bodies with lofted or swept faces are refused (`offset: only bodies with planes, cylinders, cones, spheres and tori`): hollow a loft with a smaller loft and `operation: cut`. | | `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. | | `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. | -| `solid.pattern.circular` | `features`, `axis` (`"Z"`, `{origin, dir}`, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | +| `solid.pattern.circular` | `features`, `axis` (`"Z"`, `{origin, dir}` whose origin may be length expressions the pattern follows, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | | `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:["Side"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {"body":"Side (2)","name":"Side_L"}`. The new name stays when parameters change. | - **Names:** name every feature (`"name":"Standoff"`) and keep names unique across sketches and features. `timeline.roll_to {"feature":"Plate"}` picks the first match, which can be the sketch.