Skip to content

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

Face names: pieces of a split face keep their numbers across evaluations (#3902) (#3991)

bherbruck8c861f9f4682
diff --git a/crates/doc/src/config_shell_tests.rs b/crates/doc/src/config_shell_tests.rs
index d94a72efdb..ad33c690ad 100644
--- a/crates/doc/src/config_shell_tests.rs
+++ b/crates/doc/src/config_shell_tests.rs
@@ -180,6 +180,9 @@ fn shell_planar_format13_keeps_v12_documents_and_refuses_future() {
assert_eq!(current["format"], crate::format::format_string(crate::format::FORMAT));
current["format"] = json!("solidcraft/12");
crate::format::pieces_in_shell_order(&mut legacy["features"]);
+ for f in legacy["features"].as_array_mut().into_iter().flatten() {
+ f["kernel_piece_order"] = json!(true);
+ }
assert_eq!(legacy, current, "the migration preserves every prior field");
legacy["format"] = json!(crate::format::format_string(crate::format::FORMAT + 1));
assert!(crate::format::read(&legacy.to_string()).is_err());
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index d63b108153..742b0bf6f9 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -2329,6 +2329,12 @@ pub struct Feature {
/// where newer ones number them after the first name (`Ribs (4)`, #373).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub shell_piece_order: bool,
+ /// The pieces of a face this feature splits are numbered in the kernel's order and by the
+ /// index of the face they came from, as builds before #3902 numbered them, instead of by
+ /// place. Set on the features of designs saved before then, whose stored `#k` face names
+ /// mean that numbering.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub kernel_piece_order: bool,
#[serde(flatten)]
pub kind: FeatureKind,
}
@@ -3030,6 +3036,7 @@ impl Document {
face_names: Vec::new(),
participants: Vec::new(),
shell_piece_order: false,
+ kernel_piece_order: false,
kind,
};
self.place_feature(f);
diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs
index 43fd8af5c4..fc3c9d4aae 100644
--- a/crates/doc/src/format.rs
+++ b/crates/doc/src/format.rs
@@ -1250,7 +1250,9 @@ mod tests {
file["format"] = Value::from("solidcraft/23");
let opened = read(&file.to_string()).unwrap();
assert_eq!(opened.format, format_string(FORMAT));
- assert_eq!(opened.features, plain.features);
+ let mut kept = plain.features.clone();
+ kept.iter_mut().for_each(|f| f.kernel_piece_order = true);
+ assert_eq!(opened.features, kept);
// One that chooses its relief says so in the file, which is stamped 24 and keeps it.
let mut own = Document::new("A");
own.add_feature(flange(Some("round"), Some("6 mm")), None).unwrap();
@@ -1742,7 +1744,7 @@ mod tests {
legacy["format"] = Value::from("solidcraft/6");
let original_table = legacy["configs"].clone();
let upgraded = read(&legacy.to_string()).unwrap();
- d.features.iter_mut().for_each(|f| f.shell_piece_order = true);
+ d.features.iter_mut().for_each(|f| (f.shell_piece_order, f.kernel_piece_order) = (true, true));
assert_eq!(upgraded, d, "the identity migration preserves the complete design");
assert_eq!(serde_json::to_value(&upgraded.configs).unwrap(), original_table);
assert_eq!(upgraded.format, format_string(FORMAT));
@@ -1796,9 +1798,12 @@ mod tests {
legacy["format"] = Value::from("solidcraft/7");
let mut features = legacy["features"].clone();
pieces_in_shell_order(&mut features);
+ for f in features.as_array_mut().into_iter().flatten() {
+ f["kernel_piece_order"] = Value::Bool(true);
+ }
let params = legacy["params"].clone();
let upgraded = read(&legacy.to_string()).unwrap();
- d.features.iter_mut().for_each(|f| f.shell_piece_order = true);
+ d.features.iter_mut().for_each(|f| (f.shell_piece_order, f.kernel_piece_order) = (true, true));
assert_eq!(upgraded, d);
let upgraded_json: Value = serde_json::from_str(&upgraded.to_json()).unwrap();
assert_eq!(upgraded_json["features"], features);
diff --git a/crates/doc/src/format/pending/face-pieces-by-place.rs b/crates/doc/src/format/pending/face-pieces-by-place.rs
new file mode 100644
index 0000000000..be6bdf7d9e
--- /dev/null
+++ b/crates/doc/src/format/pending/face-pieces-by-place.rs
@@ -0,0 +1,34 @@
+//! The pieces of a split face are numbered by place (#3902): `#1`, `#2`, … follow the spread of
+//! their centres, not the kernel's face order or the index of the operand face they came from,
+//! which can change from one evaluation to the next. Older designs' stored `#k` names mean the
+//! old numbering, so this step marks each of their features `kernel_piece_order`, which keeps
+//! it for them. Features added later number by place. The last release refuses a design saved
+//! with this (the newer format number).
+use serde_json::Value;
+
+pub fn step(v: &mut Value) -> crate::Result<()> {
+ let Some(Value::Array(features)) = v.get_mut("features") else {
+ return Ok(());
+ };
+ for feature in features {
+ if let Value::Object(o) = feature {
+ o.insert("kernel_piece_order".into(), Value::Bool(true));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn older_features_keep_their_piece_numbering() {
+ let mut v = json!({"features": [{"type": "sketch"}, {"type": "extrude"}]});
+ super::step(&mut v).unwrap();
+ assert!(v["features"].as_array().unwrap().iter().all(|f| f["kernel_piece_order"] == true));
+ let mut empty = json!({});
+ super::step(&mut empty).unwrap();
+ assert_eq!(empty, json!({}));
+ }
+}
diff --git a/crates/doc/src/history_names.rs b/crates/doc/src/history_names.rs
index 80d400ecc8..aa1cd5e5e4 100644
--- a/crates/doc/src/history_names.rs
+++ b/crates/doc/src/history_names.rs
@@ -17,6 +17,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, OnceLock};
+use solidcraft_geom::Vec3;
use solidcraft_kernel::history::{FaceOrigin, FaceProv, History};
use crate::ModelBody;
@@ -44,13 +45,14 @@ pub(crate) struct FaceInfo {
impl Names {
/// Names worked out from geometry: the same names, none of them verified, pieces told apart
- /// by the faces around them (`adjacent`: pairs of faces sharing an edge).
- pub(crate) fn unverified(names: Vec<String>, adjacent: &[(usize, usize)]) -> Names {
+ /// by the faces around them (`adjacent`: pairs of faces sharing an edge), then numbered by
+ /// place (`centres`, see [`qualify_at`]).
+ pub(crate) fn unverified(names: Vec<String>, adjacent: &[(usize, usize)], centres: Option<&dyn Fn() -> Vec<Vec3>>) -> Names {
let named = names
.into_iter()
.map(|name| Named { name: crate::naming::strip_piece(&name).to_string(), aliases: Vec::new(), verified: false, origins: None })
.collect();
- qualify(named, adjacent)
+ qualify_at(named, adjacent, centres)
}
/// Names given as they are (a moved copy keeps its source's), taken as exact.
@@ -95,7 +97,8 @@ pub(crate) fn derive(b: &ModelBody, o: &NamingOrigin, lineage: &Lineage) -> Opti
}
}
let named: Vec<Named> = named.into_iter().collect::<Option<_>>()?;
- Some(qualify(named, &adjacency(h)))
+ let centres = || crate::naming::face_centres(b);
+ Some(qualify_at(named, &adjacency(h), by_place(&o.feature, &centres)))
}
/// Pairs of faces that share an edge, from a history.
@@ -140,7 +143,8 @@ impl<'a> OperandNames<'a> {
.get_or_init(|| {
Arc::new(derive(body, o, &stage.lineage).unwrap_or_else(|| {
let names = crate::naming::geometric_names(body, o, body.body.face_count());
- Names::unverified(names, &crate::naming::mesh_adjacency(body))
+ let centres = || crate::naming::face_centres(body);
+ Names::unverified(names, &crate::naming::mesh_adjacency(body), by_place(&o.feature, &centres))
}))
})
.clone();
@@ -266,7 +270,32 @@ pub(crate) fn descends(name: &str, stem: &str) -> bool {
/// Tell pieces apart: faces sharing a name are named by the faces around them that the others
/// lack (`adjacent`: pairs of faces sharing an edge).
+#[cfg(test)]
fn qualify(named: Vec<Named>, adjacent: &[(usize, usize)]) -> Names {
+ qualify_at(named, adjacent, None)
+}
+
+/// How the pieces `f` splits a face into are numbered: by place (`centres`), else, for a feature
+/// saved before that (`Feature::kernel_piece_order`), as the build that saved it numbered them.
+pub(crate) fn by_place<'a>(f: &crate::Feature, centres: &'a dyn Fn() -> Vec<Vec3>) -> Option<&'a dyn Fn() -> Vec<Vec3>> {
+ (!f.kernel_piece_order).then_some(centres)
+}
+
+/// [`qualify`], with `centres` giving each face's centre (worked out only when pieces tie): pieces
+/// that nothing else tells apart are numbered along their spread, not in the kernel's order,
+/// which can differ from one evaluation to the next (#3902). Without `centres`, in the kernel's
+/// order and by the faces they came from, as builds before that numbered them.
+fn qualify_at(named: Vec<Named>, adjacent: &[(usize, usize)], centres: Option<&dyn Fn() -> Vec<Vec3>>) -> Names {
+ let by_place = centres.is_some();
+ let worked_out = std::cell::OnceCell::new();
+ // Tied pieces in the order of their spread; as they are when there are no centres.
+ let in_order = |tied: Vec<usize>| -> Vec<usize> {
+ let at: &Vec<Vec3> = worked_out.get_or_init(|| centres.map(|c| c()).unwrap_or_default());
+ if at.len() != named.len() {
+ return tied;
+ }
+ crate::naming::along_spread(tied.into_iter().filter_map(|i| Some((i, *at.get(i)?))).collect())
+ };
let n = named.len();
let mut bounds: Vec<BTreeSet<String>> = vec![BTreeSet::new(); n];
for &(a, b) in adjacent {
@@ -320,8 +349,20 @@ fn qualify(named: Vec<Named>, adjacent: &[(usize, usize)]) -> Names {
let mut tied = tied;
let origins: Vec<Option<&Vec<FaceOrigin>>> = tied.iter().map(|i| named.get(*i).and_then(|x| x.origins.as_ref())).collect();
let distinct = origins.iter().all(Option::is_some) && origins.iter().collect::<BTreeSet<_>>().len() == origins.len();
- if distinct {
+ if distinct && !by_place {
tied.sort_by_key(|i| named.get(*i).and_then(|x| x.origins.clone()));
+ } else if distinct {
+ // By what they came from, but not by where it stood in its operand's face order:
+ // an operand that came out of a boolean can list its faces in another order on
+ // the next evaluation (#3902). Pieces of faces of one kind are numbered by place.
+ let mut by_kind: BTreeMap<Vec<FaceOrigin>, Vec<usize>> = BTreeMap::new();
+ for i in tied {
+ let kind = named.get(i).and_then(|x| x.origins.as_deref()).unwrap_or_default().iter().map(|o| without_index(*o)).collect();
+ by_kind.entry(kind).or_default().push(i);
+ }
+ tied = by_kind.into_values().flat_map(&in_order).collect();
+ } else {
+ tied = in_order(tied);
}
for (k, i) in tied.iter().enumerate() {
if let Some(slot) = names.get_mut(*i) {
@@ -333,17 +374,17 @@ fn qualify(named: Vec<Named>, adjacent: &[(usize, usize)]) -> Names {
}
}
}
- // A piece's new name can meet a face that already had it: numbered too, never shared.
- let mut seen: BTreeMap<String, usize> = BTreeMap::new();
- for name in &names {
- *seen.entry(name.clone()).or_default() += 1;
+ // A piece's new name can meet a face that already had it: numbered too (along their spread),
+ // never shared.
+ let mut seen: BTreeMap<String, Vec<usize>> = BTreeMap::new();
+ for (i, name) in names.iter().enumerate() {
+ seen.entry(name.clone()).or_default().push(i);
}
- let mut counter: BTreeMap<String, usize> = BTreeMap::new();
- for (i, name) in names.iter_mut().enumerate() {
- if seen.get(name.as_str()).is_some_and(|c| *c > 1) {
- let k = counter.entry(name.clone()).or_default();
- *k += 1;
- *name = format!("{name}#{k}");
+ for (name, same) in seen.into_iter().filter(|(_, same)| same.len() > 1) {
+ for (k, i) in in_order(same).into_iter().enumerate() {
+ if let Some(slot) = names.get_mut(i) {
+ *slot = format!("{name}#{}", k + 1);
+ }
if let Some(v) = verified.get_mut(i) {
*v = false;
}
@@ -353,6 +394,17 @@ fn qualify(named: Vec<Named>, adjacent: &[(usize, usize)]) -> Names {
Names { faces: Arc::new(names), info }
}
+/// `origin` with the face or edge it names left out (its kind and operand kept).
+fn without_index(origin: FaceOrigin) -> FaceOrigin {
+ match origin {
+ FaceOrigin::Face { operand, .. } => FaceOrigin::Face { operand, face: 0 },
+ FaceOrigin::Edge { operand, .. } => FaceOrigin::Edge { operand, edge: 0 },
+ FaceOrigin::Offset { operand, .. } => FaceOrigin::Offset { operand, face: 0 },
+ // A profile's segments come in the sketch's order.
+ FaceOrigin::Profile { .. } | FaceOrigin::Cap { .. } => origin,
+ }
+}
+
/// How a stored face name matches a current face.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Match {
diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs
index 1801fca6fc..613a550493 100644
--- a/crates/doc/src/naming.rs
+++ b/crates/doc/src/naming.rs
@@ -241,13 +241,11 @@ pub(crate) fn names(b: &ModelBody) -> Arc<Names> {
.get_or_init(|| {
// Exact history needs no mesh; geometry does (its face count is the mesh's).
let names = match b.names.origin.as_ref() {
- Some(o) if o.depth < MAX_DEPTH => b
- .names
- .lineage
- .as_ref()
- .and_then(|l| crate::history_names::derive(b, o, l))
- .unwrap_or_else(|| Names::unverified(geometric_names(b, o, face_count(b)), &mesh_adjacency(b))),
- _ => Names::unverified((0..face_count(b)).map(|k| format!("{}:face:{k}", b.name)).collect(), &[]),
+ Some(o) if o.depth < MAX_DEPTH => b.names.lineage.as_ref().and_then(|l| crate::history_names::derive(b, o, l)).unwrap_or_else(|| {
+ let centres = || face_centres(b);
+ Names::unverified(geometric_names(b, o, face_count(b)), &mesh_adjacency(b), crate::history_names::by_place(&o.feature, &centres))
+ }),
+ _ => Names::unverified((0..face_count(b)).map(|k| format!("{}:face:{k}", b.name)).collect(), &[], None),
};
Arc::new(names)
})
@@ -519,35 +517,8 @@ fn number_pieces(names: &mut [String], pts: &[Vec<Vec3>], mark: char) {
let ps = pts.get(j).cloned().unwrap_or_default();
ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64)
};
- let cs: Vec<(usize, Vec3)> = same.iter().map(|j| (*j, centre(*j))).collect();
- let ext = cs.iter().map(|(_, c)| *c).collect::<Aabb3>().size();
- let key = |c: Vec3| {
- if ext.x >= ext.y && ext.x >= ext.z {
- (c.x, c.y, c.z)
- } else if ext.y >= ext.z {
- (c.y, c.z, c.x)
- } else {
- (c.z, c.x, c.y)
- }
- };
- let mut order = cs.clone();
- // Pieces lying almost level along the sort axis differ only in the last bits of their centre:
- // the centre is the mean of a tessellated boundary, and that depends on where the loop's
- // polyline starts, which can differ between processes. Comparing the keys with a tolerance
- // makes those pieces equal, so the stable sort keeps the order they arrived in and a name
- // keeps its number across runs (solidcraft#569). total_cmp keeps a NaN deterministic.
- let tol = ext.x.max(ext.y).max(ext.z).max(1.0) * 1e-9;
- let bucket = |c: Vec3| {
- let k = key(c);
- // Rounding onto the grid, rather than comparing with a tolerance, is what keeps this a
- // total order: `a` and `b` in one bucket and `b` and `c` in the next must not leave `a`
- // and `c` in different ones, or the sort has no order to work with. Since Rust 1.81
- // `sort_by` may panic on a comparator that is not one. Two pieces can still flip when
- // they straddle a bucket edge; that is the price of a key that ignores their low bits.
- ((k.0 / tol).round() as i64, (k.1 / tol).round() as i64, (k.2 / tol).round() as i64)
- };
- order.sort_by_key(|a| bucket(a.1));
- for (k, (j, _)) in order.iter().enumerate() {
+ let order = along_spread(same.iter().map(|j| (*j, centre(*j))).collect());
+ for (k, j) in order.iter().enumerate() {
if let Some(slot) = names.get_mut(*j) {
*slot = format!("{n}{mark}{}", k + 1);
}
@@ -555,6 +526,45 @@ fn number_pieces(names: &mut [String], pts: &[Vec<Vec3>], mark: char) {
}
}
+/// The items of `cs` (index, centre) ordered along the longest axis of their centres' spread,
+/// then the next: how the pieces of one face or edge are numbered, the same on every run
+/// whatever order the kernel gives them in.
+pub(crate) fn along_spread(cs: Vec<(usize, Vec3)>) -> Vec<usize> {
+ let ext = cs.iter().map(|(_, c)| *c).collect::<Aabb3>().size();
+ let key = |c: Vec3| {
+ if ext.x >= ext.y && ext.x >= ext.z {
+ (c.x, c.y, c.z)
+ } else if ext.y >= ext.z {
+ (c.y, c.z, c.x)
+ } else {
+ (c.z, c.x, c.y)
+ }
+ };
+ let mut order = cs;
+ // Pieces lying almost level along the sort axis differ only in the last bits of their centre:
+ // the centre is the mean of a tessellated boundary, and that depends on where the loop's
+ // polyline starts, which can differ between processes. Comparing the keys with a tolerance
+ // makes those pieces equal, so the stable sort keeps the order they arrived in and a name
+ // keeps its number across runs (solidcraft#569).
+ let tol = ext.x.max(ext.y).max(ext.z).max(1.0) * 1e-9;
+ let bucket = |c: Vec3| {
+ let k = key(c);
+ // Rounding onto the grid, rather than comparing with a tolerance, is what keeps this a
+ // total order: `a` and `b` in one bucket and `b` and `c` in the next must not leave `a`
+ // and `c` in different ones, or the sort has no order to work with. Since Rust 1.81
+ // `sort_by` may panic on a comparator that is not one. Two pieces can still flip when
+ // they straddle a bucket edge; that is the price of a key that ignores their low bits.
+ ((k.0 / tol).round() as i64, (k.1 / tol).round() as i64, (k.2 / tol).round() as i64)
+ };
+ order.sort_by_key(|a| bucket(a.1));
+ order.into_iter().map(|(j, _)| j).collect()
+}
+
+/// Each face's centre: the mean of the sampled centres of its triangles.
+pub(crate) fn face_centres(b: &ModelBody) -> Vec<Vec3> {
+ samples(&b.mesh(), face_count(b)).into_iter().map(|ps| ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64)).collect()
+}
+
/// The name of a face new to `f`.
fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usize, fid: u64) -> String {
let c = ps.iter().fold(Vec3::ZERO, |a, p| a + *p) * (1.0 / ps.len().max(1) as f64);
diff --git a/crates/engine/src/cmd/config_certificate_tests.rs b/crates/engine/src/cmd/config_certificate_tests.rs
index 1415d8dbff..2cb5c5f6c8 100644
--- a/crates/engine/src/cmd/config_certificate_tests.rs
+++ b/crates/engine/src/cmd/config_certificate_tests.rs
@@ -111,8 +111,9 @@ fn legacy_v9_imported_emboss_anchor_and_ordinary_face_paint_replay_without_renam
let mut legacy: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
legacy["format"] = json!("solidcraft/9");
let reopened = Session::new(solidcraft_doc::Document::from_json(&legacy.to_string()).unwrap());
- // Saved before format 14, it keeps naming the pieces it makes in the kernel's shell order.
- let anchored = solidcraft_doc::Feature { shell_piece_order: true, ..anchored };
+ // Saved before format 14, it keeps naming the pieces it makes in the kernel's shell order,
+ // and numbering the pieces of its faces as that build did (#3902).
+ let anchored = solidcraft_doc::Feature { shell_piece_order: true, kernel_piece_order: true, ..anchored };
assert_eq!(reopened.doc.feature(anchored.id).unwrap(), &anchored);
// Names saved before format 14 keep naming the face they named, marked so they are found as
// the build that saved them found them.
diff --git a/crates/engine/src/cmd/sheet_convert_tests.rs b/crates/engine/src/cmd/sheet_convert_tests.rs
index 50a477c2f1..fd108ad937 100644
--- a/crates/engine/src/cmd/sheet_convert_tests.rs
+++ b/crates/engine/src/cmd/sheet_convert_tests.rs
@@ -359,7 +359,10 @@ fn designs_from_before_bend_edges_open_unchanged() {
assert!(!older.to_string().contains("\"bends\""), "{older}");
older["format"] = json!("solidcraft/16");
let doc = solidcraft_doc::Document::from_json(&older.to_string()).unwrap();
- assert_eq!(doc, *s.doc);
+ // An older design keeps the numbering of the pieces it was saved with (#3902).
+ let mut same = solidcraft_doc::Document::clone(&s.doc);
+ same.features.iter_mut().for_each(|f| f.kernel_piece_order = true);
+ assert_eq!(doc, same);
let mut reopened = Session::new(doc);
assert!(reopened.model.results.iter().all(|x| x.error.is_none()));
assert!(same_size(flat_size(&mut reopened), (100.0, 60.0), 1e-9), "{:?}", flat_size(&mut reopened));
diff --git a/crates/engine/src/naming_history_tests.rs b/crates/engine/src/naming_history_tests.rs
index fdc57f6616..2996ebe359 100644
--- a/crates/engine/src/naming_history_tests.rs
+++ b/crates/engine/src/naming_history_tests.rs
@@ -401,3 +401,61 @@ fn a_cut_through_one_of_two_bosses_names_only_its_own_walls() {
assert_eq!(blends, 4, "{filleted:?}");
assert_eq!(named_at(&filleted, [19.98, -4.24, 19.0]), boss);
}
+
+/// #3902: a torus with a closed, twisted square sweep cut inside it splits the sweep's walls into
+/// pieces the kernel returns in a different order on each evaluation. The pieces are numbered by
+/// where they lie, so every fresh evaluation gives each piece the same name.
+#[test]
+fn split_pieces_keep_their_numbers_across_evaluations() {
+ let script: Value = serde_json::from_str(include_str!("../../../examples/regressions/closed_sweep_torus_cut.json")).unwrap();
+ let mut s = Session::default();
+ s.run_script(&script).unwrap();
+ let body = s.model.state().bodies.first().map(|b| b.name.clone()).expect("a body");
+ let named = |s: &mut Session| -> Vec<(String, [i64; 3])> {
+ let mut faces: Vec<(String, [i64; 3])> = listed(s, &body).into_iter().map(|(n, _, c)| (n, c.map(|x| x.round() as i64))).collect();
+ faces.sort();
+ faces
+ };
+ let first = named(&mut s);
+ assert!(first.iter().any(|(n, _)| n.contains('#')), "no split pieces: {first:?}");
+ for run in 0..10 {
+ let mut fresh = Session::new(solidcraft_doc::Document::clone(&s.doc));
+ fresh.refresh();
+ assert_eq!(named(&mut fresh), first, "evaluation {run}");
+ }
+}
+
+/// #3902: a design saved before the pieces of a face were numbered by place opens with the
+/// numbers it was saved with, so a reference to `…#1` stays on the piece it was made on. The
+/// block cut by the second block here has its side split in two, numbered the other way round
+/// by place.
+#[test]
+fn a_design_saved_before_pieces_were_numbered_by_place_keeps_their_numbers() {
+ let script: Value = serde_json::from_str(include_str!("../../../tests/action_matrix/designs/multi-body-join-cut.json")).unwrap();
+ let mut s = Session::default();
+ s.run_script(&script).unwrap();
+ let by_place = listed(&mut s, "Block");
+ // As a build before the change saved it: its features carry no mark, and the file does not
+ // list the change among those it has.
+ let mut file: Value = serde_json::from_str(&s.doc.to_json()).unwrap();
+ for f in file["features"].as_array_mut().unwrap() {
+ f.as_object_mut().unwrap().remove("kernel_piece_order");
+ }
+ if let Some(Value::Array(pending)) = file.get_mut("format_pending") {
+ pending.retain(|c| c != "face-pieces-by-place");
+ }
+ let old = solidcraft_doc::Document::from_json(&file.to_string()).unwrap();
+ assert!(old.features.iter().all(|f| f.kernel_piece_order), "the features of an older design keep the old numbering");
+ let mut reopened = Session::new(old);
+ reopened.refresh();
+ let kept = listed(&mut reopened, "Block");
+ let at = |faces: &[(String, bool, [f64; 3])], name: &str| faces.iter().find(|(n, _, _)| n == name).map(|(_, _, c)| *c);
+ // The pieces are numbered differently by place, and the older design keeps its own numbers.
+ let (old1, new1) = (at(&kept, "F2:side#1").unwrap(), at(&by_place, "F2:side#1").unwrap());
+ assert!((0..3).any(|k| (old1[k] - new1[k]).abs() > 1.0), "{kept:?} {by_place:?}");
+ let mut legacy = solidcraft_doc::Document::clone(&s.doc);
+ legacy.features.iter_mut().for_each(|f| f.kernel_piece_order = true);
+ let mut saved_with = Session::new(legacy);
+ saved_with.refresh();
+ assert_eq!(listed(&mut saved_with, "Block"), kept);
+}