fix: joints on an imported part's hole or face stay on that part (#6368)

The parts of one STEP assembly import share their face names, and each
part's body stays where the file has it, placed in its component by an
offset. A joint origin on a named face (a hole's centre, a face's
centre, an x reference by face, the end a round origin takes) looked the
name up on every body of the design and compared the pick, in the
joint's component coordinates, with each body as it lies. Another part's
face of that name could lie nearer, and the joint resolved on that
part's face: a pin jointed into one plate's hole landed where the other
plate's hole is relative to its plate.

named_face now looks only at the bodies of the joint's component, each
in its own coordinates, a face the name finds exactly before a piece of
it or a face it was merged into, then the nearest. The design-wide
lookup stays for a face whose body has gone to another component.
named_round, x_axis, pin_end and end_faces take the component, as
face_name_at and round_end_at already do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NOWN-DEV
2026-10-25 02:29:16 +00:00
committed by GitHub
parent b8d9db7440
commit 3592031d5e
4 changed files with 104 additions and 29 deletions
+11 -10
View File
@@ -758,11 +758,11 @@ fn component_of(doc: &Document, occ: u64) -> Result<u64> {
doc.occurrences.iter().find(|o| o.id == occ).map(|o| o.component).ok_or_else(|| DocError::Unknown(format!("occurrence {occ}")))
}
/// A snap's pick point moved onto its named face (an error when the face is gone: a joint must
/// not quietly attach elsewhere).
fn named_pick(doc: &Document, st: &ModelState, pick: Vec3, face: Option<&str>) -> Result<Vec3> {
/// A snap's pick point moved onto its named face of `component` (an error when the face is gone:
/// a joint must not quietly attach elsewhere).
fn named_pick(doc: &Document, st: &ModelState, component: u64, pick: Vec3, face: Option<&str>) -> Result<Vec3> {
match face {
Some(n) => face::named_face(doc, st, pick, n).map(|f| f.point),
Some(n) => face::named_face(doc, st, component, pick, n).map(|f| f.point),
None => Ok(pick),
}
}
@@ -805,20 +805,21 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul
Snap::FaceCenter { pick, face, x } => {
// A named planar face gives its own centre and normal; another face (or none) the
// planar face nearest the point.
let comp = component_of(doc, o.occurrence)?;
let named = match face.as_deref() {
Some(n) => Some(face::named_face(doc, st, *pick, n)?),
Some(n) => Some(face::named_face(doc, st, comp, *pick, n)?),
None => None,
};
let (c, n) = match named.as_ref().map(face::NamedFace::plane).transpose()?.flatten() {
Some(cn) => cn,
None => nearest_plane(doc, st, o, named.as_ref().map_or(*pick, |f| f.point))?,
};
frame(c, n, face::x_axis(doc, st, x.as_ref(), c)?).ok_or_else(bad)
frame(c, n, face::x_axis(doc, st, comp, x.as_ref(), c)?).ok_or_else(bad)
}
Snap::Edge { .. } => edge::edge_frame(doc, st, component_of(doc, o.occurrence)?, &o.snap),
Snap::CircleCenter { x, .. } => {
let r = round_of(doc, st, o)?;
frame(r.centre, r.z, face::x_axis(doc, st, x.as_ref(), r.centre)?).ok_or_else(bad)
frame(r.centre, r.z, face::x_axis(doc, st, component_of(doc, o.occurrence)?, x.as_ref(), r.centre)?).ok_or_else(bad)
}
}
}
@@ -828,13 +829,13 @@ pub fn resolve_origin(doc: &Document, st: &ModelState, o: &JointOrigin) -> Resul
/// it, as older builds found them. Any other snap is refused.
fn round_of(doc: &Document, st: &ModelState, o: &JointOrigin) -> Result<face::Round> {
let Snap::CircleCenter { pick, face, end, .. } = &o.snap else { return Err(DocError::Invalid("pick a round face".into())) };
let comp = component_of(doc, o.occurrence)?;
if let Some(n) = face.as_deref()
&& let Some(r) = face::named_round(doc, st, *pick, n, end.as_deref())?
&& let Some(r) = face::named_round(doc, st, comp, *pick, n, end.as_deref())?
{
return Ok(r);
}
let pick = named_pick(doc, st, *pick, face.as_deref())?;
let comp = component_of(doc, o.occurrence)?;
let pick = named_pick(doc, st, comp, *pick, face.as_deref())?;
// A body moved in from another component: looked at in its own coordinates, its cylinder
// placed by its offset (as a named face is).
let cyl = component_bodies(doc, st, comp)
+32 -17
View File
@@ -30,9 +30,23 @@ fn gone(name: &str) -> DocError {
DocError::Invalid(format!("joint origin: the face `{name}` no longer exists (edit the joint to pick again)"))
}
/// The face called `name` nearest `pick` (an error when it is gone: a joint must not quietly
/// attach elsewhere).
pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, pick: Vec3, name: &str) -> Result<NamedFace<'a>> {
/// The face called `name` on the bodies of `component` nearest `pick` (an error when it is gone:
/// a joint must not quietly attach elsewhere). Each body is looked at in its own coordinates, and
/// a face the name finds exactly comes before a piece of it or a face it was merged into. Only the
/// component's own bodies: the parts of one STEP import share their face names, and another
/// part's face of that name can lie nearer the pick than this part's own.
pub(super) fn named_face<'a>(doc: &Document, st: &'a ModelState, component: u64, pick: Vec3, name: &str) -> Result<NamedFace<'a>> {
let own = component_bodies(doc, st, component).into_iter().filter_map(|body| {
let offset = doc.model_body_offset(body).copied().unwrap_or(IDENTITY);
let (face, at, inexact) = crate::naming::face_on_body(body, name, apply_point(&mat_inverse(&offset)?, pick))?;
let point = apply_point(&offset, at);
Some(((inexact, point.dist(pick)), NamedFace { body, face, point, offset }))
});
if let Some((_, nf)) = own.min_by(|(a, _), (b, _)| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))) {
return Ok(nf);
}
// On none of them (the face's body has gone to another component since): wherever the name
// is now.
let hit = crate::name_lookup::locate_face(st, name, pick).ok_or_else(|| gone(name))?;
let body = st.bodies.get(hit.body).ok_or_else(|| gone(name))?;
let Some(offset) = doc.model_body_offset(body).copied() else {
@@ -219,8 +233,8 @@ impl Round {
/// A circle-centre snap's cylinder found through its named face (`None`: the snap names no
/// face, or the face is not a cylinder any more; the caller looks by point, as older builds
/// did). The end is the one whose rim meets the face called `end`, else the one nearer `pick`.
pub(super) fn named_round(doc: &Document, st: &ModelState, pick: Vec3, face: &str, end: Option<&str>) -> Result<Option<Round>> {
let nf = named_face(doc, st, pick, face)?;
pub(super) fn named_round(doc: &Document, st: &ModelState, component: u64, pick: Vec3, face: &str, end: Option<&str>) -> Result<Option<Round>> {
let nf = named_face(doc, st, component, pick, face)?;
let Some(own) = nf.own_cylinder() else { return Ok(None) };
let chosen = end.and_then(|name| end_named(nf.body, nf.face, &own, name)).unwrap_or_else(|| end_by_pick(&nf, &own));
Ok(Some(Round::at(placed(&nf.offset, own), chosen)))
@@ -248,13 +262,14 @@ fn end_named(b: &ModelBody, face: usize, own: &CylinderFace, name: &str) -> Opti
}
}
/// The x axis an x reference gives a frame at `o` with axis `z` (`None`: no reference).
pub(super) fn x_axis(doc: &Document, st: &ModelState, x: Option<&XRef>, o: Vec3) -> Result<Option<Vec3>> {
/// The x axis an x reference gives a frame at `o` (of `component`) with axis `z` (`None`: no
/// reference).
pub(super) fn x_axis(doc: &Document, st: &ModelState, component: u64, x: Option<&XRef>, o: Vec3) -> Result<Option<Vec3>> {
Ok(match x {
None => None,
Some(XRef::Dir(d)) => Some(*d),
Some(XRef::Face { face, pick }) => {
let nf = named_face(doc, st, pick.unwrap_or(o), face)?;
let nf = named_face(doc, st, component, pick.unwrap_or(o), face)?;
if let Some((_, n)) = nf.plane()? {
Some(n)
} else if let Some(c) = nf.cylinder() {
@@ -342,22 +357,22 @@ pub fn round_end_at(doc: &Document, st: &ModelState, component: u64, centre: Vec
Some(Snap::CircleCenter { pick: centre, face: Some(face), end, x: None })
}
/// Name the end a named circle-centre snap takes now (the face across the rim there), so it
/// keeps that end when the design changes. Other snaps, and one whose end is named already, are
/// left as they are.
pub fn pin_end(doc: &Document, st: &ModelState, snap: &mut Snap) {
/// Name the end a named circle-centre snap of `component` takes now (the face across the rim
/// there), so it keeps that end when the design changes. Other snaps, and one whose end is named
/// already, are left as they are.
pub fn pin_end(doc: &Document, st: &ModelState, component: u64, snap: &mut Snap) {
let Snap::CircleCenter { pick, face: Some(face), end: end @ None, .. } = snap else { return };
let Ok(nf) = named_face(doc, st, *pick, face) else { return };
let Ok(nf) = named_face(doc, st, component, *pick, face) else { return };
let Some(own) = nf.own_cylinder() else { return };
let (at, _) = end_by_pick(&nf, &own);
*end = rim_neighbour(nf.body, nf.face, &own, at).and_then(|n| crate::naming::face_names(nf.body).get(n).cloned()).filter(|n| !n.is_empty());
}
/// The names of the faces across the rims at the two ends of a named circle-centre snap's
/// cylinder (what its `end` can be); empty when the snap names no cylinder.
pub fn end_faces(doc: &Document, st: &ModelState, snap: &Snap) -> Vec<String> {
/// The names of the faces across the rims at the two ends of the cylinder a named circle-centre
/// snap of `component` names (what its `end` can be); empty when the snap names no cylinder.
pub fn end_faces(doc: &Document, st: &ModelState, component: u64, snap: &Snap) -> Vec<String> {
let Snap::CircleCenter { pick, face: Some(face), .. } = snap else { return Vec::new() };
let Ok(nf) = named_face(doc, st, *pick, face) else { return Vec::new() };
let Ok(nf) = named_face(doc, st, component, *pick, face) else { return Vec::new() };
let Some(own) = nf.own_cylinder() else { return Vec::new() };
let names = crate::naming::face_names(nf.body);
ends(&own)
+3 -2
View File
@@ -469,6 +469,7 @@ fn origin_by_name(s: &Session, v: &Value, what: &str, name: &str, cmd: &str) ->
/// there) set, and the end it takes named so it keeps it; refused when it doesn't resolve.
fn settle(s: &Session, mut o: JointOrigin, v: &Value, cmd: &str) -> Result<JointOrigin> {
let st = s.model.state();
let component = component_of(s, o.occurrence);
if let Some(want) = v.get("end") {
let want = want
.as_str()
@@ -476,13 +477,13 @@ fn settle(s: &Session, mut o: JointOrigin, v: &Value, cmd: &str) -> Result<Joint
.ok_or_else(|| bad(cmd, "`end` is the name of a face a round end lies on"))?;
let Snap::CircleCenter { end, .. } = &mut o.snap else { return Err(bad(cmd, "`end` is for a round origin (`circle`)")) };
*end = Some(want.to_string());
let names = joints::end_faces(&s.doc, &st, &o.snap);
let names = joints::end_faces(&s.doc, &st, component, &o.snap);
if !names.iter().any(|n| n == want) {
return Err(bad(cmd, format!("the round face doesn't end on face `{want}` (its ends lie on: {})", names.join(", "))));
}
}
let m = joints::resolve_origin(&s.doc, &st, &o).map_err(|e| bad(cmd, e.to_string()))?;
joints::pin_end(&s.doc, &st, &mut o.snap);
joints::pin_end(&s.doc, &st, component, &mut o.snap);
// A face or circle given no `x` keeps the x it has now, so its frame doesn't turn as the face
// tilts.
o.snap = o.snap.with_frame_x(Vec3::new(m[0][0], m[0][1], m[0][2]));
@@ -357,3 +357,61 @@ fn an_inserted_assembly_exports_its_nested_parts_where_they_are() {
assert_eq!(shown_boxes(&back), placed);
let _ = std::fs::remove_dir_all(&dir);
}
/// The parts of one STEP import share their face names, and each keeps its body where the file
/// has it, placed in its component by an offset. A joint on one part's hole takes that part's
/// hole, not the other part's hole of that name, though the pick (in the part's own coordinates)
/// lies nearer that one as the bodies lie.
#[test]
fn a_joint_on_an_imported_part_takes_its_own_hole() {
// Two 40 × 30 × 5 plates with a 6.2 mm hole through each: A's at (28, 20), B's at (10, 10);
// B placed 60 mm along X, so its hole is at (70, 10) in the world.
let plate = |x: f64, y: f64| {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 5}));
run(&mut s, "solid.hole", json!({"position": [x, y, 5], "diameter": 6.2, "depth": 5}));
s.model.state().bodies[0].body.clone()
};
let (a, b) = (plate(28.0, 20.0), plate(10.0, 10.0));
let part = |name: &str, body| ExportProduct {
name: name.into(),
bodies: vec![ExportBody { name: name.into(), body, color: None }],
children: Vec::new(),
};
let products = vec![
ExportProduct {
name: "Pair".into(),
bodies: Vec::new(),
children: vec![(1, at(0.0, 0.0, 0.0), "A-1".into()), (2, at(60.0, 0.0, 0.0), "B-1".into())],
},
part("A", &a),
part("B", &b),
];
let dir = temp_dir("own-hole");
let path = dir.join("pair.step");
std::fs::write(&path, step_export_products(&products, 0, &StepHeader::default()).unwrap()).unwrap();
let mut s = Session::default();
run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()}));
let _ = std::fs::remove_dir_all(&dir);
// A pin jointed into B's hole, picked on its wall.
let on_b = occurrence_named(&s, "B:1");
let pin = run(&mut s, "component.create", json!({"name": "Pin"}))["occurrence"].as_u64().unwrap();
run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 10, "base": [0, -40, 0]}));
run(&mut s, "component.activate", json!({"component": "root"}));
let a = json!({"occurrence": pin, "point": [0, -40, 0]});
run(&mut s, "joint.create", json!({"type": "rigid", "name": "Into B", "a": a, "b": {"occurrence": on_b, "circle": [73.1, 10, 2.5]}}));
let o = s.doc.assembly.joints.iter().find(|j| j.name == "Into B").unwrap().b.clone();
let st = s.model.state();
// A's hole has the very name B's has (the case this is about).
let solidcraft_doc::joints::Snap::CircleCenter { face: Some(name), .. } = &o.snap else { panic!("{:?}", o.snap) };
let a_comp = s.doc.occurrences.iter().find(|x| x.id == occurrence_named(&s, "A:1")).unwrap().component;
let a_body = st.bodies.iter().find(|x| s.doc.model_body_component(x) == a_comp).unwrap();
assert!(solidcraft_doc::naming::face_names(a_body).iter().any(|n| n == name), "{name}");
let f = solidcraft_doc::joints::resolve_origin(&s.doc, &st, &o).unwrap();
let at = solidcraft_doc::apply_point(&solidcraft_doc::joints::occurrence_world(&s.doc, on_b), Vec3::new(f[3][0], f[3][1], f[3][2]));
assert!(Vec3::new(at.x, at.y, 0.0).dist(Vec3::new(70.0, 10.0, 0.0)) < 1e-6, "B's hole is at (70, 10), the joint at {at:?}");
// And the pin stands in it.
let pin_at = solidcraft_doc::apply_point(&solidcraft_doc::joints::occurrence_world(&s.doc, pin), Vec3::new(0.0, -40.0, 0.0));
assert!(Vec3::new(pin_at.x, pin_at.y, 0.0).dist(Vec3::new(70.0, 10.0, 0.0)) < 1e-6, "the pin's base is at {pin_at:?}");
}