diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 7db144614..144c295b3 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -452,8 +452,14 @@ pub enum AxisRef { SketchAxis { axis: String }, /// World X / Y / Z axis through the origin. World { axis: String }, - /// Any line in the sketch plane, in world coordinates. - Line { origin: Position, dir: Dir }, + /// Any line in the sketch plane, in world coordinates. The origin's coordinates are length + /// expressions, so the axis follows parameter changes. + Line { + #[serde(with = "point_expr")] + #[walk(placement)] + origin: PointExpr, + dir: Dir, + }, /// An edge or round face of the model (a straight or circular edge, a cylinder, cone or /// torus face), found again on each evaluation: [`crate::construct::model_axis`]. Model { geo: GeoRef }, diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index e41355a75..c6fc6bdd7 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -713,6 +713,7 @@ impl ModelState { /// After a feature evaluated to this state from `before` with cache key `key`: bodies it /// made or changed take that key, sketches it made a digest of their solved geometry (see /// [`quantize`]); the rest keep theirs. + /// `f` must have gone through [`naming_feature`]: face naming reads no parameter values. fn stamp(&mut self, doc: &Document, before: &Arc, f: &Feature, key: u64, mats: Vec) { let feature = f.id; let depth = before.bodies.iter().filter_map(|b| b.names.depth()).max().unwrap_or(0) + 1; @@ -1381,6 +1382,12 @@ impl Document { pub fn evaluation_values(&self) -> BTreeMap { evaluation_values(self).0 } + + /// A placement point read as the features read it: the parameters, and a bare number + /// beside them in the design's length unit (#9015). + pub fn eval_point(&self, p: &crate::PointExpr) -> Result { + point(&self.evaluation_values(), p) + } } /// The values features are evaluated with: the parameters, and the design's length unit. @@ -2342,7 +2349,9 @@ impl Model { } _ => mats, }; - next.stamp(doc, &state, f, key, mats); + // A revolve axis origin that follows parameters names its faces from its values. + let named = naming_feature(&vals, f); + next.stamp(doc, &state, &named, key, mats); // Evaluated again only for what came before it (a mirror moved by a drag). if let Some(old) = self.results.get(i).filter(|old| old.id == f.id) { let made = old.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| (b.name.as_str(), b)); @@ -4226,10 +4235,26 @@ fn blend_body( Ok((Traced::step(nb.with_preserved_planar_sources(&mb.body)?, &[&from]), used, tapered)) } +/// `f` as the naming of its faces reads it: a revolve's explicit axis origin written as the values +/// it has now (the naming has no parameter values to read an expression with). +fn naming_feature<'a>(vals: &BTreeMap, f: &'a Feature) -> std::borrow::Cow<'a, Feature> { + if let FeatureKind::Revolve { axis: AxisRef::Line { origin, .. }, .. } = &f.kind + && let Ok(o) = point(vals, origin) + { + let mut g = f.clone(); + if let FeatureKind::Revolve { axis: AxisRef::Line { origin, .. }, .. } = &mut g.kind { + *origin = [format!("{} mm", o.x).into(), format!("{} mm", o.y).into(), format!("{} mm", o.z).into()]; + } + return std::borrow::Cow::Owned(g); + } + std::borrow::Cow::Borrowed(f) +} + /// The revolve axis in the sketch's plane coordinates (a point and a direction). `st` is the model /// an axis on an edge or face of it is found in; `construct` gives a construction axis, by name, in -/// the sketch's 3D frame. +/// the sketch's 3D frame; `vals` are the parameter values an explicit axis's origin is read with. pub(crate) fn revolve_axis( + vals: &BTreeMap, ss: &SolvedSketch, axis: &AxisRef, st: &ModelState, @@ -4264,7 +4289,7 @@ pub(crate) fn revolve_axis( } Ok((pl.to_local(Vec3::ZERO), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) } - AxisRef::Line { origin, dir } => line_in_sketch_plane(ss, origin.0, dir.0), + AxisRef::Line { origin, dir } => line_in_sketch_plane(ss, point(vals, origin)?, dir.0), AxisRef::Model { geo } => { let (o, d) = crate::construct::model_axis(st, geo)?; line_in_sketch_plane(ss, o, d) @@ -5377,8 +5402,9 @@ fn feature_tools_with_constructor( f, )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); - let (o, d) = - revolve_axis(&ss, axis, &*axis_state(doc, st, f.component, axis)?, &|name| construction_axis_in(Some(doc), st, name, f.component))?; + let (o, d) = revolve_axis(vals, &ss, axis, &*axis_state(doc, st, f.component, axis)?, &|name| { + construction_axis_in(Some(doc), st, name, f.component) + })?; // To Object is in this feature's component frame: the model as seen from there. let tst = if to.is_some() { state_in_frame(doc, st, f.component)? } else { std::borrow::Cow::Borrowed(st) }; let angles = if to.is_some() { diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 090dce4bb..b6ff6d3fb 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -308,7 +308,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; - let (o, d) = revolve_axis(&ss, axis, &*super::axis_state(doc, st, f.component, axis)?, &|name| { + let (o, d) = revolve_axis(vals, &ss, axis, &*super::axis_state(doc, st, f.component, axis)?, &|name| { construction_axis_in(Some(doc), st, name, f.component) })?; let a = val(vals, angle, Kind::Angle)?; diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 5c6547d84..550be0249 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -12,6 +12,7 @@ revolve moves: axis.dir[0], axis.dir[1], axis.dir[2], axis.origin[0], axis.origin[1], axis.origin[2], to[0], to[1], to[2] face points: [3, 3.5, 3.25] profiles: 1 all + placement: 9, 9.5, 9.25 fillet_constant moves: edges[0][0], edges[0][1], edges[0][2] fillet_chord @@ -167,6 +168,7 @@ surface_extrude face points: [1, 1.5, 1.25], [2, 2.5, 2.25] surface_revolve moves: axis.dir[0], axis.dir[1], axis.dir[2], axis.origin[0], axis.origin[1], axis.origin[2] + placement: 9, 9.5, 9.25 surface_sweep surface_sweep_options surface_loft diff --git a/crates/doc/src/format/pending/revolve-axis-origin-expressions.rs b/crates/doc/src/format/pending/revolve-axis-origin-expressions.rs new file mode 100644 index 000000000..2b6ed033d --- /dev/null +++ b/crates/doc/src/format/pending/revolve-axis-origin-expressions.rs @@ -0,0 +1,5 @@ +//! A revolve's explicit axis `{origin, dir}` can save its origin's coordinates as length +//! expressions (`["W / 2", 0, "groove_floor"]`) so the axis follows the parameters; a plain number +//! stays a number. An older design has numbers only and reads as before. The last release refuses +//! a design with this change and asks for an update, instead of opening it and reading an +//! expression as the origin. diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 9c5d16ddc..649a999b1 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -835,7 +835,7 @@ pub(crate) fn face_centres(b: &ModelBody) -> Vec { samples(&b.mesh(), face_count(b)).into_iter().map(|ps| ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64)).collect() } -/// The name of a face new to `f`. +/// The name of a face new to `f` (a feature that went through `eval::naming_feature`). fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usize, fid: u64, curves: &std::cell::OnceCell) -> String { let c = ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64); match &f.kind { @@ -858,7 +858,10 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi } FeatureKind::Revolve { sketch, axis, .. } => { let Some(ss) = before.sketch(sketch.0) else { return format!("F{fid}:face:{fi}") }; - let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis, before, &|name| crate::eval::construction_axis_in(None, before, name, 0)) else { + // The origin was written as its values when the feature was evaluated (`naming_feature`). + let Ok((o2, d2)) = + crate::eval::revolve_axis(&Default::default(), ss, axis, before, &|name| crate::eval::construction_axis_in(None, before, name, 0)) + else { return format!("F{fid}:face:{fi}"); }; let (o, d) = (ss.plane.to_world(o2), (ss.plane.to_world(o2 + d2) - ss.plane.to_world(o2)).normalized().unwrap_or(Vec3::Z)); diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index daab687ec..32acb1d6c 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -43,7 +43,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") - .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | {type: world, axis: X|Y|Z} (as returned by timeline.inspect) | 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); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, touching?, targets?, name?, body_name?"), + .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | {type: world, axis: X|Y|Z} (as returned by timeline.inspect) | construction axis name (followed when edited) | {origin, dir} (origin: numbers or length expressions, followed when parameters change) | {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); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, touching?, targets?, name?, body_name?"), CommandSpec::new("solid.sweep", "Sweep", sweep) .at("SOLID", "CREATE") .icon("sweep") @@ -1335,7 +1335,8 @@ fn revolve(s: &mut Session, p: &Value) -> Result { /// A revolve axis of `sketch` from its parameter: a sketch line id, the sketch's x or y axis, a /// world axis (also as saved: {type: world, axis: X|Y|Z}), a construction axis by name -/// (followed when it is edited), {origin, dir}, or an edge +/// (followed when it is edited), {origin, dir} (each origin coordinate a number or an expression over +/// the parameters, which the axis follows), or an edge /// or round face of the model ({edge|face: [x,y,z]}), which the revolve follows as the model /// changes. A line of the sketch wins over a construction axis of the same name. pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Result { @@ -1348,9 +1349,12 @@ pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Resu str_(o, "axis").filter(|a| matches!(*a, "X" | "Y" | "Z")).ok_or_else(|| bad(cmd, "world axis requires `axis` to be X, Y or Z"))?; return Ok(AxisRef::World { axis: axis.into() }); } - let origin = o.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); - let dir = o.get("dir").and_then(vec3).ok_or_else(|| bad(cmd, "axis needs `dir`"))?; - return Ok(AxisRef::Line { origin: Position(origin), dir: Dir(dir) }); + let origin = point_param(s, o, "origin", cmd)?.unwrap_or_else(|| solidcraft_doc::point_expr(Vec3::ZERO)); + let dir = match o.get("dir") { + None => return Err(bad(cmd, "axis needs `dir`")), + Some(v) => vec3(v).ok_or_else(|| bad(cmd, "axis `dir` must be a direction [x, y, z] of numbers"))?, + }; + return Ok(AxisRef::Line { origin, dir: Dir(dir) }); } match str_(p, "axis") { Some(a @ ("X" | "Y" | "Z")) => Ok(AxisRef::World { axis: a.into() }), diff --git a/crates/engine/src/cmd/revolve_convention_tests.rs b/crates/engine/src/cmd/revolve_convention_tests.rs index 5a677507f..f3cc54c7e 100644 --- a/crates/engine/src/cmd/revolve_convention_tests.rs +++ b/crates/engine/src/cmd/revolve_convention_tests.rs @@ -473,3 +473,74 @@ fn invalid_world_axis_objects_are_rejected_atomically() { assert!(s.model.state().bodies.is_empty()); } } + +#[test] +fn explicit_axis_origin_takes_expressions_and_follows_parameters() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + profile(&mut s, false); + let volume = |s: &Session| solidcraft_kernel::measure(&s.model.state().bodies[0].body).unwrap().volume; + let axis = json!({"origin": ["W / 2 - 20", 0, 0], "dir": [0, 1, 0]}); + run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": axis, "name": "Turn", "operation": "new"})); + // W / 2 - 20 is 0 mm: radii 2 to 4 about x = 0. + assert!((volume(&s) - 120.0 * PI).abs() < 0.2, "{}", volume(&s)); + let FeatureKind::Revolve { axis: solidcraft_doc::AxisRef::Line { origin, .. }, .. } = &s.doc.find_feature("Turn").unwrap().kind else { + panic!("not a line axis"); + }; + assert_eq!(origin[0].as_str(), "W / 2 - 20"); + let reopened = Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.find_feature("Turn").unwrap().kind, s.doc.find_feature("Turn").unwrap().kind); + // Moving the axis follows W: the origin is at x = 1, so the radii are 1 to 3. + run(&mut s, "parameters.change", json!({"name": "W", "expression": "42 mm"})); + assert!((volume(&s) - 80.0 * PI).abs() < 0.2, "{}", volume(&s)); +} + +#[test] +fn explicit_axis_refuses_an_origin_or_dir_it_cannot_read() { + let mut s = Session::default(); + profile(&mut s, false); + let before = s.doc.to_json(); + for axis in [ + json!({"origin": ["no_such_parameter", 0, 0], "dir": [0, 1, 0]}), + json!({"origin": ["1 +", 0, 0], "dir": [0, 1, 0]}), + json!({"origin": [0, 0], "dir": [0, 1, 0]}), + json!({"origin": [null, 0, 0], "dir": [0, 1, 0]}), + json!({"origin": [0, 0, 0], "dir": ["W", 1, 0]}), + ] { + let error = s.execute("solid.revolve", &json!({"sketch": "Profile", "axis": axis, "operation": "new"})).unwrap_err(); + assert!(matches!(error, crate::EngineError::BadParams { .. }), "{axis}: {error}"); + assert!(!error.to_string().contains("sketch plane"), "{axis}: {error}"); + assert_eq!(s.doc.to_json(), before); + } +} + +#[test] +fn surface_revolve_axis_origin_follows_a_parameter() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + profile(&mut s, false); + let axis = json!({"origin": ["W / 2 - 20", 0, 0], "dir": [0, 1, 0]}); + run(&mut s, "surface.revolve", json!({"sketch": "Profile", "axis": axis, "name": "Wall"})); + let min_x = |s: &Session| s.model.state().bodies[0].body.mesh(&solidcraft_kernel::MeshTolerance::chord(1e-3)).unwrap().bounds().min.x; + // W / 2 - 20 is 0 mm: the profile (x from 2 to 4) sweeps out to x = -4. + assert!((min_x(&s) + 4.0).abs() < 0.05, "{}", min_x(&s)); + run(&mut s, "parameters.change", json!({"name": "W", "expression": "42 mm"})); + // The axis is at x = 1: the farthest point is 3 from it. + assert!((min_x(&s) + 2.0).abs() < 0.05, "{}", min_x(&s)); + let reopened = Document::from_json(&s.doc.to_json()).unwrap(); + assert_eq!(reopened.find_feature("Wall").unwrap().kind, s.doc.find_feature("Wall").unwrap().kind); +} + +#[test] +fn a_parameter_driven_axis_origin_names_revolve_faces_as_the_numeric_origin_does() { + let names = |origin: Value| { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + profile(&mut s, false); + run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"origin": origin, "dir": [0, 1, 0]}, "operation": "new"})); + solidcraft_doc::naming::face_names(&s.model.state().bodies[0]).to_vec() + }; + let numeric = names(json!([20, 0, 0])); + assert!(numeric.iter().all(|n| !n.contains(":face:")), "index names: {numeric:?}"); + assert_eq!(names(json!(["W / 2", 0, 0])), numeric); +} diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 1e812db8d..e90ae33d1 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -44,7 +44,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.revolve", "Surface Revolve", surface_revolve) .at("SURFACE", "CREATE") .icon("surface_revolve") - .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|{type: world, axis: X|Y|Z}|construction axis name|{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); angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), + .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|{type: world, axis: X|Y|Z}|construction axis name|{origin, dir} (origin: numbers or length expressions, followed when parameters change) | {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); angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), CommandSpec::new("surface.sweep", "Surface Sweep", surface_sweep) .at("SURFACE", "CREATE") .icon("surface_sweep") diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rs index 5591dedec..150a5d64f 100644 --- a/crates/engine/src/frames.rs +++ b/crates/engine/src/frames.rs @@ -434,7 +434,11 @@ impl Drop for Nested { pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result> { // A command with no world picks has nothing to map, and may not need the bodies placed. let picks = !table(id).is_empty() || matches!(id, "library.apply" | "timeline.redefine" | "sketch.redefine"); - if !picks || !placed(s) { + // Edit Feature of a revolve restores its saved axis (and the origin's expressions) even + // where nothing is placed (`map_local`). + let revolve_edit = + id == "timeline.redefine" && matches!(params.get("command").and_then(Value::as_str), Some("solid.revolve" | "surface.revolve")); + if !picks || (!placed(s) && !revolve_edit) { return Ok(None); } // A move of bodies in differently turned frames keeps its world vectors: `solid.move` splits @@ -442,7 +446,8 @@ pub fn to_local(s: &Session, id: &str, params: &Value) -> crate::Result inner, + None if matches!(cmd, "solid.revolve" | "surface.revolve") => params.get("params")?.clone(), + None => return None, + }; // An untouched explicit axis is displayed in world coordinates by Edit // Feature. Keep its exact saved values instead of an affine round trip. - if cmd == "solid.revolve" - && let solidcraft_doc::FeatureKind::Revolve { axis: solidcraft_doc::AxisRef::Line { origin, dir }, .. } = &feature.kind + if let ( + "solid.revolve" | "surface.revolve", + solidcraft_doc::FeatureKind::Revolve { axis: solidcraft_doc::AxisRef::Line { origin, dir }, .. } + | solidcraft_doc::FeatureKind::SurfaceRevolve { axis: solidcraft_doc::AxisRef::Line { origin, dir }, .. }, + ) = (cmd, &feature.kind) + && let Ok(at) = s.doc.eval_point(origin) { let frame = context.active_component_frame(); - let displayed = serde_json::json!({"origin":pt(apply_point(&frame,origin.0)),"dir":pt(apply_vector(&frame,dir.0))}); - if params.get("params").and_then(|p| p.get("axis")) == Some(&displayed) { - inner["axis"] = serde_json::json!({"origin":pt(origin.0),"dir":pt(dir.0)}); + // Each half is kept when the dialog gives back what it showed (to float dust), so + // editing only the direction leaves the origin's expressions alone. + let given = params.get("params").and_then(|p| p.get("axis")); + let shown = |key: &str, shown: Vec3| { + let given = given.and_then(|a| a.get(key)).and_then(Value::as_array)?; + let [x, y, z] = given.as_slice() else { return None }; + let near = |g: &Value, w: f64| g.as_f64().is_some_and(|g| (g - w).abs() <= 1e-9 * (1.0 + w.abs())); + (near(x, shown.x) && near(y, shown.y) && near(z, shown.z)).then_some(()) + }; + if let Some(axis) = inner.get_mut("axis").and_then(Value::as_object_mut) { + if shown("origin", apply_point(&frame, at)).is_some() { + // The origin as saved: its expressions stay expressions. + axis.insert("origin".into(), placement_point(origin)); + } + if shown("dir", apply_vector(&frame, dir.0)).is_some() { + axis.insert("dir".into(), pt(dir.0)); + } } } let points = match (&feature.kind, cmd) { @@ -677,16 +707,19 @@ fn map_local(s: &Session, world: &solidcraft_doc::ModelState, id: &str, params: m.changed.then_some(Value::Object(out)) } +/// A placement point as saved: a plain number stays a number, an expression is its text. +fn placement_point(p: &solidcraft_doc::PointExpr) -> Value { + Value::Array( + p.iter() + .map(|e| e.as_str().trim().parse::().ok().filter(|x| x.is_finite()).map_or_else(|| Value::from(e.as_str()), Value::from)) + .collect(), + ) +} + /// A primitive's saved placement inputs, in its component's frame, for redefining it with `cmd`. fn primitive_placement(kind: &solidcraft_doc::FeatureKind, cmd: &str) -> Vec<(&'static str, Value)> { use solidcraft_doc::FeatureKind as Feature; - let point = |p: &solidcraft_doc::PointExpr| { - Value::Array( - p.iter() - .map(|e| e.as_str().trim().parse::().ok().filter(|x| x.is_finite()).map_or_else(|| Value::from(e.as_str()), Value::from)) - .collect(), - ) - }; + let point = placement_point; match (kind, cmd) { (Feature::Box { corner, .. }, "solid.box") => vec![("corner", point(corner))], (Feature::Sphere { center, .. }, "solid.sphere") | (Feature::Torus { center, .. }, "solid.torus") => vec![("center", point(center))], diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rs index fd8214030..eb49be84e 100644 --- a/crates/engine/src/frames_tests.rs +++ b/crates/engine/src/frames_tests.rs @@ -358,6 +358,48 @@ fn editing_a_primitive_in_a_turned_component_keeps_its_placement() { assert!((size.x - before.x).abs() < 1e-6 && (size.y - 12.0).abs() < 0.05 && (size.z - 12.0).abs() < 0.05, "{size:?}"); } +/// Edit Feature shows an explicit revolve axis with its origin evaluated; sending that back +/// untouched keeps the saved expressions, for a solid and a surface revolve alike. +#[test] +fn an_untouched_revolve_axis_keeps_its_origin_expressions_through_redefine() { + for (command, name) in [("solid.revolve", "Turn"), ("surface.revolve", "Shell")] { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "W", "expression": "40 mm"})); + run(&mut s, "sketch.create", json!({"name": "Profile", "plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [5, 0], "p1": [10, 5]})); + run(&mut s, "sketch.finish", json!({})); + let axis = json!({"origin": ["W / 2", 0, 0], "dir": [0, 1, 0]}); + let mut made = json!({"sketch": "Profile", "axis": axis, "angle": "90 deg", "name": name}); + if command == "solid.revolve" { + made["operation"] = json!("new"); + } + run(&mut s, command, made); + // The origin's coordinates as text (a saved 0 may read back as 0 or 0.0). + let saved = |s: &mut Session| -> Vec { + let axis = run(s, "timeline.inspect", json!({"feature": name}))["definition"]["axis"].clone(); + axis["origin"].as_array().unwrap().iter().map(|c| c.as_f64().map_or_else(|| c.as_str().unwrap().to_string(), |x| x.to_string())).collect() + }; + let original = saved(&mut s); + assert_eq!(original, ["W / 2", "0", "0"]); + // What the dialog sends back untouched: the origin as numbers. + let mut params = json!({"sketch": "Profile", "axis": {"origin": [20.0, 0.0, 0.0], "dir": [0.0, 1.0, 0.0]}, "angle": "45 deg"}); + if command == "solid.revolve" { + params["operation"] = json!("new"); + } + run(&mut s, "timeline.redefine", json!({"feature": name, "command": command, "params": params})); + assert_eq!(saved(&mut s), original, "{command}"); + // Only the direction changed: the origin keeps its expressions. + let mut turned = params.clone(); + turned["axis"]["dir"] = json!([0.0, -1.0, 0.0]); + run(&mut s, "timeline.redefine", json!({"feature": name, "command": command, "params": turned})); + assert_eq!(saved(&mut s), original, "{command}"); + // A changed origin is taken as given. + params["axis"]["origin"] = json!([21.0, 0.0, 0.0]); + run(&mut s, "timeline.redefine", json!({"feature": name, "command": command, "params": params})); + assert_eq!(saved(&mut s), ["21", "0", "0"], "{command}"); + } +} + /// A new placement given to `timeline.redefine` is still a world point. #[test] fn a_new_primitive_placement_is_still_mapped_from_the_world() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 913f9fd07..bf9cda0e8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2949,6 +2949,17 @@ fn stored_input_reference_key(d: &Dialog, index: usize) -> Option<&'static str> } } +/// An explicit revolve axis as its dialog holds it, in the world: the origin evaluated with the +/// parameters (an untouched axis is restored as saved, expressions included: +/// `solidcraft_engine::frames::to_local`). An origin that cannot be evaluated is kept as saved. +pub(crate) fn line_axis_value(s: &Session, frame: &solidcraft_engine::doc::Mat, origin: &solidcraft_engine::doc::PointExpr, dir: Vec3) -> Value { + let dir_world = pt(solidcraft_engine::doc::apply_vector(frame, dir)); + match s.doc.eval_point(origin) { + Ok(at) => json!({"origin": pt(solidcraft_engine::doc::apply_point(frame, at)), "dir": dir_world}), + Err(_) => json!({"origin": origin, "dir": dir_world}), + } +} + fn stored_revolve_axis(kind: &Kind) -> Option<&Value> { match kind { Kind::Revolve { axis, .. } | Kind::Surface(crate::dialogs_surface::Surf::Revolve { axis, .. }) => axis.as_ref(), @@ -6370,10 +6381,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option Some(json!({ - "origin": pt(solidcraft_engine::doc::apply_point(&frame, origin.0)), - "dir": pt(solidcraft_engine::doc::apply_vector(&frame, dir.0)) - })), + AxisRef::Line { origin, dir } => Some(line_axis_value(s, &frame, origin, dir.0)), // An edge or face that is gone stays the reference until another is picked. AxisRef::Model { geo } if model_axis_sel(s, geo).is_none() => serde_json::to_value(geo).ok(), _ => None, diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 87c7c28df..939025d8f 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -829,13 +829,7 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K AxisRef::SketchAxis { axis } => (Some(Sel::Axis { name: axis.to_ascii_lowercase() }), None), AxisRef::SketchLine { curve } => (Some(crate::selection::curve_pick(curve, sketch.0, s.active_sketch)), None), AxisRef::Construction { name } => (Some(Sel::Axis { name: name.to_string() }), None), - AxisRef::Line { origin, dir } => ( - None, - Some(json!({ - "origin": pt(solidcraft_engine::doc::apply_point(frame, origin.0)), - "dir": pt(solidcraft_engine::doc::apply_vector(frame, dir.0)) - })), - ), + AxisRef::Line { origin, dir } => (None, Some(crate::dialogs::line_axis_value(s, frame, origin, dir.0))), // An edge or face that is gone stays the reference until another is picked. AxisRef::Model { geo } => match crate::dialogs::model_axis_sel(s, geo) { Some(pick) => (Some(pick), None), diff --git a/crates/ui-egui/src/revolve_edit_tests.rs b/crates/ui-egui/src/revolve_edit_tests.rs index 6a1079835..81c0f3d9c 100644 --- a/crates/ui-egui/src/revolve_edit_tests.rs +++ b/crates/ui-egui/src/revolve_edit_tests.rs @@ -288,3 +288,62 @@ fn only_the_active_selection_field_looks_active() { assert_eq!(border(&h, "Profile"), filled, "filled inactive"); assert_ne!(filled, t.control_border, "filled inactive differs from empty inactive"); } + +/// A solid (or surface) revolve named `Turn` about `axis`, made in a new component `Owner` that is +/// turned and moved afterwards when `moved`, with parameter `W` = 40 mm. +fn expression_axis_design(surface: bool, moved: bool) -> Harness { + let mut h = Harness::new(); + h.app.run("parameters.add", json!({"name":"W","expression":"40 mm"})).unwrap(); + let owner = h.app.run("component.create", json!({"name":"Owner","grounded":false})).unwrap(); + let axis = json!({"origin":["W / 2", "5 mm", 0],"dir":[0,1,0]}); + let mut h = if surface { + h.app.run("sketch.create", json!({"plane":"XY","name":"Profile"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[10,0],"p1":[15,5]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("surface.revolve", json!({"sketch":"Profile","axis":axis,"angle":"90 deg","name":"Turn"})).unwrap(); + h + } else { + make(h, axis) + }; + if moved { + h.app.run("occurrence.move", json!({"occurrence":owner["occurrence"],"translate":[100,0,20],"axis":[0,0,1],"angle":"17 deg"})).unwrap(); + h.app.run("component.create", json!({"name":"Other","parent":0})).unwrap(); + } + h +} + +fn saved_axis(h: &Harness) -> Value { + match &h.app.session.doc.find_feature("Turn").unwrap().kind { + FeatureKind::Revolve { axis, .. } | FeatureKind::SurfaceRevolve { axis, .. } => serde_json::to_value(axis).unwrap(), + other => panic!("not a revolve: {other:?}"), + } +} + +#[test] +fn untouched_edit_keeps_an_explicit_axis_origin_expression_for_solid_and_surface_revolves() { + for (surface, moved) in [(false, false), (true, false), (false, true), (true, true)] { + let mut h = expression_axis_design(surface, moved); + let original = saved_axis(&h); + assert_eq!(original["origin"][0], json!("W / 2")); + open(&mut h); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "OK did not apply the edit (surface: {surface}, moved: {moved})"); + assert_eq!(saved_axis(&h), original, "surface: {surface}, moved: {moved}"); + } +} + +#[test] +fn an_axis_origin_that_cannot_be_evaluated_is_kept_by_an_untouched_edit() { + for (surface, moved) in [(false, false), (true, false), (false, true), (true, true)] { + let mut h = expression_axis_design(surface, moved); + let original = saved_axis(&h); + // W is no longer a length: the revolve fails and its origin cannot be shown as numbers. + // (`parameters.change` refuses that, so the parameter is set directly.) + let mut doc = (*h.app.session.doc).clone(); + doc.params.iter_mut().filter(|p| p.name == "W").for_each(|p| p.expr = "5 deg".into()); + h.app.session.doc = std::sync::Arc::new(doc); + open(&mut h); + h.step(&json!({"widget":"OK"})).unwrap(); + assert_eq!(saved_axis(&h), original, "surface: {surface}, moved: {moved}"); + } +}