SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Profiles and cap attachments fall back to the best match when a sketch outline changes (#2897)
SS-ENa6b44ab0d32a
diff --git a/crates/doc/src/config_certificates.rs b/crates/doc/src/config_certificates.rsindex de7c51df12..5391f5be86 100644--- a/crates/doc/src/config_certificates.rs+++ b/crates/doc/src/config_certificates.rs@@ -823,7 +823,8 @@ impl Document {let stem = |index: usize| names.faces.get(index).map(|name| crate::naming::strip_piece(name));let seed: Vec<usize> =indices.into_iter().filter(|index| stem(*index).is_some_and(|name| name.starts_with(&own) && !name.contains('@'))).collect();- let ambiguous = || DocError::Unknown("attached planar face certificate is missing or ambiguous".into());+ let feature = self.feature(origin).map_or_else(|| format!("F{origin}"), |feature| feature.name.clone());+ let ambiguous = || DocError::Invalid(format!("the attached flat face of {feature} on `{}` is missing or ambiguous", body.name));let first = seed.first().and_then(|index| stem(*index)).ok_or_else(ambiguous)?;if seed.iter().any(|index| stem(*index) != Some(first)) {return Err(ambiguous());diff --git a/crates/doc/src/config_styles.rs b/crates/doc/src/config_styles.rsindex 1987f8c9ed..30ef3d7e82 100644--- a/crates/doc/src/config_styles.rs+++ b/crates/doc/src/config_styles.rs@@ -185,6 +185,24 @@ impl Document {}Ok(())}+ /// A face target for messages: its role on its feature where the certificate tells it, else+ /// its name, and its body (`the top cap of E1 on `Body1``).+ pub(crate) fn describe_face_target(&self, target: &ConfigFaceTarget) -> String {+ let feature = self.feature(target.origin_feature).map_or_else(|| format!("F{}", target.origin_feature), |f| f.name.clone());+ let end = |high: bool| if high { "top" } else { "bottom" };+ let role = match &target.certificate {+ Some(super::FaceCertificate::ExtrudeCap { high, .. }) | Some(super::FaceCertificate::CylinderCap { high }) => {+ format!("the {} cap", end(*high))+ }+ Some(super::FaceCertificate::Box { axis, high }) => {+ format!("the {}{} side", if *high { "+" } else { "-" }, ["x", "y", "z"].get(usize::from(*axis)).copied().unwrap_or("?"))+ }+ Some(super::FaceCertificate::ExtrudeSide { curve, .. }) => format!("the side along `{curve}`"),+ _ => format!("face `{}`", target.name),+ };+ format!("{role} of {feature} on `{}`", target.body)+ }+/// Verify the current named pieces describe one surface, not ambiguous generated roles.pub fn configuration_face_indices(&self, body: &crate::ModelBody, target: &ConfigFaceTarget) -> Result<Vec<usize>> {self.certify_config_face(target)?;@@ -248,7 +266,7 @@ impl Document {}).collect();if indices.is_empty() {- return Err(DocError::Unknown("attached planar face certificate is missing or ambiguous".into()));+ return Err(DocError::Invalid(format!("{} no longer exists", self.describe_face_target(target))));}return self.certified_pieces(body, indices, target.origin_feature);}diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex e8be713406..b250d864bc 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -1359,6 +1359,16 @@ impl Model {}),});if r.is_ok() {+ // Profiles picked by curves that no longer bound a profile exactly were found+ // by their best match: say which.+ let thin = matches!(&f.kind, FeatureKind::Extrude { thin: Some(_), .. });+ for (sketch, sel) in f.kind.profile_sels() {+ if let (false, Some(ss)) = (thin, state.sketch(sketch)) {+ for note in crate::profile_fallback_notes(ss, sel) {+ append_warning(&mut warning, note);+ }+ }+ }if let Some(note) = boolean_diagnostics.warning() {append_warning(&mut warning, note);}@@ -1480,8 +1490,11 @@ pub fn select_profiles(ss: &SolvedSketch, sel: &ProfileSel) -> Result<Vec<Region}v}+ // A curve loop that no longer bounds a profile exactly falls back to the best match; the+ // feature's warning says so (`profile_fallback_notes`).ProfileSel::Curves { .. } | ProfileSel::OffsetBoundaries { .. } | ProfileSel::WholeBoundaries { .. } => {- crate::profile_selection_indices(ss, sel)?+ crate::profile_selection_indices_lenient(ss, sel)?+ .0.into_iter().map(|index| {ps.get(index)@@ -4832,7 +4845,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:None => state_in_frame(doc, st, f.component),};let (plane, face_warning) = match (anchor, plane) {- (Some(_), plane) => (doc.resolve_attached_plane(vals, plane, f.component, st, &fst)?, None),+ (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)@@ -4991,7 +5004,11 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:let pl = match crate::face_anchor::plane_face_anchor(plane) {Some(anchor) => {let fst = crate::state_in_face_anchor_frame(doc, st, anchor, f.component)?;- doc.resolve_attached_plane(vals, plane, f.component, st, &fst)?+ let (pl, note) = doc.resolve_attached_plane_noted(vals, plane, f.component, st, &fst)?;+ if let Some(note) = note {+ append_warning(warning, note);+ }+ pl}// A plane of numbers alone reads no body: placing them all is the design's size.None if plane_is_fixed(plane) => doc.resolve_plane_in(vals, plane, 0, Some(st))?,diff --git a/crates/doc/src/face_anchor.rs b/crates/doc/src/face_anchor.rsindex 8d32d9268d..38633d2cac 100644--- a/crates/doc/src/face_anchor.rs+++ b/crates/doc/src/face_anchor.rs@@ -1,4 +1,5 @@-//! Exact ordinary face attachments. Missing identities never invoke a proximity fallback.+//! Exact ordinary face attachments. Missing identities never invoke a proximity fallback; the one+//! fallback is an extrude cap whose sketch loop changed (`Document::anchored_face_indices`).use crate::config::ConfigFaceTarget;use crate::{DocError, Document, EmbossFace, FeatureKind, Model, ModelBody, ModelState, PlaneRef, Result};use serde::{Deserialize, Serialize};@@ -104,22 +105,38 @@ impl Document {state: &ModelState,framed: &ModelState,) -> Result<Plane> {- fn replace(doc: &Document, plane: &mut PlaneRef, author: u64, state: &ModelState, depth: usize) -> Result<()> {+ self.resolve_attached_plane_noted(vals, plane, author, state, framed).map(|(plane, _)| plane)+ }++ /// [`Document::resolve_attached_plane`] with the note of an attachment found by fallback+ /// ([`Document::anchored_face_indices`]).+ pub fn resolve_attached_plane_noted(+ &self,+ vals: &std::collections::BTreeMap<String, crate::expr::Value>,+ plane: &PlaneRef,+ author: u64,+ state: &ModelState,+ framed: &ModelState,+ ) -> Result<(Plane, Option<String>)> {+ fn replace(doc: &Document, plane: &mut PlaneRef, author: u64, state: &ModelState, depth: usize) -> Result<Option<String>> {if depth > 64 {return Err(DocError::Invalid("attached plane nesting exceeds budget".into()));}match plane {- PlaneRef::Face { anchor: Some(anchor), .. } => *plane = PlaneRef::Custom { plane: doc.resolve_face_anchor(anchor, author, state)? },+ PlaneRef::Face { anchor: Some(anchor), .. } => {+ let (resolved, note) = doc.resolve_face_anchor_noted(anchor, author, state)?;+ *plane = PlaneRef::Custom { plane: resolved };+ Ok(note)+ }PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => {- replace(doc, base, author, state, depth + 1)?+ replace(doc, base, author, state, depth + 1)}- _ => {}+ _ => Ok(None),}- Ok(())}let mut resolved = plane.clone();- replace(self, &mut resolved, author, state, 0)?;- self.resolve_plane_in(vals, &resolved, 0, Some(framed))+ let note = replace(self, &mut resolved, author, state, 0)?;+ Ok((self.resolve_plane_in(vals, &resolved, 0, Some(framed))?, note))}}@@ -193,11 +210,92 @@ impl Document {Ok(anchor)}+ /// The faces an attachment stands for, and a note when they were found by fallback.+ ///+ /// An extrude's cap is certified by the loop of sketch curves around it, so editing that+ /// sketch's outline (a curve that now cuts the profile, a side deleted and drawn again, a+ /// notch trimmed into it) leaves no face with the exact certificate. The attachment then+ /// takes the cap of the same (solid) extrude, at the same end, from the same sketch, on the+ /// same body, whose loop shares the most of the stored curves, at least half of them (a tie+ /// is not guessed). It never does while the exact cap is still on another body (profiles+ /// reordered: the bodies swapped names). The note names what changed. Every other identity+ /// stays exact.+ pub(crate) fn anchored_face_indices(+ &self,+ state: &ModelState,+ body: &ModelBody,+ target: &ConfigFaceTarget,+ ) -> Result<(Vec<usize>, Option<String>)> {+ let error = match self.configuration_face_indices(body, target) {+ Ok(indices) => return Ok((indices, None)),+ Err(error) => error,+ };+ let Some(crate::config::FaceCertificate::ExtrudeCap { sketch, high, outer, holes }) = &target.certificate else { return Err(error) };+ let exact = |source: &Option<solidcraft_kernel::FaceSource>| {+ matches!(source, Some(solidcraft_kernel::FaceSource::CertifiedExtrudeCap { producer, sketch: from, high: end, outer: around, holes: inside, .. })+ if *producer == target.origin_feature && from == sketch && end == high && around == outer && inside == holes)+ };+ if state.bodies.iter().any(|other| other.body.face_sources().is_some_and(|sources| sources.iter().any(exact))) {+ return Err(error);+ }+ // A thin wall's cap is signed by the curves the wall follows: a wall along other curves+ // is another wall, whose cap never stands for this one.+ let solid = self.feature(target.origin_feature).is_some_and(|feature| matches!(feature.kind, FeatureKind::Extrude { thin: None, .. }));+ if !solid || self.certify_config_face(target).is_err() || body.body.is_mesh() || body.definition_name() != target.body {+ return Err(error);+ }+ // The producer's caps at that end, grouped by the loop each was made from.+ let mut caps: std::collections::BTreeMap<&Vec<String>, Vec<usize>> = std::collections::BTreeMap::new();+ for (index, source) in body.body.face_sources().into_iter().flatten().enumerate() {+ if let Some(solidcraft_kernel::FaceSource::CertifiedExtrudeCap { producer, sketch: from, high: end, outer: around, .. }) = source+ && *producer == target.origin_feature+ && from == sketch+ && end == high+ {+ caps.entry(around).or_default().push(index);+ }+ }+ let stored: std::collections::BTreeSet<&str> = outer.iter().map(String::as_str).collect();+ let shared = |around: &[String]| around.iter().filter(|id| stored.contains(id.as_str())).count();+ let best = caps.keys().map(|around| shared(around)).max().unwrap_or(0);+ if best == 0 || best.saturating_mul(2) < stored.len() {+ return Err(error);+ }+ let mut chosen = caps.iter().filter(|(around, _)| shared(around) == best);+ let (Some((around, indices)), None) = (chosen.next(), chosen.next()) else { return Err(error) };+ let indices = self.certified_pieces(body, indices.clone(), target.origin_feature).map_err(|_| error)?;+ let now: std::collections::BTreeSet<&str> = around.iter().map(String::as_str).collect();+ let list = |ids: Vec<&str>| ids.iter().map(|id| format!("`{id}`")).collect::<Vec<_>>().join(", ");+ let mut changes = Vec::new();+ let gone: Vec<&str> = stored.difference(&now).copied().collect();+ if !gone.is_empty() {+ changes.push(format!("{} no longer around it", list(gone)));+ }+ let new: Vec<&str> = now.difference(&stored).copied().collect();+ if !new.is_empty() {+ changes.push(format!("{} new", list(new)));+ }+ let feature = self.feature(target.origin_feature).map_or_else(|| format!("F{}", target.origin_feature), |f| f.name.clone());+ let note = format!(+ "the face this sketch sits on, {}, changed when its sketch was edited ({}); using the {} cap of {feature} as it is now",+ self.describe_face_target(target),+ changes.join(", "),+ if *high { "top" } else { "bottom" },+ );+ Ok((indices, Some(note)))+ }+pub fn resolve_face_anchor(&self, anchor: &FaceAnchor, author: u64, state: &ModelState) -> Result<Plane> {+ self.resolve_face_anchor_noted(anchor, author, state).map(|(plane, _)| plane)+ }++ /// [`Document::resolve_face_anchor`] with the note of an attachment found by fallback+ /// ([`Document::anchored_face_indices`]).+ pub fn resolve_face_anchor_noted(&self, anchor: &FaceAnchor, author: u64, state: &ModelState) -> Result<(Plane, Option<String>)> {anchor.validate()?;let body =state.body(&anchor.target.body).ok_or_else(|| DocError::Unknown(format!("attached body `{}` no longer exists", anchor.target.body)))?;- let indices = self.configuration_face_indices(body, &anchor.target)?;+ let (indices, note) = self.anchored_face_indices(state, body, &anchor.target)?;let first = indices.first().copied().ok_or_else(|| DocError::Unknown("attached face no longer exists".into()))?;let certificate = anchor.target.certificate.as_ref();let plane = self@@ -214,7 +312,9 @@ impl Document {let canonical = map_plane(&anchor.source_to_author(self, author, body)?, &plane)?;let origin = canonical.origin + canonical.x * anchor.coordinates[0] + canonical.y * anchor.coordinates[1];let x = canonical.x * anchor.x_axis[0] + canonical.y * anchor.x_axis[1];- Plane::new(origin, x, canonical.normal().cross(x)).ok_or_else(|| DocError::Invalid("attached sketch basis is degenerate".into()))+ let plane =+ Plane::new(origin, x, canonical.normal().cross(x)).ok_or_else(|| DocError::Invalid("attached sketch basis is degenerate".into()))?;+ Ok((plane, note))}pub fn sketch_face_attachment(&self, feature: u64, model: &Model) -> FaceAttachmentStatus {diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 628499ac0f..163a534336 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -44,7 +44,7 @@ mod points;mod profile_refs;pub mod progress;mod walk;-pub use profile_refs::{capture_profile_selection, profile_selection_indices};+pub use profile_refs::{capture_profile_selection, profile_fallback_notes, profile_selection_indices, profile_selection_indices_lenient};pub mod plastic;pub mod project;mod project3d;diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rsindex 60ebe98a26..88902445fa 100644--- a/crates/doc/src/profile_refs.rs+++ b/crates/doc/src/profile_refs.rs@@ -97,6 +97,124 @@ fn reserved_boundaries(ss: &SolvedSketch) -> Result<std::collections::BTreeMap<V/// Resolve exact selection identities to the solved sketch's current profile indices./// Complete reserved role sets follow their association; partial sets never expand.pub fn profile_selection_indices(ss: &SolvedSketch, selection: &ProfileSel) -> Result<Vec<usize>> {+ selection_indices(ss, selection, None)+}++/// [`profile_selection_indices`] for evaluating a feature: an ordinary curve loop that no longer+/// bounds a profile exactly (a curve now cuts the region, or a side was deleted and drawn again)+/// falls back to the profiles that best match it (`fallback_loop`) instead of failing, and says+/// so in the returned notes. Commands still check picks with the exact form.+pub fn profile_selection_indices_lenient(ss: &SolvedSketch, selection: &ProfileSel) -> Result<(Vec<usize>, Vec<String>)> {+ let mut notes = Vec::new();+ let indices = selection_indices(ss, selection, Some(&mut notes))?;+ Ok((indices, notes))+}++/// What a feature's profile selection falls back to when evaluated: one note per curve loop that+/// no longer bounds a profile exactly; empty when everything matched exactly (or nothing did).+pub fn profile_fallback_notes(ss: &SolvedSketch, selection: &ProfileSel) -> Vec<String> {+ if !matches!(selection, ProfileSel::Curves { .. }) || profile_selection_indices(ss, selection).is_ok() {+ return Vec::new();+ }+ profile_selection_indices_lenient(ss, selection).map(|(_, notes)| notes).unwrap_or_default()+}++fn quoted(ids: &[String]) -> String {+ ids.iter().map(|id| format!("`{id}`")).collect::<Vec<_>>().join(", ")+}++/// The profiles that best stand for an ordinary curve loop `curves` (the outer loop of a profile+/// when it was picked) that no longer bounds any profile exactly, with a note saying what changed.+/// `None` when nothing plausibly matches.+///+/// 1. All of its curves are still there and still close a loop on their own, but other curves+/// now cut the region inside: the pieces inside that loop that touch it, whose union is the+/// region that was picked (islands inside it stay holes, as they were).+/// 2. Otherwise the profile whose outer loop shares the most of its curves, at least half of+/// them; a tie goes to the one with the fewest curves the loop did not have, and a tie left+/// after that is not guessed.+///+/// Loops of offset curves and legacy graph-span multisets (a curve listed once per piece) keep+/// their exact meaning and never fall back.+fn fallback_loop(ss: &SolvedSketch, curves: &[String]) -> Option<(Vec<usize>, String)> {+ let stored: BTreeSet<&str> = curves.iter().map(String::as_str).collect();+ if stored.is_empty() || stored.len() != curves.len() || curves.len() > 512 || ss.profiles.len() > 10_000 {+ return None;+ }+ let sketch = &ss.sketch;+ let offset =+ |id: &str| sketch.offsets.iter().any(|offset| offset.owns_output(id)) || sketch.freeform_offsets.iter().any(|offset| offset.output == id);+ if stored.iter().any(|id| offset(id)) {+ return None;+ }+ let drawn = |id: &str| sketch.curves.iter().any(|curve| curve.id == id && !curve.construction && !curve.centerline);+ let touches = |profile: &solidcraft_sketch::Profile| profile.outer_curves.iter().any(|id| stored.contains(id.as_str()));+ // 1. The loop alone still closes: take the pieces of the region it bounds.+ if stored.iter().all(|id| drawn(id)) {+ let mut alone = sketch.clone();+ for curve in &mut alone.curves {+ if !stored.contains(curve.id.as_str()) {+ curve.construction = true;+ }+ }+ let loops = solidcraft_sketch::find_profiles(&alone);+ if let Ok(index) = solidcraft_sketch::profile_by_curves(&loops, curves)+ && let Some(region) = loops.get(index).map(|profile| &profile.region)+ {+ let pieces: Vec<usize> = ss+ .profiles+ .iter()+ .enumerate()+ .filter(|(_, profile)| touches(profile) && region.outer.contains(profile.region.interior_point()))+ .map(|(index, _)| index)+ .collect();+ if !pieces.is_empty() {+ let note = format!(+ "the profile of {} bounded by {} is cut by another curve now; using the {} pieces inside it",+ ss.name,+ quoted(curves),+ pieces.len()+ );+ return Some((pieces, note));+ }+ }+ }+ // 2. The closest loop by the curves it shares.+ let count = |profile: &solidcraft_sketch::Profile, inside: bool| {+ profile.outer_curves.iter().map(String::as_str).filter(|id| stored.contains(id) == inside).collect::<BTreeSet<_>>().len()+ };+ let best = ss.profiles.iter().map(|profile| count(profile, true)).max()?;+ if best == 0 || best.saturating_mul(2) < stored.len() {+ return None;+ }+ let tied: Vec<&solidcraft_sketch::Profile> = ss.profiles.iter().filter(|profile| count(profile, true) == best).collect();+ let fewest = tied.iter().map(|profile| count(profile, false)).min()?;+ let mut chosen = ss.profiles.iter().enumerate().filter(|(_, profile)| count(profile, true) == best && count(profile, false) == fewest);+ let (index, profile) = chosen.next()?;+ if chosen.next().is_some() {+ return None;+ }+ let now: BTreeSet<&str> = profile.outer_curves.iter().map(String::as_str).collect();+ let gone: Vec<String> = curves.iter().filter(|id| !now.contains(id.as_str())).cloned().collect();+ let new: Vec<String> = solidcraft_sketch::distinct_curves(&profile.outer_curves).into_iter().filter(|id| !stored.contains(id.as_str())).collect();+ let mut changes = Vec::new();+ if !gone.is_empty() {+ changes.push(format!("{} no longer on it", quoted(&gone)));+ }+ if !new.is_empty() {+ changes.push(format!("{} new", quoted(&new)));+ }+ let note = format!(+ "no profile of {} is bounded by exactly {} any more ({}); using the profile that shares {best} of its {} curves",+ ss.name,+ quoted(curves),+ changes.join(", "),+ curves.len()+ );+ Some((vec![index], note))+}++fn selection_indices(ss: &SolvedSketch, selection: &ProfileSel, mut notes: Option<&mut Vec<String>>) -> Result<Vec<usize>> {let indices = match selection {ProfileSel::All => (0..ss.profiles.len()).collect(),ProfileSel::Indices { indices } => indices.clone(),@@ -119,10 +237,25 @@ pub fn profile_selection_indices(ss: &SolvedSketch, selection: &ProfileSel) -> R{return Err(crate::curve_pick_error(solidcraft_sketch::CurvePick::Missing, curves, &ss.name));}- indices.push(- solidcraft_sketch::profile_by_curves(&ss.profiles, curves)- .map_err(|error| crate::curve_pick_error(error, curves, &ss.name))?,- );+ match solidcraft_sketch::profile_by_curves(&ss.profiles, curves) {+ Ok(index) => indices.push(index),+ Err(error) => {+ let fallback = match (&error, notes.as_deref_mut()) {+ (solidcraft_sketch::CurvePick::Missing, Some(notes)) => fallback_loop(ss, curves).map(|found| (found, notes)),+ _ => None,+ };+ let Some(((found, note), notes)) = fallback else {+ return Err(crate::curve_pick_error(error, curves, &ss.name));+ };+ notes.push(note);+ // Two loops that fell back to one piece take it once.+ for index in found {+ if !indices.contains(&index) {+ indices.push(index);+ }+ }+ }+ }}}indices@@ -385,6 +518,42 @@ mod tests {assert!(profile_selection_indices(&ss, &ProfileSel::Indices { indices: vec![1] }).is_err());}+ fn solved_square(extra: &[(&str, [f64; 4])]) -> SolvedSketch {+ let mut sketch = Sketch::new();+ let corners = [Vec2::new(0., 0.), Vec2::new(10., 0.), Vec2::new(10., 10.), Vec2::new(0., 10.)];+ let points: Vec<_> = corners.iter().map(|corner| sketch.add_point(*corner, None).unwrap()).collect();+ for (index, id) in ["a", "b", "c", "d"].iter().enumerate() {+ sketch.add_line_pts(points[index], points[(index + 1) % 4], Some(id)).unwrap();+ }+ for (id, [x0, y0, x1, y1]) in extra {+ let p = sketch.add_point(Vec2::new(*x0, *y0), None).unwrap();+ let q = sketch.add_point(Vec2::new(*x1, *y1), None).unwrap();+ sketch.add_line_pts(p, q, Some(id)).unwrap();+ }+ let report = solve(&mut sketch);+ let profiles = find_profiles(&sketch);+ SolvedSketch { feature: 1, name: "S".into(), plane: Plane::XY, sketch, report, profiles, ends: Default::default() }+ }++ #[test]+ fn a_split_loop_falls_back_to_its_pieces_only_when_evaluating() {+ let loops = ProfileSel::Curves { loops: vec![vec!["a".into(), "b".into(), "c".into(), "d".into()]] };+ let split = solved_square(&[("cut", [4., 0., 4., 10.])]);+ assert_eq!(split.profiles.len(), 2);+ assert!(profile_selection_indices(&split, &loops).is_err(), "a command's pick stays exact");+ let (indices, notes) = profile_selection_indices_lenient(&split, &loops).unwrap();+ assert_eq!(indices.len(), 2);+ assert!(notes[0].contains("cut by another curve now"), "{notes:?}");+ assert_eq!(profile_fallback_notes(&split, &loops), notes);+ let area: f64 = crate::select_profiles(&split, &loops).unwrap().iter().map(|region| region.area()).sum();+ assert!((area - 100.).abs() < 1e-9, "{area}");+ // Exact matches have no note; a loop sharing under half its curves matches nothing.+ let whole = solved_square(&[]);+ assert!(profile_fallback_notes(&whole, &loops).is_empty());+ let few = ProfileSel::Curves { loops: vec![vec!["a".into(), "x".into(), "y".into(), "z".into(), "w".into()]] };+ assert!(crate::select_profiles(&whole, &few).is_err());+ }+#[test]fn periodic_offset_ring_whole_source_survives_adaptive_spans_and_reopen() {let mut sketch = Sketch::new();diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rsindex 39e556f5cc..9c115c3d2c 100644--- a/crates/doc/src/project.rs+++ b/crates/doc/src/project.rs@@ -429,7 +429,8 @@ fn certified_planar_construction(body: &crate::ModelBody, index: usize) -> boolpub fn resolve_anchored_face(doc: &Document, st: &ModelState, plane: &Plane, kind: LinkKind, anchor: &crate::FaceAnchor) -> Result<Resolved> {let body = st.body(&anchor.target.body).ok_or_else(|| lost("anchored projection body"))?;- let indices = doc.configuration_face_indices(body, &anchor.target)?;+ // The sketch's plane says when the face was found by fallback; its projection follows it.+ let (indices, _) = doc.anchored_face_indices(st, body, &anchor.target)?;resolve_face_indices(st, plane, kind, &body.name, &indices)}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 8ba80b51f4..5129dd1fb1 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -1047,6 +1047,8 @@ mod pattern_suppress_tests;#[cfg(test)]mod profile_curves_tests;#[cfg(test)]+mod profile_fallback_tests;+#[cfg(test)]mod profile_refs_tests;#[cfg(test)]mod sketch_edit_removed_tests;diff --git a/crates/engine/src/profile_fallback_tests.rs b/crates/engine/src/profile_fallback_tests.rsnew file mode 100644index 0000000000..34d84db890--- /dev/null+++ b/crates/engine/src/profile_fallback_tests.rs@@ -0,0 +1,204 @@+//! A profile picked by the curves around it, and a sketch on the cap such a profile makes, keep+//! working when the sketch's outline is edited so that no profile is bounded by exactly those+//! curves any more: a line that splits the region, a side deleted and drawn again, a notch+//! trimmed into the outline. The feature falls back to the best match and warns; it no longer+//! fails and takes its body (and everything after it) with it.++use serde_json::{Value, json};++use crate::Session;++const HOLE: f64 = std::f64::consts::PI * 16.0 * 10.0;++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ match s.execute(id, &p) {+ Ok(v) => v,+ Err(e) => panic!("{id} {p}: {e}"),+ }+}++fn volume(s: &Session) -> f64 {+ s.model.state().bodies.iter().map(|b| b.body.tessellate(1e-3).unwrap().measure().volume).sum()+}++fn result(s: &Session, name: &str) -> (Option<String>, Option<String>) {+ let id = s.doc.find_feature(name).unwrap().id;+ let r = s.model.result(id).unwrap();+ (r.error.clone(), r.warning.clone())+}++/// A 40 × 20 plate with a hole: the outline `l1`–`l4` (its width is the parameter `W`) and a+/// circle, the region between them picked by a point and extruded 10 mm.+fn plate() -> Session {+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "W", "expression": "40 mm"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]}));+ run(&mut s, "sketch.circle.center", json!({"center": [30, 10], "radius": 4}));+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "W"}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": "10 mm", "profiles": [{"point": [10, 10]}], "name": "E1"}));+ assert_eq!(result(&s, "E1"), (None, None));+ assert!((volume(&s) - (8000.0 - HOLE)).abs() < 0.5, "{}", volume(&s));+ s+}++fn edit(s: &mut Session, steps: &[(&str, Value)]) {+ run(s, "sketch.edit", json!({"sketch": "S1"}));+ for (id, p) in steps {+ run(s, id, p.clone());+ }+ run(s, "sketch.finish", json!({}));+}++fn assert_survives(s: &Session, feature: &str, expected: f64, says: &str) {+ let (error, warning) = result(s, feature);+ assert_eq!(error, None, "{feature} keeps its body");+ let warning = warning.unwrap_or_default();+ assert!(warning.contains(says), "{feature}: {warning}");+ assert_eq!(s.model.state().bodies.len(), 1);+ assert!((volume(s) - expected).abs() < 0.5, "{feature}: volume {} (expected {expected})", volume(s));+}++/// A line across the picked region cuts it in two: both pieces together are the region that was+/// picked, so the plate keeps its whole volume (with its hole, which stays a hole).+#[test]+fn an_extrude_survives_a_line_splitting_its_profile() {+ for x in [20, 15] {+ let mut s = plate();+ edit(&mut s, &[("sketch.line", json!({"points": [[x, 0], [x, 20]]}))]);+ assert_survives(&s, "E1", 8000.0 - HOLE, "is cut by another curve now; using the 2 pieces inside it");+ }+}++/// A side deleted and drawn again is a new curve: the profile that shares the other three sides+/// is the plate, and the warning names the side that went and the one that came.+#[test]+fn an_extrude_survives_a_side_deleted_and_drawn_again() {+ for (side, line) in [("l2", [[40, 0], [40, 20]]), ("l3", [[40, 20], [0, 20]])] {+ let mut s = plate();+ edit(&mut s, &[("sketch.delete", json!({"entities": [side]})), ("sketch.line", json!({"points": line}))]);+ assert_survives(&s, "E1", 8000.0 - HOLE, &format!("`{side}` no longer on it"));+ assert!(result(&s, "E1").1.unwrap().contains("shares 3 of its 4 curves"));+ }+}++/// A notch trimmed out of the top side adds curves to the outline: the profile still has all four+/// sides and takes the notch with it.+#[test]+fn an_extrude_survives_a_notch_trimmed_into_its_outline() {+ let mut s = plate();+ edit(+ &mut s,+ &[("sketch.line", json!({"points": [[10, 20], [10, 25], [20, 25], [20, 20]]})), ("sketch.trim", json!({"curve": "l3", "at": [15, 20]}))],+ );+ assert_survives(&s, "E1", 8000.0 + 500.0 - HOLE, "using the profile that shares 4 of its 4 curves");+}++/// Dimension edits still match exactly, with no warning; an outline replaced altogether matches+/// nothing, and that is still an error rather than a guess.+#[test]+fn exact_matches_stay_quiet_and_nothing_plausible_is_an_error() {+ let mut s = plate();+ run(&mut s, "parameters.change", json!({"name": "W", "expression": "60 mm"}));+ assert_eq!(result(&s, "E1"), (None, None));+ assert!((volume(&s) - (12000.0 - HOLE)).abs() < 0.5);+ edit(+ &mut s,+ &[("sketch.delete", json!({"entities": ["l1", "l2", "l3", "l4"]})), ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [50, 20]}))],+ );+ let (error, _) = result(&s, "E1");+ assert!(error.is_some_and(|e| e.contains("no profile of S1 is bounded by exactly")));+ assert!(s.model.state().bodies.is_empty());+}++/// A block `E1` with a sketch `S2` on its top cap and a hole cut from it, `E2`.+fn block_with_hole() -> Session {+ let mut s = Session::default();+ run(&mut s, "parameters.change", json!({"name": "W", "expression": "40 mm"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]}));+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": "W"}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": "10 mm", "name": "E1"}));+ run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 10]}, "name": "S2"}));+ run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": "3 mm", "direction": "negative", "operation": "cut", "name": "E2"}));+ for f in ["E1", "S2", "E2"] {+ assert_eq!(result(&s, f).0, None, "{f}");+ }+ s+}++fn hole_volume() -> f64 {+ std::f64::consts::PI * 9.0 * 3.0+}++fn assert_hole_follows(s: &Session, block: f64, sketch_warns: bool) {+ let (error, warning) = result(s, "S2");+ assert_eq!(error, None, "S2 keeps its face");+ if sketch_warns {+ let warning = warning.unwrap_or_default();+ assert!(warning.contains("the face this sketch sits on, the top cap of E1"), "{warning}");+ assert!(warning.contains("using the top cap of E1 as it is now"), "{warning}");+ }+ assert_eq!(result(s, "E2").0, None, "the hole after it is still cut");+ let id = s.doc.find_feature("S2").unwrap().id;+ let plane = s.model.state().sketch(id).unwrap().plane;+ assert!((plane.origin.z - 10.0).abs() < 1e-9, "{plane:?}");+ assert!((volume(s) - (block - hole_volume())).abs() < 0.5, "volume {} (expected {})", volume(s), block - hole_volume());+}++/// The base sketch cut by a line still makes one block with one top cap.+#[test]+fn a_sketch_on_a_cap_survives_a_line_splitting_the_base_profile() {+ let mut s = block_with_hole();+ edit(&mut s, &[("sketch.line", json!({"points": [[20, 0], [20, 20]]}))]);+ assert_hole_follows(&s, 8000.0, false);+}++/// A side of the base sketch deleted and drawn again: the cap is bounded by a new curve.+#[test]+fn a_sketch_on_a_cap_survives_a_base_side_deleted_and_drawn_again() {+ let mut s = block_with_hole();+ edit(&mut s, &[("sketch.delete", json!({"entities": ["l2"]})), ("sketch.line", json!({"points": [[40, 0], [40, 20]]}))]);+ assert_hole_follows(&s, 8000.0, true);+ assert!(result(&s, "S2").1.unwrap().contains("`l2` no longer around it"));+}++/// A corner notch trimmed into the base sketch.+#[test]+fn a_sketch_on_a_cap_survives_a_notch_trimmed_into_the_base_outline() {+ let mut s = block_with_hole();+ edit(+ &mut s,+ &[+ ("sketch.line", json!({"points": [[0, 15], [5, 15], [5, 20]]})),+ ("sketch.trim", json!({"curve": "l4", "at": [0, 18]})),+ ("sketch.trim", json!({"curve": "l3", "at": [2, 20]})),+ ],+ );+ assert_hole_follows(&s, 8000.0 - 25.0 * 10.0, true);+}++/// The base extrude picked by a point (stored by its curves) and the sketch on its cap both+/// survive the outline being edited.+#[test]+fn a_picked_profile_and_the_sketch_on_its_cap_survive_together() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S1"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 20]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": "10 mm", "profiles": [{"point": [10, 10]}], "name": "E1"}));+ run(&mut s, "sketch.create", json!({"plane": {"face": [10, 10, 10]}, "name": "S2"}));+ run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": "3 mm", "direction": "negative", "operation": "cut", "name": "E2"}));+ edit(&mut s, &[("sketch.delete", json!({"entities": ["l2"]})), ("sketch.line", json!({"points": [[40, 0], [40, 20]]}))]);+ assert!(result(&s, "E1").1.is_some_and(|w| w.contains("`l2` no longer on it")));+ assert_hole_follows(&s, 8000.0, true);+ // Saved and opened again, it evaluates the same way.+ let reopened = Session::new(solidcraft_doc::format::read(&s.doc.to_json()).unwrap());+ assert_hole_follows(&reopened, 8000.0, true);+}diff --git a/docs/book/src/dev/naming.md b/docs/book/src/dev/naming.mdindex 43f6e73c50..2ba80c42b4 100644--- a/docs/book/src/dev/naming.md+++ b/docs/book/src/dev/naming.md@@ -98,6 +98,29 @@ surface of a plane, cylinder, cone, sphere or torus), which the feature stores lwith the name it then gets as before. Nothing new is stored in the design. `model.faces` liststhat point for every face.+### Profiles picked by their curves++A profile picked by a point or an index is stored by the curve ids of its outer loop+(`ProfileSel::Curves`), so it follows dimension and parameter edits exactly. Editing the outline+itself can leave no profile bounded by exactly those curves; the feature then falls back to the+best match and warns, instead of failing and taking its body and everything after it along+(`profile_refs::fallback_loop`):++1. all the stored curves are still there and still close a loop on their own, but another curve+ now cuts the region: the pieces inside that loop that touch it, which together are the region+ that was picked (islands inside stay holes);+2. otherwise the profile whose outer loop shares the most of the stored curves, at least half of+ them (a side deleted and drawn again, a notch trimmed in); a tie goes to the one with the+ fewest curves the loop did not have, and a tie left after that is an error, as is a loop+ that matches nothing.++Loops of offset curves and legacy graph-span multisets keep their exact meaning. Commands still+check a pick with the exact rule, so a curve list that names no profile is refused when given.+A sketch on such an extrude's cap falls back the same way: its certificate names the loop, and+the cap of the same solid extrude at the same end, from the same sketch and on the same body,+that shares the most (at least half) of its curves stands for it, unless the exact cap is still+on another body (`Document::anchored_face_indices`).+A hole placed by a position on a face is the exception to "the point nearest the reference'spoint": its position is a place, not a pick. The hole follows its face along its own axis, so itmoves with the face when the face moves, and when the face no longer reaches the position it staysdiff --git a/docs/face-attachments.md b/docs/face-attachments.mdindex 6c22b96a92..7c2c2dcd0a 100644--- a/docs/face-attachments.md+++ b/docs/face-attachments.md@@ -75,8 +75,16 @@ the point is in world coordinates. A point-only face request must find a uniquesource. An unsupported or ambiguous request fails with an explanation instead of creatingan attachment with weaker identity.-When a source is suppressed, deleted, replaced, or loses its certificate, the sketch reports-a lost attachment. Its saved plane is only a visible repair guide: it does not produce a+A solid extrude's cap is identified by the curves around its profile, so editing that sketch's+outline (a line that now splits the profile, a side deleted and drawn again, a notch trimmed into+it) leaves no cap with the exact identity. The sketch then sits on the cap of the same extrude, at+the same end, made from the same sketch, on the same body, whose outline shares the most of the+stored curves, at least half of them (a tie is not guessed; a cap whose exact identity is still+on another body is never replaced). It warns, naming the face and the curves+that went or came, until the sketch is placed again with **Redefine Sketch Plane**.++When a source is suppressed, deleted, replaced, or loses its certificate otherwise, the sketch+reports a lost attachment, naming the face it was on (`the top cap of Extrude1 on `Body1``). Its saved plane is only a visible repair guide: it does not produce ahealthy solved sketch or let downstream features build at a substitute face.Use **Redefine Sketch Plane** to select a new supported face explicitly. The draft can be