SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Chamfer and fillet: an edge on a moved part is found where you picked it (#13239)
Kai Evansa74e78fba84f
diff --git a/apps/solidcraft-cli/tests/action_matrix.rs b/apps/solidcraft-cli/tests/action_matrix.rsindex cacfc68940..5bb5582e39 100644--- a/apps/solidcraft-cli/tests/action_matrix.rs+++ b/apps/solidcraft-cli/tests/action_matrix.rs@@ -1308,7 +1308,7 @@ fn edge_round_actions_keep_the_picked_body() {let mut unscoped = p.clone();unscoped.as_object_mut().unwrap().remove("body");let err = s.scratch().execute(id, &unscoped).unwrap_err().to_string();- assert!(err.contains("edges meet"), "{err}");+ assert!(err.contains("[10, 0, 20] lies on edges of 2 bodies, Plate and Block"), "{err}");perform(&mut s.scratch(), &a.act, &errors(&s)).unwrap();tried += 1;}diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex a93b3aa325..b14195ebab 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -87,8 +87,8 @@ pub static COMMANDS: &[CommandSpec] = &[.key("F").contract(&FILLET_CONTRACT).output(output_schema_for::<FilletResult>)- .params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?; type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); turn?: mitre|swept (where two rounds turn round a sharp, straight, convex side edge square to both on a plane, such as the rounds along a boss's base at its upright edges: mitre, the default, runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus; swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),- CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?"),+ .params("edges: [[x,y,z] point on edge | {body, index}] ; radius: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is rounded with it; false: exactly the picked edges); body?: the body the edges are on (without it, each point is looked up on every placed body, shown or hidden, and a point on edges of 2 bodies is refused, naming them); type?: constant|curvature (alias g2: curvature-continuous quintic between planar faces along straight edges, one planar end face at each end (including sloped ends); radius sets the equivalent circular setback, not constant curvature; exact fit only)|chord (radius is the width across)|variable (radius at the end nearest start, radius2 at the other; one end may be 0, where the round closes to the corner)|spline (the radius along the edge is a clamped B-spline from the end nearest start: radius is its first control radius, radii the rest, knots its knot vector from 0 to 1; one end may be 0); radius2?; start?: [x,y,z]; radii?: [expr, …]; knots?: [number, …]; mid?: [[position 0…1 from start, radius expr], …] (variable radii between the ends); smooth?: bool (smooth instead of straight between the radii); corner?: rolling|g2 (rolling, the default: the corners where three blended edges meet are pieces of the rolling ball's sphere, tangent to each blend; a curvature round's corners are always g2 patches, between its own sections; g2: each corner where three or more rounded edges meet, and every edge there is rounded, is set back (1.5 × the radius along each edge unless `setbacks` names it) and filled with a patch meeting the rounds and the faces round it to the second order (curvature-continuous seams, clear of the points where a round's section ends on a face), constant-radius exact fillets only, refused where it cannot be built); setbacks?: [{vertex: [x,y,z], distance: expr}, …] (corner setbacks: the corner at the vertex nearest `vertex`, where every edge meeting it is rounded, starts its patch `distance` along each of those edges from the vertex, past where the rounds would meet (past the radius at a square corner), so the rounds blend through a larger patch; one distance for all of a corner's edges; constant-radius exact fillets only; with `corner: g2`, the G2 patch's corners); turn?: mitre|swept (where two rounds turn round a sharp, straight, convex side edge square to both on a plane, such as the rounds along a boss's base at its upright edges: mitre, the default, runs them on to meet in a mitre; swept ends them at the side edge and fills the corner with their section revolved about it, a torus; swept takes type: constant, corner: rolling, no setbacks and fit: exact or reduce, and is refused with the reason where the rounds are unequal or the side edge is concave, curved or tangent); fit?: exact|reduce|taper (exact, the default: a radius too large for the geometry around the edges is refused, naming the largest that fits; reduce: where it doesn't fit it is reduced to the largest that does, one radius for edges sharing a face; the smallest used is returned as `radius_applied`, each edge's as `radii_applied: [{edge: [x,y,z], radius}]`, and noted in the feature's warning; taper: along each straight edge between planar faces where it doesn't fit, the radius follows the room there as a smooth spline, down to 0 where a face closes to a point, noted in the feature's warning)"),+ CommandSpec::new("solid.chamfer", "Chamfer", chamfer).at("SOLID", "MODIFY").icon("chamfer").params("edges: [[x,y,z] | {body, index}] ; distance: expr; tangent_chain?: bool (default true: each picked edge's tangent chain is cut with it; false: exactly the picked edges); distance2?: expr (along the second face) | angle?: expr (from the first face); flip?: bool (which face is first: by default the one facing up most); body?: the body the edges are on (without it, each point is looked up on every placed body, shown or hidden, and a point on edges of 2 bodies is refused, naming them)"),CommandSpec::new("solid.combine", "Combine", crate::checked!("solid.combine", combine)).at("SOLID", "MODIFY").icon("combine")@@ -177,7 +177,7 @@ pub static COMMANDS: &[CommandSpec] = &[.at("SOLID", "MODIFY").icon("presspull").key("Q")- .params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet)"),+ .params("face: [x,y,z] and distance: expr (positive adds material, negative cuts), or edges: [[x,y,z]…] and distance (a fillet); body?: the body the face or edges are on (for edges, as for solid.fillet)"),CommandSpec::new("solid.move", "Move/Copy", move_bodies).at("SOLID", "MODIFY").icon("move").key("M").enabled(not_in_sketch).params("bodies: [names]; translate?: [x,y,z] (exprs or numbers); axis?: [x,y,z]; angle?: expr; copy?: bool (default false: keeps the original bodies and transforms a new copy instead of moving them in place); occurrences?: [occurrence paths, root first] (only with copy: each component is copied as an independent component, as Paste New copies it, and the copy moves by the same translate, axis and angle in the world; the reply lists the copies in occurrences)"),];@@ -1554,20 +1554,131 @@ fn prim_cone(s: &mut Session, p: &Value) -> Result<Value> {add_feature(s, p, FeatureKind::Cone { base, axis: Dir(axis), radius, top_radius, height, operation: operation(p, cmd)? })}-/// Edge references → points on the edges.-fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {+/// What [`edge_points`] found: a point on each edge, in its body's frame, and the body the+/// feature keeps (`None`: each edge is looked up on its own).+struct EdgePicks {+ points: Vec<Vec3>,+ body: Option<String>,+}++/// A body as a pick is looked up on: the model body, the name it is shown by, and the frame it+/// is placed by and its inverse.+struct PickRow {+ body: usize,+ name: String,+ frame: solidcraft_doc::Mat,+ inverse: solidcraft_doc::Mat,+}++/// What one body's edges near a pick are: the point in its frame, its distance from the pick on+/// the exact curves and the edge there, whether any edge within reach is not a seam, and the+/// edges within reach (polyline distance, seam, the direction leaving).+struct RowHit {+ row: usize,+ q: Vec3,+ d: f64,+ edge: Option<usize>,+ edge_like: bool,+ near: Vec<(f64, bool, Option<Vec3>)>,+}++/// How many bodies a refusal names before "and N more".+const NAMED_BODIES: usize = 8;++/// A body's size, its edges' polylines and which of them are seams.+type EdgeShape = (f64, Vec<Vec<Vec3>>, Vec<bool>);++/// How far a polyline is from `q`.+fn polyline_dist(points: &[Vec3], q: Vec3) -> f64 {+ points.windows(2).filter_map(|w| Some(q.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::INFINITY, f64::min)+}++/// How far from an edge of a body this big a pick still means it.+fn edge_reach(size: f64) -> f64 {+ size * 0.05 + 1e-3+}++/// Edge references → points on the edges, each in the frame of the body it lies on.+///+/// A point is looked up where it was picked, on every placed body, shown or hidden: a part+/// whose edge is in the same place only in its own frame is not in the way, and two bodies+/// with an edge there make it ambiguous. The polylines short-list the edges; which body a pick+/// means is decided on the exact curves.+fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<EdgePicks> {let a = p.get("edges").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`edges` must be a list"))?;if a.is_empty() || a.len() > 1000 {return Err(bad(cmd, "select 1…1000 edges"));}+ let verb = if cmd == "solid.chamfer" { "chamfer" } else { "round" };let st = s.model.state();// A picked point must lie on an edge (within the distance the kernel re-finds an edge from)// of the body the feature names, or of any body: a pick far from every edge would round- // whichever edge is nearest (#783). Each body's edges are worked out once.- let named = str_(p, "body").filter(|n| st.body(n).is_some());- // Per body: its size, its edges' polylines and which of them are seams.- let mut candidates: Option<Vec<(f64, Vec<Vec<Vec3>>, Vec<bool>)>> = None;+ // whichever edge is nearest (#783).+ let given = str_(p, "body");+ let named = given.and_then(|n| st.bodies.iter().position(|b| b.name == n));+ // A pick's own body is the feature's, which keeps one.+ let agrees = |i: usize| -> Result<usize> {+ match given {+ Some(g) if named != Some(i) => {+ let n = st.bodies.get(i).map_or("", |b| b.name.as_str());+ Err(bad(cmd, format!("an edge names `{n}`, but `body` is `{g}`: give one")))+ }+ _ => Ok(i),+ }+ };+ let identity = |i: usize, b: &solidcraft_doc::ModelBody| PickRow {+ body: i,+ name: b.name.clone(),+ frame: solidcraft_doc::IDENTITY,+ inverse: solidcraft_doc::IDENTITY,+ };+ // Mesh bodies have no edges to pick: rounding one is refused later, saying why.+ let local: Vec<PickRow> = st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh()).map(|(i, b)| identity(i, b)).collect();+ let placed = crate::frames::placed(s);+ // Worked out for the first pick looked up where it was picked.+ let world: std::cell::OnceCell<Vec<PickRow>> = std::cell::OnceCell::new();+ let world_rows = || {+ world.get_or_init(|| {+ let index: std::collections::BTreeMap<&str, usize> = st.bodies.iter().enumerate().map(|(i, b)| (b.definition_name(), i)).collect();+ s.body_frames()+ .iter()+ .filter_map(|(name, own, frame)| {+ let body = *index.get(own.as_str())?;+ let inverse = solidcraft_doc::mat_inverse(frame)?;+ (!st.bodies.get(body)?.body.is_mesh()).then(|| PickRow { body, name: name.clone(), frame: *frame, inverse })+ })+ .collect()+ })+ };+ // Per body, worked out once.+ let mut shapes: std::collections::BTreeMap<usize, EdgeShape> = std::collections::BTreeMap::new();+ let shape_of = |i: usize, shapes: &mut std::collections::BTreeMap<usize, EdgeShape>| {+ if shapes.contains_key(&i) {+ return;+ }+ let Some(b) = st.bodies.get(i) else { return };+ let size = b.body.size();+ let tol = (size * 2e-3).max(1e-3);+ // The display mesh flags seams (a smooth surface meeting itself, as down the side+ // of a cylinder), which nobody means by a pick where they end.+ let shape = match b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)) {+ // An edge where the faces meet tangentially (the spans of a spline wall+ // meeting) can't be blended either: nobody means it by a pick.+ Ok(m) => Some((+ size,+ m.edges,+ m.seams.iter().zip(&m.smooth_edges).map(|(s, t)| *s || *t).chain(m.seams.iter().skip(m.smooth_edges.len()).copied()).collect(),+ )),+ Err(_) => b.body.edges(tol).ok().map(|edges| (size, edges.into_iter().map(|e| e.points).collect(), Vec::new())),+ };+ if let Some(shape) = shape {+ shapes.insert(i, shape);+ }+ };let mut out = Vec::new();+ // Per pick: the body it was found on, where it was picked, and how far from that body's edge.+ let mut found: Vec<(usize, String, Vec3, Vec3, f64)> = Vec::new();+ let mut seen: Vec<Vec3> = Vec::new();for e in a {let pt = match edge_ref_form(e).map_err(|why| bad(cmd, why))? {EdgeRefForm::Point(pt) => pt,@@ -1576,57 +1687,139 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {let b = st.body(body).ok_or_else(|| bad(cmd, format!("no body `{body}`")))?;let tol = (b.body.size() * 2e-3).max(1e-3);let edges = b.body.edges(tol)?;- out.push(edges.get(idx).ok_or_else(|| bad(cmd, format!("{body} has no edge {idx}")))?.mid);+ let mid = edges.get(idx).ok_or_else(|| bad(cmd, format!("{body} has no edge {idx}")))?.mid;+ if let Some(i) = st.bodies.iter().position(|m| m.name == b.name) {+ found.push((agrees(i)?, b.name.clone(), mid, mid, 0.0));+ }+ out.push(mid);continue;}};- let bodies = candidates.get_or_insert_with(|| {- // Mesh bodies have no edges to pick: rounding one is refused later, saying why.- st.bodies- .iter()- .filter(|b| named.is_none_or(|n| b.name == n) && !b.body.is_mesh())- .filter_map(|b| {- let size = b.body.size();- let tol = (size * 2e-3).max(1e-3);- // The display mesh flags seams (a smooth surface meeting itself, as down the side- // of a cylinder), which nobody means by a pick where they end.- match b.body.mesh(&solidcraft_kernel::MeshTolerance::chord(tol)) {- // An edge where the faces meet tangentially (the spans of a spline wall- // meeting) can't be blended either: nobody means it by a pick.- Ok(m) => Some((- size,- m.edges,- m.seams- .iter()- .zip(&m.smooth_edges)- .map(|(s, t)| *s || *t)- .chain(m.seams.iter().skip(m.smooth_edges.len()).copied())- .collect(),- )),- Err(_) => b.body.edges(tol).ok().map(|edges| (size, edges.into_iter().map(|e| e.points).collect(), Vec::new())),- }- })- .collect()- });- // A point where several edges meet (a corner) is ambiguous: the kernel would round one of- // them, picked silently (#5173). Edges that carry straight on through the point (the two- // halves of a circle) are one edge to whoever picked it, and seams and tangent joins don't- // count. Directions- // come from the polylines' end chords, which lean off a curve's tangent: within about 45°- // of opposite counts as carrying on (edges at a real corner are far from opposite).- let mut nearest = f64::INFINITY;- let mut near = Vec::new();- for (size, edges, seams) in bodies.iter() {+ // The nth pick seen at this point is the nth remembered there.+ let nth = seen.iter().filter(|q| **q == pt).count();+ seen.push(pt);+ let picked = crate::frames::picked_world(pt, nth).filter(|_| placed);+ let shown = picked.unwrap_or(pt);+ let own = match e.get("body").and_then(Value::as_str) {+ Some(n) => Some(agrees(st.bodies.iter().position(|b| b.name == n).ok_or_else(|| bad(cmd, format!("no body `{n}`")))?)?),+ None => named,+ };+ // Named: on that body only, in its frame. Else where it was picked, on every placed body;+ // a command run by another without the world point, or a design with no placement to look+ // through, sees the bodies in their own frames.+ let (w, rows): (Vec3, Vec<&PickRow>) = match (own, picked) {+ (Some(i), _) => (pt, local.iter().filter(|r| r.body == i).collect()),+ (None, Some(w)) if !world_rows().is_empty() => (w, world_rows().iter().collect()),+ _ => (pt, local.iter().collect()),+ };+ let q_of = |r: &PickRow| {+ let q = solidcraft_doc::apply_point(&r.inverse, w);+ (q.x.is_finite() && q.y.is_finite() && q.z.is_finite()).then_some(q)+ };+ // Only bodies whose box (grown by the reach) holds the pick: an edge lies in its body's box.+ let culled: Vec<(usize, Vec3)> = rows+ .iter()+ .enumerate()+ .filter_map(|(k, r)| {+ let b = st.bodies.get(r.body)?;+ let q = q_of(r)?;+ b.outline_bounds().inflated(edge_reach(b.body.size())).contains(q).then_some((k, q))+ })+ .collect();+ for (k, _) in &culled {+ if let Some(r) = rows.get(*k) {+ shape_of(r.body, &mut shapes);+ }+ }+ let mut hits: Vec<RowHit> = Vec::new();+ for (k, q) in culled {+ let Some(r) = rows.get(k) else { continue };+ let (Some((size, edges, seams)), Some(b)) = (shapes.get(&r.body), st.bodies.get(r.body)) else { continue };+ let chord = (size * 2e-3).max(1e-3);+ let mut near = Vec::new();+ let mut candidates = Vec::new();for (i, points) in edges.iter().enumerate() {- let d = points.windows(2).filter_map(|w| Some(pt.dist_to_segment(*w.first()?, *w.get(1)?))).fold(f64::INFINITY, f64::min);- nearest = nearest.min(d);- if d <= size * 0.05 + 1e-3 {- near.push((d, seams.get(i).copied().unwrap_or(false), leaving(points, pt)));+ let d = polyline_dist(points, q);+ if d <= edge_reach(*size) {+ let seam = seams.get(i).copied().unwrap_or(false);+ near.push((d, seam, leaving(points, q)));+ candidates.push((i, d, seam));}}+ if near.is_empty() {+ continue;+ }+ // Seams count only where nothing else is near.+ let edge_like = candidates.iter().any(|(_, _, seam)| !seam);+ let candidates: Vec<(usize, f64)> = candidates.into_iter().filter(|(_, _, seam)| !edge_like || !seam).map(|(i, d, _)| (i, d)).collect();+ let polyline = candidates.iter().map(|(_, d)| *d).fold(f64::INFINITY, f64::min);+ let (d, edge) = candidates+ .iter()+ .filter(|(_, d)| *d <= polyline + 2.0 * chord)+ .map(|(i, d)| (edge_foot(&b.body, *i, q).map_or(*d, |(_, foot)| solidcraft_doc::apply_point(&r.frame, foot).dist(w)), *i))+ .fold((f64::INFINITY, None), |best, (d, i)| if d < best.0 { (d, Some(i)) } else { best });+ hits.push(RowHit { row: k, q, d, edge, edge_like, near });+ }+ if hits.is_empty() {+ if rows.is_empty() {+ out.push(pt);+ continue;+ }+ // How far the nearest edge is, on every body the pick was looked up on.+ let mut nearest = f64::INFINITY;+ for r in &rows {+ let Some(q) = q_of(r) else { continue };+ shape_of(r.body, &mut shapes);+ let Some((_, edges, _)) = shapes.get(&r.body) else { continue };+ nearest = edges.iter().map(|points| polyline_dist(points, q)).fold(nearest, f64::min);+ }+ let far = if nearest.is_finite() { format!("the nearest edge is {nearest:.3} mm away") } else { "there is no edge".to_string() };+ return Err(bad(cmd, format!("no edge at [{}, {}, {}]: {far}", shown.x, shown.y, shown.z)));+ }+ // A body with only a seam there has no edge to blend, where another body has one.+ if hits.iter().any(|h| h.edge_like) {+ hits.retain(|h| h.edge_like);+ }+ // Bodies with an edge as near as the nearest one's: the pick is on both. A pick off its+ // curve by e widens the window to about 2e. The same body placed twice, at the same+ // edge or point of its frame, is one edge.+ let d_min = hits.iter().map(|h| h.d).fold(f64::INFINITY, f64::min);+ let mut groups: Vec<&RowHit> = Vec::new();+ for h in hits.iter().filter(|h| h.d <= 2.0 * d_min + 1e-3) {+ let Some(r) = rows.get(h.row) else { continue };+ let size = shapes.get(&r.body).map_or(1.0, |(size, _, _)| *size);+ let same = |g: &&RowHit| {+ rows.get(g.row).is_some_and(|o| o.body == r.body) && ((g.edge.is_some() && g.edge == h.edge) || g.q.dist(h.q) <= 1e-6 * size.max(1.0))+ };+ if !groups.iter().any(same) {+ groups.push(h);+ }+ }+ if groups.len() > 1 {+ let names: Vec<String> = groups.iter().filter_map(|g| rows.get(g.row).map(|r| r.name.clone())).collect();+ let hidden: String = names.iter().filter(|n| !s.body_visible(n)).map(|n| format!(" ({n} is hidden)")).collect();+ return Err(bad(+ cmd,+ format!(+ "[{}, {}, {}] lies on edges of {} bodies, {}: name the one to {verb} with `body`{hidden}",+ shown.x,+ shown.y,+ shown.z,+ names.len(),+ and_list(&names, NAMED_BODIES)+ ),+ ));}- let matches = near.len();- let mut meeting: Vec<Option<Vec3>> = near.iter().filter(|(d, seam, _)| !seam && *d <= nearest + 1e-3).map(|(_, _, dir)| *dir).collect();+ let Some(hit) = hits.iter().filter(|h| h.d <= d_min).chain(hits.iter()).next() else { continue };+ let Some(row) = rows.get(hit.row) else { continue };+ // A point where several edges meet (a corner) is ambiguous: the kernel would round one of+ // them, picked silently (#5173). Edges that carry straight on through the point (the two+ // halves of a circle) are one edge to whoever picked it, and seams and tangent joins don't+ // count. Directions come from the polylines' end chords, which lean off a curve's+ // tangent: within about 45° of opposite counts as carrying on (edges at a real corner are+ // far from opposite).+ let nearest = hit.near.iter().map(|(d, _, _)| *d).fold(f64::INFINITY, f64::min);+ let mut meeting: Vec<Option<Vec3>> = hit.near.iter().filter(|(d, seam, _)| !seam && *d <= nearest + 1e-3).map(|(_, _, dir)| *dir).collect();let mut chains = 0usize;while let Some(dir) = meeting.pop() {chains += 1;@@ -1639,16 +1832,107 @@ fn edge_points(s: &Session, p: &Value, cmd: &str) -> Result<Vec<Vec3>> {if chains > 1 {return Err(bad(cmd,- format!("[{}, {}, {}] is where {chains} edges meet: give a point along one edge, such as its midpoint", pt.x, pt.y, pt.z),+ format!("[{}, {}, {}] is where {chains} edges meet: give a point along one edge, such as its midpoint", shown.x, shown.y, shown.z),));}- if matches == 0 && !bodies.is_empty() {- let far = if nearest.is_finite() { format!("the nearest edge is {nearest:.3} mm away") } else { "there is no edge".to_string() };- return Err(bad(cmd, format!("no edge at [{}, {}, {}]: {far}", pt.x, pt.y, pt.z)));+ found.push((row.body, row.name.clone(), hit.q, shown, hit.d));+ out.push(hit.q);+ }+ if given.is_some() {+ return Ok(EdgePicks { points: out, body: given.map(str::to_string) });+ }+ let mut bodies: Vec<(usize, String)> = Vec::new();+ for (i, name, ..) in &found {+ if !bodies.iter().any(|(b, _)| b == i) {+ bodies.push((*i, name.clone()));+ }+ }+ let body = match bodies.as_slice() {+ // One body of several: the feature keeps it, so the model never looks the edges up on+ // another body that has one in the same place in its own frame.+ [(i, _)] => st.bodies.get(*i).filter(|_| local.len() > 1).map(|b| b.name.clone()),+ [] => None,+ _ => {+ // Several: each edge is looked up on its own when the model is built, on whichever+ // body has an edge there in its own frame, so another body's edge there is refused.+ for (i, _, q, shown, d) in &found {+ for other in local.iter().filter(|r| r.body != *i) {+ let Some(b) = st.bodies.get(other.body) else { continue };+ let reach = edge_reach(b.body.size());+ if !b.outline_bounds().inflated(reach).contains(*q) {+ continue;+ }+ shape_of(other.body, &mut shapes);+ let Some((size, edges, seams)) = shapes.get(&other.body) else { continue };+ // The exact curve is no nearer than the polyline less its chord tolerance.+ let chord = (size * 2e-3).max(1e-3);+ let ghost = edges.iter().enumerate().filter(|(k, _)| !seams.get(*k).copied().unwrap_or(false)).any(|(k, points)| {+ let poly = polyline_dist(points, *q);+ poly <= reach && poly - chord <= 2.0 * d + 1e-3 && edge_foot(&b.body, k, *q).map_or(poly, |(d, _)| d) <= 2.0 * d + 1e-3+ });+ if ghost {+ let names: Vec<String> = bodies.iter().map(|(_, n)| n.clone()).collect();+ return Err(bad(+ cmd,+ format!(+ "the picks lie on {} bodies, {}, and at [{}, {}, {}] {} has an edge in the same place in its own component: {verb} each body in a command of its own, naming it with `body`",+ names.len(),+ and_list(&names, NAMED_BODIES),+ shown.x,+ shown.y,+ shown.z,+ b.name+ ),+ ));+ }+ }+ }+ None}- out.push(pt);+ };+ Ok(EdgePicks { points: out, body })+}++/// "A", "A and B", "A, B and C", and past `most` names "A, B and 3 more".+fn and_list(names: &[String], most: usize) -> String {+ let mut shown: Vec<String> = names.iter().take(most).cloned().collect();+ if names.len() > most {+ shown.push(format!("{} more", names.len() - most));+ }+ match shown.split_last() {+ Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),+ Some((last, _)) => last.clone(),+ None => String::new(),}- Ok(out)+}++/// The distance from `q` to edge `index` of `body` on its exact curve, and the point there:+/// samples, then a golden-section search between the best one's neighbours.+fn edge_foot(body: &solidcraft_kernel::Body, index: usize, q: Vec3) -> Option<(f64, Vec3)> {+ const SAMPLES: usize = 32;+ const STEPS: usize = 40;+ let e = body.record().edges.get(index)?;+ let c = solidcraft_geom::brep::eval::CurveEval::new(e.parameters()).ok()?;+ let [t0, t1] = e.interval;+ if !(t0.is_finite() && t1.is_finite()) {+ return None;+ }+ let at = |t: f64| c.point(t).map(|p| p.dist(q)).filter(|d| d.is_finite());+ let step = (t1 - t0) / SAMPLES as f64;+ let (k, _) = (0..=SAMPLES).filter_map(|k| Some((k, at(t0 + step * k as f64)?))).min_by(|a, b| a.1.total_cmp(&b.1))?;+ let (mut lo, mut hi) = (t0 + step * k.saturating_sub(1) as f64, t0 + step * (k + 1).min(SAMPLES) as f64);+ let ratio = (5.0_f64.sqrt() - 1.0) / 2.0;+ for _ in 0..STEPS {+ let (a, b) = (hi - ratio * (hi - lo), lo + ratio * (hi - lo));+ if at(a).unwrap_or(f64::INFINITY) <= at(b).unwrap_or(f64::INFINITY) {+ hi = b;+ } else {+ lo = a;+ }+ }+ let foot = c.point((lo + hi) / 2.0)?;+ let d = foot.dist(q);+ d.is_finite().then_some((d, foot))}/// The direction an edge's polyline leaves `pt` in, when `pt` is one of its ends; `None` when@@ -1687,7 +1971,11 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "solid.press_pull";let distance = req_expr(cmd, p, "distance")?;if p.get("edges").is_some() {- return fillet(s, &json!({"edges": p.get("edges"), "radius": distance}));+ let mut q = json!({"edges": p.get("edges"), "radius": distance});+ if let Some(body) = p.get("body").filter(|b| b.is_string()) {+ q["body"] = body.clone();+ }+ return fillet(s, &q);}let face = p.get("face").ok_or_else(|| bad(cmd, "needs `face` or `edges`"))?;let d = s.doc.eval(&distance, Kind::Length).map_err(|e| bad(cmd, format!("distance: {e}")))?;@@ -1737,7 +2025,7 @@ fn press_pull(s: &mut Session, p: &Value) -> Result<Value> {fn fillet(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "solid.fillet";- let edges = edge_points(s, p, cmd)?;+ let picks = edge_points(s, p, cmd)?;let radius = req_expr(cmd, p, "radius")?;check_expr(s, &radius, Kind::Length, cmd, "radius")?;let style = match str_(p, "type").map(str::to_ascii_lowercase).as_deref() {@@ -1840,9 +2128,9 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {s,p,FeatureKind::Fillet {- edges: edges.into_iter().map(Position).collect(),+ edges: picks.points.into_iter().map(Position).collect(),radius,- body: str_(p, "body").map(BodyName::from),+ body: picks.body.map(BodyName::from),style,fit,corner,@@ -1866,7 +2154,7 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {fn chamfer(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "solid.chamfer";- let edges = edge_points(s, p, cmd)?;+ let picks = edge_points(s, p, cmd)?;let distance = req_expr(cmd, p, "distance")?;check_expr(s, &distance, Kind::Length, cmd, "distance")?;let (distance2, angle) = (expr(p, "distance2"), expr(p, "angle"));@@ -1884,12 +2172,12 @@ fn chamfer(s: &mut Session, p: &Value) -> Result<Value> {s,p,FeatureKind::Chamfer {- edges: edges.into_iter().map(Position).collect(),+ edges: picks.points.into_iter().map(Position).collect(),distance,distance2,angle,flip,- body: str_(p, "body").map(BodyName::from),+ body: picks.body.map(BodyName::from),tangent_chain: bool_(p, "tangent_chain").unwrap_or(true),},)diff --git a/crates/engine/src/frames.rs b/crates/engine/src/frames.rsindex 134c7a79ad..2d7c189b77 100644--- a/crates/engine/src/frames.rs+++ b/crates/engine/src/frames.rs@@ -72,7 +72,7 @@ fn table(id: &str) -> &'static [(&'static str, K)] {"solid.thread" => &[("face", Pick), ("from", Pick), ("up_to", Plane)],"solid.emboss" => &[("face", Make)],"solid.draft" => &[("faces", Picks), ("neutral", Plane), ("pull", Dir), ("body", Body)],- "solid.press_pull" => &[("face", Pick), ("edges", Picks)],+ "solid.press_pull" => &[("face", Pick), ("edges", Picks), ("body", Body)],"solid.replace_face" => &[("faces", Picks), ("target_face", Pick), ("target", Plane), ("body", Body)],// Align finds its picks where they are shown and takes both ends into the moved bodies'// frame itself: a pick mapped into the frame of the body under it would put the two ends@@ -227,11 +227,11 @@ impl Mapper<'_> {let m = if self.here { self.f.sketch } else { under.as_ref().map(|(m, _)| *m).unwrap_or(self.f.active) };self.first.get_or_insert(m);let out = self.local_point(&m, p);- // The command sees the pick in the frame of the body under it. Remember the bodies- // whose faces meet there, so a face of that body is found and a body that only- // shares its place in the model does not make the pick ambiguous (#419).- if let Some((_, names)) = &under {- remember(out.as_ref().and_then(vec3).unwrap_or(p), names.clone());+ // The command sees the pick in the frame of the body under it. Remember where it was+ // picked and the bodies whose faces meet there, so a face of that body is found and a+ // body that only shares its place in the model does not make the pick ambiguous (#419).+ if !self.here {+ remember(out.as_ref().and_then(vec3).unwrap_or(p), p, under.map(|(_, names)| names).unwrap_or_default());}out}@@ -361,9 +361,19 @@ thread_local! {/// The outermost command is `solid.move`, whose parameters stay in the world when its bodies/// lie in differently turned frames (`split_move`).static OUTER_MOVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };- /// The picks of the running command: the point it sees and the bodies whose faces meet- /// there (the first is the body under it; more than one means the pick is ambiguous).- static PICKS: std::cell::RefCell<Vec<(Vec3, Vec<String>)>> = const { std::cell::RefCell::new(Vec::new()) };+ /// The picks of the running command.+ static PICKS: std::cell::RefCell<Vec<Pick>> = const { std::cell::RefCell::new(Vec::new()) };+}++/// A pick of the running command.+struct Pick {+ /// The point the command sees.+ local: Vec3,+ /// Where it was picked.+ world: Vec3,+ /// The bodies whose faces meet there: the first is the body under it, more than one means+ /// the pick is ambiguous, and none that no face is under it.+ bodies: Vec<String>,}/// How many picks of one command are remembered (a command takes few).@@ -371,21 +381,28 @@ const MAX_PICKS: usize = 4096;/// How many bodies may meet at one pick (an ambiguous pick names them).const MAX_PICK_BODIES: usize = 64;-/// Remember the bodies whose faces meet at a pick, against the point the command sees.-fn remember(point: Vec3, names: Vec<String>) {- let names: Vec<String> = names.into_iter().take(MAX_PICK_BODIES).collect();+/// Remember where a pick was made and the bodies whose faces meet there, against the point the+/// command sees.+fn remember(local: Vec3, world: Vec3, names: Vec<String>) {+ let bodies: Vec<String> = names.into_iter().take(MAX_PICK_BODIES).collect();PICKS.with(|picks| {let mut picks = picks.borrow_mut();if picks.len() < MAX_PICKS {- picks.push((point, names));+ picks.push(Pick { local, world, bodies });}});}-/// The bodies whose faces meet at `point`, when the running command picked it: the first is-/// the body under the pick, and more than one means the pick is ambiguous.+/// The bodies whose faces meet at `point`, when the running command picked it on a face: the+/// first is the body under the pick, and more than one means the pick is ambiguous.pub(crate) fn picked(point: Vec3) -> Option<Vec<String>> {- PICKS.with(|picks| picks.borrow().iter().find(|(p, _)| *p == point).map(|(_, names)| names.clone()))+ PICKS.with(|picks| picks.borrow().iter().find(|p| p.local == point && !p.bodies.is_empty()).map(|p| p.bodies.clone()))+}++/// Where the running command's `nth` pick seen at `point` was picked (counting from 0: two picks+/// on parts placed apart can be the same point in their own frames).+pub(crate) fn picked_world(point: Vec3, nth: usize) -> Option<Vec3> {+ PICKS.with(|picks| picks.borrow().iter().filter(|p| p.local == point).nth(nth).map(|p| p.world))}/// Forget the picks of the last command: a new one starts with none.diff --git a/crates/engine/src/frames_tests.rs b/crates/engine/src/frames_tests.rsindex 69fd5e5367..3331236ff5 100644--- a/crates/engine/src/frames_tests.rs+++ b/crates/engine/src/frames_tests.rs@@ -611,3 +611,399 @@ fn a_combine_tool_stays_where_it_is_placed() {assert_eq!(lumps(&s), Some(2), "the boss stays where it is in the world");assert!((volume(&mut s) - 17000.0).abs() < 1e-6, "{}", volume(&mut s));}++/// The volume of one body in its own frame (a component's body once, however often it is placed).+fn body_volume(s: &Session, body: &str) -> f64 {+ s.model.state().body(body).unwrap_or_else(|| panic!("no body {body}")).measure().unwrap().volume+}++/// The body the last feature, a fillet or chamfer, keeps.+fn blend_body(s: &Session) -> Option<String> {+ match &s.doc.features.last().unwrap().kind {+ solidcraft_doc::FeatureKind::Fillet { body, .. } | solidcraft_doc::FeatureKind::Chamfer { body, .. } => body.as_ref().map(|b| b.0.clone()),+ k => panic!("{k:?}"),+ }+}++/// The points the last feature, a fillet or chamfer, keeps.+fn blend_edges(s: &Session) -> Vec<Vec3> {+ match &s.doc.features.last().unwrap().kind {+ solidcraft_doc::FeatureKind::Fillet { edges, .. } | solidcraft_doc::FeatureKind::Chamfer { edges, .. } => edges.iter().map(|p| p.0).collect(),+ k => panic!("{k:?}"),+ }+}++fn refused(s: &mut Session, id: &str, p: Value) -> String {+ let features = s.doc.features.len();+ let err = s.execute(id, &p).expect_err(&format!("{id} {p}")).to_string();+ assert_eq!(s.doc.features.len(), features, "{id} {p}: {err}");+ err+}++/// A 1 mm chamfer of a 40 mm edge between square faces.+const CUT: f64 = 20.0;+/// A box 40 x 30 x 10.+const BLOCK: f64 = 12000.0;++/// Component Base holds "Base block" and component Cap "Cap block", each a 40 x 30 x 10 box,+/// Cap's at `cap_z` in its own frame and its placement moved by `moved`; Base is active.+fn two_parts(cap_z: f64, moved: [f64; 3]) -> Session {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name": "Base"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Base block"}));+ run(&mut s, "component.create", json!({"name": "Cap", "parent": "root"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "corner": [0, 0, cap_z], "body_name": "Cap block"}));+ if moved != [0.0; 3] {+ run(&mut s, "occurrence.move", json!({"occurrence": "Cap:1", "translate": moved}));+ }+ run(&mut s, "component.activate", json!({"component": "Base"}));+ s+}++/// Component Lower holds "Lower block" (40 x 30 x 10) and component Upper "Upper block" (40 x 30+/// x 2), both from their frames' origins, so Upper's bottom edges lie on Lower's in their own+/// frames. Upper:1 sits on Lower, and a second placement, Upper:2, under it. The root is active.+fn lower_and_uppers() -> (Session, u64) {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name": "Lower"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Lower block"}));+ run(&mut s, "component.create", json!({"name": "Upper", "parent": "root"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 2, "body_name": "Upper block"}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "occurrence.move", json!({"occurrence": "Upper:1", "translate": [0, 0, 10]}));+ let under = run(&mut s, "occurrence.copy", json!({"component": "Upper"}))["occurrence"].as_u64().unwrap();+ run(&mut s, "occurrence.move", json!({"occurrence": under, "space": "world", "translate": [0, 0, -12]}));+ let (lo, hi) = world_bbox(&s, "Upper block (Upper:2)");+ assert!(near(lo, Vec3::new(0.0, 0.0, -2.0)) && near(hi, Vec3::new(40.0, 30.0, 0.0)), "{lo:?} {hi:?}");+ (s, under)+}++/// A world pick on an edge of a moved part finds that part, though another part has an edge at+/// the same point in its own frame, and the blend keeps the body it found.+#[test]+fn edge_picks_on_a_moved_part_find_it_past_other_parts_frames() {+ let round = (1.0 - std::f64::consts::PI / 4.0) * 40.0;+ for (case, mut s, id, p, body, base, cap) in [+ ("v0", two_parts(0.0, [0.0, 0.0, 50.0]), "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}), "Base block", BLOCK - CUT, BLOCK),+ ("v4", two_parts(0.0, [0.0, 0.0, 50.0]), "solid.chamfer", json!({"edges": [[20, 0, 50]], "distance": 1}), "Cap block", BLOCK, BLOCK - CUT),+ ("v5", two_parts(0.0, [500.0, 0.0, 0.0]), "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}), "Base block", BLOCK - CUT, BLOCK),+ (+ "v6",+ two_parts(0.0, [0.0, 0.0, 50.0]),+ "solid.chamfer",+ json!({"edges": [[20, 0, 0]], "distance": 1, "tangent_chain": false}),+ "Base block",+ BLOCK - CUT,+ BLOCK,+ ),+ ("fillet", two_parts(0.0, [0.0, 0.0, 50.0]), "solid.fillet", json!({"edges": [[20, 0, 0]], "radius": 1}), "Base block", BLOCK - round, BLOCK),+ (+ "press_pull",+ two_parts(0.0, [0.0, 0.0, 50.0]),+ "solid.press_pull",+ json!({"edges": [[20, 0, 0]], "distance": 1}),+ "Base block",+ BLOCK - round,+ BLOCK,+ ),+ ("v1 unplaced", two_parts(50.0, [0.0; 3]), "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}), "Base block", BLOCK - CUT, BLOCK),+ ] {+ if case == "v5" {+ run(&mut s, "component.activate", json!({"component": "root"}));+ }+ let features = s.doc.features.len();+ run(&mut s, id, p.clone());+ assert_eq!(s.doc.features.len(), features + 1, "{case}");+ assert_eq!(blend_body(&s).as_deref(), Some(body), "{case}");+ let (b, c) = (body_volume(&s, "Base block"), body_volume(&s, "Cap block"));+ assert!((b - base).abs() < 1e-3 * CUT && (c - cap).abs() < 1e-3 * CUT, "{case}: Base {b}, Cap {c}");+ }+ // The pick on Cap is kept in Cap's frame.+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 50]], "distance": 1}));+ assert_eq!(blend_edges(&s), vec![Vec3::new(20.0, 0.0, 0.0)]);+}++/// Where the edges of two parts lie in one place in the world, a pick without `body` is refused,+/// naming both; with `body`, or a pick's own `body`, the named part is cut.+#[test]+fn edge_picks_where_two_parts_meet_name_both() {+ for (case, cap_z, moved) in [("v2 unplaced", 0.0, [0.0; 3]), ("v3 moved", 50.0, [0.0, 0.0, -50.0])] {+ for (id, size) in [("solid.chamfer", "distance"), ("solid.fillet", "radius")] {+ let mut s = two_parts(cap_z, moved);+ let err = refused(&mut s, id, json!({"edges": [[20, 0, 0]], size: 1}));+ assert!(+ err.contains("[20, 0, 0] lies on edges of 2 bodies, Base block and Cap block") && err.contains("with `body`"),+ "{case} {id}: {err}"+ );+ assert!(!err.contains("hidden"), "{err}");+ assert_eq!((body_volume(&s, "Base block"), body_volume(&s, "Cap block")), (BLOCK, BLOCK));+ }+ let mut s = two_parts(cap_z, moved);+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1, "body": "Cap block"}));+ assert!((body_volume(&s, "Cap block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Base block") == BLOCK, "{case}");+ let mut s = two_parts(cap_z, moved);+ run(&mut s, "solid.chamfer", json!({"edges": [{"point": [20, 0, 0], "body": "Cap block"}], "distance": 1}));+ assert!((body_volume(&s, "Cap block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Base block") == BLOCK, "{case}");+ assert_eq!(blend_body(&s).as_deref(), Some("Cap block"), "{case}");+ }+}++/// The lower block's outer bottom edge, with a hidden upper block placed under it: that block's+/// top edge lies there too, so the pick is refused and the message says it is hidden. A lower+/// block's edge whose only twin is in the upper block's own frame is cut.+#[test]+fn edge_picks_beside_a_hidden_placement_name_it() {+ let (mut s, under) = lower_and_uppers();+ run(&mut s, "browser.visibility", json!({"visible": false, "paths": [[under]]}));+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}));+ assert!(+ err.contains("lies on edges of 2 bodies, Lower block and Upper block (Upper:2)") && err.contains("(Upper block (Upper:2) is hidden)"),+ "{err}"+ );+ run(&mut s, "browser.visibility", json!({"visible": true, "paths": [[under]]}));+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}));+ assert!(err.contains("Lower block and Upper block (Upper:2)") && !err.contains("hidden"), "{err}");+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1, "body": "Lower block"}));+ assert!((body_volume(&s, "Lower block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Upper block") == 2400.0);+ // Upper:2 out of the way: the lower block's bottom left edge has a twin only in Upper's frame.+ let (mut s, under) = lower_and_uppers();+ run(&mut s, "occurrence.move", json!({"occurrence": under, "space": "world", "translate": [0, 0, -100]}));+ run(&mut s, "solid.chamfer", json!({"edges": [[0, 15, 0]], "distance": 1}));+ assert_eq!(blend_body(&s).as_deref(), Some("Lower block"));+ assert!((body_volume(&s, "Lower block") - (BLOCK - 15.0)).abs() < 1e-3 * CUT && body_volume(&s, "Upper block") == 2400.0);+}++/// The lower block's top edge, where the upper block on it has its bottom edges, is refused+/// naming both; `body` cuts either. A second lower block placed on the upper one meets it at the+/// upper block's top edges likewise.+#[test]+fn edge_picks_on_a_top_edge_under_another_part_name_both() {+ let (mut s, _) = lower_and_uppers();+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 10]], "distance": 1}));+ assert!(err.contains("[20, 0, 10] lies on edges of 2 bodies, Lower block and Upper block:"), "{err}");+ for (body, lower, upper) in [("Lower block", BLOCK - CUT, 2400.0), ("Upper block", BLOCK, 2400.0 - CUT)] {+ let (mut s, _) = lower_and_uppers();+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 10]], "distance": 1, "body": body}));+ let (b, c) = (body_volume(&s, "Lower block"), body_volume(&s, "Upper block"));+ assert!((b - lower).abs() < 1e-3 * CUT && (c - upper).abs() < 1e-3 * CUT, "{body}: Lower {b}, Upper {c}");+ }+ let (mut s, _) = lower_and_uppers();+ let stacked = run(&mut s, "occurrence.copy", json!({"component": "Lower"}))["occurrence"].as_u64().unwrap();+ run(&mut s, "occurrence.move", json!({"occurrence": stacked, "space": "world", "translate": [0, 0, 12]}));+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 12]], "distance": 1}));+ assert!(err.contains("[20, 0, 12] lies on edges of 2 bodies, Upper block and Lower block (Lower:2):"), "{err}");+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 12]], "distance": 1, "body": "Lower block (Lower:2)"}));+ assert_eq!(blend_body(&s).as_deref(), Some("Lower block"));+ assert_eq!(blend_edges(&s), vec![Vec3::new(20.0, 0.0, 0.0)]);+ assert!((body_volume(&s, "Lower block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Upper block") == 2400.0);+}++/// A block's top edge inside the bottom face of a plate placed on it: the block alone has an edge+/// there.+#[test]+fn an_edge_inside_another_parts_face_is_picked() {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name": "Lower"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Lower block"}));+ run(&mut s, "component.create", json!({"name": "Plate", "parent": "root"}));+ run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 2, "corner": [-30, -35, 0], "body_name": "Plate block"}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "occurrence.move", json!({"occurrence": "Plate:1", "translate": [0, 0, 10]}));+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 10]], "distance": 1}));+ assert_eq!(blend_body(&s).as_deref(), Some("Lower block"));+ assert!((body_volume(&s, "Lower block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Plate block") == 20000.0);+}++/// Round edges of two parts in one place: a pick a little inside them, as a click on the drawn+/// edge lands, is refused naming both. A disc edge 0.2 mm out is another edge.+#[test]+fn coincident_round_edges_of_two_parts_are_refused() {+ let parts = |b_radius: f64| {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name": "A"}));+ run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 10, "body_name": "A rod"}));+ run(&mut s, "component.create", json!({"name": "B", "parent": "root"}));+ run(&mut s, "solid.cylinder", json!({"radius": b_radius, "height": 2, "body_name": "B disc"}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ run(&mut s, "occurrence.move", json!({"occurrence": "B:1", "translate": [0, 0, 10]}));+ s+ };+ let pi = std::f64::consts::PI;+ let disc = |r: f64| pi * r * r * 2.0;+ // A round of radius 1 on the rod's top edge, radius 10: its section's area at its centroid's+ // radius.+ let (a, c) = (1.0 - pi / 4.0, (10.0 - 3.0 * pi) / (3.0 * (4.0 - pi)));+ let rounded = pi * 100.0 * 10.0 - a * 2.0 * pi * (10.0 - c);+ let mut s = parts(10.0);+ let err = refused(&mut s, "solid.fillet", json!({"edges": [[0, 9.98, 10]], "radius": 1}));+ assert!(err.contains("lies on edges of 2 bodies, A rod and B disc"), "{err}");+ for pick in [[0.0, 9.98, 10.0], [0.0, 10.0, 10.0]] {+ let mut s = parts(10.2);+ run(&mut s, "solid.fillet", json!({"edges": [pick], "radius": 1}));+ assert_eq!(blend_body(&s).as_deref(), Some("A rod"), "{pick:?}");+ let (v, b) = (body_volume(&s, "A rod"), body_volume(&s, "B disc"));+ assert!((v - rounded).abs() < 2e-4 * rounded && (b - disc(10.2)).abs() < 1e-6 * b, "{pick:?}: {v} vs {rounded}, {b}");+ }+}++/// Two picks at one point of their parts' frames, on two parts, in one command: each is looked+/// up where it was picked, and as the feature keeps one body or none, it is refused.+#[test]+fn two_picks_at_one_point_of_two_parts_frames_are_refused() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0], [20, 0, 50]], "distance": 1}));+ assert!(err.contains("the picks lie on 2 bodies, Base block and Cap block") && err.contains("in a command of its own"), "{err}");+ assert_eq!((body_volume(&s, "Base block"), body_volume(&s, "Cap block")), (BLOCK, BLOCK));+}++/// One part placed twice: its edge picked through both placements, or through two placements in+/// one place, is one edge of one body.+#[test]+fn one_edge_of_two_placements_is_one_edge() {+ for (offset, edges) in [+ ([0.0, 40.0, 0.0], json!([[20, 0, 0], [20, 40, 0]])),+ ([0.0; 3], json!([[20, 0, 0]])),+ // Overlapping along the edge: the pick is at x 25 of one placement and x 15 of the other.+ ([10.0, 0.0, 0.0], json!([[25, 0, 0]])),+ ] {+ let mut s = Session::default();+ run(&mut s, "component.create", json!({"name": "Pin"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Pin block"}));+ run(&mut s, "component.activate", json!({"component": "root"}));+ let copy = run(&mut s, "occurrence.copy", json!({"component": "Pin"}))["occurrence"].as_u64().unwrap();+ if offset != [0.0; 3] {+ run(&mut s, "occurrence.move", json!({"occurrence": copy, "space": "world", "translate": offset}));+ }+ run(&mut s, "solid.chamfer", json!({"edges": edges, "distance": 1}));+ assert!((body_volume(&s, "Pin block") - (BLOCK - CUT)).abs() < 1e-3 * CUT, "{offset:?}: {}", body_volume(&s, "Pin block"));+ assert!((volume(&mut s) - 2.0 * (BLOCK - CUT)).abs() < 2e-3 * CUT, "{offset:?}");+ assert_eq!(blend_body(&s), None, "one body in the model");+ }+}++/// An edge given by body and index keeps its body on the feature.+#[test]+fn an_edge_by_index_keeps_its_body() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ let tol = 1e-3_f64.max(s.model.state().body("Base block").unwrap().body.size() * 2e-3);+ let edges = s.model.state().body("Base block").unwrap().body.edges(tol).unwrap();+ let index = edges.iter().position(|e| e.mid.dist(Vec3::new(20.0, 0.0, 0.0)) < 1e-6).unwrap();+ run(&mut s, "solid.chamfer", json!({"edges": [{"body": "Base block", "index": index}], "distance": 1}));+ assert_eq!(blend_body(&s).as_deref(), Some("Base block"));+ assert!((body_volume(&s, "Base block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Cap block") == BLOCK);+}++/// A pick 0.42 mm off a moved part's edge, beyond the faces the placement is found by, is still+/// looked up where it was picked: another part's edge there in its own frame is not in the way.+#[test]+fn a_pick_beside_an_edge_is_looked_up_where_it_was_picked() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ run(&mut s, "solid.chamfer", json!({"edges": [[20, -0.3, -0.3]], "distance": 1}));+ assert_eq!(blend_body(&s).as_deref(), Some("Base block"));+ assert!((body_volume(&s, "Base block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Cap block") == BLOCK);+}++/// A chamfer of a moved part, found by a world pick, stays on that part through an edit of+/// the other part, a recompute, undo and redo, and Edit Feature.+#[test]+fn a_blend_found_by_a_world_pick_keeps_its_part() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 50]], "distance": 1, "name": "Edge"}));+ let check = |s: &Session, base: f64, cap: f64, step: &str| {+ let (b, c) = (body_volume(s, "Base block"), body_volume(s, "Cap block"));+ assert!((b - base).abs() < 1e-3 * CUT && (c - cap).abs() < 1e-3 * CUT, "{step}: Base {b}, Cap {c}");+ assert!(s.model.results.iter().all(|r| r.error.is_none()), "{step}: {:?}", s.model.results);+ };+ check(&s, BLOCK, BLOCK - CUT, "made");+ run(&mut s, "timeline.edit", json!({"feature": "Box1", "set": {"length": "50"}}));+ check(&s, 15000.0, BLOCK - CUT, "Base edited");+ run(&mut s, "timeline.compute_all", json!({}));+ check(&s, 15000.0, BLOCK - CUT, "computed");+ run(&mut s, "edit.undo", json!({}));+ check(&s, BLOCK, BLOCK - CUT, "undone");+ run(&mut s, "edit.redo", json!({}));+ check(&s, 15000.0, BLOCK - CUT, "redone");+ run(&mut s, "timeline.redefine", json!({"feature": "Edge", "command": "solid.chamfer", "params": {"edges": [[20, 0, 50]], "distance": 2}}));+ check(&s, 15000.0, BLOCK - 4.0 * CUT, "redefined");+ assert_eq!(blend_body(&s).as_deref(), Some("Cap block"));+}++/// A corner of a moved part is refused at the point picked, in the world.+#[test]+fn a_corner_of_a_moved_part_is_refused_where_it_was_picked() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[0, 0, 50]], "distance": 1}));+ assert!(err.contains("[0, 0, 50] is where 3 edges meet"), "{err}");+}++/// Picks far out, or overflowing a placement, in a design with moved parts are refused.+#[test]+fn hostile_edge_picks_in_a_placed_design_are_refused() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ for pick in [json!([1e300, 0, 0]), json!([1.7e308, -1.7e308, 1.7e308]), json!([[1e300, 0, 0]])] {+ let err = s.execute("solid.chamfer", &json!({"edges": [pick], "distance": 1})).expect_err("refused");+ assert!(matches!(err, crate::EngineError::BadParams { .. }), "{pick}: {err}");+ }+ assert_eq!((body_volume(&s, "Base block"), body_volume(&s, "Cap block")), (BLOCK, BLOCK));+}++/// The index of the edge of `body` whose midpoint is `mid`.+fn edge_index(s: &Session, body: &str, mid: Vec3) -> usize {+ let b = s.model.state().body(body).unwrap().body.clone();+ let edges = b.edges(1e-3_f64.max(b.size() * 2e-3)).unwrap();+ edges.iter().position(|e| e.mid.dist(mid) < 1e-6).unwrap()+}++/// A pick's own `body` must exist and agree with the feature's `body`: the feature keeps one+/// body, and the pick is found on its own.+#[test]+fn a_picks_own_body_must_agree_with_body() {+ let mut s = two_parts(0.0, [0.0, 0.0, 50.0]);+ let index = edge_index(&s, "Cap block", Vec3::new(20.0, 0.0, 0.0));+ for edge in [json!({"point": [20, 0, 50], "body": "Cap block"}), json!({"body": "Cap block", "index": index})] {+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [edge], "body": "Base block", "distance": 1}));+ assert!(err.contains("an edge names `Cap block`, but `body` is `Base block`: give one"), "{edge}: {err}");+ }+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [{"point": [20, 0, 0], "body": "Nobody"}], "distance": 1}));+ assert!(err.contains("no body `Nobody`"), "{err}");+ assert_eq!((body_volume(&s, "Base block"), body_volume(&s, "Cap block")), (BLOCK, BLOCK));+ run(&mut s, "solid.chamfer", json!({"edges": [{"point": [20, 0, 50], "body": "Cap block"}], "body": "Cap block", "distance": 1}));+ assert!((body_volume(&s, "Cap block") - (BLOCK - CUT)).abs() < 1e-3 * CUT && body_volume(&s, "Base block") == BLOCK);+}++/// Press Pull on an edge is a fillet: where two parts meet it is refused naming both, and+/// `body`, by its own name or a placement's, rounds that part.+#[test]+fn press_pull_on_an_edge_where_two_parts_meet_takes_body() {+ let round = (1.0 - std::f64::consts::PI / 4.0) * 40.0;+ let mut s = two_parts(50.0, [0.0, 0.0, -50.0]);+ let err = refused(&mut s, "solid.press_pull", json!({"edges": [[20, 0, 0]], "distance": 1}));+ assert!(err.contains("[20, 0, 0] lies on edges of 2 bodies, Base block and Cap block: name the one to round with `body`"), "{err}");+ run(&mut s, "solid.press_pull", json!({"edges": [[20, 0, 0]], "distance": 1, "body": "Cap block"}));+ assert_eq!(blend_body(&s).as_deref(), Some("Cap block"));+ assert!((body_volume(&s, "Cap block") - (BLOCK - round)).abs() < 1e-3 * CUT && body_volume(&s, "Base block") == BLOCK);+ let (mut s, _) = lower_and_uppers();+ let stacked = run(&mut s, "occurrence.copy", json!({"component": "Lower"}))["occurrence"].as_u64().unwrap();+ run(&mut s, "occurrence.move", json!({"occurrence": stacked, "space": "world", "translate": [0, 0, 12]}));+ run(&mut s, "solid.press_pull", json!({"edges": [[20, 0, 12]], "distance": 1, "body": "Lower block (Lower:2)"}));+ assert_eq!(blend_body(&s).as_deref(), Some("Lower block"));+ assert_eq!(blend_edges(&s), vec![Vec3::new(20.0, 0.0, 0.0)]);+ assert!((body_volume(&s, "Lower block") - (BLOCK - round)).abs() < 1e-3 * CUT && body_volume(&s, "Upper block") == 2400.0);+}++/// A body offset squashed flat, as only a hostile file has, leaves no placement to look a pick+/// up through: the pick is looked up in the body's own frame, so one far from every edge is+/// refused and one on an edge is cut.+#[test]+fn edge_picks_with_no_placement_to_look_through_are_checked() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Box"}));+ let mut flat = solidcraft_doc::IDENTITY;+ flat[2][2] = 0.0;+ s.doc_mut().body_offsets.insert("Box".into(), flat);+ let err = refused(&mut s, "solid.chamfer", json!({"edges": [[20, 15, 10]], "distance": 1}));+ assert!(err.contains("no edge at [20, 15, 10]"), "{err}");+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}));+ assert!((body_volume(&s, "Box") - (BLOCK - CUT)).abs() < 1e-3 * CUT, "{}", body_volume(&s, "Box"));+}diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rsindex ec2ebdcbe7..dc36f7024c 100644--- a/crates/engine/src/schema/features.rs+++ b/crates/engine/src/schema/features.rs@@ -529,7 +529,8 @@ pub struct FilletParams {/// The radius; the chord's width with `type: chord`, the equivalent circular setback with/// `type: curvature`, the start radius with `type: variable` or `spline`.pub radius: LengthExpr,- /// The body whose edges the points pick. Default: whichever body has an edge there.+ /// The body whose edges the points pick. Default: each point is looked up on every placed+ /// body, shown or hidden, and a point on edges of 2 bodies is refused, naming them.#[serde(default)]pub body: Option<String>,/// Round each picked edge's tangent chain with it. Default: true; false rounds exactly thediff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex fe656208e6..4e4edd5480 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -96,6 +96,74 @@ fn edge_picks_at_a_corner_are_refused() {}}+/// Edge picks on bodies apart: one pick keeps its body on the feature (the model has two), and+/// picks on both keep none, each found where it lies.+#[test]+fn edge_picks_on_bodies_apart_keep_the_body_they_lie_on() {+ let boxes = || {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Low"}));+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "corner": [0, 0, 50], "operation": "new", "body_name": "High"}));+ s+ };+ let kept = |s: &Session| match &s.doc.features.last().unwrap().kind {+ solidcraft_doc::FeatureKind::Chamfer { body, .. } => body.as_ref().map(|b| b.0.clone()),+ k => panic!("{k:?}"),+ };+ let each = |s: &Session| ["Low", "High"].map(|b| s.model.state().body(b).unwrap().measure().unwrap().volume);+ let mut s = boxes();+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0]], "distance": 1}));+ assert_eq!(kept(&s).as_deref(), Some("Low"));+ let [low, high] = each(&s);+ assert!((low - 11980.0).abs() < 0.02 && high == 12000.0, "{low} {high}");+ let mut s = boxes();+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 0, 0], [20, 0, 60]], "distance": 1}));+ assert_eq!(kept(&s), None);+ let [low, high] = each(&s);+ assert!((low - 11980.0).abs() < 0.02 && (high - 11980.0).abs() < 0.02, "{low} {high}");+}++/// The halves of a split box share the edges along the cut: a pick on one is refused naming both+/// halves, and `body` cuts the half named.+#[test]+fn edge_picks_on_the_cut_of_a_split_body_name_both_halves() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Box"}));+ run(&mut s, "solid.split_body", json!({"body": "Box", "plane": {"origin": [20, 0, 0], "normal": [1, 0, 0]}}));+ let features = s.doc.features.len();+ let err = s.execute("solid.chamfer", &json!({"edges": [[20, 15, 10]], "distance": 1})).unwrap_err().to_string();+ assert!(err.contains("[20, 15, 10] lies on edges of 2 bodies, Box and Box (1)") && err.contains("with `body`"), "{err}");+ assert_eq!(s.doc.features.len(), features);+ run(&mut s, "solid.chamfer", json!({"edges": [[20, 15, 10]], "distance": 1, "body": "Box (1)"}));+ let half = |s: &Session, b: &str| s.model.state().body(b).unwrap().measure().unwrap().volume;+ assert!((half(&s, "Box (1)") - 5985.0).abs() < 0.02 && (half(&s, "Box") - 6000.0).abs() < 1e-6, "{} {}", half(&s, "Box"), half(&s, "Box (1)"));+}++/// A box touching a cylinder along the cylinder's seam: the seam is not an edge to blend, so the+/// box's edge there is cut.+#[test]+fn an_edge_along_another_bodys_seam_is_picked() {+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 10, "body_name": "Rod"}));+ let rod = s.model.state().body("Rod").unwrap().body.clone();+ let mesh = rod.mesh(&solidcraft_kernel::MeshTolerance::chord(0.06)).unwrap();+ let seam = mesh.edges.iter().zip(&mesh.seams).find(|(_, seam)| **seam).unwrap().0[0];+ // The box's quarter past the seam's line is outside the cylinder: they touch along it.+ run(+ &mut s,+ "solid.box",+ json!({"length": 20, "width": 20, "height": 10, "corner": [seam.x, seam.y, 0], "operation": "new", "body_name": "Block"}),+ );+ run(&mut s, "solid.chamfer", json!({"edges": [[seam.x, seam.y, 5]], "distance": 1}));+ let kept = match &s.doc.features.last().unwrap().kind {+ solidcraft_doc::FeatureKind::Chamfer { body, .. } => body.as_ref().map(|b| b.0.clone()),+ k => panic!("{k:?}"),+ };+ assert_eq!(kept.as_deref(), Some("Block"));+ let v = |b: &str| s.model.state().body(b).unwrap().measure().unwrap().volume;+ assert!((v("Block") - 3995.0).abs() < 0.02 && (v("Rod") - PI * 1000.0).abs() < 1.0, "{} {}", v("Block"), v("Rod"));+}+#[test]fn fillet_as_wide_as_a_face_rounds_it_off() {// #199: 14 x 6 x 10 box, the four vertical edges at r = 3 (half the 6 mm end faces).diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.mdindex a9b65b9a1d..d44942205c 100644--- a/skills/solidcraft-modeling/reference.md+++ b/skills/solidcraft-modeling/reference.md@@ -78,7 +78,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim| `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. `body_name` names the body it makes. With `operation:"cut"`, `targets:["Top"]` cuts only the bodies listed, so the cutter can pass through other bodies. || `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. To tie a cylinder standing on a flat face to the part, give `base` as numbers on that face and add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face, as for `solid.hole`): the base centre then sits at those distances from the edges and follows them. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. || `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the "Ids" section above. |-| `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge. A pick farther than 5% of the body's size from every edge is refused, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. |+| `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge. A pick farther than 5% of the body's size from every edge is refused, so check that the face count changed. A pick where two bodies have an edge, shown or hidden (parts touching, the halves of a split), is refused naming both: give `body`. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. || `solid.shell` | `faces:[[x,y,z]]`, `thickness` | A point on each face to remove, or its name from `body_topology`. Fillet first, except an edge of a removed face or a fillet between curved faces (see Order in `SKILL.md`). Bodies with lofted or swept faces are refused (`offset: only bodies with planes, cylinders, cones, spheres and tori`): hollow a loft with a smaller loft and `operation: cut`. || `solid.hole` | `position:[x,y,z]` on a face (numbers or length expressions such as `["40", "width/2", "t"]`, which the hole then follows) + `diameter`, or `sketch` (+ `points`) | `clearance:"M3"`. `depth` defaults to through all. `type` is one of simple/drilled/counterbore/countersink. A `countersink` needs `cs_diameter` and `cs_angle`; a `counterbore` needs `cb_diameter` and `cb_depth`. `position` is a fixed point; to tie it to the part, add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face): the centre then sits at those distances from the edges and follows them. || `solid.pattern.rectangular` | `features`, `dir1`, `count1`, `spacing1` (+ `dir2`, `count2`, `spacing2`) | Spacing takes expressions and follows parameters. |