Skip to content

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

Sketch: a sketch that lost a projected edge opens for editing with its curves and the lost link marked (#12085) (#12714)

PaddleStrokefd02123b3e7f
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index 5de3e43319..5c0721d5c5 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1161,6 +1161,18 @@ pub struct Model {
placement_inputs: Option<placement_reuse::Inputs>,
/// All evaluated features use supported local inputs; computed with the existing owner index.
placement_local: bool,
+ /// A failed sketch shown while it is edited ([`Model::hold_failed_sketch`]).
+ held: Option<HeldSketch>,
+}
+
+/// A failed sketch built for its editor (#12085): `shown` is the final state `base` with that
+/// sketch in it. [`Model::state`] gives it only while the results still end in `base`, so the
+/// next evaluation, or anything else that changes the results, lets it go.
+#[derive(Clone, Debug)]
+struct HeldSketch {
+ feature: u64,
+ base: Arc<ModelState>,
+ shown: Arc<ModelState>,
}
/// Parameters a feature uses directly (inputs, sketch dimensions and the expressions of a
@@ -2004,9 +2016,56 @@ impl Model {
/// The final model state.
pub fn state(&self) -> Arc<ModelState> {
+ let last = self.evaluated_state();
+ match &self.held {
+ Some(held) if Arc::ptr_eq(&held.base, &last) => held.shown.clone(),
+ _ => last,
+ }
+ }
+
+ /// The state after the last feature evaluated, without a failed sketch held for its editor.
+ fn evaluated_state(&self) -> Arc<ModelState> {
self.results.iter().rev().find(|r| !r.skipped).map(|r| r.state.clone()).unwrap_or_else(|| self.empty.clone())
}
+ /// Show the sketch `feature` while it is edited although it failed (#12085): a link whose
+ /// named face or edge is gone fails the sketch, so the evaluation keeps no sketch for it, and
+ /// its editor had nothing to show or repair. Here the sketch is built as it is evaluated, but
+ /// with such a link marked lost and kept where it was (no other face or edge is taken for
+ /// it), and added to the final state only: the sketch's result keeps its error and the
+ /// features after it still fail. `None`, a sketch that did not fail, or one that fails for
+ /// another reason too, shows nothing more. Returns whether a held sketch is shown.
+ pub fn hold_failed_sketch(&mut self, doc: &Document, feature: Option<u64>) -> bool {
+ let Some(id) = feature else {
+ self.held = None;
+ return false;
+ };
+ let base = self.evaluated_state();
+ if self.held.as_ref().is_some_and(|held| held.feature == id && Arc::ptr_eq(&held.base, &base)) {
+ return true;
+ }
+ self.held = None;
+ if base.sketch(id).is_some() || !self.result(id).is_some_and(|r| r.error.is_some() && !r.skipped && !r.stale) {
+ return false;
+ }
+ let Some(f) = doc.feature(id) else { return false };
+ let FeatureKind::Sketch { plane, sketch } = &f.kind else { return false };
+ let mut next = (*self.state_before(id)).clone();
+ let vals = evaluation_values(doc).0;
+ let mut warning = None;
+ let built = kernel::guard(&f.name, || {
+ let _frames = ToolFrames::install(doc, f, &next);
+ eval_sketch(doc, &vals, f, plane, sketch, &mut next, &mut warning, crate::project::LostNames::Mark)
+ .map_err(|e| kernel::KernelError::Failed(e.to_string()))
+ });
+ let Some(solved) = built.ok().and_then(|()| next.sketches.iter().find(|s| s.feature == id).cloned()) else { return false };
+ let mut shown = (*base).clone();
+ shown.sketches.retain(|s| s.feature != id);
+ shown.sketches.push(solved);
+ self.held = Some(HeldSketch { feature: id, base, shown: Arc::new(shown) });
+ true
+ }
+
/// State just before the feature with this id (for editing a sketch in context).
pub fn state_before(&self, id: u64) -> Arc<ModelState> {
let Some(i) = self.results.iter().position(|r| r.id == id) else { return self.state() };
@@ -2170,6 +2229,10 @@ impl Model {
/// Re-evaluate the document, reusing results up to the first changed feature.
pub fn evaluate(&mut self, doc: &Document) {
+ // A failed sketch held for its editor is built again from the evaluated design: when the
+ // sketch and every feature after it fail, the results end in the state they ended in
+ // before, which would keep showing the sketch as it was before the edit.
+ self.held = None;
let _span = solidcraft_profile::span("doc", "evaluate");
self.placement_inputs = None;
self.fingerprinted = None;
@@ -7406,72 +7469,7 @@ fn eval_feature(
| FeatureKind::ReplaceFace { .. }
| FeatureKind::Align { .. }
| FeatureKind::Remove { .. } => more::eval(doc, vals, f, st, warning),
- FeatureKind::Sketch { plane, sketch } => {
- let anchor = crate::face_anchor::plane_face_anchor(plane);
- let fst = match anchor {
- Some(anchor) => crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?,
- // A sketch that reads no geometry (a fixed plane, no projections) needs no other
- // component's bodies moved into its frame: placing every body of a large
- // assembly again is what made each sketch edit as slow as the design is big.
- None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st),
- None => state_in_frame(doc, st, f.component)?,
- };
- // A further placement a link reads is placed in its frame too (#9957).
- let named: Vec<&str> = sketch.links.iter().flat_map(|l| l.source.bodies()).collect();
- let fst = match anchor.map(|anchor| anchor.author_frame(doc, f.component)) {
- _ if named.is_empty() => fst,
- Some(Ok(frame)) => with_placed_copies(doc, st, fst, &frame, &named),
- Some(Err(_)) => fst,
- None => with_placed_copies(doc, st, fst, &doc.component_transform(f.component), &named),
- };
- let (plane, face_warning) = match (anchor, plane) {
- (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?,
- // A flat face of a sheet: the panel's exact plane, from its flat region and fold.
- (None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => {
- (doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None)
- }
- (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref())?,
- (None, other) => (doc.resolve_plane_in(vals, other, 0, Some(&fst))?, None),
- };
- let mut sk = sketch.clone();
- // A text's outlines are rebuilt from its numbers when the links are refreshed: the
- // ones its expressions give come first.
- doc.apply_text_values(vals, &mut sk)?;
- let mut warns = match anchor {
- Some(anchor) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor)?,
- None => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk)?,
- };
- drop(fst);
- sk.refresh_offsets()?;
- if let Some(w) = face_warning {
- warns.insert(0, w);
- }
- // The stored sketch is solved for its stored values, with its links where they
- // were stored: a link that moved must not change the side a dimension from it is on.
- let stored = sk.driving_values();
- let report = doc.solve_sketch(vals, &mut sk, &stored, Some(sketch))?;
- if !report.keeps_orientation() {
- warns.insert(0, report.failure(|f| format!("the sketch constraints conflict ({f})")));
- } else {
- // The solve may have moved the curve a text runs along.
- warns.extend(crate::project::relay_path_texts(&mut sk));
- }
- if !warns.is_empty() {
- *warning = Some(warns.join("; "));
- }
- sk.validate_periodic_splines()?;
- // A group of touching curves too large to search whole says so, rather than
- // leaving profiles out silently (#6896).
- let search = solidcraft_sketch::find_profiles_checked(&sk);
- if search.incomplete {
- append_warning(warning, profiles_cut_short_note());
- }
- let profiles = search.profiles;
- let ends = solidcraft_sketch::loose_ends(&sk);
- st.sketches.retain(|s| s.feature != f.id);
- st.sketches.push(Arc::new(SolvedSketch { feature: f.id, name: f.name.clone(), plane, sketch: sk, report, profiles, ends }));
- Ok(())
- }
+ FeatureKind::Sketch { plane, sketch } => eval_sketch(doc, vals, f, plane, sketch, st, warning, crate::project::LostNames::Fail),
FeatureKind::Extrude { operation, targets, .. }
| FeatureKind::Pipe { operation, targets, .. }
| FeatureKind::Revolve { operation, targets, .. }
@@ -8290,6 +8288,88 @@ fn eval_feature(
}
}
+/// A sketch feature: its links refreshed against the model before it, solved, its profiles
+/// found. `lost_names` says what a link whose named face or edge is gone does: the evaluation
+/// fails the sketch ([`crate::project::LostNames::Fail`]); a failed sketch shown for editing
+/// marks the link lost instead ([`Model::hold_failed_sketch`]).
+#[allow(clippy::too_many_arguments)]
+fn eval_sketch(
+ doc: &Document,
+ vals: &BTreeMap<String, Value>,
+ f: &Feature,
+ plane: &PlaneRef,
+ sketch: &solidcraft_sketch::Sketch,
+ st: &mut ModelState,
+ warning: &mut Option<String>,
+ lost_names: crate::project::LostNames,
+) -> Result<()> {
+ let anchor = crate::face_anchor::plane_face_anchor(plane);
+ let fst = match anchor {
+ Some(anchor) => crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?,
+ // A sketch that reads no geometry (a fixed plane, no projections) needs no other
+ // component's bodies moved into its frame: placing every body of a large
+ // assembly again is what made each sketch edit as slow as the design is big.
+ None if !plane_reads_geometry(plane) && sketch.links.is_empty() => std::borrow::Cow::Borrowed(st),
+ None => state_in_frame(doc, st, f.component)?,
+ };
+ // A further placement a link reads is placed in its frame too (#9957).
+ let named: Vec<&str> = sketch.links.iter().flat_map(|l| l.source.bodies()).collect();
+ let fst = match anchor.map(|anchor| anchor.author_frame(doc, f.component)) {
+ _ if named.is_empty() => fst,
+ Some(Ok(frame)) => with_placed_copies(doc, st, fst, &frame, &named),
+ Some(Err(_)) => fst,
+ None => with_placed_copies(doc, st, fst, &doc.component_transform(f.component), &named),
+ };
+ let (plane, face_warning) = match (anchor, plane) {
+ (Some(_), plane) => doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?,
+ // A flat face of a sheet: the panel's exact plane, from its flat region and fold.
+ (None, plane) if crate::sheet::plane_sheet_face(plane).is_some() => {
+ (doc.resolve_plane_in(vals, &sheet_face_plane_in_frame(doc, st, f.component, plane)?, 0, Some(&fst))?, None)
+ }
+ (None, PlaneRef::Face { plane: picked, at, name, anchor: None }) => face_plane(&fst, picked, *at, name.as_deref())?,
+ (None, other) => (doc.resolve_plane_in(vals, other, 0, Some(&fst))?, None),
+ };
+ let mut sk = sketch.clone();
+ // A text's outlines are rebuilt from its numbers when the links are refreshed: the
+ // ones its expressions give come first.
+ doc.apply_text_values(vals, &mut sk)?;
+ let mut warns = match (anchor, lost_names) {
+ (Some(anchor), crate::project::LostNames::Fail) => crate::project::refresh_face_anchor_links(doc, vals, &fst, &plane, &mut sk, anchor)?,
+ (None, crate::project::LostNames::Fail) => crate::project::refresh_links(doc, vals, &fst, &plane, &mut sk)?,
+ (anchor, crate::project::LostNames::Mark) => crate::project::refresh_links_marking_lost(doc, vals, &fst, &plane, &mut sk, anchor)?,
+ };
+ drop(fst);
+ sk.refresh_offsets()?;
+ if let Some(w) = face_warning {
+ warns.insert(0, w);
+ }
+ // The stored sketch is solved for its stored values, with its links where they
+ // were stored: a link that moved must not change the side a dimension from it is on.
+ let stored = sk.driving_values();
+ let report = doc.solve_sketch(vals, &mut sk, &stored, Some(sketch))?;
+ if !report.keeps_orientation() {
+ warns.insert(0, report.failure(|f| format!("the sketch constraints conflict ({f})")));
+ } else {
+ // The solve may have moved the curve a text runs along.
+ warns.extend(crate::project::relay_path_texts(&mut sk));
+ }
+ if !warns.is_empty() {
+ *warning = Some(warns.join("; "));
+ }
+ sk.validate_periodic_splines()?;
+ // A group of touching curves too large to search whole says so, rather than
+ // leaving profiles out silently (#6896).
+ let search = solidcraft_sketch::find_profiles_checked(&sk);
+ if search.incomplete {
+ append_warning(warning, profiles_cut_short_note());
+ }
+ let profiles = search.profiles;
+ let ends = solidcraft_sketch::loose_ends(&sk);
+ st.sketches.retain(|s| s.feature != f.id);
+ st.sketches.push(Arc::new(SolvedSketch { feature: f.id, name: f.name.clone(), plane, sketch: sk, report, profiles, ends }));
+ Ok(())
+}
+
/// `copy`, a moved copy of `source` (instance `instance` of a pattern or mirror): its faces are
/// named after the source's.
fn moved_copy(source: &ModelBody, copy: Body, instance: usize) -> Traced {
diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs
index b4bf99f1f1..8856406c37 100644
--- a/crates/doc/src/project.rs
+++ b/crates/doc/src/project.rs
@@ -912,7 +912,31 @@ pub fn refresh_face_anchor_links(
sk: &mut Sketch,
anchor: &crate::FaceAnchor,
) -> Result<Vec<String>> {
- refresh_links_in(doc, vals, st, plane, sk, Some(anchor))
+ refresh_links_in(doc, vals, st, plane, sk, Some(anchor), LostNames::Fail)
+}
+
+/// What a link kept by the name of a face or edge does when the name finds nothing any more.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum LostNames {
+ /// The sketch fails, asking for the reference to be picked again ([`DocError::Reselect`]).
+ Fail,
+ /// The link is marked lost and keeps its last geometry, with a warning naming the reference.
+ /// No other face or edge is taken for it. Only for showing a failed sketch while it is edited
+ /// (#12085), never for the evaluation the features after it build from.
+ Mark,
+}
+
+/// [`refresh_links`] (or [`refresh_face_anchor_links`] with `anchor`) that marks a link whose
+/// named face or edge is gone lost instead of failing ([`LostNames::Mark`]).
+pub(crate) fn refresh_links_marking_lost(
+ doc: &Document,
+ vals: &BTreeMap<String, Value>,
+ st: &ModelState,
+ plane: &Plane,
+ sk: &mut Sketch,
+ anchor: Option<&crate::FaceAnchor>,
+) -> Result<Vec<String>> {
+ refresh_links_in(doc, vals, st, plane, sk, anchor, LostNames::Mark)
}
/// Remove degree-two straight stations introduced by coplanar face subdivision.
@@ -989,7 +1013,7 @@ fn merge_family_lines(geom: Vec<LinkGeom>) -> Result<Vec<LinkGeom>> {
/// longer finds exactly that face or edge is not lost: the sketch fails, asking for the
/// reference to be picked again ([`DocError::Reselect`]).
pub fn refresh_links(doc: &Document, vals: &BTreeMap<String, Value>, st: &ModelState, plane: &Plane, sk: &mut Sketch) -> Result<Vec<String>> {
- refresh_links_in(doc, vals, st, plane, sk, None)
+ refresh_links_in(doc, vals, st, plane, sk, None, LostNames::Fail)
}
/// Lay every text that runs along a curve of its sketch along that curve as the solve left it.
@@ -1025,6 +1049,7 @@ fn refresh_links_in(
plane: &Plane,
sk: &mut Sketch,
anchor: Option<&crate::FaceAnchor>,
+ lost_names: LostNames,
) -> Result<Vec<String>> {
let mut warn = Vec::new();
let links = sk.links.clone();
@@ -1034,16 +1059,17 @@ fn refresh_links_in(
if !l.auto_face
&& let (Some(name), LinkSource::Face { body, at }) = (&l.face_name, &mut source)
{
- let (index, p) = st
- .body(body)
- .and_then(|target| {
- if l.kind == LinkKind::Project {
- crate::name_lookup::locate_projected_face(target, name, *at)
- } else {
- crate::naming::face_on_body(target, name, *at)
- }
- })
- .ok_or_else(|| DocError::reselect(name.as_str()))?;
+ let found = st.body(body).and_then(|target| {
+ if l.kind == LinkKind::Project {
+ crate::name_lookup::locate_projected_face(target, name, *at)
+ } else {
+ crate::naming::face_on_body(target, name, *at)
+ }
+ });
+ let Some((index, p)) = found else {
+ lose_named(sk, &l.id, name, lost_names, &mut warn)?;
+ continue;
+ };
*at = p;
named_face = Some((body.clone(), index, p));
}
@@ -1051,7 +1077,10 @@ fn refresh_links_in(
// edge has the name any more no other edge is taken for it: the sketch fails.
let mut named_edge = None;
if let (Some(name), LinkSource::Edge { body, at }) = (&l.edge_name, &source) {
- let (body, hit) = locate_named_edge(st, body, name, *at).ok_or_else(|| DocError::reselect(name.as_str()))?;
+ let Some((body, hit)) = locate_named_edge(st, body, name, *at) else {
+ lose_named(sk, &l.id, name, lost_names, &mut warn)?;
+ continue;
+ };
warn.extend(hit.note(name).map(|note| format!("projected {note}")));
named_edge = Some((body, hit.edge, *at));
}
@@ -1119,6 +1148,19 @@ fn refresh_links_in(
Ok(warn)
}
+/// A link whose face or edge `name` finds nothing: the sketch fails asking for it again, or (only
+/// while a failed sketch is shown for editing) the link is marked lost, with a warning naming it.
+fn lose_named(sk: &mut Sketch, id: &str, name: &str, lost_names: LostNames, warn: &mut Vec<String>) -> Result<()> {
+ match lost_names {
+ LostNames::Fail => Err(DocError::reselect(name)),
+ LostNames::Mark => {
+ sk.set_link_lost(id, true);
+ warn.push(format!("projected reference lost: `{name}` no longer exists as it was picked; reselect it"));
+ Ok(())
+ }
+ }
+}
+
// ---------------------------------------------------------------------------------------------
// Model lookups
diff --git a/crates/engine/src/cmd/sketch_project_edge_tests.rs b/crates/engine/src/cmd/sketch_project_edge_tests.rs
index dee4d18713..60ab8fbb87 100644
--- a/crates/engine/src/cmd/sketch_project_edge_tests.rs
+++ b/crates/engine/src/cmd/sketch_project_edge_tests.rs
@@ -171,6 +171,59 @@ fn a_projected_edge_that_is_gone_fails_its_sketch_not_replaced() {
/// A boss 20 x 20 x 10 made as its own body on the plate and joined into it afterwards: no body
/// has the link's body name any more. The join left the boss's top edge from (30, 10, 30) to
/// (30, 30, 30) as it was, and the link finds it by its name on the body that has it now.
+/// A sketch that fails for an edge gone by name still opens for editing (#12085): its own circle
+/// and the projected line, kept where it was and marked lost, are there to repair. It still
+/// fails, as does the extrude built from it; deleting the lost projection repairs both.
+#[test]
+fn a_sketch_that_lost_its_projected_edge_opens_with_its_curves_and_the_link_marked_lost() {
+ let mut s = Session::default();
+ plate(&mut s);
+ run(&mut s, "solid.fillet", json!({"edges": [[100, 25, 20]], "radius": "4 mm", "name": "Round"}));
+ run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": true}));
+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "20 mm", "name": "Top"}));
+ let projected_curves = run(&mut s, "sketch.project", json!({"refs": [{"edge": [100, 25, 20], "body": "Body1"}]}))["created"]["curves"].clone();
+ run(&mut s, "sketch.circle.center", json!({"center": [50, 25], "radius": 10}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Top", "distance": "5 mm", "name": "Boss"}));
+ let top = s.doc.find_feature("Top").unwrap().id;
+ let boss_error = |s: &Session| s.model.result(s.doc.find_feature("Boss").unwrap().id).unwrap().error.clone();
+ let curves = |s: &mut Session| run(s, "sketch.inspect", json!({"sketch": "Top"}))["curves"].as_array().map_or(0, Vec::len);
+ let name = stored(&s).edge_name.unwrap();
+ run(&mut s, "timeline.suppress", json!({"feature": "Round", "suppressed": false}));
+ assert_eq!(reselect(&s), Some(name.clone()), "{}", trouble(&s));
+ assert!(s.model.state().sketch(top).is_none(), "a failed sketch not edited is not shown");
+ assert!(boss_error(&s).is_some());
+
+ run(&mut s, "sketch.edit", json!({"sketch": "Top"}));
+ assert_eq!(reselect(&s), Some(name.clone()), "still fails while edited");
+ assert!(boss_error(&s).is_some(), "the extrude does not build from the held sketch");
+ assert!(link(&s).lost);
+ assert_line(&s, 100.0, (0.0, 50.0), "kept where it was");
+ assert_eq!(curves(&mut s), 2, "the circle and the lost projection");
+ // Another edit keeps it shown, with what the edit added: the sketch and the extrude after it
+ // fail again, so the design ends in the same state as before the edit.
+ let has_point = |s: &Session| {
+ let st = s.model.state();
+ let sk = &st.sketch(top).unwrap().sketch;
+ (0..sk.points.len()).filter_map(|i| sk.point(i)).any(|p| (p.x - 10.0).abs() < 1e-6 && (p.y - 10.0).abs() < 1e-6)
+ };
+ assert!(!has_point(&s));
+ run(&mut s, "sketch.point", json!({"point": [10, 10]}));
+ assert!(link(&s).lost);
+ assert!(has_point(&s), "the held sketch shows the new point");
+ assert_eq!(curves(&mut s), 2);
+ run(&mut s, "sketch.finish", json!({}));
+ assert!(s.model.state().sketch(top).is_none(), "finished, it is not shown");
+
+ // Repaired from inside: the lost projection deleted.
+ run(&mut s, "sketch.edit", json!({"sketch": "Top"}));
+ run(&mut s, "sketch.delete", json!({"entities": projected_curves}));
+ run(&mut s, "sketch.finish", json!({}));
+ assert_eq!(trouble(&s), "");
+ assert_eq!(boss_error(&s), None);
+ assert!(s.doc.sketch(top).unwrap().links.is_empty());
+}
+
#[test]
fn a_projected_edge_whose_body_was_joined_into_another_is_found_there() {
let mut s = Session::default();
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 2fe4d78a76..9507faf68c 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1800,6 +1800,11 @@ impl Session {
Err(e)
}
};
+ // A sketch open for editing that failed (a projected edge lost by name) is still shown, its
+ // lost link marked, so it can be repaired from inside it (#12085).
+ if outermost {
+ self.model.hold_failed_sketch(&self.doc, self.active_sketch);
+ }
if let Some((before, changed, failed)) = crash_outcome {
// Refresh and body-name pinning can copy the shared document. Remember the final
// document, so the next command does not mistake that work for an outside edit