diff --git a/crates/doc/src/format/pending/joint-edge-axis.rs b/crates/doc/src/format/pending/joint-edge-axis.rs new file mode 100644 index 000000000..64e01d249 --- /dev/null +++ b/crates/doc/src/format/pending/joint-edge-axis.rs @@ -0,0 +1,5 @@ +//! An edge joint origin (`Snap::Edge`) saves an optional `axis`: `{"along": [x, y, z]}` (z runs +//! along the edge, the way the vector points) or `{"fixed": [x, y, z]}` (z is that direction), for +//! an edge or a corner picked in the Joint dialog, which used to be saved as a point. Older +//! designs have no `axis` and resolve as before (z out of the face). The last release refuses a +//! design with this change by its newer format number. diff --git a/crates/doc/src/joints.rs b/crates/doc/src/joints.rs index 53d122ccc..257c7a49c 100644 --- a/crates/doc/src/joints.rs +++ b/crates/doc/src/joints.rs @@ -75,6 +75,10 @@ pub enum Snap { face: Option, #[serde(default, skip_serializing_if = "Option::is_none")] corner: Option, + /// The frame's z when it isn't the face's normal (an edge or a corner picked as it is, + /// not on a face): the point still follows the edge, found by name. + #[serde(default, skip_serializing_if = "Option::is_none")] + axis: Option, }, /// A point, z along `z` (default +Z) and x toward `x` laid square to z (default: one chosen /// from z alone). @@ -87,6 +91,25 @@ pub enum Snap { }, } +/// The z of an edge origin that isn't its face's normal (component coordinates); its x follows +/// from z alone, as a point origin's does. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EdgeAxis { + /// Along a straight edge, the way this points: a hinge on the edge turns about it as it moves. + Along(Vec3), + /// This direction. + Fixed(Vec3), +} + +impl EdgeAxis { + pub fn dir(self) -> Vec3 { + match self { + EdgeAxis::Along(d) | EdgeAxis::Fixed(d) => d, + } + } +} + /// What sets a joint origin's x axis (its turn about z): a direction, or a face found by its /// persistent name, so a round origin keeps its turn when the design changes. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -179,7 +202,7 @@ impl Snap { Snap::Frame { origin, z, x } => origin.is_finite() && z.is_finite() && x.is_none_or(|x| x.is_finite()), Snap::FaceCenter { pick, x, .. } | Snap::CircleCenter { pick, x, .. } => pick.is_finite() && x_ok(x), Snap::Point { point, z, x } => point.is_finite() && z.is_none_or(|z| z.is_finite()) && x.is_none_or(|x| x.is_finite()), - Snap::Edge { pick, .. } => pick.is_finite(), + Snap::Edge { pick, axis, .. } => pick.is_finite() && axis.is_none_or(|a| a.dir().is_finite()), } } } @@ -2079,7 +2102,7 @@ pub mod cam; #[path = "joints_edge.rs"] mod edge; -pub use edge::edge_snap; +pub use edge::{edge_axis, edge_snap}; #[path = "joints_reach.rs"] mod reach; diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs index c803ca87b..afa006976 100644 --- a/crates/doc/src/joints_edge.rs +++ b/crates/doc/src/joints_edge.rs @@ -10,7 +10,7 @@ use solidcraft_geom::Vec3; -use super::{Snap, component_bodies, frame}; +use super::{EdgeAxis, Snap, component_bodies, frame}; use crate::{DocError, Document, IDENTITY, Mat, ModelBody, ModelState, Result, apply_point, mat_inverse, mat_mul}; /// A body's placement in its component and its inverse: a body moved in from another component @@ -108,7 +108,7 @@ fn meeting(e: &[Vec3], f: &[Vec3], tol: f64) -> Option { /// The frame of an edge snap in its component's coordinates. pub(super) fn edge_frame(doc: &Document, st: &ModelState, comp: u64, snap: &Snap) -> Result { - let Snap::Edge { pick, edge, face, corner } = snap else { return Err(DocError::Invalid("not an edge origin".into())) }; + let Snap::Edge { pick, edge, face, corner, axis } = snap else { return Err(DocError::Invalid("not an edge origin".into())) }; let bad = || DocError::Invalid("joint origin: degenerate frame".into()); let gone = |what: &str| DocError::Invalid(format!("joint origin: {what} no longer exists (edit the joint to pick again)")); let found = component_bodies(doc, st, comp).into_iter().find_map(|b| { @@ -143,6 +143,27 @@ pub(super) fn edge_frame(doc: &Document, st: &ModelState, comp: u64, snap: &Snap frame(at, z, Some(x)).ok_or_else(bad) } }?; + // A z of its own: x from z alone, at the point the edge gives. + let local = match axis { + None => local, + Some(a) => { + let at = Vec3::new(local[3][0], local[3][1], local[3][2]); + let (_, inv) = placement(doc, b); + let want = crate::apply_vector(&inv, a.dir()); + let z = match a { + EdgeAxis::Fixed(_) => want, + // The edge's run, the way `want` points. + EdgeAxis::Along(_) => { + let run = match (e.first(), e.last()) { + (Some(p), Some(q)) => (*q - *p).normalized().ok_or_else(bad)?, + _ => return Err(bad()), + }; + if run.dot(want) < 0.0 { -run } else { run } + } + }; + frame(at, z, None).ok_or_else(bad)? + } + }; Ok(mat_mul(&placed, &local)) } @@ -207,5 +228,16 @@ pub fn edge_snap(doc: &Document, st: &ModelState, comp: u64, pick: Vec3, on: Opt ) } }; - Ok(Snap::Edge { pick, edge: names.get(i).cloned().filter(|n| !n.is_empty()), face, corner }) + Ok(Snap::Edge { pick, edge: names.get(i).cloned().filter(|n| !n.is_empty()), face, corner, axis: None }) +} + +/// Edge snap `snap` of component `comp` given z `z` (component coordinates) of its own: along the +/// edge when the edge runs that way (so a hinge on it keeps turning about it), else fixed. +pub fn edge_axis(doc: &Document, st: &ModelState, comp: u64, snap: Snap, z: Vec3) -> Snap { + let Snap::Edge { pick, edge, face, corner, .. } = snap else { return snap }; + let with = |axis| Snap::Edge { pick, edge: edge.clone(), face: face.clone(), corner: corner.clone(), axis: Some(axis) }; + let along = with(EdgeAxis::Along(z)); + let runs = + edge_frame(doc, st, comp, &along).is_ok_and(|m| z.normalized().is_some_and(|z| Vec3::new(m[2][0], m[2][1], m[2][2]).dot(z) > 1.0 - 1e-9)); + if runs { along } else { with(EdgeAxis::Fixed(z)) } } diff --git a/crates/engine/src/cmd/component_clone_assembly_tests.rs b/crates/engine/src/cmd/component_clone_assembly_tests.rs index 308aa5285..082f2fbf0 100644 --- a/crates/engine/src/cmd/component_clone_assembly_tests.rs +++ b/crates/engine/src/cmd/component_clone_assembly_tests.rs @@ -250,7 +250,13 @@ fn an_edge_origin_is_copied_onto_the_copys_edges() { name: "Corner".into(), origin: JointOrigin { occurrence: 1, - snap: Snap::Edge { pick: Vec3::new(1.0, 2.0, 3.0), edge: edge("F1:top|F1:side"), face: edge("F1:top"), corner: edge("F1:top|F10:end") }, + snap: Snap::Edge { + pick: Vec3::new(1.0, 2.0, 3.0), + edge: edge("F1:top|F1:side"), + face: edge("F1:top"), + corner: edge("F1:top|F10:end"), + axis: None, + }, }, }]; destination.assembly.origins.clear(); diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index b3e93a939..1cfbdff3c 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -596,6 +596,39 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Two arms jointed top face to bottom face, both occurrences of one linked arm design: when + /// the arm is made thicker, its holes moved or it is made longer, Update Links brings the + /// change in and every joint type re-solves onto the moved faces, edges and corners, as it + /// does inside one design (`jointed_arms_stay_together_as_the_arm_changes`). + #[test] + fn jointed_linked_arms_stay_together_through_update_links() { + use crate::cmd::joints::face_tests::{ARM_EDITS, ARM_FORMS, arm_pairs, arm_part, arm_size, arms_apart, joint_arms}; + let dir = std::env::temp_dir().join(format!("solidcraft-link-arms-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("arm.solidcraft"); + let mut apart = Vec::new(); + for form in ARM_FORMS { + let mut part = Session::default(); + arm_part(&mut part); + run(&mut part, "file.save", json!({"path": path})); + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": path, "name": "Arm"}))["occurrence"].as_u64().unwrap(); + let pairs = arm_pairs(&mut s, first); + joint_arms(&mut s, form, &pairs); + apart.extend(arms_apart(&mut s, "as made", form, &pairs, arm_size(&[]))); + for (i, (name, value)) in ARM_EDITS.into_iter().enumerate() { + run(&mut part, "parameters.change", json!({"name": name, "expression": format!("{value} mm")})); + run(&mut part, "file.save", json!({})); + let update = run(&mut s, "component.update_links", json!({})); + assert_eq!(update["updated"], json!(["Arm"]), "{form} {name}: {update}"); + assert_eq!(update["warnings"], json!([]), "{form} {name}: {update}"); + apart.extend(arms_apart(&mut s, &format!("{name} = {value}"), form, &pairs, arm_size(&ARM_EDITS[..=i]))); + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(apart.is_empty(), "{} joints apart:\n{}", apart.len(), apart.join("\n")); + } + /// A joint made on a link that kept no face names (an older design) names the faces by their /// place in the file: Update Links says it can't vouch for it, and keeps the names from then on. #[test] diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index c1d8bd6fb..c74f5767d 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -20,7 +20,7 @@ mod inspect; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("joint.origin", "Joint Origin", joint_origin).at("SOLID", "CREATE").icon("joint_origin").params( - "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size) | point: [x,y,z], z?: [x,y,z]; body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", + "name?, occurrence?: id|name (default: from the pick, or the named face's component), face: [x,y,z] | \"\" (centre of a planar face) | circle: [x,y,z] | \"\" (centre of a round end: a point on its wall or rim, the end's centre, or the round face's name as model.faces lists it) | edge: [x,y,z] (a point on an edge of a planar face: the edge's middle, z out of the face, y into it; on?: [x,y,z] a point on the face (default: the larger planar face beside the edge); corner?: [x,y,z] near one end: the corner there, x and y along its two edges into the face; found again by name, so it follows the face as it changes size; z?: [x,y,z] the frame's z instead of the face's normal, along the edge when it runs that way, x chosen from z: an edge or corner picked as it is, kept as a point where it can't be found by name) | point: [x,y,z], z?: [x,y,z]; a circle's z?: [x,y,z] (a round edge's centre with the way out of it: its end by name when that is the frame it shows, else a point there); body?: the named face's body; end?: \"\" (a circle's end: the face across its rim there; default the end nearer the pick); x?: [x,y,z] (a direction, world) | \"\" | {face: [x,y,z]} (the frame's x: a direction, a plane's normal, or the way to another hole's axis; keeps a round origin's turn; a point's x is a direction, laid square to its z, default: chosen from z alone). Faces are kept by name: the origin follows its face, and a circle its end, when the design changes", ), CommandSpec::new("joint.create", "Joint", joint).at("SOLID", "ASSEMBLE").icon("joint").key("J").params( "type: rigid|revolute|slider|cylindrical|pin_slot|planar|ball, or a relation: parallel|perpendicular|angle|point_on_plane|point_on_line|line_on_plane \ @@ -384,7 +384,20 @@ pub(crate) fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result< } "edge" => { let (on, corner) = (v.get("on").and_then(vec3).map(local), v.get("corner").and_then(vec3).map(local)); - joints::edge_snap(&s.doc, &st, component, local(world), on, corner).map_err(|e| bad(cmd, e.to_string()))? + let snap = joints::edge_snap(&s.doc, &st, component, local(world), on, corner); + match given_z(v, &local_dir, cmd)? { + None => snap.map_err(|e| bad(cmd, e.to_string()))?, + // An edge or a corner picked as it is (z given): it follows the edge by name with + // that z, or, where it can't be (no planar face beside it, no names), stays a + // point there as before. + Some(z) => { + let at = corner.unwrap_or(local(world)); + let point = Snap::Point { point: at, z: Some(z), x: None }; + let followed = snap.ok().map(|snap| joints::edge_axis(&s.doc, &st, component, snap, z)); + let o = followed.map(|snap| JointOrigin { occurrence, snap }).filter(|o| same_frame(s, o, at, z)); + return Ok(o.unwrap_or(JointOrigin { occurrence, snap: point })); + } + } } "point" => { let z = v.get("z").and_then(vec3).map(local_dir); @@ -407,6 +420,28 @@ pub(crate) fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result< } }; let o = JointOrigin { occurrence, snap }; + // A round edge's centre with the z it was picked with: its end, by name, where that is the + // frame it shows; else a point there as before. + if what == "circle" + && let Some(z) = given_z(v, &local_dir, cmd)? + { + let at = local(world); + // The turn the point gave, kept. + let point = Snap::Point { point: at, z: Some(z), x: None }; + let px = + joints::resolve_origin(&s.doc, &st, &JointOrigin { occurrence, snap: point.clone() }).ok().map(|m| Vec3::new(m[0][0], m[0][1], m[0][2])); + let turn = |snap: Snap| match (snap, px) { + (Snap::CircleCenter { pick, face, end, x: None }, Some(x)) => Snap::CircleCenter { pick, face, end, x: Some(XRef::Dir(x)) }, + (snap, _) => snap, + }; + let by_wall = settle(s, JointOrigin { occurrence, snap: turn(o.snap.clone()) }, v, cmd).ok(); + let by_centre = || { + let snap = joints::round_end_at(&s.doc, &st, component, at)?; + settle(s, JointOrigin { occurrence, snap: turn(snap) }, v, cmd).ok() + }; + let found = by_wall.filter(|o| same_frame(s, o, at, z)).or_else(|| by_centre().filter(|o| same_frame(s, o, at, z))); + return Ok(found.unwrap_or(JointOrigin { occurrence, snap: point })); + } match settle(s, o, v, cmd) { Ok(o) => Ok(o), // A circle given by its centre, where no face lies (#393): that end of the cylinder, by @@ -422,6 +457,24 @@ pub(crate) fn origin_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result< } } +/// An origin's `z` (world), in its component's coordinates. +fn given_z(v: &Value, local_dir: &dyn Fn(Vec3) -> Vec3, cmd: &str) -> Result> { + match v.get("z") { + None | Some(Value::Null) => Ok(None), + Some(z) => { + vec3(z).filter(|z| z.is_finite() && z.len() > 1e-9).map(|z| Some(local_dir(z))).ok_or_else(|| bad(cmd, "`z` is a direction [x, y, z]")) + } + } +} + +/// Whether origin `o` resolves, now, to the frame at `at` with z along `z` (component coordinates) +/// that its pick showed. +fn same_frame(s: &Session, o: &JointOrigin, at: Vec3, z: Vec3) -> bool { + let Ok(m) = joints::resolve_origin(&s.doc, &s.model.state(), o) else { return false }; + let (o, oz) = (Vec3::new(m[3][0], m[3][1], m[3][2]), Vec3::new(m[2][0], m[2][1], m[2][2])); + o.dist(at) <= 1e-6 * at.len().max(100.0) && z.normalized().is_some_and(|z| oz.dot(z) > 1.0 - 1e-9) +} + /// The longest face name a joint origin takes. A face that cuts split and merged keeps the names /// of the faces around it (`#[,…]`): several hundred characters on a part a text or /// a pattern of holes was cut through. @@ -1462,7 +1515,7 @@ mod edge_tests; mod exprs_tests; #[cfg(test)] #[path = "joints_face_tests.rs"] -mod face_tests; +pub(crate) mod face_tests; #[cfg(test)] #[path = "joint_frames_tests.rs"] mod frames_tests; diff --git a/crates/engine/src/cmd/joints_face_tests.rs b/crates/engine/src/cmd/joints_face_tests.rs index 1a74c7a42..181e532f6 100644 --- a/crates/engine/src/cmd/joints_face_tests.rs +++ b/crates/engine/src/cmd/joints_face_tests.rs @@ -400,3 +400,177 @@ fn a_face_centre_stays_put_when_a_hole_in_its_face_moves_or_goes() { } } } + +// ---- Two arms jointed together, the arm part edited: every joint type keeps its origins +// together, for each way the joint dialog picks an origin, inside one design and through a link. + +/// The arm: a plate `L` × 20 × `T` (100 × 20 × 5 to start) along +X from the origin, with a Ø 6 +/// hole through it at x = `HX` (10) and another 10 mm in from its far end. Made at the active +/// component. +pub(crate) fn arm_part(s: &mut Session) { + for (name, e) in [("T", "5 mm"), ("L", "100 mm"), ("HX", "10 mm")] { + run(s, "parameters.add", json!({"name": name, "expression": e})); + } + run(s, "solid.box", json!({"length": "L", "width": 20, "height": "T", "corner": [0, -10, 0], "body_name": "Arm"})); + run(s, "solid.cylinder", json!({"diameter": 6, "height": 100, "base": ["HX", 0, -50], "operation": "cut"})); + run(s, "solid.cylinder", json!({"diameter": 6, "height": 100, "base": ["L - 10 mm", 0, -50], "operation": "cut"})); +} + +/// The arm's edits, (parameter, value), applied in turn: thicker (A's top face moves along the +/// joint's axis, as does B's bottom hole rim relative to A), A's hole moves sideways, and the arm +/// grows so its far end (B's hole, edge and corner) moves sideways. +pub(crate) const ARM_EDITS: [(&str, f64); 4] = [("T", 12.0), ("HX", 15.0), ("L", 140.0), ("T", 3.0)]; + +/// The joint types tried (each between its own pair of arms) and as-built. +pub(crate) const ARM_KINDS: [&str; 9] = ["rigid", "revolute", "slider", "cylindrical", "pin_slot", "planar", "ball", "point_on_plane", "as_built"]; + +/// How the joint dialog picks an origin on arm A's top (a) and arm B's bottom (b), as world +/// params, for the arms at A (0, y, 0) and B (0, y + 60, 0) in the arm's starting size. +pub(crate) fn arm_origins(form: &str, y: f64) -> (serde_json::Value, serde_json::Value) { + let b = y + 60.0; + match form { + // A hole's rim (a round edge): its centre and the way out of the material. + "rim" => (json!({"circle": [10, y, 5], "z": [0, 0, 1]}), json!({"circle": [90, b, 0], "z": [0, 0, -1]})), + // A hole's wall. + "wall" => (json!({"circle": [13, y, 4]}), json!({"circle": [93, b, 1]})), + // The plate's top and bottom faces. + "face" => (json!({"face": [50, y + 5.0, 5]}), json!({"face": [50, b + 5.0, 0]})), + // A straight edge: its middle, z along it. + "edge" => (json!({"edge": [50, y + 10.0, 5], "z": [1, 0, 0]}), json!({"edge": [50, b + 10.0, 0], "z": [1, 0, 0]})), + // A corner (a vertex), z along the part's +Z. + _ => ( + json!({"edge": [100, y + 10.0, 5], "corner": [100, y + 10.0, 5], "z": [0, 0, 1]}), + json!({"edge": [100, b + 10.0, 0], "corner": [100, b + 10.0, 0], "z": [0, 0, 1]}), + ), + } +} + +pub(crate) const ARM_FORMS: [&str; 5] = ["rim", "wall", "face", "edge", "corner"]; + +/// One joint of each of [`ARM_KINDS`] between arm pairs `pairs` (A, B occurrences), its origins +/// picked as `form` picks them. +pub(crate) fn joint_arms(s: &mut Session, form: &str, pairs: &[(u64, u64)]) { + for (k, (kind, (a, b))) in ARM_KINDS.iter().zip(pairs).enumerate() { + let (mut pa, mut pb) = arm_origins(form, 120.0 * k as f64); + pa["occurrence"] = json!(a); + pb["occurrence"] = json!(b); + let name = format!("{form}-{kind}"); + let r = if *kind == "as_built" { + run(s, "joint.as_built", json!({"type": "rigid", "name": name, "a": a, "b": b, "at": pa})) + } else { + run(s, "joint.create", json!({"type": kind, "name": name, "a": pa, "b": pb})) + }; + assert_eq!(r["errors"], json!([]), "{name}: {r}"); + } +} + +/// The arm's size as edited so far: T, HX, L (mm). +pub(crate) fn arm_size(edits: &[(&str, f64)]) -> (f64, f64, f64) { + let at = |n: &str, d: f64| edits.iter().rev().find(|(m, _)| *m == n).map_or(d, |(_, v)| *v); + (at("T", 5.0), at("HX", 10.0), at("L", 100.0)) +} + +/// Where `form` picked A's and B's origins, on the arm as it is now (T, HX, L): component +/// coordinates of the geometry itself (the hole's rim, the plate's top face's centre, …). +fn arm_spots(form: &str, (t, hx, l): (f64, f64, f64)) -> (Vec3, Vec3) { + match form { + "rim" | "wall" => (Vec3::new(hx, 0.0, t), Vec3::new(l - 10.0, 0.0, 0.0)), + "face" => (Vec3::new(l / 2.0, 0.0, t), Vec3::new(l / 2.0, 0.0, 0.0)), + "edge" => (Vec3::new(l / 2.0, 10.0, t), Vec3::new(l / 2.0, 10.0, 0.0)), + _ => (Vec3::new(l, 10.0, t), Vec3::new(l, 10.0, 0.0)), + } +} + +/// Each joint between `pairs` checked against the arm's geometry as it is now (`size`): A's +/// origin is on the rim, face, edge or corner it was picked on; B's is on its own and sits on +/// A's, z against z (point-on-plane: on A's plane; as-built: B keeps its place from A's +/// origin). The joints that aren't, with why. +pub(crate) fn arms_apart(s: &mut Session, edit: &str, form: &str, pairs: &[(u64, u64)], size: (f64, f64, f64)) -> Vec { + let list = run(s, "joint.list", json!({})); + let mut out: Vec = list["errors"].as_array().into_iter().flatten().map(|e| format!("{edit}: {} {}", e["name"], e["why"])).collect(); + let v = |f: &serde_json::Value, k: &str| { + Vec3::new(f[k][0].as_f64().unwrap_or(f64::NAN), f[k][1].as_f64().unwrap_or(f64::NAN), f[k][2].as_f64().unwrap_or(f64::NAN)) + }; + let world = |o: u64, p: Vec3| solidcraft_doc::apply_point(&solidcraft_doc::joints::occurrence_world(&s.doc, o), p); + let (sa, sb) = arm_spots(form, size); + let (sa0, _) = arm_spots(form, arm_size(&[])); + for (kind, (a, b)) in ARM_KINDS.iter().zip(pairs) { + let name = format!("{form}-{kind}"); + let Some(j) = list["joints"].as_array().into_iter().flatten().find(|j| j["name"] == name.as_str()) else { + out.push(format!("{edit}: {name} is gone")); + continue; + }; + let (oa, ob, za, zb) = (v(&j["frame_a"], "origin"), v(&j["frame_b"], "origin"), v(&j["frame_a"], "z"), v(&j["frame_b"], "z")); + let (at_a, at_b) = (world(*a, sa), world(*b, sb)); + let mut why = Vec::new(); + if oa.dist(at_a) > 1e-6 { + why.push(format!("A's origin at {oa:?}, its geometry at {at_a:?}")); + } + match *kind { + "as_built" => { + // B was made 60 mm along Y from A, the origin wherever it was on A. + let want = world(*a, Vec3::new(0.0, 60.0, 0.0) + sa - sa0); + if world(*b, Vec3::ZERO).dist(want) > 1e-6 || oa.dist(ob) > 1e-6 { + why.push(format!("B at {:?}, not {want:?}", world(*b, Vec3::ZERO))); + } + } + "point_on_plane" => { + if (at_b - at_a).dot(za).abs() > 1e-6 { + why.push(format!("B's spot {at_b:?} is off A's plane at {at_a:?} z {za:?}")); + } + } + _ => { + if ob.dist(at_b) > 1e-6 || at_a.dist(at_b) > 1e-6 || za.dot(zb) > -1.0 + 1e-9 { + why.push(format!("B's origin at {ob:?} z {zb:?}, its geometry at {at_b:?}, A's at {at_a:?} z {za:?}")); + } + } + } + if !why.is_empty() { + out.push(format!("{edit}: {name}: {}", why.join("; "))); + } + } + out +} + +/// The A, B arm occurrence pairs (one per joint type), A grounded, from the arm's first +/// occurrence `first` (at the origin). +pub(crate) fn arm_pairs(s: &mut Session, first: u64) -> Vec<(u64, u64)> { + run(s, "occurrence.ground", json!({"occurrence": first, "grounded": true})); + (0..ARM_KINDS.len()) + .map(|k| { + let y = 120.0 * k as f64; + let a = if k == 0 { + first + } else { + run(s, "occurrence.copy", json!({"occurrence": first, "translate": [0, y, 0]}))["occurrence"].as_u64().unwrap_or(0) + }; + run(s, "occurrence.ground", json!({"occurrence": a, "grounded": true})); + let b = run(s, "occurrence.copy", json!({"occurrence": first, "translate": [0, y + 60.0, 0]}))["occurrence"].as_u64().unwrap_or(0); + (a, b) + }) + .collect() +} + +/// Two arms jointed top face to bottom face, the arm's thickness, holes and length changed in the +/// design: every joint re-solves onto the moved faces, edges and corners (the joint dialog kept +/// a round edge, a straight one and a corner as points where they were picked, so a thicker +/// arm overlapped the one jointed to it). +#[test] +fn jointed_arms_stay_together_as_the_arm_changes() { + let mut apart = Vec::new(); + for form in ARM_FORMS { + let mut s = Session::default(); + run(&mut s, "component.create", json!({"name": "Arm"})); + arm_part(&mut s); + run(&mut s, "component.activate", json!({"component": "root"})); + let first = occ(&s, "Arm"); + let pairs = arm_pairs(&mut s, first); + joint_arms(&mut s, form, &pairs); + apart.extend(arms_apart(&mut s, "as made", form, &pairs, arm_size(&[]))); + for (i, (name, value)) in ARM_EDITS.into_iter().enumerate() { + run(&mut s, "parameters.change", json!({"name": name, "expression": format!("{value} mm")})); + apart.extend(arms_apart(&mut s, &format!("{name} = {value}"), form, &pairs, arm_size(&ARM_EDITS[..=i]))); + } + } + assert!(apart.is_empty(), "{} joints apart:\n{}", apart.len(), apart.join("\n")); +} diff --git a/crates/engine/src/cmd/motion_trace.rs b/crates/engine/src/cmd/motion_trace.rs index cac54af4e..954f3ba76 100644 --- a/crates/engine/src/cmd/motion_trace.rs +++ b/crates/engine/src/cmd/motion_trace.rs @@ -58,12 +58,16 @@ pub(super) fn source(s: &Session, p: &Value, cmd: &str) -> Result { let placed = placed_world(s, &occurrence)?; let inverse = solidcraft_doc::mat_inverse(&placed).ok_or_else(|| bad(cmd, "invalid occurrence placement"))?; let canonical = joints::occurrence_world(&s.doc, id); - for key in ["face", "circle", "edge", "point"] { + for key in ["face", "circle", "edge", "point", "corner"] { if let Some(at) = reference.get(key).and_then(crate::params::vec3) { let at = apply_point(&canonical, apply_point(&inverse, at)); reference[key] = json!([at.x, at.y, at.z]); } } + if let Some(z) = reference.get("z").and_then(crate::params::vec3) { + let z = solidcraft_doc::apply_vector(&canonical, solidcraft_doc::apply_vector(&inverse, z)); + reference["z"] = json!([z.x, z.y, z.z]); + } let o = super::super::joints::origin_param(s, Some(&reference), cmd)?; if o.occurrence != occurrence.last().copied().unwrap_or(0) { return Err(bad(cmd, "point_ref must belong to the traced occurrence")); diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index b1b4272b8..59ee719a4 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -487,18 +487,27 @@ pub fn snap_of(s: &Session, sel: &Sel) -> Option { let faces = m.edge_faces.get(*index).cloned().unwrap_or_default(); let out = faces.iter().filter_map(|f| face_normal_near(&m, *f, *point)).fold(Vec3::ZERO, |a, x| a + x); let z = if out.dot(n) < 0.0 { -n } else { n }; - (body, SnapPt { at: c, z, kind: SnapKind::CircleCenter, param: json!({"point": pt(c), "z": pt(z)}) }) + // Its round end, kept by name so it follows the hole or boss as the part + // changes (a point where it has none). + (body, SnapPt { at: c, z, kind: SnapKind::CircleCenter, param: json!({"circle": pt(c), "z": pt(z)}) }) } None => { let mid = polyline_mid(e); let z = straight_edge_axis(e) .or_else(|| m.edge_faces.get(*index).and_then(|fs| fs.first()).and_then(|f| face_normal_near(&m, *f, mid))) .unwrap_or(Vec3::Z); - (body, SnapPt { at: mid, z, kind: SnapKind::EdgeMid, param: json!({"point": pt(mid), "z": pt(z)}) }) + // Its middle, kept by the edge's name. + (body, SnapPt { at: mid, z, kind: SnapKind::EdgeMid, param: json!({"edge": pt(mid), "z": pt(z)}) }) } } } - Sel::Vertex { body, point } => (body, SnapPt { at: *point, z: Vec3::Z, kind: SnapKind::Vertex, param: json!({"point": pt(*point)}) }), + Sel::Vertex { body, point } => { + // The corner of the edges meeting there, kept by their names, z along the part's +Z + // as a point's is. + let z = occurrence_of_body(s, body) + .map_or(Vec3::Z, |o| solidcraft_engine::doc::apply_vector(&solidcraft_engine::doc::joints::occurrence_world(&s.doc, o), Vec3::Z)); + (body, SnapPt { at: *point, z: Vec3::Z, kind: SnapKind::Vertex, param: json!({"edge": pt(*point), "corner": pt(*point), "z": pt(z)}) }) + } _ => return None, }; if let (Some(occ), Value::Object(m)) = (occurrence_of_body(s, body), &mut snap.param) { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 67eef3934..07b060104 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -98,6 +98,60 @@ fn revolute_joint_uses_the_picked_straight_edges() { assert_eq!(app.session.doc.occurrence_of(a).unwrap().transform, ground); } +/// Two arms (a 100 x 20 x `T` plate with a hole 10 mm in from each end), B jointed by its +/// bottom to A's top at a round edge, a straight edge or a corner picked in the dialog: when the +/// arm is made thicker, B sits on A's new top. (These picks were kept as points where they were +/// picked, so B stayed at the old top, sunk into A.) +#[test] +fn arms_jointed_at_edges_and_corners_follow_a_thicker_arm() { + let picks: [(&str, Vec3, Vec3, bool); 3] = [ + ("round edge", Vec3::new(13.0, 0.0, 5.0), Vec3::new(93.0, 60.0, 0.0), false), + ("straight edge", Vec3::new(50.0, 10.0, 5.0), Vec3::new(50.0, 70.0, 0.0), false), + ("corner", Vec3::new(100.0, 10.0, 5.0), Vec3::new(100.0, 70.0, 0.0), true), + ]; + for (what, pa, pb, corner) in picks { + let mut s = Session::default(); + s.execute("parameters.add", &json!({"name": "T", "expression": "5 mm"})).unwrap(); + s.execute("component.create", &json!({"name": "Arm"})).unwrap(); + s.execute("solid.box", &json!({"length": 100, "width": 20, "height": "T", "corner": [0, -10, 0]})).unwrap(); + for x in [10, 90] { + s.execute("solid.cylinder", &json!({"diameter": 6, "height": 100, "base": [x, 0, -50], "operation": "cut"})).unwrap(); + } + s.execute("component.activate", &json!({"component": "root"})).unwrap(); + let mut app = SolveApp::new(s, Services::default()); + let a = occ(&app, "Arm"); + app.run("occurrence.ground", json!({"occurrence": a, "grounded": true})).unwrap(); + let b = app.run("occurrence.copy", json!({"occurrence": a, "translate": [0, 60, 0]})).unwrap()["occurrence"].as_u64().unwrap(); + app.start("joint.create"); + let mut d = app.dialog.clone().unwrap(); + for p in [pa, pb] { + let edge = edge_sel(&app.session, p).unwrap(); + let sel = match (&edge, corner) { + (Sel::Edge { body, .. }, true) => Sel::Vertex { body: body.clone(), point: p }, + _ => edge, + }; + d.pick(&app.session, sel); + } + if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind { + f.kind = 1; + f.fit_limits(&app.session.doc); + } + for (id, p) in apply_commands(&app, &d).unwrap() { + app.run(&id, p).unwrap(); + } + let world = |app: &SolveApp, o: u64, p: Vec3| { + solidcraft_engine::doc::apply_point(&solidcraft_engine::doc::joints::occurrence_world(&app.session.doc, o), p) + }; + // The spots: a round edge's centre, else the pick; B's in the arm's own coordinates. + let spot = |p: Vec3| if what == "round edge" { Vec3::new(p.x - 3.0, p.y, p.z) } else { p }; + let (spot_a, spot_b) = (spot(pa), spot(pb) - Vec3::new(0.0, 60.0, 0.0)); + assert!(world(&app, b, spot_b).dist(spot_a) < 1e-6, "{what}: as made, B's spot is at {:?}", world(&app, b, spot_b)); + app.run("parameters.change", json!({"name": "T", "expression": "12 mm"})).unwrap(); + let top = spot_a + Vec3::new(0.0, 0.0, 7.0); + assert!(world(&app, b, spot_b).dist(top) < 1e-6, "{what}: B's spot is at {:?}, not on A's new top at {top:?}", world(&app, b, spot_b)); + } +} + /// The preview moves B where the joint puts it and plays the motion while animating. #[test] fn joint_and_drive_preview_on_the_placed_model() { diff --git a/crates/ui-egui/src/dialogs_trace.rs b/crates/ui-egui/src/dialogs_trace.rs index c18788070..ad0846aa7 100644 --- a/crates/ui-egui/src/dialogs_trace.rs +++ b/crates/ui-egui/src/dialogs_trace.rs @@ -86,11 +86,14 @@ pub fn params(s: &Session, f: &TraceForm, inputs: &[SelInput]) -> Result