Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Edit Joint: show the two sides and pick them again (#9686) (#9692)

momysnow60b9e9d188d4
diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs
index 0608885f1c..11568023ee 100644
--- a/crates/engine/src/cmd/joints.rs
+++ b/crates/engine/src/cmd/joints.rs
@@ -13,8 +13,12 @@ use solidcraft_geom::{Aabb3, Vec3};
use super::CommandSpec;
use crate::params::{bad, bool_, num, str_, vec3};
+use crate::schema::joints::EditJointResult;
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
+const EDIT_CONTRACT: TypedContract<crate::schema::joints::EditJointParams> = TypedContract::new();
+
#[path = "joints_inspect.rs"]
mod inspect;
@@ -75,9 +79,15 @@ pub static COMMANDS: &[CommandSpec] = &[
"a: the cam's joint (revolute); b: the follower's joint, a slider (a translating follower) or a revolute (an oscillating one), b driven by a; profile: {sketch: id|name, index?: the profile (default: the largest)} | {edges: [[x,y,z]…] (points on edges of the cam's bodies forming one closed loop, world), occurrence?}: the cam's outline, in a plane square to its axis, read again whenever the design changes; follower?: knife|roller|flat (default knife; flat: a face square to a slider's line); radius?: the roller's radius (mm, an expression or {circle: [x,y,z], occurrence?}: the roller's round face, which is its tip too); tip?: a joint origin where the follower touches: its knife's point or its roller's centre, such as {circle: [x,y,z]} on the roller (needed for an oscillating follower; a translating one's line runs through it, by default along its slider's axis); flip?: bool (ride the cam from the other side than the one the follower is on now); link?: index (replace that motion link) → link, lift: {min, max, rise, unit} (b's travel over a turn of the cam), reverse (the side it rides from), follower_offset (mm: how far a translating follower's line passes from the cam's axis); b keeps where it is, also when the link replaces another (at the current pose)",
),
CommandSpec::new("joint.limits", "Joint Limits", limits).icon("joint").params("joint; index?: value index (default 0); min?, max? (omit both to clear)"),
- CommandSpec::new("joint.edit", "Edit Joint", edit)
+ CommandSpec::new("joint.edit", "Edit Joint", crate::checked!("joint.edit", edit))
.icon("edit")
- .params("joint; type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?"),
+ .contract(&EDIT_CONTRACT)
+ .output(output_schema_for::<EditJointResult>)
+ .params(
+ "joint; a?, b?: joint origins as joint.create takes them (a side left out keeps its place; the two must stay on different occurrences); \
+ type?, flip?, offset?, angle? (a number, or an expression the joint then follows), suppressed?, name?; the joint re-solves, keeping \
+ its limits and expressions (a relation's values start again where its parts are)",
+ ),
CommandSpec::new("joint.delete", "Delete Joint", delete).icon("delete").params("joint: id|name (or origin: name, link: index)"),
CommandSpec::new("joint.list", "List Joints", list).icon("list").noundo().params(
"→ joints (type, occurrences, values, limits; expressions: {offset?, angle?, values?} when they were typed as expressions), origins, links, degrees of freedom, conflicts, floating: [{occurrences, joints}] \
@@ -671,19 +681,24 @@ fn limits_param(s: &Session, p: &Value, kind: JointKind, cmd: &str) -> Result<Ve
Ok(out)
}
-fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {
- if s.doc.assembly.joints.len() >= 10_000 {
- return Err(EngineError::Other("too many joints".into()));
- }
- // Several parts as bodies of one component (a multi-body STEP import, #1239): say how to
- // get two components.
- if j.a.occurrence == j.b.occurrence {
+/// A joint's two origins on different occurrences (joint.create and joint.edit). Several parts as
+/// bodies of one component (a multi-body STEP import, #1239) say how to get two components.
+fn check_sides(a: &JointOrigin, b: &JointOrigin, cmd: &str) -> Result<()> {
+ if a.occurrence == b.occurrence {
return Err(bad(
- "joint.create",
+ cmd,
"a joint needs two different occurrences: both origins are on one component; give each part a component of its own first \
(component.from_bodies)",
));
}
+ Ok(())
+}
+
+fn add_joint(s: &mut Session, mut j: Joint, p: &Value) -> Result<Value> {
+ if s.doc.assembly.joints.len() >= 10_000 {
+ return Err(EngineError::Other("too many joints".into()));
+ }
+ check_sides(&j.a, &j.b, "joint.create")?;
// It starts at its values inside its limits. A value moved to a limit moves the part as it
// is joined, which the answer says.
let mut q = j.values.clone();
@@ -1366,8 +1381,22 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => Some(value(s, v, true, cmd)?),
None => None,
};
+ // The sides, read as joint.create reads them; a side left out keeps its place.
+ let a = p.get("a").map(|v| origin_param(s, Some(v), cmd)).transpose()?;
+ let b = p.get("b").map(|v| origin_param(s, Some(v), cmd)).transpose()?;
+ let sides = a.is_some() || b.is_some();
+ if sides {
+ let j = s.doc.assembly.joints.iter().find(|j| j.id == id).ok_or_else(|| bad(cmd, "joint"))?;
+ check_sides(a.as_ref().unwrap_or(&j.a), b.as_ref().unwrap_or(&j.b), cmd)?;
+ }
let doc = s.doc_mut();
let Some(j) = doc.assembly.joints.iter_mut().find(|j| j.id == id) else { return Err(bad(cmd, "joint")) };
+ if let Some(a) = a {
+ j.a = a;
+ }
+ if let Some(b) = b {
+ j.b = b;
+ }
if let Some(k) = kind {
let was = j.kind;
j.kind = k;
@@ -1399,8 +1428,19 @@ fn edit(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(x) = bool_(p, "suppressed") {
suppress_joints(s.doc_mut(), &[id], x);
}
+ // A side moved without an angle turns B as joint.create would: the least turn from where it
+ // is now (a relation's angle is its tilt, which stays; an angle expression keeps driving it).
+ if sides
+ && p.get("angle").is_none()
+ && let Some(j) = s.doc.assembly.joints.iter().find(|j| j.id == id).filter(|j| !j.kind.is_relation() && j.exprs.angle.is_none()).cloned()
+ {
+ let turn = joints::least_turn_angle(&s.doc, &s.model.state(), &j);
+ if let Some(j) = s.doc_mut().assembly.joints.iter_mut().find(|j| j.id == id) {
+ j.angle = turn;
+ }
+ }
// A relation whose type, offset, tilt or flip changes starts again from where its parts are.
- let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some();
+ let reseat = kind.is_some() || offset.is_some() || angle.is_some() || p.get("flip").is_some() || sides;
if reseat {
let edited = s.doc.assembly.joints.iter().find(|j| j.id == id).cloned();
if let Some(q) = edited.and_then(|j| joints::relation_values(&s.doc, &s.model.state(), &j))
diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs
index 6bf63d80d0..7a772adaef 100644
--- a/crates/engine/src/cmd/joints_tests.rs
+++ b/crates/engine/src/cmd/joints_tests.rs
@@ -304,6 +304,114 @@ fn faces_mate_by_default() {
assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 0.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0)));
}
+/// Edit Joint takes new sides as joint.create does: the joint moves its attachment to them, and
+/// keeps its limits, its drive and the expression its offset follows.
+#[test]
+fn edit_moves_a_side_and_keeps_limits_and_expressions() {
+ let mut s = two_cubes();
+ run(&mut s, "parameters.add", json!({"name": "gap", "expression": "2 mm"}));
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "slider", "name": "Rail", "offset": "gap", "limits": [[0, 10]], "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}),
+ );
+ run(&mut s, "joint.drive", json!({"joint": "Rail", "value": 4}));
+ // B's bottom centre rides 2 mm (the gap) plus 4 mm (the drive) above A's top centre.
+ assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), Vec3::new(5.0, 5.0, 16.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 0.0)));
+ // B's top centre, where B is placed now, is the new side (`face` is a world point).
+ let top = place(&s, "B", Vec3::new(25.0, 5.0, 10.0));
+ let r = run(&mut s, "joint.edit", json!({"joint": "Rail", "b": {"occurrence": "B", "face": [top.x, top.y, top.z]}}));
+ assert_eq!(r["conflicts"].as_array().map(Vec::len), Some(0), "{r}");
+ assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 16.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0)));
+ let j = s.doc.assembly.joints.first().cloned().unwrap_or_else(|| panic!("no joint"));
+ assert_eq!(j.limits, vec![Some((0.0, 10.0))]);
+ assert_eq!(j.exprs.offset.as_deref(), Some("gap"));
+ assert_eq!(j.values, vec![4.0]);
+ assert_eq!(j.name, "Rail");
+}
+
+/// Sides left out of joint.edit stay as they are; the other parameters still change.
+#[test]
+fn omitted_sides_stay() {
+ let mut s = two_cubes();
+ run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}));
+ let before = s.doc.assembly.joints[0].clone();
+ run(&mut s, "joint.edit", json!({"joint": "Stack", "flip": true, "name": "Flipped"}));
+ let after = &s.doc.assembly.joints[0];
+ assert_eq!((&after.a, &after.b), (&before.a, &before.b));
+ assert!(after.flip && after.name == "Flipped");
+}
+
+/// One undo step puts the sides back, and the parts with them.
+#[test]
+fn one_undo_restores_the_old_sides() {
+ let mut s = two_cubes();
+ run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}));
+ let before = s.doc.assembly.joints[0].clone();
+ let top = place(&s, "B", Vec3::new(25.0, 5.0, 10.0));
+ run(&mut s, "joint.edit", json!({"joint": "Stack", "b": {"occurrence": "B", "face": [top.x, top.y, top.z]}}));
+ assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 10.0)), Vec3::new(5.0, 5.0, 10.0)), "{:?}", place(&s, "B", Vec3::new(25.0, 5.0, 10.0)));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc.assembly.joints[0], before);
+ assert!(near(place(&s, "B", Vec3::new(25.0, 5.0, 0.0)), Vec3::new(5.0, 5.0, 10.0)));
+}
+
+/// Moving a side re-solves the joint as joint.create would at the same pose: the turn B keeps
+/// about the joint's axis follows its new origin, so B does not turn by a half turn (or any turn
+/// a fresh create would not give). Both designs start from the same pose; one moves the side,
+/// the other deletes the joint and creates it with the new sides.
+#[test]
+fn moving_a_side_places_the_part_as_create_would() {
+ let a_faces = [[5, 5, 10], [5, 0, 5], [5, 10, 5], [10, 5, 5], [0, 5, 5]];
+ let b_faces = [[25, 5, 0], [25, 5, 10], [25, 0, 5], [25, 10, 5], [20, 5, 5], [30, 5, 5]];
+ // A point of B off the axes of every face above.
+ let probe = |s: &Session| place(s, "B", Vec3::new(22.0, 3.0, 7.0));
+ let mut differ = Vec::new();
+ for a in a_faces {
+ for b in b_faces {
+ let mut edited = two_cubes();
+ run(&mut edited, "joint.create", json!({"type": "rigid", "name": "J", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}));
+ let mut created = Session::new(solidcraft_doc::Document::from_json(&edited.doc.to_json()).unwrap());
+ // The new sides in world coordinates, where B is before the move.
+ let (aw, bw) = (Vec3::new(a[0] as f64, a[1] as f64, a[2] as f64), place(&edited, "B", Vec3::new(b[0] as f64, b[1] as f64, b[2] as f64)));
+ let side = |occurrence: &str, p: Vec3| json!({"occurrence": occurrence, "face": [p.x, p.y, p.z]});
+ run(&mut edited, "joint.edit", json!({"joint": "J", "a": side("A", aw), "b": side("B", bw)}));
+ run(&mut created, "joint.delete", json!({"joint": "J"}));
+ run(&mut created, "joint.create", json!({"type": "rigid", "name": "J", "a": side("A", aw), "b": side("B", bw)}));
+ if !near(probe(&edited), probe(&created)) {
+ differ.push((a, b, probe(&edited), probe(&created)));
+ }
+ }
+ }
+ assert!(differ.is_empty(), "moved sides place B differently from create: {differ:?}");
+}
+
+/// A side that makes no joint is refused, and the joint is left as it was: a side on the other
+/// side's component, a side that is not a joint origin, an unknown occurrence.
+#[test]
+fn an_invalid_side_is_refused_and_the_joint_is_kept() {
+ let mut s = two_cubes();
+ run(&mut s, "joint.create", json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}));
+ let before = s.doc.assembly.joints[0].clone();
+ // A is a's occurrence and B is b's: each side is tried on the other's occurrence, and with
+ // the faults every side can have.
+ let cases = [
+ ("a", json!({"occurrence": "B", "face": [25, 5, 10]})),
+ ("a", json!({"occurrence": "Nope", "face": [5, 5, 10]})),
+ ("a", json!({"occurrence": "A"})),
+ ("a", json!(5)),
+ ("b", json!({"occurrence": "A", "face": [5, 5, 0]})),
+ ("b", json!({"occurrence": "Nope", "face": [25, 5, 0]})),
+ ("b", json!({"occurrence": "B"})),
+ ("b", json!("NoSuchOrigin")),
+ ];
+ for (key, side) in cases {
+ let r = s.execute("joint.edit", &json!({"joint": "Stack", key: side.clone()}));
+ assert!(r.is_err(), "{key}: {side} should be refused");
+ assert_eq!(s.doc.assembly.joints[0], before, "{key}: {side} changed the joint");
+ }
+}
+
/// A move of a jointed part that the joint takes back: the model is evaluated for the
/// placements the solve leaves, so a mirror of the part's body, made from the root, is where a
/// fresh evaluation of the design puts it. The model was the one evaluated for the move before
diff --git a/crates/engine/src/schema/joints.rs b/crates/engine/src/schema/joints.rs
new file mode 100644
index 0000000000..81c0afd61e
--- /dev/null
+++ b/crates/engine/src/schema/joints.rs
@@ -0,0 +1,113 @@
+//! Contracts and result types for the commands in `cmd/joints.rs`.
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+
+use super::types::{AngleExpr, IdOrName, LengthExpr, present};
+
+/// A joint origin as joint.create takes it: a joint origin's name, or an object with the snap
+/// (`occurrence`, then `face`, `circle`, `edge` or `point`, or a `frame`). Kept as given, for the
+/// handler, which reads it as it reads joint.create's sides.
+#[derive(Clone, Debug, PartialEq)]
+pub struct JointOriginParam(pub Value);
+
+impl<'de> Deserialize<'de> for JointOriginParam {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ v @ (Value::String(_) | Value::Object(_)) => Ok(JointOriginParam(v)),
+ _ => Err(D::Error::custom("must be a joint origin's name or an object")),
+ }
+ }
+}
+
+impl JsonSchema for JointOriginParam {
+ fn schema_name() -> Cow<'static, str> {
+ "JointOrigin".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A joint origin, as joint.create takes a side: a joint origin's name, or an object with occurrence and face, circle, edge or point (world coordinates, or a face's name), with z?, x?, end?, on?, corner?, or with a frame {origin, z, x?}.",
+ "anyOf": [
+ {"type": "string", "minLength": 1},
+ {"type": "object"}
+ ]
+ })
+ }
+}
+
+/// Edit a joint in place. The sides `a` and `b` take a joint origin as joint.create does; a side
+/// left out keeps its place, and the two must stay on different occurrences. The joint re-solves
+/// and keeps its limits, its drive and the expressions it follows; a relation's values start
+/// again where its parts are when its sides, type, offset, angle or flip change.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct EditJointParams {
+ /// The joint, by id or name.
+ pub joint: IdOrName,
+ /// Side a: a joint origin, as joint.create takes it. Default: a keeps its place.
+ #[serde(default, deserialize_with = "present")]
+ pub a: Option<JointOriginParam>,
+ /// Side b: a joint origin, as joint.create takes it. Default: b keeps its place.
+ #[serde(default, deserialize_with = "present")]
+ pub b: Option<JointOriginParam>,
+ /// The joint's type, as joint.create takes it (rigid, revolute, slider, ...).
+ #[serde(default, rename = "type", deserialize_with = "present")]
+ pub kind: Option<String>,
+ /// Whether b's z lies along a's instead of against it, as joint.create's `flip`.
+ #[serde(default, deserialize_with = "present")]
+ pub flip: Option<bool>,
+ /// The distance from a's frame to b's along z: a length, or an expression the joint follows.
+ #[serde(default, deserialize_with = "present")]
+ pub offset: Option<LengthExpr>,
+ /// The turn about that distance: an angle, or an expression the joint follows.
+ #[serde(default, deserialize_with = "present")]
+ pub angle: Option<AngleExpr>,
+ /// Suppress the joint (true) or bring it back (false).
+ #[serde(default, deserialize_with = "present")]
+ pub suppressed: Option<bool>,
+ /// The joint's new name.
+ #[serde(default, deserialize_with = "present")]
+ pub name: Option<String>,
+ /// Leave out the degrees of freedom and the fixed occurrences in the reply.
+ #[serde(default, deserialize_with = "present")]
+ pub quiet: Option<bool>,
+}
+
+/// A joint the solve reports: its id, name and why.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct JointProblem {
+ pub joint: u64,
+ pub name: String,
+ pub why: String,
+}
+
+/// The degrees of freedom one occurrence keeps (6 free, 0 fixed).
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OccurrenceDof {
+ pub occurrence: u64,
+ pub dof: usize,
+}
+
+/// What `joint.edit` returns: the joints that disagree with the solved placement, and those the
+/// solve could not apply. Unless `quiet`, also each occurrence's degrees of freedom and the
+/// occurrences fixed in place.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct EditJointResult {
+ pub conflicts: Vec<JointProblem>,
+ pub errors: Vec<JointProblem>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub dof: Option<Vec<OccurrenceDof>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fixed: Option<Vec<u64>>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "joints_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/joints_tests.rs b/crates/engine/src/schema/joints_tests.rs
new file mode 100644
index 0000000000..5fc406abcf
--- /dev/null
+++ b/crates/engine/src/schema/joints_tests.rs
@@ -0,0 +1,27 @@
+use serde_json::json;
+
+use super::{EditJointParams, EditJointResult};
+use crate::Session;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{input_schema_for, output_schema_for};
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<EditJointParams>(), &["a", "angle", "b", "flip", "joint", "name", "offset", "quiet", "suppressed", "type"]);
+}
+
+#[test]
+fn replies_match_the_output_schema() {
+ let schema = output_schema_for::<EditJointResult>();
+ let schema = schema.as_value();
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("component.create", &json!({"name": "B", "grounded": false})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("joint.create", &json!({"type": "rigid", "name": "Stack", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}}))
+ .unwrap_or_else(|e| panic!("{e}"));
+ let full = s.execute("joint.edit", &json!({"joint": "Stack", "flip": true})).unwrap_or_else(|e| panic!("{e}"));
+ assert!(conforms(schema, schema, &full), "{full} doesn't match {schema}");
+ let quiet = s.execute("joint.edit", &json!({"joint": "Stack", "quiet": true})).unwrap_or_else(|e| panic!("{e}"));
+ assert!(quiet.get("dof").is_none() && conforms(schema, schema, &quiet), "{quiet}");
+}
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index fa7b7a5920..7103af6f0b 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -59,6 +59,7 @@ pub mod construct;
pub mod edit;
pub mod features;
pub mod inspect;
+pub mod joints;
pub mod print_face;
pub mod render;
pub mod render_lights;
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 511bc1cd7e..d1852f9b3d 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -110,7 +110,6 @@ joint.cam
joint.create
joint.delete
joint.drive
-joint.edit
joint.gear
joint.inspect
joint.limits
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index a753771d3c..845cbe9d7d 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -12,7 +12,7 @@ use serde_json::{Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::Session;
use solidcraft_engine::doc::expr::Kind as ValueKind;
-use solidcraft_engine::doc::joints::JointKind;
+use solidcraft_engine::doc::joints::{JointKind, JointOrigin, Snap};
use solidcraft_engine::geom::{Aabb3, Mesh, Vec3};
use crate::SolveApp;
@@ -137,9 +137,15 @@ pub struct JointForm {
/// Editing this joint (its origins stay; type, alignment and limits change).
pub editing: Option<u64>,
pub kind: usize,
+ /// Edit Joint: the sides as the dialog opened on them. A side still that pick is not sent,
+ /// so it keeps its origin exactly.
+ pub sides: [Option<Sel>; 2],
/// Flip B relative to the mate (faces apart instead of together).
pub flip: bool,
pub angle: String,
+ /// Edit Joint: the angle as the dialog opened on it. Sent only when changed, so a side moved
+ /// without it turns B as joint.create would.
+ pub angle_shown: String,
pub offset: [String; 3],
/// Per joint value: limited, minimum, maximum.
pub limits: Vec<(bool, String, String)>,
@@ -155,8 +161,10 @@ impl JointForm {
as_built,
editing: None,
kind: 0,
+ sides: [None, None],
flip: false,
angle: "0 deg".into(),
+ angle_shown: "0 deg".into(),
offset: std::array::from_fn(|_| crate::length_input::default(doc, "0")),
limits: Vec::new(),
animate: false,
@@ -217,10 +225,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
let s = &app.session;
let (asm, inputs) = match id {
"component.create" => (Asm::NewComponent { name: String::new(), activate: true }, vec![SelInput::new("Bodies (optional)", BODIES, true)]),
- "joint.create" => (
- Asm::Joint(Box::new(JointForm::new(false, &app.session.doc))),
- vec![SelInput::new("Component 1", SNAPS, false), SelInput::new("Component 2", SNAPS, false)],
- ),
+ "joint.create" => (Asm::Joint(Box::new(JointForm::new(false, &app.session.doc))), side_inputs()),
"joint.as_built" => (
Asm::Joint(Box::new(JointForm::new(true, &app.session.doc))),
vec![SelInput::new("Components", BODIES, true), SelInput::new("Position", SNAPS, false)],
@@ -321,16 +326,121 @@ pub(crate) fn num(v: f64, unit: &str) -> String {
format!("{} {unit}", crate::dialogs_coupling::trim(v))
}
-/// The Edit Joint dialog for a joint (by id).
+/// The two side inputs of the Joint dialog (Joint and Edit Joint): the picks of each origin.
+fn side_inputs() -> Vec<SelInput> {
+ vec![SelInput::new("Component 1", SNAPS, false), SelInput::new("Component 2", SNAPS, false)]
+}
+
+/// The pick a joint side shows in the side inputs: the face or edge of its own occurrence that
+/// the side's snap names (the piece nearest its pick, when the name has several), else the face
+/// or edge nearest the pick. A point or frame side names no face: None.
+fn side_pick(app: &SolveApp, o: &JointOrigin) -> Option<Sel> {
+ let s = &app.session;
+ let (pick, face, edge) = match &o.snap {
+ Snap::FaceCenter { pick, face, .. } | Snap::CircleCenter { pick, face, .. } => (*pick, face.as_deref(), None),
+ Snap::Edge { pick, edge, .. } => (*pick, None, edge.as_deref()),
+ Snap::Point { .. } | Snap::Frame { .. } => return None,
+ };
+ // The pick is in the component's coordinates; the placed bodies are in the world.
+ let at =
+ if o.occurrence == 0 { solidcraft_engine::doc::IDENTITY } else { solidcraft_engine::doc::joints::occurrence_world(&s.doc, o.occurrence) };
+ let p = solidcraft_engine::doc::apply_point(&at, pick);
+ let st = s.world_state();
+ let own: Vec<&solidcraft_engine::doc::ModelBody> = st.bodies.iter().filter(|b| occurrence_of_body(s, &b.name) == Some(o.occurrence)).collect();
+ let named = match (face, edge) {
+ (Some(name), _) => own.iter().filter_map(|b| named_face(b, name, p)).min_by(|a, b| a.0.total_cmp(&b.0)),
+ (None, Some(name)) => own.iter().filter_map(|b| named_edge(b, name, p)).min_by(|a, b| a.0.total_cmp(&b.0)),
+ (None, None) => None,
+ };
+ named.map(|(_, sel)| sel).or_else(|| nearest_pick(&own, p, matches!(o.snap, Snap::Edge { .. })))
+}
+
+/// The distance from `p` to the face `f` of `m`, measured to its triangles.
+fn face_dist(m: &Mesh, f: usize, p: Vec3) -> Option<f64> {
+ m.triangles
+ .iter()
+ .zip(&m.tri_face)
+ .filter(|(_, tf)| **tf as usize == f)
+ .filter_map(|(t, _)| m.tri(t))
+ .map(|[a, c, e]| crate::preview::point_triangle_dist(p, a, c, e))
+ .reduce(f64::min)
+}
+
+/// The distance from `p` to the mesh edge `i` of `m`.
+fn edge_dist(m: &Mesh, i: usize, p: Vec3) -> Option<f64> {
+ m.edges.get(i)?.windows(2).map(|w| p.dist_to_segment(w[0], w[1])).reduce(f64::min)
+}
+
+/// The face of `b` the name `name` names, the piece nearest `p` when it has several.
+fn named_face(b: &solidcraft_engine::doc::ModelBody, name: &str, p: Vec3) -> Option<(f64, Sel)> {
+ let m = b.mesh();
+ let names = solidcraft_engine::doc::naming::face_names(b);
+ names
+ .iter()
+ .enumerate()
+ .filter(|(_, n)| n.as_str() == name)
+ .filter_map(|(f, _)| face_dist(&m, f, p).map(|d| (d, Sel::Face { body: b.name.clone(), index: f, point: p })))
+ .min_by(|a, b| a.0.total_cmp(&b.0))
+}
+
+/// The edge of `b` the name `name` names (a split edge: the piece nearest `p`).
+fn named_edge(b: &solidcraft_engine::doc::ModelBody, name: &str, p: Vec3) -> Option<(f64, Sel)> {
+ let m = b.mesh();
+ let names = solidcraft_engine::doc::naming::edge_names(b);
+ let index = match names.iter().position(|n| n == name) {
+ Some(i) => i,
+ None => {
+ let (at, _) = solidcraft_engine::doc::naming::find_edge(b, name, p).ok()?;
+ (0..m.edges.len())
+ .min_by(|x, y| edge_dist(&m, *x, at).unwrap_or(f64::INFINITY).total_cmp(&edge_dist(&m, *y, at).unwrap_or(f64::INFINITY)))?
+ }
+ };
+ let d = edge_dist(&m, index, p)?;
+ Some((d, Sel::Edge { body: b.name.clone(), index, point: p }))
+}
+
+/// The face (or edge) of the bodies `own` nearest `p`.
+fn nearest_pick(own: &[&solidcraft_engine::doc::ModelBody], p: Vec3, edges: bool) -> Option<Sel> {
+ let mut best: Option<(f64, Sel)> = None;
+ for b in own {
+ let m = b.mesh();
+ if edges {
+ for i in 0..m.edges.len() {
+ let Some(d) = edge_dist(&m, i, p) else { continue };
+ if best.as_ref().is_none_or(|(bd, _)| d < *bd) {
+ best = Some((d, Sel::Edge { body: b.name.clone(), index: i, point: p }));
+ }
+ }
+ } else {
+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {
+ let Some([a, c, e]) = m.tri(t) else { continue };
+ let d = crate::preview::point_triangle_dist(p, a, c, e);
+ if best.as_ref().is_none_or(|(bd, _)| d < *bd) {
+ best = Some((d, Sel::Face { body: b.name.clone(), index: *f as usize, point: p }));
+ }
+ }
+ }
+ }
+ best.map(|(_, sel)| sel)
+}
+
+/// The Edit Joint dialog for a joint (by id). Its two sides show as the Joint dialog's do, each
+/// pre-filled with the pick it sits on.
pub fn edit_joint(app: &SolveApp, id: u64) -> Option<Dialog> {
let j = app.session.doc.assembly.joints.iter().find(|j| j.id == id)?;
let mut f = JointForm::new(false, &app.session.doc);
f.editing = Some(id);
+ f.sides = [side_pick(app, &j.a), side_pick(app, &j.b)];
+ let mut inputs = side_inputs();
+ for (input, pick) in inputs.iter_mut().zip(&f.sides) {
+ input.items = pick.iter().cloned().collect();
+ }
f.kind = TYPES.iter().position(|t| JointKind::parse(t) == Some(j.kind)).unwrap_or(0);
f.flip = j.flip;
// An offset or angle typed as an expression shows (and is sent back) as that expression, so
// the joint keeps following its parameters.
f.angle = j.exprs.angle.clone().unwrap_or_else(|| num(j.angle.to_degrees(), "deg"));
+ f.angle_shown = f.angle.clone();
f.offset[2] = j.exprs.offset.clone().unwrap_or_else(|| crate::length_input::model(&app.session.doc, j.offset));
f.fit_limits(&app.session.doc);
for (i, l) in f.limits.iter_mut().enumerate() {
@@ -339,7 +449,7 @@ pub fn edit_joint(app: &SolveApp, id: u64) -> Option<Dialog> {
*l = (true, fmt(*lo), fmt(*hi));
}
}
- Some(Dialog::new(Kind::Assembly(Asm::Joint(Box::new(f))), vec![]))
+ Some(Dialog::new(Kind::Assembly(Asm::Joint(Box::new(f))), inputs))
}
/// The Drive Joints dialog on a joint (by id).
@@ -970,7 +1080,20 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
let limits: Vec<Value> =
f.limits.iter().take(jk.dofs().len()).map(|(on, lo, hi)| if *on { json!([lo, hi]) } else { Value::Null }).collect();
if let Some(id) = f.editing {
- let mut out = cmd("joint.edit", json!({"joint": id, "type": kind, "flip": f.flip, "offset": f.offset[2], "angle": f.angle}));
+ let mut p = json!({"joint": id, "type": kind, "flip": f.flip, "offset": f.offset[2]});
+ // The angle only when the user changed it: a side moved without it turns B as joint.create would.
+ if f.angle != f.angle_shown {
+ p["angle"] = json!(f.angle);
+ }
+ // A side picked again moves the joint's attachment there; one left as it was keeps its origin.
+ for (i, key) in ["a", "b"].into_iter().enumerate() {
+ let picked = sel_items(inputs, i).first();
+ if picked != f.sides[i].as_ref() {
+ let what = if i == 0 { "component 1's joint origin" } else { "component 2's joint origin" };
+ p[key] = snap(i, what)?.param;
+ }
+ }
+ let mut out = cmd("joint.edit", p);
for (i, l) in limits.iter().enumerate() {
let p = match l.as_array() {
Some(a) => json!({"joint": id, "index": i, "min": a.first(), "max": a.get(1)}),
diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs
index 12883f17d1..07feadc53a 100644
--- a/crates/ui-egui/src/dialogs_assembly_tests.rs
+++ b/crates/ui-egui/src/dialogs_assembly_tests.rs
@@ -215,7 +215,7 @@ fn edit_joint_runs_edit_and_limits() {
.unwrap();
let id = app.session.doc.assembly.joints[0].id;
let mut d = edit_joint(&app, id).unwrap();
- assert!(d.inputs.is_empty());
+ assert_eq!(d.inputs.len(), 2, "the two sides show as in the Joint dialog");
if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {
assert_eq!(TYPES[f.kind], "slider");
f.limits[0] = (true, "0 mm".into(), "15 mm".into());
@@ -281,6 +281,75 @@ fn edit_joint_keeps_an_offset_typed_as_an_expression() {
assert_eq!((j.exprs.offset.as_deref(), j.exprs.angle.as_deref()), (Some("gap"), None));
}
+/// Edit Joint shows both sides pre-filled, each on its own component. OK sends no side while
+/// they are as they were; picking one side again sends only that side, and the joint keeps its
+/// other side.
+#[test]
+fn edit_joint_shows_both_sides_and_a_repick_sends_only_that_side() {
+ let mut app = two_boxes();
+ let (a, b) = (occ(&app, "A"), occ(&app, "B"));
+ app.run("joint.create", json!({"type": "rigid", "a": {"occurrence": a, "face": [10, 10, 10]}, "b": {"occurrence": b, "face": [40, 10, 0]}}))
+ .unwrap();
+ let before = app.session.doc.assembly.joints[0].clone();
+ let mut d = edit_joint(&app, before.id).unwrap();
+ assert_eq!(d.inputs.len(), 2);
+ for (input, occurrence) in d.inputs.iter().zip([a, b]) {
+ let Some(Sel::Face { body, .. }) = input.items.first() else { panic!("no side pick: {:?}", input.items) };
+ assert_eq!(occurrence_of_body(&app.session, body), Some(occurrence), "{body}");
+ }
+ let c = apply_commands(&app, &d).unwrap();
+ assert!(c[0].1.get("a").is_none() && c[0].1.get("b").is_none(), "{}", c[0].1);
+ // B's top face, where B now sits on A: side b alone is picked again, and the angle the
+ // dialog opened on is not sent (a side moved turns B as joint.create would).
+ d.active = 1;
+ d.pick(&app.session, face_sel(&app.session, Vec3::new(10.0, 10.0, 20.0)).unwrap());
+ let c = apply_commands(&app, &d).unwrap();
+ assert_eq!(c[0].0, "joint.edit");
+ assert!(c[0].1.get("a").is_none() && c[0].1.get("angle").is_none(), "{}", c[0].1);
+ assert_eq!(c[0].1["b"]["occurrence"], json!(b));
+ // An angle the user types is sent.
+ if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {
+ f.angle = "45 deg".into();
+ }
+ let c = apply_commands(&app, &d).unwrap();
+ assert_eq!(c[0].1["angle"], json!("45 deg"), "{}", c[0].1);
+ for (id, p) in c {
+ app.run(&id, p).unwrap();
+ }
+ assert!((app.session.doc.assembly.joints[0].angle.to_degrees() - 45.0).abs() < 1e-9);
+ let after = app.session.doc.assembly.joints[0].clone();
+ assert_eq!(after.a, before.a);
+ assert_eq!(after.b.occurrence, b);
+ assert_ne!(after.b, before.b);
+}
+
+/// A side on a hole's wall shows the wall, a cylinder, not the plate's face beside the hole: the
+/// face its snap names is the one the pre-fill takes, however near the other face's plane lies.
+#[test]
+fn a_hole_side_shows_its_wall_not_the_plate_beside_it() {
+ let mut s = Session::default();
+ s.execute("component.create", &json!({"name": "Plate"})).unwrap();
+ s.execute("solid.box", &json!({"length": 40, "width": 40, "height": 10, "corner": [0, 0, 0]})).unwrap();
+ s.execute("solid.cylinder", &json!({"diameter": 10, "height": 20, "base": [20, 20, -5], "operation": "cut"})).unwrap();
+ s.execute("component.create", &json!({"name": "Peg"})).unwrap();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0]})).unwrap();
+ s.execute("component.activate", &json!({"component": "root"})).unwrap();
+ let mut app = SolveApp::new(s, Services::default());
+ let (plate, peg) = (occ(&app, "Plate"), occ(&app, "Peg"));
+ app.run("occurrence.ground", json!({"occurrence": plate, "grounded": true})).unwrap();
+ app.run(
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": plate, "circle": [25, 20, 8]}, "b": {"occurrence": peg, "face": [65, 5, 0]}}),
+ )
+ .unwrap();
+ let joint = app.session.doc.assembly.joints[0].clone();
+ assert!(matches!(joint.a.snap, solidcraft_engine::doc::joints::Snap::CircleCenter { face: Some(_), .. }), "{:?}", joint.a.snap);
+ let d = edit_joint(&app, joint.id).unwrap();
+ let item = d.inputs[0].items.first().unwrap_or_else(|| panic!("no pre-fill for the hole side"));
+ let snap = snap_of(&app.session, item).unwrap();
+ assert_eq!(snap.kind, SnapKind::CircleCenter, "the pre-fill is the plate's face, not the hole's wall: {item:?}");
+}
+
#[test]
fn as_built_animation_drives_the_new_shared_id_and_handles_exhaustion() {
let mut app = two_boxes();
diff --git a/skills/solidcraft-mechanisms/reference.md b/skills/solidcraft-mechanisms/reference.md
index 22076d486d..c120a3bd81 100644
--- a/skills/solidcraft-mechanisms/reference.md
+++ b/skills/solidcraft-mechanisms/reference.md
@@ -20,6 +20,7 @@ Each of `a` and `b` in `joint.create` is one of these:
- `occurrence` is an occurrence name (`Wing:1`), an id, or a component name (its first occurrence). Without it, the body nearest the point is used, which can be the wrong part where two touch.
- **Use the same form on both sides.** `point` picks its x axis from z. A `frame` with an `x` on one side and a `point` on the other turned a test panel 90 degrees when it was joined.
- **`flip`:** `false` (the default) mates the origins as two faces meet: b's z points against a's. Two origins at one point with the same `z` then turn part b 180 degrees about the axis, and a joint that closes a loop reports a conflict ("off by 71 mm and 180 degrees" on SELENE). `true` lines b's z up with a's, so parts stay where they are. `joint.edit {"joint":..., "flip":true}` changes it afterwards.
+- **Moving a side:** `joint.edit` takes `a` or `b` in joint.create's form (a joint origin, or a name), so a joint moves its attachment without being deleted and recreated; its limits, values and expressions stay.
## Joint types