diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index 2b2465301..72da5f138 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -260,6 +260,9 @@ impl EdgeHit { /// answering to it (merged into it, or the named piece told apart by the faces around it); else /// the piece of it nearest `p` (`split`). pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { + if crate::sheet::split_sheet_face_name(name).is_some() { + return sheet_locate(st, name, p); + } // Every body's names are read below: work out the ones not known yet on all cores first // (each body's names are its own, whichever thread works them out). if legacy_name(name).is_none() { @@ -278,6 +281,9 @@ pub fn locate_face(st: &ModelState, name: &str, p: Vec3) -> Option { /// face), or on this body it names a piece of a split face or a merged one. The same face on /// another body (a copy of this one) is not a piece of this body's face. pub(crate) fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &str, p: Vec3) -> Option { + if crate::sheet::split_sheet_face_name(name).is_some() { + return sheet_locate(st, name, p); + } if legacy_name(name).is_none() && let Some(i) = body.and_then(|n| st.bodies.iter().position(|b| b.name == n)) && let Some(b) = st.bodies.get(i).filter(|b| !b.body.is_mesh()) @@ -290,6 +296,30 @@ pub(crate) fn locate_face_on_body(st: &ModelState, body: Option<&str>, name: &st locate_face(st, name, p) } +/// [`locate_face`] for a sheet face's readable name (`sheet:::`, see +/// [`crate::sheet::body_sheet_face_names`]): the face of that body the sheet names so, else the +/// piece of it nearest `p` (`split`). The sheet itself says which face it is, so the name holds +/// however the faces of the body are numbered. +fn sheet_locate(st: &ModelState, name: &str, p: Vec3) -> Option { + let (body, _) = crate::sheet::split_sheet_face_name(name)?; + let (bi, b) = st.bodies.iter().enumerate().find(|(_, b)| b.name == body && !b.body.is_mesh())?; + let names = crate::sheet::body_sheet_face_names(st, b); + let faces: Vec = names.iter().enumerate().filter(|(_, n)| n.as_deref() == Some(name)).map(|(i, _)| i).collect(); + let m = b.mesh(); + let (distance, face, point) = + faces.iter().filter_map(|f| nearest_on_face(&m, *f, p).map(|(d, q)| (d, *f, q))).min_by(|a, c| a.0.total_cmp(&c.0))?; + Some(FaceHit { + body: bi, + face, + point, + split: faces.len() > 1, + merged: false, + verified: true, + on_point: distance <= (b.body.size() * 1e-3).max(1e-3), + legacy: false, + }) +} + /// [`locate_face`] among `bodies` (with their indices). fn locate_in<'a>(bodies: impl Iterator, name: &str, p: Vec3) -> Option { if let Some(old) = legacy_name(name) { @@ -401,6 +431,16 @@ pub fn locate_one(st: &ModelState, body: Option<&str>, name: &str) -> Result = st.bodies.iter().enumerate().filter(|(_, b)| !b.body.is_mesh() && body.is_none_or(|n| b.name == n)).collect(); // As [`locate_face`]: the names of several bodies are worked out on all cores first. diff --git a/crates/doc/src/sheet.rs b/crates/doc/src/sheet.rs index f209d20f8..22b4ca0d0 100644 --- a/crates/doc/src/sheet.rs +++ b/crates/doc/src/sheet.rs @@ -18,8 +18,11 @@ use crate::{DocError, Document, IDENTITY, Mat, Result, apply_point, apply_vector #[path = "sheet_convert.rs"] mod convert; +#[path = "sheet_face_names.rs"] +mod face_names; pub use convert::{bend_edge_names, convert_body}; pub(crate) use convert::{outline_loop, round_wall}; +pub use face_names::body_sheet_face_names; // Bound the aggregate geometry, including sampled curves and intermediate clipping pieces. // These are work limits, never geometry truncation: a larger input returns a useful error. diff --git a/crates/doc/src/sheet_face_names.rs b/crates/doc/src/sheet_face_names.rs new file mode 100644 index 000000000..3e37736f5 --- /dev/null +++ b/crates/doc/src/sheet_face_names.rs @@ -0,0 +1,131 @@ +//! Readable names of a sheet metal body's faces, from the sheet itself: `:top`, +//! `:bottom` and `:rim.` (the names sketches on sheet faces keep, see +//! [`SheetBody::panel_face_at`]); a bend's curved faces, `:bend.inner` and +//! `:bend.outer`; and where a flange's panel runs on past its bend's ends (toward a +//! neighbouring flange), the rim along the bend there, `:rim.ext0` and `rim.ext1`. A panel is `base` or a flange's tag (`F.`), so the names +//! say what each face is and stay with it when sizes change or other flanges come and go. + +use solidcraft_geom::{Vec2, Vec3}; + +use super::SheetBody; +use crate::{ModelBody, ModelState, apply_point, mat_inverse}; + +/// The share of a face's sample points that must agree on a name for the face to take it. +const AGREE: f64 = 0.8; + +impl SheetBody { + /// The readable name of the face of this sheet a point lies on (sheet coordinates, within + /// `tol`, kept below a quarter of the thickness): a flat face's (see + /// [`panel_face_at`](Self::panel_face_at)), else a bend's inner or outer face. + pub fn face_name_at(&self, p: Vec3, tol: f64) -> Option { + self.panel_face_at(p, tol).map(|(name, _)| name).or_else(|| self.bend_face_at(p, tol)).or_else(|| self.ext_rim_at(p, tol)) + } + + /// The rim of a flange's panel along its bend line, where the panel runs on past the + /// bend's start (`:rim.ext0`) or end (`rim.ext1`). + fn ext_rim_at(&self, p: Vec3, tol: f64) -> Option { + if self.flat { + return None; + } + let tol = tol.min(self.t * 0.25); + for (pi, region) in self.panels() { + let Some(i) = pi else { continue }; + let Some(f) = self.flanges.get(i) else { continue }; + let Some(inverse) = mat_inverse(&self.world(pi)) else { continue }; + let q = apply_point(&inverse, p); + if q.z < -tol || q.z > self.t + tol { + continue; + } + let q2 = Vec2::new(q.x, q.y); + let pts = region.outer.ccw().polyline(1e-3); + let m = pts.len(); + for k in 0..m { + let (Some(&a), Some(&b)) = (pts.get(k), pts.get((k + 1) % m)) else { continue }; + let d = b - a; + if d.len2() < 1e-18 || self.rim_edge(pi, a, b, k).as_deref() != Some("bend") { + continue; + } + let along = (q2 - a).dot(d) / d.len2(); + if !(-1e-9..=1.0 + 1e-9).contains(&along) || ((a + d * along) - q2).len() > tol { + continue; + } + let end = if (q2 - f.p).dot(f.d) < f.len / 2.0 { "ext0" } else { "ext1" }; + return Some(format!("{}:rim.{end}", self.panel_name(pi))); + } + } + None + } + + /// The curved face of a bend a point lies on: `:bend.inner` (the bend's radius) or + /// `:bend.outer` (the radius plus the thickness). + fn bend_face_at(&self, p: Vec3, tol: f64) -> Option { + if self.flat { + return None; + } + let tol = tol.min(self.t * 0.25); + for (i, f) in self.flanges.iter().enumerate() { + let Some((world, o, d, start, toward)) = self.bend_frame(f) else { continue }; + let Some(inverse) = mat_inverse(&world) else { continue }; + let q = apply_point(&inverse, p) - o; + let u = q.dot(d); + let (u0, u1) = self.zone_span(f); + if u < u0 - tol || u > u1 + tol { + continue; + } + let radial = q - d * u; + let rho = radial.len(); + let side = if (rho - f.radius).abs() <= tol { + "inner" + } else if (rho - f.radius - self.t).abs() <= tol { + "outer" + } else { + continue; + }; + let phi = radial.dot(toward).atan2(radial.dot(start)); + if phi < -1e-6 || phi > f.angle.abs() + 1e-6 { + continue; + } + return Some(format!("{}:bend.{side}", self.panel_name(Some(i)))); + } + None + } +} + +/// The readable sheet names of a body's faces (by B-rep face index), as +/// [`sheet_face_name`](super::sheet_face_name)s: `sheet:::`. `None` for a face +/// the sheet does not name (a hole's wall, a pocket's floor) and for every face of a body that is +/// no folded sheet of `st`. +pub fn body_sheet_face_names(st: &ModelState, b: &ModelBody) -> Vec> { + let m = b.mesh(); + let nf = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap_or(0); + let Some(sheet) = st.sheets.iter().find(|s| s.body == b.name && !s.flat) else { return vec![None; nf] }; + // Triangle centres lie inside a face, off a curved one by its facets' sag: a fifth of the + // thickness takes them and still tells a flat face from the rim beside it. + let tol = sheet.t * 0.2; + let mut votes: Vec> = vec![Vec::new(); nf]; + let mut total = vec![0usize; nf]; + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + let (Some(v), Some(n), Some([a, b2, c])) = (votes.get_mut(*f as usize), total.get_mut(*f as usize), m.tri(t)) else { continue }; + // At most a few dozen points a face: enough to tell its name, cheap on a fine mesh. + if *n >= 48 { + continue; + } + *n += 1; + if let Some(name) = sheet.face_name_at((a + b2 + c) * (1.0 / 3.0), tol) { + match v.iter_mut().find(|(x, _)| *x == name) { + Some(x) => x.1 += 1, + None => v.push((name, 1)), + } + } + } + votes + .into_iter() + .zip(total) + .map(|(v, n)| { + v.into_iter() + .max_by_key(|x| x.1) + .filter(|(_, k)| *k as f64 >= AGREE * n.max(1) as f64) + .map(|(name, _)| super::sheet_face_name(&b.name, &name)) + }) + .collect() +} diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs index 6b02a84a6..fc82f8864 100644 --- a/crates/engine/src/cmd/inspect.rs +++ b/crates/engine/src/cmd/inspect.rs @@ -19,7 +19,9 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("model.edges", "List Edges", model_edges).icon("inspect").noundo().params("body: name"), CommandSpec::new("model.faces", "List Faces", model_faces).icon("inspect").noundo().params( "body: name → per face: index, name (what face.delete, sheet.convert `face`, solid.shell … take in place of a point), exact, area, centroid (not always on the face), \ - plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face)", + plane_normal, point (a point on the face that picks it), cylinder? ({origin, axis, radius} of a cylindrical face), \ + sheet_face? (a folded sheet's face: `sheet:::`, panel base or a flange's tag F., side top | bottom | rim. | bend.inner | bend.outer; \ + taken wherever a face name is, and it holds while sizes change and flanges come and go)", ), CommandSpec::new("model.threads", "List Threads", model_threads).icon("inspect").noundo(), CommandSpec::new("material.assign", "Physical Material", physical_material) @@ -291,6 +293,10 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { let names = solidcraft_doc::naming::face_names(b); let tol = (b.body.size() * 2e-3).max(1e-3); let spots = solidcraft_doc::naming::face_spots(b); + // A folded sheet's faces also have the readable names its sheet gives them, worked out in + // the body's own coordinates. + let model = s.model.state(); + let sheet_names = model.body(&b.name).map(|own| solidcraft_doc::sheet::body_sheet_face_names(&model, own)).unwrap_or_default(); let faces: Vec = b .body .faces(tol)? @@ -299,6 +305,9 @@ fn model_faces(s: &mut Session, p: &Value) -> Result { let spot = spots.get(f.index).copied().flatten(); let mut v = json!({"index": f.index, "name": names.get(f.index), "exact": solidcraft_doc::naming::face_name_exact(b, f.index), "area": f.area, "centroid": f.centroid, "plane_normal": f.plane_normal, "point": spot.map(|x| x.point)}); + if let (Some(Some(name)), Some(o)) = (sheet_names.get(f.index), v.as_object_mut()) { + o.insert("sheet_face".into(), json!(name)); + } if let (Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }), Some(o)) = (spot.and_then(|x| x.surface), v.as_object_mut()) { diff --git a/crates/engine/src/cmd/sheet.rs b/crates/engine/src/cmd/sheet.rs index 423a5bd96..68c56c3ec 100644 --- a/crates/engine/src/cmd/sheet.rs +++ b/crates/engine/src/cmd/sheet.rs @@ -904,3 +904,7 @@ mod convert_tests; #[cfg(test)] #[path = "sheet_dxf_tests.rs"] mod dxf_tests; + +#[cfg(test)] +#[path = "sheet_face_names_tests.rs"] +mod face_names_tests; diff --git a/crates/engine/src/cmd/sheet_face_names_tests.rs b/crates/engine/src/cmd/sheet_face_names_tests.rs new file mode 100644 index 000000000..6c5d656f3 --- /dev/null +++ b/crates/engine/src/cmd/sheet_face_names_tests.rs @@ -0,0 +1,114 @@ +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use crate::Session; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +/// A tray: a base `w` x 200 (its width a sketch dimension: the parameter returned), 1 mm thick +/// with 1 mm bends, front and back flanges 30 high in one feature, left and right in another, +/// and a 6.6 mm hole in the base: the two flange features' ids. +fn tray(s: &mut Session, w: f64) -> (String, u64, u64) { + run(s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true})); + run(s, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [w, 200]})); + let d = run(s, "sketch.dimension", json!({"entities": ["l1"], "value": w})); + run(s, "sketch.finish", json!({})); + run(s, "sheet.flange", json!({"sketch": "Base"})); + run(s, "sheet.flange", json!({"edges": [[100, 0, 1], [100, 200, 1]], "height": 30})); + let front_back = s.doc.features.last().map_or(0, |f| f.id); + run(s, "sheet.flange", json!({"edges": [[0, 100, 1], [w, 100, 1]], "height": 30})); + let sides = s.doc.features.last().map_or(0, |f| f.id); + run(s, "solid.hole", json!({"position": [100, 100, 1], "diameter": 6.6})); + let param = d["param"].as_str().or_else(|| d["name"].as_str()).map(str::to_string).unwrap_or_else(|| "d1".into()); + (param, front_back, sides) +} + +/// Each face's readable sheet name, with its centroid and cylinder radius. +fn faces(s: &mut Session) -> Vec<(Option, Vec3, Option)> { + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let r = run(s, "model.faces", json!({"body": body})); + r["faces"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + let c = &f["centroid"]; + let at = Vec3::new(c[0].as_f64().unwrap_or(f64::NAN), c[1].as_f64().unwrap_or(f64::NAN), c[2].as_f64().unwrap_or(f64::NAN)); + (f["sheet_face"].as_str().map(str::to_string), at, f["cylinder"]["radius"].as_f64()) + }) + .collect() +} + +fn named<'a>(faces: &'a [(Option, Vec3, Option)], name: &str) -> Vec<&'a (Option, Vec3, Option)> { + faces.iter().filter(|f| f.0.as_deref() == Some(name)).collect() +} + +/// The point on the face with this name, as a command taking a face name finds it. +fn point(s: &Session, name: &str) -> Vec3 { + solidcraft_doc::naming::named_face_point(&s.model.state(), None, name).unwrap_or_else(|e| panic!("{name}: {e}")) +} + +#[test] +fn a_trays_faces_have_readable_sheet_names_that_follow_its_size() { + let mut s = Session::default(); + let (width, fb, sd) = tray(&mut s, 320.0); + let all = faces(&mut s); + // Every face but the hole's wall (two halves) has a sheet name, and no two faces share one. + let unnamed: Vec<_> = all.iter().filter(|f| f.0.is_none()).collect(); + assert!(unnamed.len() == 2 && unnamed.iter().all(|f| f.2.is_some_and(|r| (r - 3.3).abs() < 1e-6)), "only the hole's wall: {unnamed:?}"); + let mut names: Vec<&str> = all.iter().filter_map(|f| f.0.as_deref()).collect(); + names.sort_unstable(); + let n = names.len(); + names.dedup(); + assert_eq!(names.len(), n, "{names:?}"); + for (name, at) in [ + ("sheet:Body1:base:top".to_string(), Vec3::new(160.0, 100.0, 1.0)), + ("sheet:Body1:base:bottom".to_string(), Vec3::new(160.0, 100.0, 0.0)), + (format!("sheet:Body1:F{sd}.1:top"), Vec3::new(319.0, 100.0, 16.0)), + (format!("sheet:Body1:F{sd}.1:bottom"), Vec3::new(320.0, 100.0, 16.0)), + (format!("sheet:Body1:F{sd}.1:rim.far"), Vec3::new(319.5, 100.0, 30.0)), + (format!("sheet:Body1:F{fb}.0:bottom"), Vec3::new(160.0, 0.0, 16.0)), + // The front flange runs on past its bend to the right one, under its corner. + (format!("sheet:Body1:F{fb}.0:rim.ext1"), Vec3::new(319.0, 0.5, 2.0)), + ] { + let f = named(&all, &name); + assert!(f.len() == 1 && f[0].1.dist(at) < 2.5, "{name}: {f:?}"); + } + // A bend's two curved faces: its radius and the radius plus the thickness. + let radius = |name: &str| named(&all, name).first().and_then(|f| f.2); + assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.inner")).map(|r| (r * 1e6).round() / 1e6), Some(1.0)); + assert_eq!(radius(&format!("sheet:Body1:F{fb}.0:bend.outer")).map(|r| (r * 1e6).round() / 1e6), Some(2.0)); + // 80 mm wider: the same names, each on the same face where it now is. + let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); + assert!((right.x - 319.0).abs() < 1e-3, "{right:?}"); + run(&mut s, "parameters.change", json!({"name": width, "expression": "400"})); + let wider = faces(&mut s); + let mut again: Vec<&str> = wider.iter().filter_map(|f| f.0.as_deref()).collect(); + again.sort_unstable(); + assert_eq!(again, names); + let right = point(&s, &format!("sheet:Body1:F{sd}.1:top")); + assert!((right.x - 399.0).abs() < 1e-3, "{right:?}"); + let far = point(&s, &format!("sheet:Body1:F{fb}.1:rim.far")); + assert!((far.y - 199.5).abs() < 1e-3 && (far.z - 30.0).abs() < 1e-3, "{far:?}"); +} + +#[test] +fn a_flanges_sheet_names_hold_when_another_flange_goes() { + let mut s = Session::default(); + let (_, fb, sd) = tray(&mut s, 320.0); + let right = format!("sheet:Body1:F{sd}.1:top"); + let before = point(&s, &right); + run(&mut s, "timeline.suppress", json!({"feature": fb, "suppressed": true})); + let after = point(&s, &right); + assert!((after.x - 319.0).abs() < 1e-3 && (after.z - before.z).abs() < 16.0, "{before:?} {after:?}"); + // The names of the flanges that went are gone; asking for one says so. + let gone = format!("sheet:Body1:F{fb}.0:top"); + assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), None, &gone).is_err()); + assert!(solidcraft_doc::naming::named_face_point(&s.model.state(), Some("Body2"), &right).is_err()); +} diff --git a/docs/book/src/guide/sheet-metal.md b/docs/book/src/guide/sheet-metal.md index b3ad5f805..25f9c800d 100644 --- a/docs/book/src/guide/sheet-metal.md +++ b/docs/book/src/guide/sheet-metal.md @@ -312,3 +312,12 @@ flat pattern and its DXF have it, and on the bottom face y runs the other way, a below. When the face is gone (its flange is suppressed or deleted) the sketch reports a lost attachment instead of moving to another face; **Redefine Sketch Plane** attaches it to another face. `fixed: true` still freezes the picked plane in space. + +Every face of a folded sheet has a name of that kind, which `model.faces` lists as `sheet_face`: +`:top` and `:bottom`, `:rim.` for a rim (a base sketch line's id, or a +flange's `far`, `side0`, `side1`; `rim.bend0`/`rim.bend1` for a bend's flat ends and +`rim.ext0`/`rim.ext1` where a flange runs on past its bend toward a neighbour), and +`:bend.inner` / `:bend.outer` for a bend's curved faces. A command that takes a +face name takes it too (`sheet:Body1:F3.1:top`), and finds the face from the sheet itself, so the +name stays with that face while the sheet's sizes change and other flanges come and go. Faces the +sheet does not describe (a hole's wall) have none.