Skip to content

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

Mirror and pattern: a pattern or mirror feature as the source (#395) (#3998)

Martin Pålsson4dc30c092d0a
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index bd81c6ed2f..0215579129 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -1975,6 +1975,13 @@ impl Model {
}
_ => Vec::new(),
};
+ // 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)
+ }
+ _ => mats,
+ };
next.stamp(&state, f, key, mats);
for b in &mut next.bodies {
if !b.transferred {
@@ -5513,6 +5520,108 @@ 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}`")))
+}
+
+/// 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>)>> {
+ 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)?)))
+ }
+ 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(None),
+ }
+}
+
+/// The copies a pattern or mirror of `features` at `mats` makes, source by source: the source
+/// feature, the transforms of its copies, and the instance number of its first copy less one.
+/// A source that is itself a pattern or mirror of features (#395) stands for what it copied: its
+/// own sources, at each of its transforms moved by each of ours. Those copies are numbered after
+/// `mats`' own (which keep the numbers they always had), each nested source in a block of its
+/// own, so no two copies of one feature share an instance. Suppressed sources copy nothing.
+fn copy_plan<'a>(
+ doc: &'a Document,
+ vals: &BTreeMap<String, Value>,
+ st: &ModelState,
+ features: &[String],
+ mats: &[Mat],
+) -> Result<Vec<(&'a Feature, Vec<Mat>, usize)>> {
+ #[allow(clippy::too_many_arguments)]
+ fn walk<'a>(
+ doc: &'a Document,
+ vals: &BTreeMap<String, Value>,
+ st: &ModelState,
+ features: &[String],
+ 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) {
+ continue;
+ }
+ let src = source_feature(doc, name)?;
+ let Some((inner, inner_mats)) = copied_features(doc, vals, st, src)? else {
+ out.push((src, mats.to_vec(), first));
+ continue;
+ };
+ if depth >= MAX_NESTING {
+ return Err(DocError::Invalid(format!("patterns and mirrors of patterns and mirrors nest at most {MAX_NESTING} deep")));
+ }
+ let moved: Vec<Mat> = mats.iter().flat_map(|m| inner_mats.iter().map(move |mi| crate::mat_mul(m, mi))).collect();
+ if moved.len() > MAX_INSTANCES || next.saturating_add(moved.len()) > MAX_INSTANCES * MAX_NESTING {
+ return Err(DocError::Invalid("too many pattern instances".into()));
+ }
+ let block = *next;
+ *next += moved.len();
+ walk(doc, vals, st, &inner, &moved, block, next, depth + 1, out)?;
+ }
+ Ok(())
+ }
+ let mut next = mats.len();
+ let mut out = Vec::new();
+ walk(doc, vals, st, features, mats, 0, &mut next, 0, &mut out)?;
+ Ok(out)
+}
+
+/// 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>> {
+ 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];
+ for (slot, m) in all.iter_mut().zip(mats) {
+ *slot = *m;
+ }
+ for (_, ms, first) in &plan {
+ for (k, m) in ms.iter().enumerate() {
+ if let Some(slot) = all.get_mut(first + k) {
+ *slot = *m;
+ }
+ }
+ }
+ Ok(all)
+}
+
/// Apply transformed copies of the tools of `features` (patterns, mirrors).
fn replay(
doc: &Document,
@@ -5537,14 +5646,9 @@ fn replay(
});
}
let (mut missed, mut total) = (0usize, 0usize);
- for name in features.iter().filter(|n| !suppressed.contains(n)) {
- // A sketch and its extrude often share a name; the feature that makes geometry wins.
- let src = 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}`")))?;
+ let kept: Vec<String> = features.iter().filter(|n| !suppressed.contains(n)).cloned().collect();
+ let plan = copy_plan(doc, vals, st, &kept, mats)?;
+ for (src, mats, first) in &plan {
// A fillet or chamfer repeats at the copied edges.
if let FeatureKind::Fillet { edges, radius, .. } | FeatureKind::Chamfer { edges, distance: radius, .. } = &src.kind {
let r = val(vals, radius, Kind::Length)?;
@@ -5601,7 +5705,7 @@ fn replay(
copies.extend(
hole_tools(vals, st, &at, d, diameter, &depth, hole)?
.into_iter()
- .map(|t| Traced { lineage: t.lineage.map(|l| l.copied(src.id, k + 1)), body: t.body }),
+ .map(|t| Traced { lineage: t.lineage.map(|l| l.copied(src.id, first + k + 1)), body: t.body }),
);
}
instances.push(start..copies.len());
@@ -5613,7 +5717,7 @@ fn replay(
for body in more::rib_tools(vals, st, src, Some(m))? {
// Each copy's faces are named as the rib's, with the instance.
let t = Traced::unnamed(body);
- copies.push(Traced { lineage: t.lineage.map(|l| l.copied(src.id, k + 1)), body: t.body });
+ copies.push(Traced { lineage: t.lineage.map(|l| l.copied(src.id, first + k + 1)), body: t.body });
}
}
} else {
@@ -5622,7 +5726,7 @@ fn replay(
for (k, m) in mats.iter().enumerate() {
let start = copies.len();
for t in &tools {
- copies.push(t.copied(kernel::transform_matrix(&t.body, *m)?, src.id, k + 1));
+ copies.push(t.copied(kernel::transform_matrix(&t.body, *m)?, src.id, first + k + 1));
}
instances.push(start..copies.len());
}
diff --git a/crates/engine/src/cmd/patterns_tests.rs b/crates/engine/src/cmd/patterns_tests.rs
index 12802150d6..7375af0172 100644
--- a/crates/engine/src/cmd/patterns_tests.rs
+++ b/crates/engine/src/cmd/patterns_tests.rs
@@ -707,3 +707,99 @@ fn patterns_and_mirrors_of_a_rib() {
check(&s, &[ribs[0], ribs[2]]);
assert!(rel(volume(&mut s), before + 2.0 * rib) < 1e-6, "two ribs: {} vs {}", volume(&mut s), before + 2.0 * rib);
}
+
+/// #395: a pattern or mirror of features takes a pattern or mirror of features as a source: it
+/// copies what that one made (its copies, not its source). The issue's design: a 40 × 30 × 20
+/// box with a hole `H` at (−15, −10) and `Pat`, two more holes along x at 10 mm steps.
+#[test]
+fn patterns_and_mirrors_of_patterns_and_mirrors() {
+ use solidcraft_geom::Vec3;
+ let hole = PI * 1.5 * 1.5 * 20.0;
+ let design = || {
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20, "corner": [-20, -15, 0], "name": "Box"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Spot"}));
+ run(&mut s, "sketch.circle.center", json!({"center": [-15, -10], "radius": 1.5}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Spot", "through_all": true, "operation": "cut", "name": "H"}));
+ run(&mut s, "solid.pattern.rectangular", json!({"features": ["H"], "dir1": [1, 0, 0], "count1": 3, "spacing1": 10, "name": "Pat"}));
+ s
+ };
+ let across_xz = json!({"origin": [0, 0, 0], "normal": [0, 1, 0]});
+ let across_yz = json!({"origin": [0, 0, 0], "normal": [1, 0, 0]});
+ // Each case: the steps after `design`, the holes there must be, and the spots that must
+ // stay material.
+ type Case = (Vec<(&'static str, Value)>, Vec<[f64; 2]>, Vec<[f64; 2]>);
+ let cases: Vec<(&str, Case)> = vec![
+ // The issue's step: the mirror of `Pat` is its two copies mirrored.
+ (
+ "mirror of a pattern",
+ (vec![("solid.mirror", json!({"features": ["Pat"], "plane": across_xz}))], vec![[-5.0, 10.0], [5.0, 10.0]], vec![[-15.0, 10.0]]),
+ ),
+ // With its source too: the six holes the issue expects.
+ (
+ "mirror of a hole and its pattern",
+ (
+ vec![("solid.mirror", json!({"features": ["H", "Pat"], "plane": across_xz}))],
+ vec![[-15.0, 10.0], [-5.0, 10.0], [5.0, 10.0]],
+ vec![[15.0, 10.0]],
+ ),
+ ),
+ (
+ "pattern of a pattern",
+ (
+ vec![("solid.pattern.rectangular", json!({"features": ["Pat"], "dir1": [0, 1, 0], "count1": 2, "spacing1": 20}))],
+ vec![[-5.0, 10.0], [5.0, 10.0]],
+ vec![[-15.0, 10.0]],
+ ),
+ ),
+ (
+ "mirror of a mirror",
+ (
+ vec![
+ ("solid.mirror", json!({"features": ["H"], "plane": across_yz, "name": "Mir"})),
+ ("solid.mirror", json!({"features": ["Mir"], "plane": across_xz})),
+ ],
+ vec![[15.0, -10.0], [15.0, 10.0]],
+ vec![[-15.0, 10.0]],
+ ),
+ ),
+ (
+ "pattern of a mirror",
+ (
+ vec![
+ ("solid.mirror", json!({"features": ["H"], "plane": across_yz, "name": "Mir"})),
+ ("solid.pattern.rectangular", json!({"features": ["Mir"], "dir1": [0, 1, 0], "count1": 2, "spacing1": 20})),
+ ],
+ vec![[15.0, -10.0], [15.0, 10.0]],
+ vec![[-15.0, 10.0]],
+ ),
+ ),
+ ];
+ for (what, (steps, holes, material)) in cases {
+ let mut s = design();
+ let before = volume(&mut s);
+ for (id, p) in steps {
+ run(&mut s, id, p);
+ }
+ for r in &s.model.results {
+ assert!(r.error.is_none(), "{what}: {}: {:?}", r.name, r.error);
+ }
+ let st = s.world_state();
+ assert_eq!(st.bodies.len(), 1, "{what}");
+ let body = &st.bodies[0].body;
+ for [x, y] in &holes {
+ assert!(!body.contains(Vec3::new(*x, *y, 10.0)), "{what}: a hole at ({x}, {y})");
+ assert!(body.contains(Vec3::new(*x, *y + 2.5, 10.0)), "{what}: material beside ({x}, {y})");
+ }
+ for [x, y] in &material {
+ assert!(body.contains(Vec3::new(*x, *y, 10.0)), "{what}: no hole at ({x}, {y})");
+ }
+ // The listed holes the steps added (in the last two cases `Mir` made the first of them).
+ let added = holes.len();
+ // Measured on the body's mesh, like the other tests here: to 1e-5 of the whole body.
+ let after = volume(&mut s);
+ let want = before - added as f64 * hole;
+ assert!(rel(after, want) < 1e-5, "{what}: {after} mm³, {added} more holes than {before} = {want}");
+ }
+}