* claim: #1134 * doc: key pattern/mirror seeds and construction planes by feature id (#1134) * engine: resolve seed names the way evaluation did; keep timeline.edit name input (#1134) * fmt/clippy cleanups (#1134) * ui: resolve construction-plane names by feature id in plane_description (#1134) * fmt: sketch_attachment_ui after rebase adaptation * engine: timeline.add resolves legacy name-keyed seeds and plane names (#1134) * chore: re-trigger CI (GPU runner timeout flake) * doc: replayed_sources walks id-keyed pattern seeds (rebase adaptation) --------- Co-authored-by: Dahak Builds <dahakbuilds@users.noreply.github.com>
This commit is contained in:
@@ -351,7 +351,9 @@ mod clone_tests {
|
||||
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"}});
|
||||
// Construction plane references are keyed by id (#1134): a copy remap moves the id map,
|
||||
// not this one; the axis and point names below are what a rename and a copy rewrite.
|
||||
let origin = json!({"type": "plane", "plane": {"type": "construction", "feature": 7}});
|
||||
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}}),
|
||||
|
||||
+28
-10
@@ -5,7 +5,7 @@ use solidcraft_sketch::Sketch;
|
||||
|
||||
use crate::construct::{AxisDef, GeoRef, PointDef};
|
||||
use crate::expr::{self, Expr, Kind};
|
||||
use crate::names::{BodyName, FeatureName, SketchId};
|
||||
use crate::names::{BodyName, FeatureId, FeatureName, SketchId};
|
||||
use crate::points::{Dir, FacePick, Position};
|
||||
use crate::{DocError, Result};
|
||||
|
||||
@@ -83,8 +83,8 @@ pub enum PlaneRef {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
line: Option<Box<GeoRef>>,
|
||||
},
|
||||
/// A construction plane feature (by name).
|
||||
Construction { name: FeatureName },
|
||||
/// A construction plane feature (by id).
|
||||
Construction { feature: FeatureId },
|
||||
/// `base` seen from its other side: the normal reversed by a half turn about the base's
|
||||
/// own x axis (y reversed), or about its y axis (x reversed) when `about_y`. A sketch
|
||||
/// started from behind a plane faces the viewer this way.
|
||||
@@ -722,16 +722,18 @@ pub enum FeatureKind {
|
||||
keep_tools: bool,
|
||||
},
|
||||
/// Copies of other features' results, or of bodies (rectangular, circular or along a path).
|
||||
/// The copied features are named by id (#1134).
|
||||
Pattern {
|
||||
features: Vec<FeatureName>,
|
||||
features: Vec<FeatureId>,
|
||||
pattern: PatternKind,
|
||||
/// Copy these bodies (as new bodies) instead of replaying features.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
bodies: Vec<BodyName>,
|
||||
},
|
||||
/// Mirror copies of other features' results in a plane.
|
||||
/// Mirror copies of other features' results in a plane. The copied features are named by
|
||||
/// id (#1134).
|
||||
Mirror {
|
||||
features: Vec<FeatureName>,
|
||||
features: Vec<FeatureId>,
|
||||
plane: PlaneRef,
|
||||
/// Mirror these bodies instead of replaying features.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
@@ -3311,6 +3313,17 @@ impl Document {
|
||||
self.features.iter().find(|f| f.name.eq_ignore_ascii_case(r))
|
||||
}
|
||||
|
||||
/// The feature a pattern or mirror seed names, resolved the way `replay()` resolved seed
|
||||
/// names before seeds were keyed by id (#1134): an exact name match on a feature that is
|
||||
/// not a sketch or a construction plane wins — a sketch and its extrude often share a
|
||||
/// name, and the feature that makes geometry is the one to copy — else [`find_feature`].
|
||||
pub fn seed_feature(&self, name: &str) -> Option<&Feature> {
|
||||
self.features
|
||||
.iter()
|
||||
.find(|x| x.name == name && !matches!(x.kind, FeatureKind::Sketch { .. } | FeatureKind::ConstructionPlane { .. }))
|
||||
.or_else(|| self.find_feature(name))
|
||||
}
|
||||
|
||||
fn unique_name(&self, base: &str) -> String {
|
||||
// The numbers taken after `base`, gathered once: the thousandth cylinder of a design
|
||||
// tried Cylinder1, Cylinder2 … each against every feature's name.
|
||||
@@ -3745,16 +3758,21 @@ impl Document {
|
||||
Plane::new(o, rot(b.x), rot(b.y)).ok_or_else(|| DocError::Invalid("degenerate plane".into()))
|
||||
}
|
||||
PlaneRef::Flipped { base, about_y } => Ok(self.resolve_plane_in(vals, base, depth + 1, st)?.flipped(*about_y)),
|
||||
PlaneRef::Construction { name } => {
|
||||
PlaneRef::Construction { feature } => {
|
||||
// Evaluated already: as it came out.
|
||||
if let Some(c) = st.and_then(|st| st.construct.iter().find(|c| &c.name == name))
|
||||
if let Some(c) = st.and_then(|st| st.construct.iter().find(|c| c.feature == feature.0))
|
||||
&& let crate::construct::ConstructGeom::Plane(pl) = &c.geom
|
||||
{
|
||||
return Ok(*pl);
|
||||
}
|
||||
match self.find_feature(name).map(|f| &f.kind) {
|
||||
match self.feature(feature.0).map(|f| &f.kind) {
|
||||
Some(FeatureKind::ConstructionPlane { plane }) => self.resolve_plane_in(vals, plane, depth + 1, st),
|
||||
_ => Err(DocError::Unknown(format!("construction plane `{name}`"))),
|
||||
// A name that could not be resolved when an older design opened keeps id 0,
|
||||
// which no feature has (#1134): the reference dangles, as it always did.
|
||||
_ => {
|
||||
let shown = self.feature(feature.0).map(|f| f.name.clone()).unwrap_or_else(|| feature.to_string());
|
||||
Err(DocError::Unknown(format!("construction plane `{shown}`")))
|
||||
}
|
||||
}
|
||||
}
|
||||
PlaneRef::Midplane { .. }
|
||||
|
||||
+32
-31
@@ -15,7 +15,7 @@ use solidcraft_sketch::{CurveKind, Profile, SolveReport, find_profiles};
|
||||
|
||||
use crate::expr::{self, Kind, Value};
|
||||
use crate::lineage::Traced;
|
||||
use crate::{AxisRef, DocError, Document, Feature, FeatureKind, HoleKind, Operation, PlaneRef, ProfileSel, Result};
|
||||
use crate::{AxisRef, DocError, Document, Feature, FeatureId, FeatureKind, HoleKind, Operation, PlaneRef, ProfileSel, Result};
|
||||
|
||||
type JointFaces = (Body, kernel::Result<Arc<[kernel::FaceInfo]>>);
|
||||
|
||||
@@ -1561,20 +1561,20 @@ fn chain_fingerprint(
|
||||
|
||||
/// The features a pattern or mirror of `features` replays: each source, and the sources of one
|
||||
/// that is itself a pattern or mirror of features (see `copy_plan`), each once.
|
||||
fn replayed_sources<'a>(doc: &'a Document, features: &[crate::FeatureName]) -> Vec<&'a Feature> {
|
||||
fn replayed_sources<'a>(doc: &'a Document, features: &[crate::FeatureId]) -> Vec<&'a Feature> {
|
||||
let mut out: Vec<&Feature> = Vec::new();
|
||||
let mut todo: Vec<String> = crate::plain(features);
|
||||
let mut todo: Vec<crate::FeatureId> = features.to_vec();
|
||||
// A bound on the walk, as on the copy plan's nesting: a design can't make it run on.
|
||||
for _ in 0..1024 {
|
||||
let Some(name) = todo.pop() else { break };
|
||||
let Ok(g) = source_feature(doc, &name) else { continue };
|
||||
let Some(id) = todo.pop() else { break };
|
||||
let Ok(g) = source_feature(doc, id) else { continue };
|
||||
if out.iter().any(|x| x.id == g.id) {
|
||||
continue;
|
||||
}
|
||||
if let FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } = &g.kind
|
||||
&& bodies.is_empty()
|
||||
{
|
||||
todo.extend(crate::plain(features));
|
||||
todo.extend(features.iter().copied());
|
||||
}
|
||||
out.push(g);
|
||||
}
|
||||
@@ -2280,7 +2280,7 @@ impl Model {
|
||||
// Copies made through a pattern or mirror among the sources come after (#395).
|
||||
let mats = match &f.kind {
|
||||
FeatureKind::Pattern { features, bodies, .. } | FeatureKind::Mirror { features, bodies, .. } if bodies.is_empty() => {
|
||||
copy_instances(doc, &vals, &state, &crate::plain(features), &mats).unwrap_or(mats)
|
||||
copy_instances(doc, &vals, &state, features, &mats).unwrap_or(mats)
|
||||
}
|
||||
_ => mats,
|
||||
};
|
||||
@@ -6312,27 +6312,28 @@ fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced
|
||||
/// The deepest a pattern or mirror reaches through patterns and mirrors of features (#395).
|
||||
const MAX_NESTING: usize = 8;
|
||||
|
||||
/// The feature a pattern or mirror names as a source. A sketch and its extrude often share a
|
||||
/// name; the feature that makes geometry wins.
|
||||
fn source_feature<'a>(doc: &'a Document, name: &str) -> Result<&'a Feature> {
|
||||
doc.features
|
||||
.iter()
|
||||
.find(|x| x.name == name && !matches!(x.kind, FeatureKind::Sketch { .. } | FeatureKind::ConstructionPlane { .. }))
|
||||
.or_else(|| doc.find_feature(name))
|
||||
.ok_or_else(|| DocError::Unknown(format!("feature `{name}`")))
|
||||
/// The feature a pattern or mirror names as a source. Seeds are keyed by id (#1134): a
|
||||
/// reference that names no feature dangles, as a missing name did before.
|
||||
fn source_feature(doc: &Document, id: FeatureId) -> Result<&Feature> {
|
||||
doc.feature(id.0).ok_or_else(|| DocError::Unknown(format!("feature `{id}`")))
|
||||
}
|
||||
|
||||
/// How a source feature shows in a warning: its name, or its id when it names no feature.
|
||||
fn source_label(doc: &Document, id: FeatureId) -> String {
|
||||
doc.feature(id.0).map(|f| f.name.clone()).unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// What a pattern or mirror of features copies, when it is the source of another one (#395): its
|
||||
/// own sources, and the transforms of its copies. `None` for any other feature, and for a pattern
|
||||
/// or mirror of bodies (its copies are bodies, which a pattern or mirror of features can't take).
|
||||
fn copied_features(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, src: &Feature) -> Result<Option<(Vec<String>, Vec<Mat>)>> {
|
||||
fn copied_features(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, src: &Feature) -> Result<Option<(Vec<FeatureId>, Vec<Mat>)>> {
|
||||
match &src.kind {
|
||||
FeatureKind::Pattern { features, pattern, bodies } if bodies.is_empty() => {
|
||||
Ok(Some((crate::plain(features), pattern_transforms(doc, vals, st, src.component, pattern)?)))
|
||||
Ok(Some((features.clone(), pattern_transforms(doc, vals, st, src.component, pattern)?)))
|
||||
}
|
||||
FeatureKind::Mirror { features, plane, bodies, .. } if bodies.is_empty() => {
|
||||
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
|
||||
Ok(Some((crate::plain(features), vec![mirror_matrix(&pl)])))
|
||||
Ok(Some((features.clone(), vec![mirror_matrix(&pl)])))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
@@ -6396,7 +6397,7 @@ fn copy_plan<'a>(
|
||||
doc: &'a Document,
|
||||
vals: &BTreeMap<String, Value>,
|
||||
st: &ModelState,
|
||||
features: &[String],
|
||||
features: &[FeatureId],
|
||||
mats: &[Mat],
|
||||
) -> Result<Vec<(&'a Feature, Vec<Mat>, usize)>> {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -6404,18 +6405,18 @@ fn copy_plan<'a>(
|
||||
doc: &'a Document,
|
||||
vals: &BTreeMap<String, Value>,
|
||||
st: &ModelState,
|
||||
features: &[String],
|
||||
features: &[FeatureId],
|
||||
mats: &[Mat],
|
||||
first: usize,
|
||||
next: &mut usize,
|
||||
depth: usize,
|
||||
out: &mut Vec<(&'a Feature, Vec<Mat>, usize)>,
|
||||
) -> Result<()> {
|
||||
for name in features {
|
||||
if doc.find_feature(name).is_some_and(|x| x.suppressed) {
|
||||
for id in features {
|
||||
if doc.feature(id.0).is_some_and(|x| x.suppressed) {
|
||||
continue;
|
||||
}
|
||||
let src = source_feature(doc, name)?;
|
||||
let src = source_feature(doc, *id)?;
|
||||
let Some((inner, inner_mats)) = copied_features(doc, vals, st, src)? else {
|
||||
out.push((src, mats.to_vec(), first));
|
||||
continue;
|
||||
@@ -6442,7 +6443,7 @@ fn copy_plan<'a>(
|
||||
/// The transforms of a pattern's or mirror's copies in their instance order (instance `k + 1`
|
||||
/// is the `k`-th): `mats`, then those of the copies made through patterns and mirrors among
|
||||
/// `features` ([`copy_plan`]). Naming finds a copy's faces through them.
|
||||
fn copy_instances(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, features: &[String], mats: &[Mat]) -> Result<Vec<Mat>> {
|
||||
fn copy_instances(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, features: &[FeatureId], mats: &[Mat]) -> Result<Vec<Mat>> {
|
||||
let plan = copy_plan(doc, vals, st, features, mats)?;
|
||||
let len = plan.iter().map(|(_, ms, first)| first + ms.len()).max().unwrap_or(0).max(mats.len());
|
||||
let mut all = vec![crate::IDENTITY; len];
|
||||
@@ -6465,7 +6466,7 @@ fn replay(
|
||||
vals: &BTreeMap<String, Value>,
|
||||
f: &Feature,
|
||||
st: &mut ModelState,
|
||||
features: &[String],
|
||||
features: &[FeatureId],
|
||||
mats: &[Mat],
|
||||
warning: &mut Option<String>,
|
||||
) -> Result<()> {
|
||||
@@ -6473,9 +6474,9 @@ fn replay(
|
||||
return Err(DocError::Invalid("no features selected".into()));
|
||||
}
|
||||
// A suppressed feature has nothing to copy: its copies go with it.
|
||||
let suppressed: Vec<&String> = features.iter().filter(|n| doc.find_feature(n).is_some_and(|x| x.suppressed)).collect();
|
||||
let suppressed: Vec<FeatureId> = features.iter().copied().filter(|n| doc.feature(n.0).is_some_and(|x| x.suppressed)).collect();
|
||||
if !suppressed.is_empty() {
|
||||
let list = suppressed.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(", ");
|
||||
let list = suppressed.iter().map(|n| format!("`{}`", source_label(doc, *n))).collect::<Vec<_>>().join(", ");
|
||||
*warning = Some(if suppressed.len() == features.len() {
|
||||
format!("nothing to copy: {list} suppressed")
|
||||
} else {
|
||||
@@ -6484,8 +6485,8 @@ fn replay(
|
||||
}
|
||||
// The copies are made in timeline order, whatever order the features were picked in: a
|
||||
// chamfer picked before the hole it blends would otherwise find no edge to copy.
|
||||
let mut kept: Vec<String> = features.iter().filter(|n| !suppressed.contains(n)).cloned().collect();
|
||||
let at = |name: &String| source_feature(doc, name).ok().and_then(|f| doc.features.iter().position(|x| std::ptr::eq(x, f))).unwrap_or(usize::MAX);
|
||||
let mut kept: Vec<FeatureId> = features.iter().copied().filter(|n| !suppressed.contains(n)).collect();
|
||||
let at = |id: &FeatureId| doc.features.iter().position(|x| x.id == id.0).unwrap_or(usize::MAX);
|
||||
kept.sort_by_key(at);
|
||||
kept.dedup();
|
||||
let (mut missed, mut total) = (0usize, 0usize);
|
||||
@@ -7435,7 +7436,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
|
||||
FeatureKind::Pattern { features, pattern, bodies } => {
|
||||
let mats = pattern_transforms(doc, vals, st, f.component, pattern)?;
|
||||
if bodies.is_empty() {
|
||||
return replay(doc, vals, f, st, &crate::plain(features), &mats, warning);
|
||||
return replay(doc, vals, f, st, features, &mats, warning);
|
||||
}
|
||||
// Bodies: each copy is a new body named after its source.
|
||||
let mut output = 0;
|
||||
@@ -7454,7 +7455,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
|
||||
FeatureKind::Mirror { features, plane, bodies, combine, placements } => {
|
||||
let pl = doc.resolve_plane_in(vals, plane, 0, Some(st))?;
|
||||
if bodies.is_empty() {
|
||||
return replay(doc, vals, f, st, &crate::plain(features), &[mirror_matrix(&pl)], warning);
|
||||
return replay(doc, vals, f, st, features, &[mirror_matrix(&pl)], warning);
|
||||
}
|
||||
let m = mirror_matrix(&pl);
|
||||
let mut output = 0;
|
||||
|
||||
@@ -184,11 +184,10 @@ fn a_sketch_on_a_fixed_plane_costs_the_same_in_a_large_placed_design() {
|
||||
let plane = doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XZ".into() } }, Some("Datum")).unwrap();
|
||||
assert_eq!(counted(|| model.evaluate(&doc)), Counts::default(), "construction plane");
|
||||
assert!(model.result(plane).unwrap().error.is_none());
|
||||
let datum = doc.feature(plane).unwrap().name.clone();
|
||||
let planes = [
|
||||
PlaneRef::Origin { name: "XY".into() },
|
||||
PlaneRef::Offset { base: Box::new(PlaneRef::Origin { name: "YZ".into() }), distance: "5 mm".into() },
|
||||
PlaneRef::Construction { name: datum.into() },
|
||||
PlaneRef::Construction { feature: plane.into() },
|
||||
];
|
||||
for (k, plane) in planes.into_iter().enumerate() {
|
||||
let id = doc.add_feature(line_sketch(plane, Vec2::new(10.0, 1.0 + k as f64)), None).unwrap();
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
//! References from a feature to the rest of the design: the sketches it is built from (by id),
|
||||
//! the features it names (patterned and mirrored features, the construction plane a plane is
|
||||
//! built on) and the bodies it works on (by name). The walk (`crate::walk`) is behind
|
||||
//! the features it names (patterned and mirrored features and the construction plane a plane is
|
||||
//! built on, by id since #1134; construction axes and points, still by name) and the bodies it
|
||||
//! works on (by name). The walk (`crate::walk`) is behind
|
||||
//! `input_sketches`, `remap_refs` and `remap_bodies`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::walk::Walk;
|
||||
use crate::{BodyName, FeatureKind, FeatureName, SketchId};
|
||||
use crate::{BodyName, FeatureId, FeatureKind, FeatureName, SketchId};
|
||||
|
||||
/// A reference a feature holds: `S` is `&SketchId` or `&mut SketchId`, and so on.
|
||||
pub(crate) enum Ref<S, F, B> {
|
||||
/// A reference a feature holds: `S` is `&SketchId` or `&mut SketchId`, and so on. `Feature`
|
||||
/// carries a feature id (pattern and mirror seeds, construction planes); `FeatureName` carries
|
||||
/// a feature name, for the references that are still keyed by name (construction axes and
|
||||
/// points).
|
||||
pub(crate) enum Ref<S, F, N, B> {
|
||||
Sketch(S),
|
||||
Feature(F),
|
||||
FeatureName(N),
|
||||
Body(B),
|
||||
}
|
||||
|
||||
@@ -28,28 +33,34 @@ impl FeatureKind {
|
||||
v
|
||||
}
|
||||
|
||||
/// Whether the feature names the feature `name` (the construction plane a plane is built on,
|
||||
/// a patterned or mirrored feature).
|
||||
pub fn names_feature(&self, name: &str) -> bool {
|
||||
/// Whether the feature refers to the feature `id` (by id: a patterned or mirrored feature,
|
||||
/// the construction plane a plane is built on) or names it (`name`: a construction axis or
|
||||
/// point it is built from). Used to refuse a feature built on itself (#3567).
|
||||
pub fn names_feature(&self, id: u64, name: &str) -> bool {
|
||||
let mut found = false;
|
||||
self.walk_refs(&mut |r| {
|
||||
if let Ref::Feature(n) = r {
|
||||
found |= n.as_ref() == name;
|
||||
}
|
||||
self.walk_refs(&mut |r| match r {
|
||||
Ref::Feature(x) => found |= x.0 == id,
|
||||
Ref::FeatureName(n) => found |= n.as_ref() == name,
|
||||
_ => {}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Point references to sketches (by id) and features (by name) at their copies, or at a
|
||||
/// feature's new name (`timeline.rename`).
|
||||
pub fn remap_refs(&mut self, sketches: &BTreeMap<u64, u64>, names: &BTreeMap<String, String>) {
|
||||
/// Point references to sketches and features (both by id) at their copies, and references
|
||||
/// that are still keyed by name at a feature's new name (`timeline.rename`).
|
||||
pub fn remap_refs(&mut self, ids: &BTreeMap<u64, u64>, names: &BTreeMap<String, String>) {
|
||||
self.walk_refs_mut(&mut |r| match r {
|
||||
Ref::Sketch(id) => {
|
||||
if let Some(n) = sketches.get(&id.0) {
|
||||
if let Some(n) = ids.get(&id.0) {
|
||||
*id = SketchId(*n);
|
||||
}
|
||||
}
|
||||
Ref::Feature(name) => {
|
||||
Ref::Feature(id) => {
|
||||
if let Some(n) = ids.get(&id.0) {
|
||||
*id = FeatureId(*n);
|
||||
}
|
||||
}
|
||||
Ref::FeatureName(name) => {
|
||||
if let Some(n) = names.get(name.as_ref()) {
|
||||
*name = FeatureName(n.clone());
|
||||
}
|
||||
@@ -72,8 +83,9 @@ impl FeatureKind {
|
||||
|
||||
impl crate::Document {
|
||||
/// Rename feature `old` to `new` where the design names it outside the features' own
|
||||
/// references (`remap_refs`): sketch projections of a construction plane and the canvases
|
||||
/// placed on it (#4353). (The features are the rename command's to change.)
|
||||
/// references (`remap_refs`): sketch projections of a construction plane (#4353). The
|
||||
/// features are the rename command's to change; feature references inside features are keyed
|
||||
/// by id since #1134 and follow a rename on their own.
|
||||
pub fn rename_feature_keys(&mut self, old: &str, new: &str) {
|
||||
let names = BTreeMap::from([(old.to_string(), new.to_string())]);
|
||||
let (ids, bodies) = (BTreeMap::new(), BTreeMap::new());
|
||||
@@ -84,14 +96,5 @@ impl crate::Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in &mut self.canvases {
|
||||
c.plane.walk_refs_mut(&mut |r| {
|
||||
if let Ref::Feature(name) = r
|
||||
&& name.as_ref() == old
|
||||
{
|
||||
*name = FeatureName(new.to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +184,8 @@ fn construction_names_follow_renames_in_every_definition() {
|
||||
|
||||
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"}});
|
||||
// Construction plane references are keyed by id (#1134): a rename leaves them alone.
|
||||
let plane = json!({"type": "plane", "plane": {"type": "construction", "feature": 7}});
|
||||
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}}),
|
||||
@@ -217,7 +218,7 @@ fn construction_names_follow_renames_in_every_definition() {
|
||||
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 {
|
||||
if let Ref::FeatureName(name) = r {
|
||||
seen.push(name.to_string());
|
||||
}
|
||||
});
|
||||
@@ -233,13 +234,13 @@ 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() };
|
||||
let mut plane = crate::PlaneRef::Construction { feature: crate::FeatureId(7) };
|
||||
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 {
|
||||
if let Ref::FeatureName(name) = r {
|
||||
seen.push(name.to_string());
|
||||
}
|
||||
});
|
||||
@@ -247,7 +248,7 @@ fn construction_reference_walk_keeps_its_depth_limit_across_geometry() {
|
||||
assert!(seen.iter().all(|name| name == "Side"));
|
||||
let mut changed = 0;
|
||||
plane.walk_refs_mut(&mut |r| {
|
||||
if let Ref::Feature(name) = r {
|
||||
if let Ref::FeatureName(name) = r {
|
||||
assert_eq!(name.as_ref(), "Side");
|
||||
*name = "Renamed".into();
|
||||
changed += 1;
|
||||
|
||||
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
|
||||
|
||||
fn plane(chain: &str) -> Value {
|
||||
json!({"type": "at_angle", "angle": format!("{chain}.angle"), "axis_origin": [0, 0, 0], "axis_dir": [1, 0, 0],
|
||||
"base": {"type": "offset", "distance": format!("{chain}.offset"), "base": {"type": "construction", "name": "CP"}}})
|
||||
"base": {"type": "offset", "distance": format!("{chain}.offset"), "base": {"type": "construction", "feature": 8}}})
|
||||
}
|
||||
|
||||
fn geo_plane(chain: &str) -> Value {
|
||||
@@ -25,7 +25,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
|
||||
"taper": format!("{n}.taper"), "to_offset": format!("{n}.to_offset")})
|
||||
};
|
||||
let fillet = |style: Value| json!({"type": "fillet", "edges": [o], "radius": "fillet.radius", "style": style});
|
||||
let pattern = |p: Value| json!({"type": "pattern", "features": ["F"], "pattern": p});
|
||||
let pattern = |p: Value| json!({"type": "pattern", "features": [7], "pattern": p});
|
||||
let hole =
|
||||
|h: Value| json!({"type": "hole", "position": o, "direction": [0, 0, 1], "diameter": "hole.diameter", "depth": "hole.depth", "hole": h});
|
||||
vec![
|
||||
@@ -67,7 +67,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
|
||||
),
|
||||
("pattern_circular", pattern(json!({"type": "circular", "origin": o, "axis": [0, 0, 1], "count": "circ.count", "angle": "circ.angle"}))),
|
||||
("pattern_path", pattern(json!({"type": "path", "path_sketch": 1, "path": ["l1"], "count": "path.count", "spacing": "path.spacing"}))),
|
||||
("mirror", json!({"type": "mirror", "features": ["F"], "plane": plane("mirror")})),
|
||||
("mirror", json!({"type": "mirror", "features": [7], "plane": plane("mirror")})),
|
||||
("hole_simple", hole(json!({"type": "simple"}))),
|
||||
("hole_drilled", hole(json!({"type": "drilled", "tip_angle": "hole.tip_angle"}))),
|
||||
("hole_counterbore", hole(json!({"type": "counterbore", "cb_diameter": "hole.cb_diameter", "cb_depth": "hole.cb_depth"}))),
|
||||
@@ -232,7 +232,7 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
|
||||
|
||||
/// The reference fields a fixture leaves out (they don't change its expressions), set here so
|
||||
/// every sketch, feature and body reference is exercised: sketches 1–8, feature `F`,
|
||||
/// construction plane `CP`, body `B`.
|
||||
/// construction plane feature 8, body `B`.
|
||||
pub(super) fn with_refs(name: &str, mut v: Value) -> Value {
|
||||
let o = [0, 0, 0];
|
||||
let tool = json!({"body": "B", "point": o});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
body_transfer
|
||||
remap_bodies: bodies[0]
|
||||
sketch
|
||||
remap_refs: plane.base.base.name
|
||||
remap_refs: plane.base.base.feature
|
||||
sketch_along_path
|
||||
extrude
|
||||
sketches: [1]
|
||||
@@ -44,7 +44,7 @@ pattern_path
|
||||
remap_refs: features[0], pattern.path_sketch
|
||||
remap_bodies: bodies[0]
|
||||
mirror
|
||||
remap_refs: features[0], plane.base.base.name
|
||||
remap_refs: features[0], plane.base.base.feature
|
||||
remap_bodies: bodies[0]
|
||||
hole_simple
|
||||
sketches: [3]
|
||||
@@ -75,25 +75,25 @@ sweep_options
|
||||
shell
|
||||
remap_bodies: body
|
||||
draft
|
||||
remap_refs: neutral.base.base.name
|
||||
remap_refs: neutral.base.base.feature
|
||||
remap_bodies: body
|
||||
construction_plane
|
||||
remap_refs: plane.base.base.name
|
||||
remap_refs: plane.base.base.feature
|
||||
split
|
||||
remap_refs: plane.base.base.name
|
||||
remap_refs: plane.base.base.feature
|
||||
remap_bodies: body, tool.body
|
||||
split_line
|
||||
sketches: [6]
|
||||
remap_refs: plane.base.base.name, sketch
|
||||
remap_refs: plane.base.base.feature, sketch
|
||||
remap_bodies: body
|
||||
construction_axis
|
||||
remap_refs: def.a.plane.base.base.name, def.b.plane.base.base.name
|
||||
remap_refs: def.a.plane.base.base.feature, def.b.plane.base.base.feature
|
||||
construction_point_planes
|
||||
remap_refs: def.a.plane.base.base.name, def.b.plane.base.base.name, def.c.plane.base.base.name
|
||||
remap_refs: def.a.plane.base.base.feature, def.b.plane.base.base.feature, def.c.plane.base.base.feature
|
||||
construction_point_along
|
||||
split_face
|
||||
sketches: [6]
|
||||
remap_refs: plane.base.base.name, sketch
|
||||
remap_refs: plane.base.base.feature, sketch
|
||||
remap_bodies: body, tool.body
|
||||
scale
|
||||
remap_bodies: bodies[0]
|
||||
@@ -121,7 +121,7 @@ rib
|
||||
sketches: [1]
|
||||
remap_refs: sketch
|
||||
replace_face
|
||||
remap_refs: target.base.base.name
|
||||
remap_refs: target.base.base.feature
|
||||
remap_bodies: body
|
||||
align
|
||||
remap_bodies: bodies[0]
|
||||
@@ -215,21 +215,21 @@ surface_untrim
|
||||
surface_extend
|
||||
remap_bodies: body
|
||||
surface_extend_to_plane
|
||||
remap_refs: up_to.plane.base.base.name
|
||||
remap_refs: up_to.plane.base.base.feature
|
||||
remap_bodies: body
|
||||
surface_extend_to_face
|
||||
remap_bodies: body, up_to.face.body
|
||||
surface_ruled
|
||||
remap_bodies: body
|
||||
surface_trim
|
||||
remap_refs: plane.base.base.name
|
||||
remap_refs: plane.base.base.feature
|
||||
remap_bodies: body, tool.body
|
||||
surface_trim_curves
|
||||
sketches: [1]
|
||||
remap_refs: curves.sketch, plane.base.base.name
|
||||
remap_refs: curves.sketch, plane.base.base.feature
|
||||
remap_bodies: body
|
||||
surface_trim_mutual
|
||||
remap_refs: plane.base.base.name
|
||||
remap_refs: plane.base.base.feature
|
||||
remap_bodies: body, with
|
||||
move
|
||||
remap_bodies: bodies[0]
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Pattern and mirror seeds (`Pattern`/`Mirror` `features`) and construction plane references
|
||||
//! (`PlaneRef::Construction`) are saved as feature ids (#1134), like every other feature
|
||||
//! reference. An older design has its names resolved to ids once as it opens, exactly the way
|
||||
//! `replay()` resolved them: an exact name match on a feature that is not a sketch or a
|
||||
//! construction plane, else a feature id written as a number, else a case-insensitive name
|
||||
//! match; a name that resolves to nothing keeps id 0, which no feature has, so it dangles at
|
||||
//! evaluation with the same warning or error it always gave. New saves write ids; a rename no
|
||||
//! longer has to rewrite anything. The last release refuses a design that has them (it refuses
|
||||
//! the newer format number).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::Result;
|
||||
|
||||
/// A design's features as `(id, name, type)`, for resolving names the way `replay()` did.
|
||||
type Features<'a> = &'a [(u64, String, String)];
|
||||
|
||||
/// `Document::find_feature` at the JSON level: an id written as a number, then a
|
||||
/// case-insensitive name match.
|
||||
fn find_feature(feats: Features, name: &str) -> Option<u64> {
|
||||
name.parse::<u64>()
|
||||
.ok()
|
||||
.and_then(|id| feats.iter().find(|(i, ..)| *i == id))
|
||||
.or_else(|| feats.iter().find(|(_, n, _)| n.eq_ignore_ascii_case(name)))
|
||||
.map(|(i, ..)| *i)
|
||||
}
|
||||
|
||||
/// The feature a pattern or mirror seed named: an exact name match on a feature that is not a
|
||||
/// sketch or a construction plane (a sketch and its extrude often share a name; the feature
|
||||
/// that makes geometry wins), else [`find_feature`]; nothing is id 0, which dangles at
|
||||
/// evaluation as the missing name did.
|
||||
fn resolve_seed(feats: Features, name: &str) -> u64 {
|
||||
feats
|
||||
.iter()
|
||||
.find(|(_, n, t)| n == name && !matches!(t.as_str(), "sketch" | "construction_plane"))
|
||||
.map(|(i, ..)| *i)
|
||||
.or_else(|| find_feature(feats, name))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The feature a construction plane reference named ([`find_feature`]); nothing is id 0.
|
||||
fn resolve_plane(feats: Features, name: &str) -> u64 {
|
||||
find_feature(feats, name).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Rewrite every `{"type": "construction", "name": …}` plane reference in `v` to carry the
|
||||
/// feature's id. `skip_axis` leaves a revolve's `axis` alone: an `AxisRef::Construction` has
|
||||
/// the same shape but names a construction axis, which is still keyed by name.
|
||||
fn rewrite(v: &mut Value, feats: Features, skip_axis: bool) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("construction") {
|
||||
if let Some(Value::String(name)) = o.get("name") {
|
||||
let id = resolve_plane(feats, name);
|
||||
o.remove("name");
|
||||
o.insert("feature".into(), Value::from(id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (key, x) in o.iter_mut() {
|
||||
if !(skip_axis && key == "axis") {
|
||||
rewrite(x, feats, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(|x| rewrite(x, feats, false)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn step(v: &mut Value) -> Result<()> {
|
||||
let feats: Vec<(u64, String, String)> = v
|
||||
.get("features")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_object)
|
||||
.filter_map(|f| {
|
||||
let id = f.get("id")?.as_u64()?;
|
||||
let name = f.get("name")?.as_str()?.to_string();
|
||||
let kind = f.get("type")?.as_str()?.to_string();
|
||||
Some((id, name, kind))
|
||||
})
|
||||
.collect();
|
||||
if let Some(Value::Array(features)) = v.get_mut("features") {
|
||||
for f in features.iter_mut() {
|
||||
let kind = f.get("type").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
// A pattern's or mirror's seeds: each name becomes the feature's id.
|
||||
if matches!(kind.as_str(), "pattern" | "mirror")
|
||||
&& let Some(Value::Array(seeds)) = f.get_mut("features")
|
||||
{
|
||||
for s in seeds.iter_mut() {
|
||||
if let Value::String(name) = s {
|
||||
let id = resolve_seed(&feats, name);
|
||||
*s = Value::from(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Construction plane references, everywhere but a revolve's axis.
|
||||
let skip_axis = matches!(kind.as_str(), "revolve" | "surface_revolve");
|
||||
rewrite(f, &feats, skip_axis);
|
||||
}
|
||||
}
|
||||
// References outside the features: canvases placed on a construction plane and the like.
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
for (key, x) in o.iter_mut() {
|
||||
if key != "features" {
|
||||
rewrite(x, &feats, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::step;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A design's feature list: a sketch and an extrude sharing the name `Boss` (the sketch
|
||||
/// first, as designs write them), a construction plane, a construction axis and a lower-
|
||||
/// cased extrude `boss`.
|
||||
fn features() -> Vec<Value> {
|
||||
vec![
|
||||
json!({"id": 1, "name": "Boss", "type": "sketch"}),
|
||||
json!({"id": 2, "name": "Boss", "type": "extrude"}),
|
||||
json!({"id": 3, "name": "Mid", "type": "construction_plane"}),
|
||||
json!({"id": 4, "name": "Axis1", "type": "construction_axis"}),
|
||||
json!({"id": 5, "name": "boss", "type": "extrude"}),
|
||||
]
|
||||
}
|
||||
|
||||
fn design(features: Vec<Value>) -> Value {
|
||||
json!({"format": "solidcraft/36", "features": features})
|
||||
}
|
||||
|
||||
fn migrated(mut v: Value) -> Value {
|
||||
step(&mut v).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeds_resolve_exactly_as_replay_resolved_them() {
|
||||
let mut feats = features();
|
||||
feats.push(json!({"id": 6, "name": "Copies", "type": "pattern", "features": ["Boss", "mid", "5", "Gone"], "pattern": {"type": "circular"}}));
|
||||
let out = migrated(design(feats));
|
||||
// `Boss`: the exact name on a feature that is not a sketch wins over the sketch and
|
||||
// over the case-insensitive `boss`. `mid`: no exact match, so the case-insensitive
|
||||
// find_feature fallback. `5`: an id written as a number. `Gone`: dangling, id 0.
|
||||
assert_eq!(out["features"][5]["features"], json!([2, 3, 5, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_planes_resolve_by_find_feature_and_dangle_as_zero() {
|
||||
let mut feats = features();
|
||||
feats.push(json!({"id": 7, "name": "On Mid", "type": "sketch", "plane": {"type": "construction", "name": "MID"}}));
|
||||
feats.push(json!({"id": 8, "name": "Lost", "type": "sketch", "plane": {"type": "offset", "distance": "5", "base": {"type": "construction", "name": "Gone"}}}));
|
||||
let out = migrated(design(feats));
|
||||
assert_eq!(out["features"][5]["plane"], json!({"type": "construction", "feature": 3}));
|
||||
assert_eq!(out["features"][6]["plane"]["base"], json!({"type": "construction", "feature": 0}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revolve_axis_naming_a_construction_axis_keeps_its_name() {
|
||||
let mut feats = features();
|
||||
feats.push(json!({"id": 9, "name": "Turn", "type": "revolve", "axis": {"type": "construction", "name": "Axis1"}}));
|
||||
feats.push(json!({"id": 10, "name": "Surface Turn", "type": "surface_revolve", "axis": {"type": "construction", "name": "Axis1"}}));
|
||||
let out = migrated(design(feats));
|
||||
assert_eq!(out["features"][5]["axis"], json!({"type": "construction", "name": "Axis1"}));
|
||||
assert_eq!(out["features"][6]["axis"], json!({"type": "construction", "name": "Axis1"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_outside_the_features_are_migrated_too() {
|
||||
let mut d = design(features());
|
||||
d["canvases"] = json!([{"id": 1, "plane": {"type": "construction", "name": "Mid"}}]);
|
||||
let out = migrated(d);
|
||||
assert_eq!(out["canvases"][0]["plane"], json!({"type": "construction", "feature": 3}));
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ pub use eval::{
|
||||
world_state_reusing,
|
||||
};
|
||||
pub use expr::Expr;
|
||||
pub use names::{BodyName, FeatureName, SketchId};
|
||||
pub use names::{BodyName, FeatureId, FeatureName, SketchId};
|
||||
pub use params::{ParamRow, ParamUser, cycles};
|
||||
pub use points::{Dir, FacePick, Position, plain};
|
||||
pub use solidcraft_kernel as kernel;
|
||||
|
||||
@@ -103,6 +103,55 @@ name_type!(
|
||||
FeatureName
|
||||
);
|
||||
|
||||
/// A feature, by its id. Pattern and mirror seeds and construction planes name features by id
|
||||
/// (#1134); a reference that resolves to nothing keeps id 0, which no feature ever has.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct FeatureId(pub u64);
|
||||
|
||||
impl FeatureId {
|
||||
/// A reference that names no feature: a name that could not be resolved when an older
|
||||
/// design was migrated (#1134). Evaluation reports it like today's dangling name.
|
||||
pub const DANGLING: FeatureId = FeatureId(0);
|
||||
}
|
||||
|
||||
impl Deref for FeatureId {
|
||||
type Target = u64;
|
||||
fn deref(&self) -> &u64 {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u64> for FeatureId {
|
||||
fn from(id: u64) -> Self {
|
||||
FeatureId(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FeatureId> for u64 {
|
||||
fn from(id: FeatureId) -> u64 {
|
||||
id.0
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<u64> for FeatureId {
|
||||
fn eq(&self, other: &u64) -> bool {
|
||||
self.0 == *other
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<FeatureId> for u64 {
|
||||
fn eq(&self, other: &FeatureId) -> bool {
|
||||
*self == other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FeatureId {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
/// A sketch, by its feature id.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
|
||||
@@ -263,7 +263,10 @@ fn resolve_uncached(
|
||||
let pr = if Plane::named(name).is_some() {
|
||||
PlaneRef::Origin { name: name.clone() }
|
||||
} else {
|
||||
PlaneRef::Construction { name: name.clone().into() }
|
||||
// Resolved to the feature's id here, once (#1134); a name that finds no feature
|
||||
// dangles below, as it did when the reference carried the name.
|
||||
let feature = doc.find_feature(name).map(|f| crate::FeatureId(f.id)).unwrap_or(crate::FeatureId::DANGLING);
|
||||
PlaneRef::Construction { feature }
|
||||
};
|
||||
let other = doc.resolve_plane_in(vals, &pr, 0, Some(st)).map_err(|_| lost(&format!("plane {name}")))?;
|
||||
plane_trace(plane, &other).into_iter().collect()
|
||||
|
||||
@@ -567,20 +567,21 @@ fn feature_inserted_at_a_marker_inside_a_timeline_folder_joins_it() {
|
||||
/// aborts the process, which no panic guard can intercept.
|
||||
#[test]
|
||||
fn self_referencing_construction_planes_are_errors() {
|
||||
let selfref = |name: &str| Box::new(construct::GeoRef::Plane { plane: PlaneRef::Construction { name: name.into() } });
|
||||
// Feature ids are assigned from 1, so each design below knows its own feature's id.
|
||||
let selfref = |id: u64| Box::new(construct::GeoRef::Plane { plane: PlaneRef::Construction { feature: id.into() } });
|
||||
let xz = || Box::new(construct::GeoRef::Plane { plane: PlaneRef::Origin { name: "XZ".into() } });
|
||||
|
||||
// Directly its own first side.
|
||||
let mut doc = Document::new("selfplane");
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref("P1"), b: xz() } }, Some("P1")).unwrap();
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref(1), b: xz() } }, Some("P1")).unwrap();
|
||||
let mut m = Model::new();
|
||||
m.evaluate(&doc);
|
||||
assert!(m.results.iter().any(|r| r.error.is_some()), "a plane that is its own side must report an error: {:?}", m.results);
|
||||
|
||||
// Two planes that are each other's side.
|
||||
let mut doc = Document::new("twoplanes");
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref("P2"), b: xz() } }, Some("P1")).unwrap();
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref("P1"), b: xz() } }, Some("P2")).unwrap();
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref(2), b: xz() } }, Some("P1")).unwrap();
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Midplane { a: selfref(1), b: xz() } }, Some("P2")).unwrap();
|
||||
let mut m = Model::new();
|
||||
m.evaluate(&doc);
|
||||
assert!(m.results.iter().any(|r| r.error.is_some()), "a two-plane cycle must report an error: {:?}", m.results);
|
||||
@@ -588,8 +589,8 @@ fn self_referencing_construction_planes_are_errors() {
|
||||
// A perpendicular plane whose base is itself, and a sketch placed on it.
|
||||
let mut doc = Document::new("perpplane");
|
||||
let line = Box::new(construct::GeoRef::World { axis: "X".into() });
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Perpendicular { plane: selfref("P1"), line } }, Some("P1")).unwrap();
|
||||
doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Construction { name: "P1".into() }, sketch: Sketch::new() }, Some("Sketch1")).unwrap();
|
||||
doc.add_feature(FeatureKind::ConstructionPlane { plane: PlaneRef::Perpendicular { plane: selfref(1), line } }, Some("P1")).unwrap();
|
||||
doc.add_feature(FeatureKind::Sketch { plane: PlaneRef::Construction { feature: 1.into() }, sketch: Sketch::new() }, Some("Sketch1")).unwrap();
|
||||
let mut m = Model::new();
|
||||
m.evaluate(&doc);
|
||||
assert!(m.results.iter().any(|r| r.error.is_some()), "a cyclic perpendicular plane must report an error: {:?}", m.results);
|
||||
|
||||
@@ -13,13 +13,13 @@ pub(crate) use crate::expr::Kind;
|
||||
pub(crate) use crate::feature_geometry::Geo;
|
||||
pub(crate) use crate::feature_refs::Ref;
|
||||
pub(crate) use crate::params::ExprRole;
|
||||
use crate::{BodyName, Dir, Expr, FacePick, FeatureName, PlaneRef, PointExpr, Position, SketchId};
|
||||
use crate::{BodyName, Dir, Expr, FacePick, FeatureId, FeatureName, PlaneRef, PointExpr, Position, SketchId};
|
||||
|
||||
/// An expression: its label, the expression, its kind and its role.
|
||||
pub(crate) type ExprItem<'a> = (&'static str, &'a Expr, Kind, ExprRole);
|
||||
pub(crate) type ExprItemMut<'a> = (&'static str, &'a mut Expr, Kind, ExprRole);
|
||||
pub(crate) type RefItem<'a> = Ref<&'a SketchId, &'a FeatureName, &'a BodyName>;
|
||||
pub(crate) type RefItemMut<'a> = Ref<&'a mut SketchId, &'a mut FeatureName, &'a mut BodyName>;
|
||||
pub(crate) type RefItem<'a> = Ref<&'a SketchId, &'a FeatureId, &'a FeatureName, &'a BodyName>;
|
||||
pub(crate) type RefItemMut<'a> = Ref<&'a mut SketchId, &'a mut FeatureId, &'a mut FeatureName, &'a mut BodyName>;
|
||||
pub(crate) type GeoItem<'a> = Geo<&'a Vec3, &'a PlaneRef, &'a GeoRef, &'a PointExpr, &'a ProfileSel>;
|
||||
pub(crate) type GeoItemMut<'a> = Geo<&'a mut Vec3, &'a mut PlaneRef, &'a mut GeoRef, &'a mut PointExpr, &'a mut ProfileSel>;
|
||||
|
||||
@@ -78,7 +78,8 @@ macro_rules! reference {
|
||||
}
|
||||
|
||||
reference!(SketchId, Sketch);
|
||||
reference!(FeatureName, Feature);
|
||||
reference!(FeatureId, Feature);
|
||||
reference!(FeatureName, FeatureName);
|
||||
reference!(BodyName, Body);
|
||||
|
||||
/// A point walks itself with its role: a face pick, a position or a direction. As a plain
|
||||
@@ -393,7 +394,7 @@ impl PlaneRef {
|
||||
return;
|
||||
}
|
||||
match self {
|
||||
Self::Construction { name } => f(Ref::Feature(name)),
|
||||
Self::Construction { feature } => f(Ref::Feature(feature)),
|
||||
Self::Offset { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs(f, depth + 1),
|
||||
Self::ThroughPoint { base, point } => {
|
||||
base.walk_feature_refs(f, depth + 1);
|
||||
@@ -424,7 +425,7 @@ impl PlaneRef {
|
||||
return;
|
||||
}
|
||||
match self {
|
||||
Self::Construction { name } => f(Ref::Feature(name)),
|
||||
Self::Construction { feature } => f(Ref::Feature(feature)),
|
||||
Self::Offset { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs_mut(f, depth + 1),
|
||||
Self::ThroughPoint { base, point } => {
|
||||
base.walk_feature_refs_mut(f, depth + 1);
|
||||
@@ -458,7 +459,7 @@ impl GeoRef {
|
||||
return;
|
||||
}
|
||||
match self {
|
||||
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::Feature(name)),
|
||||
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::FeatureName(name)),
|
||||
Self::Plane { plane } => plane.walk_feature_refs(f, depth + 1),
|
||||
Self::Point { .. }
|
||||
| Self::Origin
|
||||
@@ -476,7 +477,7 @@ impl GeoRef {
|
||||
return;
|
||||
}
|
||||
match self {
|
||||
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::Feature(name)),
|
||||
Self::Axis { name } | Self::ConstructPoint { name } => f(Ref::FeatureName(name)),
|
||||
Self::Plane { plane } => plane.walk_feature_refs_mut(f, depth + 1),
|
||||
Self::Point { .. }
|
||||
| Self::Origin
|
||||
|
||||
@@ -595,9 +595,9 @@ pub(super) fn paste(
|
||||
}
|
||||
}
|
||||
if let FeatureKind::Pattern { features: references, .. } | FeatureKind::Mirror { features: references, .. } = &feature.kind {
|
||||
for name in references {
|
||||
if !names.contains_key(name.as_ref()) {
|
||||
notices.push(format!("{} retains external feature reference {name}", feature.name));
|
||||
for id in references {
|
||||
if !features.contains_key(&id.0) {
|
||||
notices.push(format!("{} retains external feature reference {id}", feature.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -952,6 +952,42 @@ fn command_profiles(set: &Value, cmd: &str) -> Result<Value> {
|
||||
/// the name and suppression, which timeline.rename and timeline.suppress change.
|
||||
const NOT_EDITABLE: &[&str] = &["id", "type", "name", "suppressed", "param_names", "edge_refs", "edge_names", "face_names"];
|
||||
|
||||
/// timeline.edit keeps accepting names for pattern and mirror seeds and for construction planes
|
||||
/// (#1134): each name in the merged definition resolves to the feature's id, refused when it
|
||||
/// finds no feature, as the commands that take names refuse it.
|
||||
fn resolve_feature_names(v: &mut Value, doc: &solidcraft_doc::Document, cmd: &str) -> Result<()> {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("construction") {
|
||||
// Only a construction plane's name becomes an id: a revolve axis with the same
|
||||
// shape names a construction axis, which is still keyed by name.
|
||||
if let Some(name) = o.get("name").and_then(Value::as_str)
|
||||
&& let Some(f) = doc.find_feature(name).filter(|f| matches!(f.kind, FeatureKind::ConstructionPlane { .. }))
|
||||
{
|
||||
o.remove("name");
|
||||
o.insert("feature".into(), json!(f.id));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
for (_, x) in o.iter_mut() {
|
||||
resolve_feature_names(x, doc, cmd)?;
|
||||
}
|
||||
if let Some(Value::Array(seeds)) = o.get_mut("features") {
|
||||
for s in seeds.iter_mut() {
|
||||
if let Value::String(name) = s {
|
||||
let name = name.clone();
|
||||
let id = doc.seed_feature(&name).ok_or_else(|| bad(cmd, format!("no feature `{name}`")))?;
|
||||
*s = json!(id.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().try_for_each(|x| resolve_feature_names(x, doc, cmd)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Large payloads that timeline.edit cannot change, left out of a feature's definition: (field,
|
||||
/// what it holds).
|
||||
fn heavy_fields(kind: &FeatureKind) -> &'static [(&'static str, &'static str)] {
|
||||
@@ -1009,6 +1045,7 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let set = &numbers_as_expressions(command_profiles(&set, cmd)?, &before);
|
||||
let mut v = before.clone();
|
||||
merge(&mut v, set, 0);
|
||||
resolve_feature_names(&mut v, &s.doc, cmd)?;
|
||||
let mut nf: Feature = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("invalid feature: {e}")))?;
|
||||
nf.id = f.id;
|
||||
if let (FeatureKind::Extrude { extent: old, .. }, FeatureKind::Extrude { extent: new, .. }) = (&f.kind, &mut nf.kind)
|
||||
@@ -1436,7 +1473,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// The trial still holds the old feature, so a plane offset from its own name was made there,
|
||||
// and once swapped in it would be built on itself (#3567).
|
||||
if new.kind.names_feature(&old.name) {
|
||||
if new.kind.names_feature(old.id, &old.name) {
|
||||
return Err(bad(cmd, format!("{} can't be built on itself: pick another plane or face", old.name)));
|
||||
}
|
||||
// Optional inputs can move other inputs' positions (e.g. Distance 2 goes before Taper).
|
||||
|
||||
@@ -976,19 +976,22 @@ fn renaming_a_feature_evaluates_nothing() {
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(labels(&s), renamed);
|
||||
assert_eq!(s.evaluations, 0, "undo and redo of a rename evaluate nothing");
|
||||
// A sketch on the plane names it: renaming the plane renames it there too, which is evaluated.
|
||||
// A sketch on the plane names it by id (#1134): renaming the plane changes no reference,
|
||||
// so it now evaluates nothing — the name follows everywhere without a rebuild.
|
||||
run(&mut s, "sketch.create", json!({"plane": "Shelf", "name": "Top"}));
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
s.evaluations = 0;
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Shelf", "name": "Ledge"}));
|
||||
assert!(s.evaluations > 0);
|
||||
assert_eq!(s.evaluations, 0, "renaming a plane a sketch is built on evaluates nothing");
|
||||
assert!(labels(&s).2.contains(&"Ledge".to_string()));
|
||||
// A failed pattern's error quotes its source's name: renaming the source is evaluated, so
|
||||
// the error names it as an evaluation does.
|
||||
// A failed pattern's error quotes its source's name (the seed is keyed by id, #1134, and
|
||||
// the error is rendered from the source feature at evaluation): renaming the source is
|
||||
// evaluated, so the error names it as an evaluation does.
|
||||
run(&mut s, "solid.pattern.rectangular", json!({"features": ["Base plate"], "dir1": [0, 0, 1], "count1": 2, "spacing1": 10, "name": "Copies"}));
|
||||
let copies = s.doc.find_feature("Copies").unwrap().id;
|
||||
let top = s.doc.find_feature("Top").unwrap().id;
|
||||
if let Some(solidcraft_doc::FeatureKind::Pattern { features, .. }) = s.doc_mut().feature_mut(copies).map(|f| &mut f.kind) {
|
||||
*features = vec!["Top".into()];
|
||||
*features = vec![top.into()];
|
||||
}
|
||||
s.refresh();
|
||||
let failed = |s: &Session| s.model.results.iter().filter_map(|r| r.error.clone()).collect::<Vec<_>>();
|
||||
@@ -1030,11 +1033,13 @@ fn renaming_a_plane_keeps_its_projections_canvases_and_hidden_state() {
|
||||
r["points"].as_array().unwrap().iter().find(|p| p["link"] == "j1").unwrap()["world"][2].as_f64().unwrap()
|
||||
};
|
||||
let warnings = |s: &Session| s.model.results.iter().filter_map(|r| r.warning.clone()).collect::<Vec<_>>();
|
||||
// The canvas keeps its plane by id (#1134): the rename leaves the reference alone.
|
||||
let shelf = s.doc.find_feature("Shelf").unwrap().id;
|
||||
run(&mut s, "select.set", json!({"items": [{"type": "plane", "name": "Shelf"}]}));
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Shelf", "name": "Ledge"}));
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Guide", "name": "Rail"}));
|
||||
assert_eq!(plane_link(&s), "Ledge");
|
||||
assert_eq!(canvas_plane(&s), solidcraft_doc::PlaneRef::Construction { name: "Ledge".into() });
|
||||
assert_eq!(canvas_plane(&s), solidcraft_doc::PlaneRef::Construction { feature: shelf.into() });
|
||||
assert_eq!(s.visibility.hidden_origin, ["Rail"]);
|
||||
assert_eq!(s.selection, [Sel::Plane { name: "Ledge".into() }]);
|
||||
assert!(warnings(&s).is_empty(), "{:?}", warnings(&s));
|
||||
@@ -1047,7 +1052,7 @@ fn renaming_a_plane_keeps_its_projections_canvases_and_hidden_state() {
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
}
|
||||
assert_eq!(plane_link(&s), "Shelf");
|
||||
assert_eq!(canvas_plane(&s), solidcraft_doc::PlaneRef::Construction { name: "Shelf".into() });
|
||||
assert_eq!(canvas_plane(&s), solidcraft_doc::PlaneRef::Construction { feature: shelf.into() });
|
||||
assert_eq!(s.visibility.hidden_origin, ["Guide"], "the hidden plane stays hidden");
|
||||
assert!(warnings(&s).is_empty(), "{:?}", warnings(&s));
|
||||
assert!((projected_z(&mut s) - 20.0).abs() < 1e-9);
|
||||
|
||||
@@ -1778,17 +1778,14 @@ fn copy_keeps_appearance(s: &mut Session, reply: &Value, sources: &[String], cmd
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn source_features(s: &Session, p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
fn source_features(s: &Session, p: &Value, cmd: &str) -> Result<Vec<solidcraft_doc::FeatureId>> {
|
||||
let names = string_list(p, "features");
|
||||
if names.is_empty() {
|
||||
return Err(bad(cmd, "`features` must list features to copy"));
|
||||
}
|
||||
for n in &names {
|
||||
if s.doc.find_feature(n).is_none() {
|
||||
return Err(bad(cmd, format!("no feature `{n}`")));
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
// Names stay input only: the feature stores its seeds by id (#1134), resolved the way
|
||||
// evaluation used to resolve them (a shared sketch name does not win over the geometry).
|
||||
names.iter().map(|n| s.doc.seed_feature(n).map(|f| f.id.into()).ok_or_else(|| bad(cmd, format!("no feature `{n}`")))).collect()
|
||||
}
|
||||
|
||||
/// An axis line from its parameter, with what it follows: an edge or round face of the model
|
||||
@@ -1833,18 +1830,16 @@ fn named_axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Opt
|
||||
}
|
||||
|
||||
/// A pattern feature, or for `components`, new occurrences of them at each placement.
|
||||
fn finish_pattern(s: &mut Session, p: &Value, features: Vec<String>, pattern: solidcraft_doc::PatternKind, bodies: Vec<String>) -> Result<Value> {
|
||||
fn finish_pattern(
|
||||
s: &mut Session,
|
||||
p: &Value,
|
||||
features: Vec<solidcraft_doc::FeatureId>,
|
||||
pattern: solidcraft_doc::PatternKind,
|
||||
bodies: Vec<String>,
|
||||
) -> Result<Value> {
|
||||
let comps = string_list(p, "components");
|
||||
if comps.is_empty() {
|
||||
return add_feature(
|
||||
s,
|
||||
p,
|
||||
FeatureKind::Pattern {
|
||||
features: features.into_iter().map(FeatureName).collect(),
|
||||
pattern,
|
||||
bodies: bodies.into_iter().map(BodyName).collect(),
|
||||
},
|
||||
);
|
||||
return add_feature(s, p, FeatureKind::Pattern { features, pattern, bodies: bodies.into_iter().map(BodyName).collect() });
|
||||
}
|
||||
let cmd = "pattern (components)";
|
||||
let mats = solidcraft_doc::pattern_matrices(&s.doc, &s.model.state(), &pattern)?;
|
||||
@@ -1861,7 +1856,7 @@ fn finish_pattern(s: &mut Session, p: &Value, features: Vec<String>, pattern: so
|
||||
|
||||
/// What a pattern copies: features (replayed), bodies (`bodies: [names]`), or components
|
||||
/// (`components: [names]`, placed again as occurrences).
|
||||
fn pattern_sources(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<String>, Vec<String>)> {
|
||||
fn pattern_sources(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<solidcraft_doc::FeatureId>, Vec<String>)> {
|
||||
if !string_list(p, "components").is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
@@ -1961,17 +1956,7 @@ fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plane = plane_param(s, p.get("plane"), cmd)?;
|
||||
let combine = bool_(p, "combine").unwrap_or(false);
|
||||
let (bodies, placements) = placed_bodies(s, bodies, cmd)?;
|
||||
add_feature(
|
||||
s,
|
||||
p,
|
||||
FeatureKind::Mirror {
|
||||
features: features.into_iter().map(FeatureName).collect(),
|
||||
plane,
|
||||
bodies: bodies.into_iter().map(BodyName).collect(),
|
||||
combine,
|
||||
placements,
|
||||
},
|
||||
)
|
||||
add_feature(s, p, FeatureKind::Mirror { features, plane, bodies: bodies.into_iter().map(BodyName).collect(), combine, placements })
|
||||
}
|
||||
|
||||
/// Bodies picked where the viewport shows them: each world name ("Body1", or "Body1 (Occ:2)"
|
||||
@@ -2031,7 +2016,7 @@ pub(super) fn plane_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result<s
|
||||
use solidcraft_doc::PlaneRef;
|
||||
const WANT: &str = "XY, XZ, YZ, a construction plane name or id, or {origin, normal} (origin coordinates may be length expressions)";
|
||||
let construction = |r: &str| match s.doc.find_feature(r) {
|
||||
Some(f) if matches!(f.kind, FeatureKind::ConstructionPlane { .. }) => Ok(PlaneRef::Construction { name: f.name.clone().into() }),
|
||||
Some(f) if matches!(f.kind, FeatureKind::ConstructionPlane { .. }) => Ok(PlaneRef::Construction { feature: f.id.into() }),
|
||||
Some(f) => Err(bad(cmd, format!("`{}` is not a construction plane (a plane is {WANT})", f.name))),
|
||||
None => Err(bad(cmd, format!("no plane `{r}` (a plane is {WANT})"))),
|
||||
};
|
||||
|
||||
@@ -436,23 +436,42 @@ fn patterns_of_a_blind_hole_drill_every_copy() {
|
||||
assert!((c - 2.0 * one).abs() < 1e-3 * one, "{c} vs 2 × {one}");
|
||||
}
|
||||
|
||||
/// Feature patterns and mirrors reference features by name; a rename follows (#401).
|
||||
/// Feature patterns and mirrors reference features by id (#1134): a rename leaves the
|
||||
/// references alone, and they keep pointing at the same feature (#401).
|
||||
#[test]
|
||||
fn renaming_a_source_feature_follows_pattern_and_mirror_references() {
|
||||
fn renaming_a_source_feature_leaves_pattern_and_mirror_references_alone() {
|
||||
let mut s = plate_with_hole();
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "YZ", "offset": 0, "name": "Mirror plane"}));
|
||||
run(&mut s, "solid.pattern.rectangular", json!({"features": ["Hole1"], "dir1": [1, 0, 0], "count1": 2, "spacing1": 20, "name": "Copies"}));
|
||||
run(&mut s, "solid.mirror", json!({"features": ["Hole1"], "plane": "Mirror plane", "name": "Mirrored"}));
|
||||
let hole = s.doc.find_feature("Hole1").unwrap().id;
|
||||
let mirror_plane = s.doc.find_feature("Mirror plane").unwrap().id;
|
||||
let renamed = run(&mut s, "timeline.rename", json!({"feature": "Hole1", "name": "Single hole"}));
|
||||
assert_eq!(renamed["name"], "Single hole", "{renamed}");
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Mirror plane", "name": "Renamed plane"}));
|
||||
for feature in ["Copies", "Mirrored"] {
|
||||
let inspected = run(&mut s, "timeline.inspect", json!({"feature": feature}));
|
||||
assert!(inspected["error"].is_null(), "{feature}: {inspected}");
|
||||
assert_eq!(inspected["definition"]["features"], json!(["Single hole"]), "{inspected}");
|
||||
assert_eq!(inspected["definition"]["features"], json!([hole]), "{inspected}");
|
||||
}
|
||||
let inspected = run(&mut s, "timeline.inspect", json!({"feature": "Mirrored"}));
|
||||
assert_eq!(inspected["definition"]["plane"]["name"], "Renamed plane", "{inspected}");
|
||||
assert_eq!(inspected["definition"]["plane"], json!({"type": "construction", "feature": mirror_plane}), "{inspected}");
|
||||
}
|
||||
|
||||
/// timeline.edit keeps accepting seed and plane names as input: they resolve to ids (#1134).
|
||||
#[test]
|
||||
fn editing_a_pattern_by_seed_name_resolves_it_to_the_id() {
|
||||
let mut s = plate_with_hole();
|
||||
run(&mut s, "solid.pattern.rectangular", json!({"features": ["Hole1"], "dir1": [1, 0, 0], "count1": 2, "spacing1": 20, "name": "Copies"}));
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Hole1", "name": "Single hole"}));
|
||||
run(&mut s, "timeline.edit", json!({"feature": "Copies", "set": {"features": ["Single hole"]}}));
|
||||
let inspected = run(&mut s, "timeline.inspect", json!({"feature": "Copies"}));
|
||||
assert!(inspected["error"].is_null(), "{inspected}");
|
||||
let hole = s.doc.find_feature("Single hole").unwrap().id;
|
||||
assert_eq!(inspected["definition"]["features"], json!([hole]), "{inspected}");
|
||||
// A name that finds no feature is refused, as the commands that take names refuse it.
|
||||
let e = s.execute("timeline.edit", &json!({"feature": "Copies", "set": {"features": ["Nope"]}})).unwrap_err().to_string();
|
||||
assert!(e.contains("Nope"), "{e}");
|
||||
}
|
||||
|
||||
/// A plate with a `count1` × `count2` feature pattern of one through-hole cut: its volume and how
|
||||
|
||||
@@ -35,7 +35,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.get("feature")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| bad(cmd, "`feature` must be a feature object, as a design file or timeline.inspect has it"))?;
|
||||
let feature = recorded_feature(cmd, raw)?;
|
||||
let mut raw = raw.clone();
|
||||
resolve_legacy_names(&mut raw, &s.doc);
|
||||
let feature = recorded_feature(cmd, &raw)?;
|
||||
let params = step_params(cmd, p.get("params"))?;
|
||||
let id = s.doc_mut().insert_feature(feature, params)?;
|
||||
s.refresh();
|
||||
@@ -44,6 +46,58 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"feature": id, "name": name, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone())}))
|
||||
}
|
||||
|
||||
/// timeline.add keeps accepting legacy name-keyed pattern and mirror seeds and construction
|
||||
/// plane names (#1134): a script recorded before these references were keyed by id resolves
|
||||
/// them against the design as it stands, exactly the way opening a saved design migrates them
|
||||
/// (`format::pending::feature_id_refs`) — a name that finds no feature keeps id 0, which
|
||||
/// dangles at evaluation with the same warning or error it always gave.
|
||||
fn resolve_legacy_names(raw: &mut Map<String, Value>, doc: &Document) {
|
||||
let kind = raw.get("type").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
// A pattern's or mirror's seeds: each name becomes the feature's id.
|
||||
if matches!(kind.as_str(), "pattern" | "mirror")
|
||||
&& let Some(Value::Array(seeds)) = raw.get_mut("features")
|
||||
{
|
||||
for seed in seeds.iter_mut() {
|
||||
if let Value::String(name) = seed {
|
||||
let name = name.clone();
|
||||
*seed = json!(doc.seed_feature(&name).map(|f| f.id).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Construction plane references, everywhere but a revolve's axis: an
|
||||
// `AxisRef::Construction` has the same shape but names a construction axis, which is
|
||||
// still keyed by name.
|
||||
let skip_axis = matches!(kind.as_str(), "revolve" | "surface_revolve");
|
||||
for (key, v) in raw.iter_mut() {
|
||||
if !(skip_axis && key == "axis") {
|
||||
resolve_plane_refs(v, doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrite every `{"type": "construction", "name": …}` plane reference in `v` to carry the
|
||||
/// feature's id, resolved by `Document::find_feature`; nothing is id 0.
|
||||
fn resolve_plane_refs(v: &mut Value, doc: &Document) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("type").and_then(Value::as_str) == Some("construction") {
|
||||
if let Some(name) = o.get("name").and_then(Value::as_str) {
|
||||
let name = name.to_string();
|
||||
let id = doc.find_feature(&name).map(|f| f.id).unwrap_or(0);
|
||||
o.remove("name");
|
||||
o.insert("feature".into(), json!(id));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (_, x) in o.iter_mut() {
|
||||
resolve_plane_refs(x, doc);
|
||||
}
|
||||
}
|
||||
Value::Array(a) => a.iter_mut().for_each(|x| resolve_plane_refs(x, doc)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The feature, through the checks a design file gets when it opens (numbers, sketch sizes, 3D
|
||||
/// curves, face attachments…), so a script step can hold nothing a design could not.
|
||||
fn recorded_feature(cmd: &str, raw: &Map<String, Value>) -> Result<Feature> {
|
||||
|
||||
@@ -293,3 +293,36 @@ fn a_replayed_feature_keeps_a_name_another_feature_has() {
|
||||
);
|
||||
assert_eq!(r["name"], "Box1");
|
||||
}
|
||||
|
||||
/// #1134: a script recorded before pattern and mirror seeds and construction planes were
|
||||
/// keyed by id names them by name; timeline.add resolves the names to ids exactly the way
|
||||
/// opening a saved design migrates them, and a name that finds no feature keeps id 0, which
|
||||
/// dangles at evaluation with the same error it always gave.
|
||||
#[test]
|
||||
fn add_resolves_legacy_seed_and_plane_names() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": "5", "width": "5", "height": "5", "name": "Base"}));
|
||||
run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Shelf"}));
|
||||
let base = s.doc.find_feature("Base").unwrap().id;
|
||||
let shelf = s.doc.find_feature("Shelf").unwrap().id;
|
||||
let r = run(
|
||||
&mut s,
|
||||
"timeline.add",
|
||||
json!({"feature": {"type": "mirror", "name": "Copied", "features": ["Base"], "plane": {"type": "construction", "name": "Shelf"}}}),
|
||||
);
|
||||
assert!(r["error"].is_null(), "{r}");
|
||||
let kind = serde_json::to_value(&s.doc.find_feature("Copied").unwrap().kind).unwrap();
|
||||
assert_eq!(kind["features"], json!([base]), "{kind}");
|
||||
assert_eq!(kind["plane"], json!({"type": "construction", "feature": shelf}), "{kind}");
|
||||
// A name that finds no feature keeps id 0: the mirror fails at evaluation, as a design
|
||||
// migrated with a dangling seed does.
|
||||
let r = run(
|
||||
&mut s,
|
||||
"timeline.add",
|
||||
json!({"feature": {"type": "mirror", "name": "Lost", "features": ["Nope"], "plane": {"type": "construction", "name": "Gone"}}}),
|
||||
);
|
||||
assert!(!r["error"].is_null(), "a dangling seed fails at evaluation: {r}");
|
||||
let kind = serde_json::to_value(&s.doc.find_feature("Lost").unwrap().kind).unwrap();
|
||||
assert_eq!(kind["features"], json!([0]), "{kind}");
|
||||
assert_eq!(kind["plane"], json!({"type": "construction", "feature": 0}), "{kind}");
|
||||
}
|
||||
|
||||
@@ -35,14 +35,16 @@ fn section(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A construction plane (name or id): where it is now.
|
||||
Some(v @ (Value::String(_) | Value::Number(_))) => {
|
||||
let r = super::features::plane_param(s, Some(v), cmd)?;
|
||||
let solidcraft_doc::PlaneRef::Construction { name } = &r else { return Err(bad(cmd, "`plane` must be a plane")) };
|
||||
let solidcraft_doc::PlaneRef::Construction { feature } = &r else { return Err(bad(cmd, "`plane` must be a plane")) };
|
||||
let st = s.model.state();
|
||||
let pl = st
|
||||
let c = st
|
||||
.construct
|
||||
.iter()
|
||||
.find(|c| &c.name == name)
|
||||
.and_then(|c| if let solidcraft_doc::construct::ConstructGeom::Plane(pl) = &c.geom { Some(*pl) } else { None })
|
||||
.ok_or_else(|| bad(cmd, format!("construction plane `{name}` is not built (rolled back, suppressed or failed)")))?;
|
||||
.find(|c| c.feature == feature.0)
|
||||
.ok_or_else(|| bad(cmd, format!("construction plane `{feature}` is not built (rolled back, suppressed or failed)")))?;
|
||||
let solidcraft_doc::construct::ConstructGeom::Plane(pl) = &c.geom else {
|
||||
return Err(bad(cmd, format!("construction plane `{}` is not built (rolled back, suppressed or failed)", c.name)));
|
||||
};
|
||||
(pl.origin, pl.normal(), None)
|
||||
}
|
||||
Some(o @ Value::Object(_)) => {
|
||||
|
||||
@@ -1581,7 +1581,9 @@ mod tests {
|
||||
run(&mut s, "timeline.rename", json!({"feature": "Cut", "name": "Cutter"}));
|
||||
assert!(s.model.results.iter().all(|r| r.error.is_none()), "the trim still finds its plane");
|
||||
let def = run(&mut s, "timeline.inspect", json!({"feature": "Trim"}));
|
||||
assert_eq!(def["definition"]["plane"]["name"], "Cutter", "{def}");
|
||||
// The trim keeps its plane by id (#1134): the rename changed nothing in the reference.
|
||||
let cutter = s.doc.find_feature("Cutter").unwrap().id;
|
||||
assert_eq!(def["definition"]["plane"], serde_json::json!({"type": "construction", "feature": cutter}), "{def}");
|
||||
assert!((area(&s, "Sheet") - trimmed).abs() < 1e-6, "{} vs {trimmed}", area(&s, "Sheet"));
|
||||
assert!(trimmed < 40.0 * 20.0 * 0.9, "the sheet is trimmed: {trimmed}");
|
||||
}
|
||||
|
||||
@@ -4965,7 +4965,7 @@ fn geo_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Option
|
||||
pub(crate) fn plane_sel(s: &Session, pl: &PlaneRef) -> Option<Sel> {
|
||||
match pl {
|
||||
PlaneRef::Origin { name } => Some(Sel::Plane { name: name.clone() }),
|
||||
PlaneRef::Construction { name } => Some(Sel::Plane { name: name.to_string() }),
|
||||
PlaneRef::Construction { feature } => s.doc.feature(feature.0).map(|f| Sel::Plane { name: f.name.clone() }),
|
||||
PlaneRef::Custom { plane } => face_sel(s, plane.origin),
|
||||
// The point picked on the face: the plane's origin can lie off the face (#3567).
|
||||
PlaneRef::Face { at, .. } => face_sel(s, *at),
|
||||
@@ -5451,7 +5451,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
|
||||
}
|
||||
FeatureKind::Mirror { features, plane, bodies, placements, .. } => {
|
||||
let mut d = start("solid.mirror")?;
|
||||
let ids: Vec<u64> = features.iter().filter_map(|n| s.doc.find_feature(n).map(|f| f.id)).collect();
|
||||
let ids: Vec<u64> = features.iter().map(|f| f.0).collect();
|
||||
// Replay references stay features, including features that created a body.
|
||||
let as_features = !features.is_empty();
|
||||
if let Some(inp) = d.inputs.get_mut(0) {
|
||||
@@ -5477,7 +5477,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
|
||||
d
|
||||
}
|
||||
FeatureKind::Pattern { features, pattern, bodies: copied } => {
|
||||
let ids: Vec<u64> = features.iter().filter_map(|n| s.doc.find_feature(n).map(|f| f.id)).collect();
|
||||
let ids: Vec<u64> = features.iter().map(|f| f.0).collect();
|
||||
let bodies: Vec<Sel> = if copied.is_empty() {
|
||||
st.bodies.iter().filter(|b| ids.contains(&b.feature)).map(|b| Sel::Body { name: b.name.clone() }).collect()
|
||||
} else {
|
||||
|
||||
@@ -1023,8 +1023,9 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K
|
||||
Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Origin { name })) => {
|
||||
extra.insert("up_to".into(), json!(name));
|
||||
}
|
||||
Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Construction { name })) => {
|
||||
extra.insert("up_to".into(), json!(name));
|
||||
Some(solidcraft_engine::doc::ExtendTo::Plane(PlaneRef::Construction { feature })) => {
|
||||
let shown = s.doc.feature(feature.0).map(|f| json!(f.name)).unwrap_or_else(|| json!(feature.0));
|
||||
extra.insert("up_to".into(), shown);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -102,12 +102,14 @@ pub fn face_plane(app: &SolveApp, selection: &Sel) -> Option<Value> {
|
||||
|
||||
/// What a sketch's plane is, for the Redefine Sketch Plane panel: `XY`, a construction plane's
|
||||
/// name, or the plane it's offset from, turned from or flipped from (#5103).
|
||||
pub(crate) fn plane_description(plane: &PlaneRef) -> String {
|
||||
fn describe(plane: &PlaneRef, depth: usize) -> String {
|
||||
let base = |b: &PlaneRef| if depth < 8 { describe(b, depth + 1) } else { crate::i18n::tr("sketch_panel.plane_fixed").to_owned() };
|
||||
pub(crate) fn plane_description(doc: &solidcraft_engine::doc::Document, plane: &PlaneRef) -> String {
|
||||
fn describe(doc: &solidcraft_engine::doc::Document, plane: &PlaneRef, depth: usize) -> String {
|
||||
let base = |b: &PlaneRef| if depth < 8 { describe(doc, b, depth + 1) } else { crate::i18n::tr("sketch_panel.plane_fixed").to_owned() };
|
||||
match plane {
|
||||
PlaneRef::Origin { name } => crate::i18n::format("sketch_panel.plane_origin", &[("plane", name)]),
|
||||
PlaneRef::Construction { name } => name.to_string(),
|
||||
PlaneRef::Construction { feature } => {
|
||||
doc.feature(feature.0).map(|f| f.name.clone()).unwrap_or_else(|| crate::i18n::tr("sketch_panel.plane_fixed").to_owned())
|
||||
}
|
||||
PlaneRef::Offset { base: b, distance } => {
|
||||
crate::i18n::format("sketch_panel.plane_offset", &[("plane", &base(b)), ("distance", distance)])
|
||||
}
|
||||
@@ -116,7 +118,7 @@ pub(crate) fn plane_description(plane: &PlaneRef) -> String {
|
||||
_ => crate::i18n::tr("sketch_panel.plane_fixed").to_owned(),
|
||||
}
|
||||
}
|
||||
describe(plane, 0)
|
||||
describe(doc, plane, 0)
|
||||
}
|
||||
|
||||
fn face_label(app: &SolveApp, selection: &Sel) -> String {
|
||||
@@ -225,7 +227,7 @@ pub fn panel(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
FaceAttachmentStatus::Fixed { plane } => {
|
||||
// Name the plane it's on now: an origin or construction plane (#5103).
|
||||
if let Some(FeatureKind::Sketch { plane: on, .. }) = app.session.doc.feature(sketch).map(|f| &f.kind) {
|
||||
let now = plane_description(on);
|
||||
let now = plane_description(&app.session.doc, on);
|
||||
ui_kit::row(ui, "Current plane", |ui| {
|
||||
ui.label(now);
|
||||
});
|
||||
|
||||
@@ -413,10 +413,10 @@ fn redefine_panel_names_the_plane_a_sketch_is_on() {
|
||||
let id = h.app.run("sketch.create", json!({"plane": plane})).unwrap()["sketch"].as_u64().unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
let FeatureKind::Sketch { plane: on, .. } = &h.app.session.doc.feature(id).unwrap().kind else { panic!("a sketch") };
|
||||
assert_eq!(plane_description(on), expected, "{plane}");
|
||||
assert_eq!(plane_description(&h.app.session.doc, on), expected, "{plane}");
|
||||
}
|
||||
let xy = Box::new(PlaneRef::Origin { name: "XY".into() });
|
||||
let offset = PlaneRef::Offset { base: xy.clone(), distance: "12 mm".into() };
|
||||
assert_eq!(plane_description(&offset), "The XY plane, offset by 12 mm");
|
||||
assert_eq!(plane_description(&PlaneRef::Flipped { base: xy, about_y: false }), "The XY plane, from its other side");
|
||||
assert_eq!(plane_description(&h.app.session.doc, &offset), "The XY plane, offset by 12 mm");
|
||||
assert_eq!(plane_description(&h.app.session.doc, &PlaneRef::Flipped { base: xy, about_y: false }), "The XY plane, from its other side");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user