Preserve construction references when axes and points are renamed (#4419) (#4449)

* claim: #4419

* fix: preserve renamed construction references (#4419)
This commit is contained in:
Colin Faulkingham
2026-10-24 00:24:51 +00:00
committed by GitHub
parent a199a2cc25
commit 2e5924ed5e
9 changed files with 295 additions and 51 deletions
+36 -28
View File
@@ -77,13 +77,7 @@ pub fn clone_expression(source: &str, parameters: &BTreeMap<String, String>) ->
result
}
fn remap_geo(
g: &mut crate::construct::GeoRef,
ids: &BTreeMap<u64, u64>,
names: &BTreeMap<String, String>,
bodies: &BTreeMap<String, String>,
depth: usize,
) -> crate::Result<()> {
fn remap_geo(g: &mut crate::construct::GeoRef, ids: &BTreeMap<u64, u64>, bodies: &BTreeMap<String, String>, depth: usize) -> crate::Result<()> {
use crate::construct::GeoRef;
if depth > 64 {
return Err(crate::DocError::Invalid("clone plane reference depth exceeded".into()));
@@ -100,28 +94,18 @@ fn remap_geo(
*n = remap_topology(n, ids, bodies);
}
}
GeoRef::ConstructPoint { name } | GeoRef::Axis { name } => mapped_name(name, names),
GeoRef::Plane { plane } => remap_plane(plane, ids, names, bodies, depth + 1)?,
GeoRef::Plane { plane } => remap_plane(plane, ids, bodies, depth + 1)?,
_ => {}
}
Ok(())
}
fn remap_plane(
p: &mut PlaneRef,
ids: &BTreeMap<u64, u64>,
names: &BTreeMap<String, String>,
bodies: &BTreeMap<String, String>,
depth: usize,
) -> crate::Result<()> {
fn remap_plane(p: &mut PlaneRef, ids: &BTreeMap<u64, u64>, bodies: &BTreeMap<String, String>, depth: usize) -> crate::Result<()> {
if depth > 64 {
return Err(crate::DocError::Invalid("clone plane reference depth exceeded".into()));
}
match p {
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => {
remap_plane(base, ids, names, bodies, depth + 1)?
}
PlaneRef::Construction { name } => mapped_name(&mut name.0, names),
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => remap_plane(base, ids, bodies, depth + 1)?,
PlaneRef::Face { name, anchor, .. } => {
if let Some(name) = name {
*name = remap_topology(name, ids, bodies);
@@ -132,7 +116,7 @@ fn remap_plane(
}
_ => {
for r in p.refs_mut() {
remap_geo(r, ids, names, bodies, depth + 1)?;
remap_geo(r, ids, bodies, depth + 1)?;
}
}
}
@@ -214,6 +198,8 @@ impl crate::Feature {
}
_ => {}
}
// Feature names are remapped once here; the geometry pass below handles only
// sketch ids and topology, so a copy whose new name is also an old key is not remapped twice.
self.kind.remap_refs(ids, names);
for n in &mut self.body_names {
mapped_name(n, bodies);
@@ -236,7 +222,7 @@ impl crate::Feature {
self.kind.remap_bodies(bodies);
match &mut self.kind {
K::Sketch { plane, sketch } => {
remap_plane(plane, ids, names, bodies, 0)?;
remap_plane(plane, ids, bodies, 0)?;
for c in &mut sketch.constraints {
if let Some(n) = &mut c.param {
mapped_name(n, parameters);
@@ -256,18 +242,18 @@ impl crate::Feature {
| K::Split { plane, .. }
| K::SplitFace { plane, .. }
| K::Mirror { plane, .. }
| K::SurfaceTrim { plane, .. } => remap_plane(plane, ids, names, bodies, 0)?,
K::Draft { neutral, .. } => remap_plane(neutral, ids, names, bodies, 0)?,
K::ReplaceFace { target, .. } => remap_plane(target, ids, names, bodies, 0)?,
K::SurfaceExtend { up_to: Some(crate::ExtendTo::Plane(plane)), .. } => remap_plane(plane, ids, names, bodies, 0)?,
| K::SurfaceTrim { plane, .. } => remap_plane(plane, ids, bodies, 0)?,
K::Draft { neutral, .. } => remap_plane(neutral, ids, bodies, 0)?,
K::ReplaceFace { target, .. } => remap_plane(target, ids, bodies, 0)?,
K::SurfaceExtend { up_to: Some(crate::ExtendTo::Plane(plane)), .. } => remap_plane(plane, ids, bodies, 0)?,
K::ConstructionAxis { def } => {
for r in def.refs_mut() {
remap_geo(r, ids, names, bodies, 0)?;
remap_geo(r, ids, bodies, 0)?;
}
}
K::ConstructionPoint { def } => {
for r in def.refs_mut() {
remap_geo(r, ids, names, bodies, 0)?;
remap_geo(r, ids, bodies, 0)?;
}
}
_ => {}
@@ -324,6 +310,28 @@ fn checked_link(source: &solidcraft_sketch::LinkSource, depth: usize) -> crate::
#[cfg(test)]
mod clone_tests {
use super::*;
#[test]
fn construction_feature_names_are_remapped_only_once_when_copied() {
use serde_json::json;
let names = BTreeMap::from([("Old".into(), "New".into()), ("New".into(), "Wrong".into())]);
let origin = json!({"type": "plane", "plane": {"type": "construction", "name": "Old"}});
for kind in [
json!({"type": "construction_axis", "def": {"type": "two_points", "a": {"type": "construct_point", "name": "Old"}, "b": {"type": "point", "p": [1, 2, 3]}}}),
json!({"type": "construction_point", "def": {"type": "edge_and_plane", "edge": {"type": "axis", "name": "Old"}, "plane": origin}}),
json!({"type": "construction_plane", "plane": {"type": "perpendicular", "plane": origin, "line": {"type": "axis", "name": "Old"}}}),
] {
let mut value = kind;
value["id"] = json!(1);
value["name"] = json!("Copy");
let mut feature: crate::Feature = serde_json::from_value(value).unwrap();
let before = serde_json::to_string(&feature).unwrap();
feature.remap_clone(&BTreeMap::new(), &names, &BTreeMap::new(), &BTreeMap::new()).unwrap();
assert_eq!(serde_json::to_string(&feature).unwrap(), before.replace("\"Old\"", "\"New\""));
}
}
#[test]
fn imported_names_and_topology_tokens_have_separate_identity() {
let ids = BTreeMap::from([(1, 2), (10, 20)]);
+2 -2
View File
@@ -48,9 +48,9 @@ pub enum GeoRef {
/// World X, Y or Z axis.
World { axis: String },
/// A construction axis feature, by name.
Axis { name: String },
Axis { name: crate::FeatureName },
/// A construction point feature, by name.
ConstructPoint { name: String },
ConstructPoint { name: crate::FeatureName },
/// A sketch point (by sketch feature id and point id).
SketchPoint { sketch: u64, point: String },
/// A sketch curve (by sketch feature id and curve id).
+79
View File
@@ -177,6 +177,85 @@ fn references_match_the_golden_record() {
check_golden("golden_refs.txt", GOLDEN_REFS, &ref_record());
}
#[test]
fn construction_names_follow_renames_in_every_definition() {
use crate::walk::{Ref, Walk};
use serde_json::json;
let axis = json!({"type": "axis", "name": "Old"});
let point = json!({"type": "construct_point", "name": "Old"});
let plane = json!({"type": "plane", "plane": {"type": "construction", "name": "Old"}});
let definitions = [
json!({"type": "construction_axis", "def": {"type": "through_face", "face": axis}}),
json!({"type": "construction_axis", "def": {"type": "normal_to_face", "face": plane, "point": point}}),
json!({"type": "construction_axis", "def": {"type": "two_planes", "a": plane, "b": plane}}),
json!({"type": "construction_axis", "def": {"type": "two_points", "a": point, "b": point}}),
json!({"type": "construction_axis", "def": {"type": "edge", "edge": axis}}),
json!({"type": "construction_point", "def": {"type": "at", "point": point}}),
json!({"type": "construction_point", "def": {"type": "two_edges", "a": axis, "b": axis}}),
json!({"type": "construction_point", "def": {"type": "three_planes", "a": plane, "b": plane, "c": plane}}),
json!({"type": "construction_point", "def": {"type": "center", "of": axis}}),
json!({"type": "construction_point", "def": {"type": "edge_and_plane", "edge": axis, "plane": plane}}),
json!({"type": "construction_point", "def": {"type": "along_path", "path": axis, "t": "0.5"}}),
];
let planes = [
json!({"type": "midplane", "a": plane, "b": plane}),
json!({"type": "two_edges", "a": axis, "b": axis}),
json!({"type": "three_points", "a": point, "b": point, "c": point}),
json!({"type": "tangent", "face": plane, "at": [0, 0, 0]}),
json!({"type": "along_path", "path": axis, "t": "0.5"}),
json!({"type": "perpendicular", "plane": plane, "line": axis}),
];
let wrapped = planes.into_iter().map(|plane| {
json!({"type": "construction_plane", "plane": {"type": "flipped", "base": {
"type": "offset", "distance": "10", "base": {"type": "at_angle", "angle": "20 deg",
"axis_origin": [0, 0, 0], "axis_dir": [1, 0, 0], "base": plane}}}})
});
let names = BTreeMap::from([("Old".into(), "New".into()), ("New".into(), "Wrong".into())]);
for definition in definitions.into_iter().chain(wrapped) {
let mut kind: FeatureKind = serde_json::from_value(definition.clone()).unwrap();
let expected_count = definition.to_string().matches("\"Old\"").count();
let mut seen = Vec::new();
kind.walk_refs(&mut |r| {
if let Ref::Feature(name) = r {
seen.push(name.to_string());
}
});
assert_eq!(seen, vec!["Old"; expected_count], "{definition}");
kind.remap_refs(&BTreeMap::new(), &names);
let expected: serde_json::Value = serde_json::from_str(&definition.to_string().replace("\"Old\"", "\"New\"")).unwrap();
assert_eq!(serde_json::to_value(kind).unwrap(), serde_json::to_value(serde_json::from_value::<FeatureKind>(expected).unwrap()).unwrap());
}
}
#[test]
fn construction_reference_walk_keeps_its_depth_limit_across_geometry() {
use crate::construct::GeoRef;
use crate::walk::{Ref, Walk};
let mut plane = crate::PlaneRef::Construction { name: "TooDeep".into() };
for _ in 0..80 {
plane = crate::PlaneRef::Perpendicular { plane: Box::new(GeoRef::Plane { plane }), line: Box::new(GeoRef::Axis { name: "Side".into() }) };
}
let mut seen = Vec::new();
plane.walk_refs(&mut |r| {
if let Ref::Feature(name) = r {
seen.push(name.to_string());
}
});
assert!(!seen.is_empty() && seen.len() < 64);
assert!(seen.iter().all(|name| name == "Side"));
let mut changed = 0;
plane.walk_refs_mut(&mut |r| {
if let Ref::Feature(name) = r {
assert_eq!(name.as_ref(), "Side");
*name = "Renamed".into();
changed += 1;
}
});
assert_eq!(changed, seen.len());
}
#[test]
fn inputs_and_expressions_match_the_golden_record() {
check_golden("golden_exprs.txt", GOLDEN_EXPRS, &record());
@@ -86,7 +86,9 @@ split_line
remap_refs: plane.base.base.name, sketch
remap_bodies: body
construction_axis
remap_refs: def.a.plane.base.base.name, def.b.plane.base.base.name
construction_point_planes
remap_refs: def.a.plane.base.base.name, def.b.plane.base.base.name, def.c.plane.base.base.name
construction_point_along
split_face
sketches: [6]
+98 -19
View File
@@ -319,7 +319,7 @@ impl<F: Fn(usize, usize) -> &'static str> Label for F {
/// The offsets and angles of a plane, outermost first, and an explicit origin's coordinates
/// (nesting is capped like every walk over a plane), the construction plane it is built on, and
/// the plane itself.
/// the plane itself. Feature references also reach the geometry used to construct a plane.
impl Walk for PlaneRef {
fn walk_exprs<'a>(&'a self, f: &mut dyn FnMut(ExprItem<'a>)) {
let mut p = self;
@@ -374,24 +374,10 @@ impl Walk for PlaneRef {
}
}
fn walk_refs<'a>(&'a self, f: &mut dyn FnMut(RefItem<'a>)) {
let mut p = self;
for _ in 0..64 {
match p {
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => p = base,
PlaneRef::Construction { name } => return f(Ref::Feature(name)),
_ => return,
}
}
self.walk_feature_refs(f, 0);
}
fn walk_refs_mut<'a>(&'a mut self, f: &mut dyn FnMut(RefItemMut<'a>)) {
let mut p = self;
for _ in 0..64 {
match p {
PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => p = base,
PlaneRef::Construction { name } => return f(Ref::Feature(name)),
_ => return,
}
}
self.walk_feature_refs_mut(f, 0);
}
fn walk_geometry<'a>(&'a self, f: &mut dyn FnMut(GeoItem<'a>)) {
f(Geo::Plane(self))
@@ -401,9 +387,92 @@ impl Walk for PlaneRef {
}
}
impl PlaneRef {
fn walk_feature_refs<'a>(&'a self, f: &mut dyn FnMut(RefItem<'a>), depth: usize) {
if depth >= 64 {
return;
}
match self {
Self::Construction { name } => f(Ref::Feature(name)),
Self::Offset { base, .. } | Self::AtAngle { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs(f, depth + 1),
Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => {
a.walk_feature_refs(f, depth + 1);
b.walk_feature_refs(f, depth + 1);
}
Self::ThreePoints { a, b, c } => {
a.walk_feature_refs(f, depth + 1);
b.walk_feature_refs(f, depth + 1);
c.walk_feature_refs(f, depth + 1);
}
Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs(f, depth + 1),
Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {}
}
}
fn walk_feature_refs_mut<'a>(&'a mut self, f: &mut dyn FnMut(RefItemMut<'a>), depth: usize) {
if depth >= 64 {
return;
}
match self {
Self::Construction { name } => f(Ref::Feature(name)),
Self::Offset { base, .. } | Self::AtAngle { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs_mut(f, depth + 1),
Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => {
a.walk_feature_refs_mut(f, depth + 1);
b.walk_feature_refs_mut(f, depth + 1);
}
Self::ThreePoints { a, b, c } => {
a.walk_feature_refs_mut(f, depth + 1);
b.walk_feature_refs_mut(f, depth + 1);
c.walk_feature_refs_mut(f, depth + 1);
}
Self::Tangent { face, .. } | Self::AlongPath { path: face, .. } => face.walk_feature_refs_mut(f, depth + 1),
Self::Origin { .. } | Self::Custom { .. } | Self::Placed { .. } | Self::Face { .. } => {}
}
}
}
impl GeoRef {
// Carry the depth across GeoRef -> PlaneRef -> GeoRef, rather than restarting its cap.
fn walk_feature_refs<'a>(&'a self, f: &mut dyn FnMut(RefItem<'a>), depth: usize) {
if depth >= 64 {
return;
}
match self {
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::Feature(name)),
Self::Plane { plane } => plane.walk_feature_refs(f, depth + 1),
Self::Point { .. }
| Self::Origin
| Self::Vertex { .. }
| Self::Edge { .. }
| Self::Face { .. }
| Self::World { .. }
| Self::SketchPoint { .. }
| Self::SketchCurve { .. } => {}
}
}
fn walk_feature_refs_mut<'a>(&'a mut self, f: &mut dyn FnMut(RefItemMut<'a>), depth: usize) {
if depth >= 64 {
return;
}
match self {
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::Feature(name)),
Self::Plane { plane } => plane.walk_feature_refs_mut(f, depth + 1),
Self::Point { .. }
| Self::Origin
| Self::Vertex { .. }
| Self::Edge { .. }
| Self::Face { .. }
| Self::World { .. }
| Self::SketchPoint { .. }
| Self::SketchCurve { .. } => {}
}
}
}
/// Construction axes and points: the expressions of the planes they are built from (and a point
/// along a path's distance), and their references to the model. They name no sketches, features
/// or bodies: copies remap their geometry references on their own (`Feature::remap_clone`).
/// along a path's distance), and their feature and geometry references. Copies still remap
/// sketch ids and persistent topology names through their geometry (`Feature::remap_clone`).
fn plane_exprs<'a>(refs: Vec<&'a GeoRef>, f: &mut dyn FnMut(ExprItem<'a>)) {
for r in refs {
if let GeoRef::Plane { plane } = r {
@@ -422,6 +491,16 @@ fn plane_exprs_mut<'a>(refs: Vec<&'a mut GeoRef>, f: &mut dyn FnMut(ExprItemMut<
macro_rules! construct_geometry {
() => {
fn walk_refs<'a>(&'a self, f: &mut dyn FnMut(RefItem<'a>)) {
for r in self.refs() {
r.walk_feature_refs(f, 0);
}
}
fn walk_refs_mut<'a>(&'a mut self, f: &mut dyn FnMut(RefItemMut<'a>)) {
for r in self.refs_mut() {
r.walk_feature_refs_mut(f, 0);
}
}
fn walk_geometry<'a>(&'a self, f: &mut dyn FnMut(GeoItem<'a>)) {
for r in self.refs() {
f(Geo::Construct(r));
+2 -2
View File
@@ -116,13 +116,13 @@ fn geo(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result<GeoRef>
GeoRef::World { axis: a.to_ascii_uppercase() }
} else {
match s.doc.find_feature(a).map(|f| &f.kind) {
Some(FeatureKind::ConstructionAxis { .. }) => GeoRef::Axis { name: a.to_string() },
Some(FeatureKind::ConstructionAxis { .. }) => GeoRef::Axis { name: a.into() },
_ => return Err(bad(cmd, format!("no axis `{a}`"))),
}
}
} else if let Some(n) = str_(v, "construct_point") {
match s.doc.find_feature(n).map(|f| &f.kind) {
Some(FeatureKind::ConstructionPoint { .. }) => GeoRef::ConstructPoint { name: n.to_string() },
Some(FeatureKind::ConstructionPoint { .. }) => GeoRef::ConstructPoint { name: n.into() },
_ => return Err(bad(cmd, format!("no construction point `{n}`"))),
}
} else if v.as_str().is_some() {
+55
View File
@@ -43,6 +43,61 @@ fn plane(s: &Session, name: &str) -> Plane {
construction_planes(s).into_iter().find(|p| p.1 == name).map(|p| p.2).unwrap_or_else(|| panic!("no plane {name}"))
}
#[test]
fn renamed_construction_references_survive_edits_and_reopening() {
let mut s = Session::default();
run(&mut s, "construct.axis.two_planes", json!({"a": "XZ", "b": "YZ", "name": "Spine"}));
run(&mut s, "construct.plane.perpendicular", json!({"plane": "XZ", "line": {"axis": "Spine"}, "name": "Fence"}));
run(&mut s, "construct.point.three_planes", json!({"a": "XY", "b": "XZ", "c": "YZ", "name": "Pin"}));
run(&mut s, "construct.axis.two_points", json!({"a": {"construct_point": "Pin"}, "b": {"point": [30, 30, 30]}, "name": "Brace"}));
run(&mut s, "construct.point.vertex", json!({"point": {"construct_point": "Pin"}, "name": "Copy"}));
let before = (*s.doc).clone();
run(&mut s, "timeline.rename", json!({"feature": "Spine", "name": "Mast"}));
run(&mut s, "timeline.rename", json!({"feature": "Pin", "name": "Peg"}));
let fence = run(&mut s, "timeline.inspect", json!({"feature": "Fence"}));
assert_eq!(fence["definition"]["plane"]["line"]["name"], "Mast");
let brace = run(&mut s, "timeline.inspect", json!({"feature": "Brace"}));
assert_eq!(brace["definition"]["def"]["a"]["name"], "Peg");
let renamed = (*s.doc).clone();
for _ in 0..2 {
run(&mut s, "edit.undo", json!({}));
}
assert_eq!(*s.doc, before);
for _ in 0..2 {
run(&mut s, "edit.redo", json!({}));
}
assert_eq!(*s.doc, renamed);
run(&mut s, "timeline.edit", json!({"feature": "Mast", "set": {"def.b": {"type": "plane", "plane": {"type": "origin", "name": "XY"}}}}));
let saved = serde_json::to_vec(&*s.doc).unwrap();
let mut reopened = Session::new(serde_json::from_slice(&saved).unwrap());
reopened.refresh();
for session in [&s, &reopened] {
assert!(session.model.results.iter().all(|r| r.error.is_none()), "{:?}", session.model.results);
assert!(parallel(plane(session, "Fence").normal(), Vec3::Z));
assert!(parallel(axis(session, "Brace").1, Vec3::new(1.0, 1.0, 1.0)));
assert!(near(point(session, "Copy"), Vec3::ZERO));
}
}
#[test]
fn renamed_hidden_axes_and_points_stay_hidden_through_undo_redo() {
let mut s = Session::default();
run(&mut s, "construct.axis.two_planes", json!({"a": "XZ", "b": "YZ", "name": "Spine"}));
run(&mut s, "construct.point.three_planes", json!({"a": "XY", "b": "XZ", "c": "YZ", "name": "Pin"}));
run(&mut s, "browser.visibility", json!({"items": ["Spine", "Pin", "XY"], "visible": false}));
for (old, new) in [("Spine", "Mast"), ("Pin", "Peg")] {
run(&mut s, "timeline.rename", json!({"feature": old, "name": new}));
assert!(!s.construction_visible(new));
assert!(!s.visibility.hidden_origin.iter().any(|n| n == old));
run(&mut s, "edit.undo", json!({}));
assert!(!s.construction_visible(old));
assert!(!s.visibility.hidden_origin.iter().any(|n| n == new));
run(&mut s, "edit.redo", json!({}));
assert!(!s.construction_visible(new));
}
assert!(!s.construction_visible("XY"));
}
/// The line through `o` along `d` contains `p`.
fn on_line(o: Vec3, d: Vec3, p: Vec3) -> bool {
let d = d.normalized().unwrap_or(Vec3::Z);
+1
View File
@@ -685,6 +685,7 @@ impl Session {
/// which keeps every result and mesh (#3044).
fn refresh_from(&mut self, previous: &Arc<Document>) {
self.follow_plane_renames(previous);
self.follow_axis_point_renames(previous);
if let Some((old, new)) = self.body_rename(previous)
&& self.model.rename_body(&self.doc, &old, &new)
{
+20
View File
@@ -41,6 +41,26 @@ pub(crate) struct RemovedLaterCache {
}
impl Session {
/// Visibility keeps construction names, while undo history keeps feature ids. Follow the
/// same axis or point into the new document on rename, undo and redo (#4419).
pub(crate) fn follow_axis_point_renames(&mut self, previous: &solidcraft_doc::Document) {
if self.visibility.hidden_origin.is_empty() {
return;
}
let names: std::collections::HashMap<_, _> = self.doc.features.iter().map(|f| (f.id, &f.name)).collect();
let renamed: std::collections::HashMap<_, _> = previous
.features
.iter()
.filter(|f| matches!(f.kind, FeatureKind::ConstructionAxis { .. } | FeatureKind::ConstructionPoint { .. }))
.filter_map(|f| names.get(&f.id).filter(|name| **name != &f.name).map(|name| (f.name.as_str(), *name)))
.collect();
for name in &mut self.visibility.hidden_origin {
if let Some(new) = renamed.get(name.as_str()) {
name.clone_from(new);
}
}
}
/// Document with uncaptured occurrence positions applied, without changing saved geometry.
pub fn placed_document(&self) -> std::borrow::Cow<'_, solidcraft_doc::Document> {
if self.pending_moves.is_empty() {