From e063a7778e5e29ac7aa56a733b95e141595ea6dd Mon Sep 17 00:00:00 2001 From: froglemonade2 <64703083+froglemonade2@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:27:32 +0000 Subject: [PATCH] Axes and points from circular edges and round faces (#3128) (#4610) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Axes and points from circular edges and round faces In 3D, a round edge or face stands for its circle wherever a command takes an axis or a point. Revolve, Surface Revolve, both Circular Pattern dialogs, Plane at Angle and Move -> Rotate take a circular edge (through its centre, along its normal) or a cylinder, cone or torus face (its axis). The features keep the pick as a model reference, so they follow the model when a parameter moves it. Straight edges work as before; flat faces are refused. Every 3D point input takes a circle's centre: construction points (which follow the circle), To Object, patch points, hole placement, and Move's pivot and points. Hovering shows the axis as a dashed construction line or the centre as a star, and the dialog's chip names what the pick stands for ("centre of edge 10", "axis of face 3"). Co-Authored-By: Claude Opus 5.5 * Format the round-pick hover check Co-Authored-By: Claude Opus 5.5 * Selection chips: name a round pick as a circle centre or axis The chip has room for little more than the body and a word or two: "Shaft · circle centre", "Shaft · circle axis", "Shaft · face 2 axis", and "Shaft · point" for a point of the model. Co-Authored-By: Claude Opus 5.5 * Move: a circle's centre in a placed component is where the component shows it Move's pivot and points read a picked circle from the model in its component's own frame, while the pick is in the world. They now read it from the world state (and, editing a Move, from the state before it, placed the same way), as the viewport and the other round picks do. Co-Authored-By: Claude Opus 5.5 * Plane at Angle on a planar face about a model edge: test that it follows both Upstream #1956 made a planar face a base for Plane at Angle; this branch makes a model edge an axis. The rebase keeps both in one PlaneRef::AtAngle. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/assembly.rs | 5 +- crates/doc/src/clipboard.rs | 22 +- crates/doc/src/construct.rs | 102 ++++-- crates/doc/src/document.rs | 32 +- crates/doc/src/eval.rs | 68 ++-- crates/doc/src/eval_surface.rs | 4 +- .../pending/axis-on-round-edges-and-faces.rs | 7 + crates/doc/src/naming.rs | 2 +- crates/doc/src/walk.rs | 33 +- crates/engine/src/cmd/construct.rs | 13 + crates/engine/src/cmd/features.rs | 55 ++-- crates/engine/src/cmd/model_axis_tests.rs | 197 ++++++++++++ crates/engine/src/cmd/sketch_face_tests.rs | 8 +- crates/engine/src/cmd/surface.rs | 2 +- crates/ui-egui/src/dialogs.rs | 260 ++++++++++++--- crates/ui-egui/src/dialogs_move.rs | 30 +- crates/ui-egui/src/dialogs_surface.rs | 14 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/round_pick_tests.rs | 296 ++++++++++++++++++ crates/ui-egui/src/selection.rs | 5 + .../ui-egui/src/sketch_attachment_ui_tests.rs | 1 + crates/ui-egui/src/viewport.rs | 90 +++++- docs/book/src/guide/features.md | 26 +- skills/solidcraft-modeling/reference.md | 2 +- 24 files changed, 1133 insertions(+), 143 deletions(-) create mode 100644 crates/doc/src/format/pending/axis-on-round-edges-and-faces.rs create mode 100644 crates/engine/src/cmd/model_axis_tests.rs create mode 100644 crates/ui-egui/src/round_pick_tests.rs diff --git a/crates/doc/src/assembly.rs b/crates/doc/src/assembly.rs index 31f312b68..7f3ef823b 100644 --- a/crates/doc/src/assembly.rs +++ b/crates/doc/src/assembly.rs @@ -150,10 +150,13 @@ fn map_plane_ref(m: &Mat, p: &mut PlaneRef) { map_plane_ref(m, base); map_geo_ref(m, point); } - PlaneRef::AtAngle { base, axis_origin, axis_dir, .. } => { + PlaneRef::AtAngle { base, axis_origin, axis_dir, line, .. } => { map_plane_ref(m, base); *axis_origin = apply_point(m, *axis_origin); *axis_dir = apply_vector(m, *axis_dir); + if let Some(g) = line { + map_geo_ref(m, g); + } } // Named origin planes and construction planes are the component's own. PlaneRef::Origin { .. } | PlaneRef::Construction { .. } => {} diff --git a/crates/doc/src/clipboard.rs b/crates/doc/src/clipboard.rs index ce3af7144..631164cc0 100644 --- a/crates/doc/src/clipboard.rs +++ b/crates/doc/src/clipboard.rs @@ -114,11 +114,17 @@ fn remap_plane(p: &mut PlaneRef, ids: &BTreeMap, bodies: &BTreeMap remap_plane(base, ids, bodies, depth + 1)?, + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => remap_plane(base, ids, bodies, depth + 1)?, PlaneRef::ThroughPoint { base, point } => { remap_plane(base, ids, bodies, depth + 1)?; remap_geo(point, ids, bodies, depth + 1)?; } + PlaneRef::AtAngle { base, line, .. } => { + remap_plane(base, ids, bodies, depth + 1)?; + if let Some(g) = line { + remap_geo(g, ids, bodies, depth + 1)?; + } + } PlaneRef::Face { name, anchor, .. } => { if let Some(name) = name { *name = remap_topology(name, ids, bodies); @@ -209,6 +215,9 @@ impl crate::Feature { checked_geo(r, 0)?; } } + K::Revolve { axis: crate::AxisRef::Model { geo }, .. } + | K::SurfaceRevolve { axis: crate::AxisRef::Model { geo }, .. } + | K::Pattern { pattern: crate::PatternKind::Circular { axis_ref: Some(geo), .. }, .. } => checked_geo(geo, 0)?, _ => {} } // Feature names are remapped once here; the geometry pass below handles only @@ -269,6 +278,9 @@ impl crate::Feature { remap_geo(r, ids, bodies, 0)?; } } + K::Revolve { axis: crate::AxisRef::Model { geo }, .. } + | K::SurfaceRevolve { axis: crate::AxisRef::Model { geo }, .. } + | K::Pattern { pattern: crate::PatternKind::Circular { axis_ref: Some(geo), .. }, .. } => remap_geo(geo, ids, bodies, 0)?, _ => {} } Ok(()) @@ -289,7 +301,13 @@ fn checked_plane(p: &PlaneRef, depth: usize) -> crate::Result<()> { return Err(crate::DocError::Invalid("copy reference nesting exceeds 64".into())); } match p { - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => checked_plane(base, depth + 1)?, + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => checked_plane(base, depth + 1)?, + PlaneRef::AtAngle { base, line, .. } => { + checked_plane(base, depth + 1)?; + if let Some(g) = line { + checked_geo(g, depth + 1)?; + } + } PlaneRef::Midplane { a, b } | PlaneRef::TwoEdges { a, b } => { checked_geo(a, depth + 1)?; checked_geo(b, depth + 1)?; diff --git a/crates/doc/src/construct.rs b/crates/doc/src/construct.rs index 284bde93b..dc41296c3 100644 --- a/crates/doc/src/construct.rs +++ b/crates/doc/src/construct.rs @@ -162,6 +162,11 @@ fn face_of<'a>(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(& /// The edge picked, as a polyline. fn edge_points(st: &ModelState, at: Vec3, name: &Option) -> Result> { + edge_pick(st, at, name).map(|(_, _, pts)| pts) +} + +/// The edge picked: its body, its index there (as `Body::edges` lists it) and its polyline. +fn edge_pick<'a>(st: &'a ModelState, at: Vec3, name: &Option) -> Result<(&'a ModelBody, usize, Vec)> { let mut at = at; if let Some(n) = name { for b in bodies(st) { @@ -171,23 +176,33 @@ fn edge_points(st: &ModelState, at: Vec3, name: &Option) -> Result)> = None; + let mut best: Option<(f64, &ModelBody, usize, Vec)> = None; for b in bodies(st) { let tol = (b.body.size() * 1e-3).max(1e-3); let Ok(edges) = b.body.edges(tol) else { continue }; - for e in edges { + for (i, e) in edges.into_iter().enumerate() { let d = e.points.windows(2).map(|w| at.dist_to_segment(w[0], w[1])).fold(f64::MAX, f64::min); - if best.as_ref().is_none_or(|(bd, _)| d < *bd) { - best = Some((d, e.points)); + if best.as_ref().is_none_or(|(bd, ..)| d < *bd) { + best = Some((d, b, i, e.points)); } } } match best { - Some((d, pts)) if pts.len() >= 2 && d <= 1e-3 + 1e-2 * pts.iter().fold(0.0, |m: f64, p| m.max(p.len())).max(1.0) => Ok(pts), + Some((d, b, i, pts)) if pts.len() >= 2 && d <= 1e-3 + 1e-2 * pts.iter().fold(0.0, |m: f64, p| m.max(p.len())).max(1.0) => Ok((b, i, pts)), _ => Err(bad(format!("no edge at {at:?}"))), } } +/// The circle a picked edge lies on, from its exact curve (`kernel::edge_circle`) when the drawn +/// edge lies on it, else fitted to the drawn points: (centre, unit normal). +fn edge_circle(b: &ModelBody, index: usize, pts: &[Vec3]) -> Option<(Vec3, Vec3)> { + let exact = kernel::edge_circle(&b.body, index).filter(|c| { + let tol = (b.body.size() * 1e-6).max(1e-9) * 10.0; + pts.iter().all(|p| (p.dist(c.center) - c.radius).abs() <= tol && (*p - c.center).dot(*c.axis).abs() <= tol) + }); + exact.map(|c| (c.center, *c.axis)).or_else(|| as_circle(pts).map(|(c, n, _)| (c, n))) +} + /// The most edge names a vertex reference keeps. const MAX_VERTEX_EDGES: usize = 16; @@ -306,13 +321,52 @@ pub(crate) fn point(ctx: &Ctx, g: &GeoRef) -> Result { } } +/// An edge or face of the model as a line: along a straight edge, through the centre of a +/// circular edge along its normal, or the axis of a cylinder, cone or torus face. +fn model_line(st: &ModelState, g: &GeoRef) -> Result<(Vec3, Vec3)> { + match g { + GeoRef::Edge { at, name } => { + let (b, i, pts) = edge_pick(st, *at, name)?; + as_line(&pts).or_else(|| edge_circle(b, i, &pts)).ok_or_else(|| bad("the edge is neither straight nor circular")) + } + GeoRef::Face { at, name } => { + let (b, fi, _) = face_of(st, *at, name)?; + match kernel::face_surface(&b.body, fi) { + Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, *axis)), + Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, *axis)), + Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, *axis)), + _ => Err(bad("the face is not a cylinder, cone or torus")), + } + } + _ => Err(bad("pick a straight or circular edge, or a cylinder, cone or torus face")), + } +} + +/// The axis a feature turns about when an edge or face of the model is picked for it (a revolve, +/// a circular pattern, a plane at an angle), as [`model_line`] finds it. The direction is +/// oriented the same way however the edge or surface runs (its largest component positive), so +/// the feature keeps its turn when an edit rebuilds the edge reversed. +pub fn model_axis(st: &ModelState, g: &GeoRef) -> Result<(Vec3, Vec3)> { + let (o, d) = model_line(st, g)?; + let d = d.normalized().filter(|_| o.is_finite()).ok_or_else(|| bad("the axis has no direction"))?; + Ok((o, canonical_dir(d))) +} + +/// `d` or `-d`, whichever has its largest component (the first of equal ones) positive: how +/// [`model_axis`] orients an axis, for a preview of one to point the same way. +pub fn canonical_dir(d: Vec3) -> Vec3 { + let c = [d.x, d.y, d.z]; + let big = c.iter().fold(0.0_f64, |m, v| m.max(v.abs())); + match c.iter().find(|v| v.abs() >= big - 1e-9) { + Some(v) if *v < 0.0 => -d, + _ => d, + } +} + /// A reference as a line (origin, unit direction). pub(crate) fn line(ctx: &Ctx, g: &GeoRef) -> Result<(Vec3, Vec3)> { match g { - GeoRef::Edge { at, name } => { - let pts = edge_points(ctx.st, *at, name)?; - as_line(&pts).or_else(|| as_circle(&pts).map(|(c, n, _)| (c, n))).ok_or_else(|| bad("the edge is neither straight nor circular")) - } + GeoRef::Edge { .. } | GeoRef::Face { .. } => model_line(ctx.st, g), GeoRef::SketchCurve { sketch, curve } => { let pts = sketch_curve_points(ctx, *sketch, curve)?; as_line(&pts).ok_or_else(|| bad(format!("sketch curve `{curve}` is not a line"))) @@ -330,15 +384,6 @@ pub(crate) fn line(ctx: &Ctx, g: &GeoRef) -> Result<(Vec3, Vec3)> { ConstructGeom::Axis { origin, dir } => Ok((*origin, *dir)), _ => Err(bad(format!("`{name}` is not an axis"))), }, - GeoRef::Face { at, name } => { - let (b, fi, _) = face_of(ctx.st, *at, name)?; - match kernel::face_surface(&b.body, fi) { - Some(FaceSurface::Cylinder { origin, axis, .. }) => Ok((origin, *axis)), - Some(FaceSurface::Cone { apex, axis, .. }) => Ok((apex, *axis)), - Some(FaceSurface::Torus { center, axis, .. }) => Ok((center, *axis)), - _ => Err(bad("the face is not a cylinder, cone or torus")), - } - } _ => Err(bad("pick an edge, line or axis")), } } @@ -602,6 +647,20 @@ pub(crate) fn resolve_geo_plane(ctx: &Ctx, p: &PlaneRef) -> Result { } impl GeoRef { + /// Where a picked edge or face is now, found the way evaluation finds it (by its persistent + /// name, else at the picked point): a point on it. `None` for other references and for an + /// edge or face that is gone. + pub fn picked_point(&self, st: &ModelState) -> Option { + match self { + GeoRef::Edge { at, name } => { + let on = name.as_deref().and_then(|n| bodies(st).find_map(|b| crate::naming::find_edge(b, n, *at).ok())).map_or(*at, |(q, _)| q); + edge_pick(st, on, &None).ok().map(|_| on) + } + GeoRef::Face { at, name } => face_of(st, *at, name).ok().map(|(_, _, p)| p), + _ => None, + } + } + /// Map the reference's world points (component frames). pub fn map_points(&mut self, pt: &mut dyn FnMut(&mut Vec3), plane: &mut dyn FnMut(&mut PlaneRef)) { match self { @@ -710,7 +769,12 @@ impl PlaneRef { refs.push(point.as_mut()); refs } - PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => base.refs_mut(), + PlaneRef::AtAngle { base, line, .. } => { + let mut v = base.refs_mut(); + v.extend(line.as_deref_mut()); + v + } + PlaneRef::Offset { base, .. } | PlaneRef::Flipped { base, .. } => base.refs_mut(), _ => Vec::new(), } } diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 565158931..4512e5895 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -57,8 +57,17 @@ pub enum PlaneRef { /// Another plane moved along its normal until it goes through a point (a vertex, sketch /// point or construction point), so it follows the point. ThroughPoint { base: Box, point: Box }, - /// Another plane rotated about a line (in world coordinates) by an angle expression. - AtAngle { base: Box, axis_origin: Vec3, axis_dir: Vec3, angle: Expr }, + /// Another plane rotated about a line (in world coordinates) by an angle expression. With + /// `line`, an edge or round face of the model ([`crate::construct::model_axis`]), the line is + /// found there on each evaluation and `axis_origin`/`axis_dir` are where it was when picked. + AtAngle { + base: Box, + axis_origin: Vec3, + axis_dir: Vec3, + angle: Expr, + #[serde(default, skip_serializing_if = "Option::is_none")] + line: Option>, + }, /// A construction plane feature (by name). Construction { name: FeatureName }, /// `base` seen from its other side: the normal reversed by a half turn about the base's @@ -394,6 +403,9 @@ pub enum AxisRef { World { axis: String }, /// Any line in the sketch plane, in world coordinates. Line { origin: Position, dir: Dir }, + /// An edge or round face of the model (a straight or circular edge, a cylinder, cone or + /// torus face), found again on each evaluation: [`crate::construct::model_axis`]. + Model { geo: GeoRef }, /// A construction axis feature, by name, where it is when the revolve is evaluated. Construction { name: FeatureName }, } @@ -2152,6 +2164,11 @@ pub enum PatternKind { alignment: solidcraft_sketch::PatternAlignment, #[serde(default, skip_serializing_if = "std::ops::Not::not")] reversed: bool, + /// The edge or round face of the model the copies turn about, found again on each + /// evaluation ([`crate::construct::model_axis`]); `origin` and `axis` are where it was + /// when picked. + #[serde(default, skip_serializing_if = "Option::is_none")] + axis_ref: Option, /// A construction axis the copies turn about, by name, followed when it moves; /// `origin` and `axis` are where it was when the pattern was made. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -3675,12 +3692,19 @@ impl Document { let b = self.resolve_plane_in(vals, base, depth + 1, st)?; Ok(b.offset(Self::eval_in(vals, distance, Kind::Length)?)) } - PlaneRef::AtAngle { base, axis_origin, axis_dir, angle } => { + PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line } => { let b = self.resolve_plane_in(vals, base, depth + 1, st)?; let a = Self::eval_in(vals, angle, Kind::Angle)?; + let (axis_origin, axis_dir) = match line { + Some(g) => { + let st = st.ok_or_else(|| DocError::Invalid("this plane is built from the model: evaluate first".into()))?; + crate::construct::model_axis(st, g)? + } + None => (*axis_origin, *axis_dir), + }; let d = axis_dir.normalized().ok_or_else(|| DocError::Invalid("rotation axis".into()))?; let rot = |v: Vec3| v * a.cos() + d.cross(v) * a.sin() + d * (d.dot(v) * (1.0 - a.cos())); - let o = *axis_origin + rot(b.origin - *axis_origin); + let o = axis_origin + rot(b.origin - axis_origin); Plane::new(o, rot(b.x), rot(b.y)).ok_or_else(|| DocError::Invalid("degenerate plane".into())) } PlaneRef::Flipped { base, about_y } => Ok(self.resolve_plane_in(vals, base, depth + 1, st)?.flipped(*about_y)), diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 174291b8d..c473fd0b0 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4077,17 +4077,15 @@ fn blend_body( Ok((Traced::step(nb.with_preserved_planar_sources(&mb.body)?, &[&from]), used, tapered)) } -/// The revolve axis in the sketch's 2D coordinates (a point on it, its direction). `construct` -/// gives a construction axis, by name, in the sketch's 3D frame. -pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef, construct: &dyn Fn(&str) -> Result<(Vec3, Vec3)>) -> Result<(Vec2, Vec2)> { - let in_plane = |origin: Vec3, dir: Vec3| { - let pl = &ss.plane; - let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?; - if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin).abs() > 1e-6 { - return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into())); - } - Ok((pl.to_local(origin), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) - }; +/// The revolve axis in the sketch's plane coordinates (a point and a direction). `st` is the model +/// an axis on an edge or face of it is found in; `construct` gives a construction axis, by name, in +/// the sketch's 3D frame. +pub(crate) fn revolve_axis( + ss: &SolvedSketch, + axis: &AxisRef, + st: &ModelState, + construct: &dyn Fn(&str) -> Result<(Vec3, Vec3)>, +) -> Result<(Vec2, Vec2)> { match axis { AxisRef::SketchLine { curve } => { let ci = ss.sketch.curve_index(curve).ok_or_else(|| DocError::Unknown(format!("sketch line `{curve}`")))?; @@ -4117,14 +4115,38 @@ pub(crate) fn revolve_axis(ss: &SolvedSketch, axis: &AxisRef, construct: &dyn Fn } Ok((pl.to_local(Vec3::ZERO), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) } - AxisRef::Line { origin, dir } => in_plane(origin.0, dir.0), + AxisRef::Line { origin, dir } => line_in_sketch_plane(ss, origin.0, dir.0), + AxisRef::Model { geo } => { + let (o, d) = crate::construct::model_axis(st, geo)?; + line_in_sketch_plane(ss, o, d) + } AxisRef::Construction { name } => { - let (origin, dir) = construct(name)?; - in_plane(origin, dir) + let (o, d) = construct(name)?; + line_in_sketch_plane(ss, o, d) } } } +/// The model a revolve axis is found in: what construction geometry of component `comp` is built +/// on when the axis is an edge or face of it (only then is it worth placing). +pub(super) fn axis_state<'a>(doc: &Document, st: &'a ModelState, comp: u64, axis: &AxisRef) -> std::borrow::Cow<'a, ModelState> { + match axis { + AxisRef::Model { .. } => construction_state(doc, st, comp), + _ => std::borrow::Cow::Borrowed(st), + } +} + +/// A world line through `origin` along `dir` in the sketch's plane coordinates, or an error when it +/// does not lie in the sketch plane. +fn line_in_sketch_plane(ss: &SolvedSketch, origin: Vec3, dir: Vec3) -> Result<(Vec2, Vec2)> { + let pl = &ss.plane; + let d = dir.normalized().ok_or_else(|| DocError::Invalid("revolve axis has no direction".into()))?; + if d.dot(pl.normal()).abs() > 1e-9 || pl.height(origin).abs() > 1e-6 { + return Err(DocError::Invalid("the revolve axis does not lie in the sketch plane".into())); + } + Ok((pl.to_local(origin), Vec2::new(d.dot(pl.x), d.dot(pl.y)))) +} + /// A construction axis `name` of the timeline so far, as evaluated, in the frame of component /// `comp`: a point on it and its direction. Without a document (`doc` None) it is taken in its /// own component's frame. @@ -5286,7 +5308,8 @@ fn feature_tools_with_constructor( f.component, )?; let regions = solidcraft_sketch::merge_regions(&select_profiles(&ss, profiles)?); - let (o, d) = revolve_axis(&ss, axis, &|name| construction_axis_in(Some(doc), st, name, f.component))?; + let (o, d) = + revolve_axis(&ss, axis, &axis_state(doc, st, f.component, axis), &|name| construction_axis_in(Some(doc), st, name, f.component))?; // To Object is in this feature's component frame: the model as seen from there. let tst = if to.is_some() { state_in_frame(doc, st, f.component) } else { std::borrow::Cow::Borrowed(st) }; // Where the tool meets its targets is measured where they are shown (#3383). @@ -6100,10 +6123,12 @@ fn pattern_transforms(doc: &Document, vals: &BTreeMap, st: &Model out.push(m); } } - crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_feature } => { - let (origin, axis) = match axis_feature { - Some(name) => construction_axis_in(Some(doc), st, name, component)?, - None => (origin.0, axis.0), + crate::PatternKind::Circular { origin, axis, count: c, angle, alignment, reversed, axis_ref, axis_feature } => { + // On an edge or round face: about it as it is now; on a construction axis: where it is. + let (origin, axis) = match (axis_ref, axis_feature) { + (Some(g), _) => crate::construct::model_axis(&construction_state(doc, st, component), g)?, + (None, Some(name)) => construction_axis_in(Some(doc), st, name, component)?, + (None, None) => (origin.0, axis.0), }; let n = count(c)?; let total = val(vals, angle, Kind::Angle)?; @@ -6773,11 +6798,12 @@ pub(crate) fn sheet_face_plane_in_frame(doc: &Document, st: &ModelState, comp: u PlaneRef::Offset { base, distance } => { PlaneRef::Offset { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), distance: distance.clone() } } - PlaneRef::AtAngle { base, axis_origin, axis_dir, angle } => PlaneRef::AtAngle { + PlaneRef::AtAngle { base, axis_origin, axis_dir, angle, line } => PlaneRef::AtAngle { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), axis_origin: *axis_origin, axis_dir: *axis_dir, angle: angle.clone(), + line: line.clone(), }, PlaneRef::Flipped { base, about_y } => { PlaneRef::Flipped { base: Box::new(sheet_face_plane_in_frame(doc, st, comp, base)?), about_y: *about_y } @@ -7770,6 +7796,7 @@ fn construction_state<'a>(doc: &Document, st: &'a ModelState, comp: u64) -> std: fn plane_is_fixed(plane: &PlaneRef) -> bool { match plane { PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } => true, + PlaneRef::AtAngle { line: Some(_), .. } => false, PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_is_fixed(base), _ => false, } @@ -7780,6 +7807,7 @@ fn plane_is_fixed(plane: &PlaneRef) -> bool { fn plane_reads_geometry(plane: &PlaneRef) -> bool { match plane { PlaneRef::Origin { .. } | PlaneRef::Custom { .. } | PlaneRef::Placed { .. } | PlaneRef::Construction { .. } => false, + PlaneRef::AtAngle { line: Some(_), .. } => true, PlaneRef::Offset { base, .. } | PlaneRef::AtAngle { base, .. } | PlaneRef::Flipped { base, .. } => plane_reads_geometry(base), PlaneRef::ThroughPoint { .. } | PlaneRef::Midplane { .. } diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index 085243ad3..e4e6a18d7 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -304,7 +304,9 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?, f.component, )?; - let (o, d) = revolve_axis(&ss, axis, &|name| construction_axis_in(Some(doc), st, name, f.component))?; + let (o, d) = revolve_axis(&ss, axis, &super::axis_state(doc, st, f.component, axis), &|name| { + construction_axis_in(Some(doc), st, name, f.component) + })?; let a = val(vals, angle, Kind::Angle)?; let (start, sweep) = match (angle2, symmetric) { (Some(a2), _) => { diff --git a/crates/doc/src/format/pending/axis-on-round-edges-and-faces.rs b/crates/doc/src/format/pending/axis-on-round-edges-and-faces.rs new file mode 100644 index 000000000..9b2166139 --- /dev/null +++ b/crates/doc/src/format/pending/axis-on-round-edges-and-faces.rs @@ -0,0 +1,7 @@ +//! A Revolve, Surface Revolve, Circular Pattern or Plane at Angle can turn about an edge or round +//! face of the model, kept as a reference (`AxisRef::Model`, a pattern's `axis_ref`, an angle +//! plane's `line`: a circular edge's axis through its centre, a cylinder's, cone's or torus's +//! axis, or a straight edge), found again by its persistent name on each evaluation so the +//! feature follows the edge or face when the model changes. Older designs need no +//! transformation: their axes stay the fixed lines or named axes they were saved with. The last +//! release refuses a design saved with this (the newer format number). diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs index 25af341f6..85209e816 100644 --- a/crates/doc/src/naming.rs +++ b/crates/doc/src/naming.rs @@ -696,7 +696,7 @@ fn role_name(f: &Feature, before: &ModelState, ps: &[Vec3], ns: &[Vec3], fi: usi } FeatureKind::Revolve { sketch, axis, .. } => { let Some(ss) = before.sketch(sketch.0) else { return format!("F{fid}:face:{fi}") }; - let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis, &|name| crate::eval::construction_axis_in(None, before, name, 0)) else { + let Ok((o2, d2)) = crate::eval::revolve_axis(ss, axis, before, &|name| crate::eval::construction_axis_in(None, before, name, 0)) else { return format!("F{fid}:face:{fi}"); }; let (o, d) = (ss.plane.to_world(o2), (ss.plane.to_world(o2 + d2) - ss.plane.to_world(o2)).normalized().unwrap_or(Vec3::Z)); diff --git a/crates/doc/src/walk.rs b/crates/doc/src/walk.rs index aa4fc74c5..15f5d2e73 100644 --- a/crates/doc/src/walk.rs +++ b/crates/doc/src/walk.rs @@ -394,11 +394,17 @@ impl PlaneRef { } match self { Self::Construction { name } => f(Ref::Feature(name)), - Self::Offset { base, .. } | Self::AtAngle { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs(f, depth + 1), + Self::Offset { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs(f, depth + 1), Self::ThroughPoint { base, point } => { base.walk_feature_refs(f, depth + 1); point.walk_feature_refs(f, depth + 1); } + Self::AtAngle { base, line, .. } => { + base.walk_feature_refs(f, depth + 1); + if let Some(g) = line { + g.walk_feature_refs(f, depth + 1); + } + } Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => { a.walk_feature_refs(f, depth + 1); b.walk_feature_refs(f, depth + 1); @@ -419,11 +425,17 @@ impl PlaneRef { } match self { Self::Construction { name } => f(Ref::Feature(name)), - Self::Offset { base, .. } | Self::AtAngle { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs_mut(f, depth + 1), + Self::Offset { base, .. } | Self::Flipped { base, .. } => base.walk_feature_refs_mut(f, depth + 1), Self::ThroughPoint { base, point } => { base.walk_feature_refs_mut(f, depth + 1); point.walk_feature_refs_mut(f, depth + 1); } + Self::AtAngle { base, line, .. } => { + base.walk_feature_refs_mut(f, depth + 1); + if let Some(g) = line { + g.walk_feature_refs_mut(f, depth + 1); + } + } Self::Midplane { a, b } | Self::TwoEdges { a, b } | Self::Perpendicular { plane: a, line: b } => { a.walk_feature_refs_mut(f, depth + 1); b.walk_feature_refs_mut(f, depth + 1); @@ -532,6 +544,23 @@ impl Walk for AxisDef { construct_geometry!(); } +/// A feature's own reference to the model (a revolve's or circular pattern's axis on an edge or +/// round face): walked like a construction axis's. +impl Walk for GeoRef { + fn walk_exprs<'a>(&'a self, f: &mut dyn FnMut(ExprItem<'a>)) { + plane_exprs(vec![self], f) + } + fn walk_exprs_mut<'a>(&'a mut self, f: &mut dyn FnMut(ExprItemMut<'a>)) { + plane_exprs_mut(vec![self], f) + } + fn walk_geometry<'a>(&'a self, f: &mut dyn FnMut(GeoItem<'a>)) { + f(Geo::Construct(self)) + } + fn walk_geometry_mut<'a>(&'a mut self, f: &mut dyn FnMut(GeoItemMut<'a>)) { + f(Geo::Construct(self)) + } +} + impl Walk for PointDef { fn walk_exprs<'a>(&'a self, f: &mut dyn FnMut(ExprItem<'a>)) { match self { diff --git a/crates/engine/src/cmd/construct.rs b/crates/engine/src/cmd/construct.rs index 26b6a8074..b815b94aa 100644 --- a/crates/engine/src/cmd/construct.rs +++ b/crates/engine/src/cmd/construct.rs @@ -9,6 +9,7 @@ use serde_json::Value; use solidcraft_doc::construct::{AxisDef, GeoRef, PointDef}; use solidcraft_doc::{FeatureKind, PlaneRef}; +use solidcraft_geom::Vec3; use super::CommandSpec; use super::features::{add_feature, check_expr, plane_param, sketch_id}; @@ -88,6 +89,18 @@ pub static COMMANDS: &[CommandSpec] = &[ ), ]; +/// An axis on an edge or round face of the model (`{edge: [x,y,z]}` or `{face: [x,y,z]}`, the +/// point on it), with the line it gives now (`solidcraft_doc::construct::model_axis`); `None` +/// for any other form of `axis`. +pub(super) fn model_axis_param(s: &Session, v: Option<&Value>, cmd: &str) -> Result> { + // Also as saved (`{type: edge|face, at, name?}`), as an edit dialog gives back one it kept. + let saved = |v: &Value| matches!(v.get("type").and_then(Value::as_str), Some("edge" | "face")); + let Some(v) = v.filter(|v| v.get("edge").is_some() || v.get("face").is_some() || saved(v)) else { return Ok(None) }; + let g = geo(s, Some(v), cmd, "axis")?; + let (o, d) = solidcraft_doc::construct::model_axis(&s.world_state(), &g).map_err(|e| bad(cmd, format!("`axis`: {e}")))?; + Ok(Some((g, o, d))) +} + /// A reference from its JSON form. pub(super) fn geo(s: &Session, v: Option<&Value>, cmd: &str, what: &str) -> Result { let v = v.ok_or_else(|| bad(cmd, format!("`{what}` is required: {REF}")))?; diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 9f765eb23..e9a8b3d9e 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -29,7 +29,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.revolve", "Revolve", revolve) .at("SOLID", "CREATE") .icon("revolve") - .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | construction axis name (followed when edited) | {origin, dir}; angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"), + .params("axis: sketch line id | x | y (sketch axes) | X|Y|Z (world) | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (Two Sides: the other side's angle); direction?: symmetric (angle split either side, independent of axis direction); convention?: sketch_normal|legacy_axis_start (default sketch_normal; legacy retains older angular starts); to?: [x,y,z] (To Object: turn until that face, vertex or point); sketch?, profiles? | face: [x,y,z] (a planar body face as the profile) and face_body?: name (whose face, where faces of several bodies meet), operation?, targets?, name?, body_name?"), CommandSpec::new("solid.sweep", "Sweep", sweep) .at("SOLID", "CREATE") .icon("sweep") @@ -58,7 +58,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("solid.pattern.circular", "Circular Pattern", pattern_circ) .at("SOLID", "CREATE") .icon("pattern_circ") - .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir}; count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), + .params("features: [names] | bodies: [names] | components: [names]; axis: X|Y|Z | construction axis name (followed when edited) | {origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); count; angle? (default 360 deg; partial arcs include both ends); alignment?: left|center|right (default right; original stays fixed); reversed?: bool (Flip; selects the extra side for even centered counts)"), CommandSpec::new("solid.pattern.path", "Pattern on Path", pattern_path) .at("SOLID", "CREATE") .icon("pattern_path") @@ -108,7 +108,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("construct.plane.at_angle", "Plane at Angle", plane_angle) .at("SOLID", "CONSTRUCT") .icon("plane_angle") - .params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir}; angle: expr; name?"), + .params("base: XY|XZ|YZ|plane name, or a planar face {face: [x,y,z], body?, index?, path?}; axis: X|Y|Z|construction axis name (where it is now)|{origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle: expr; name?"), CommandSpec::new("solid.split_face", "Split Face", split_face) .at("SOLID", "MODIFY") .icon("split_face") @@ -1171,9 +1171,13 @@ fn revolve(s: &mut Session, p: &Value) -> Result { } /// A revolve axis of `sketch` from its parameter: a sketch line id, the sketch's x or y axis, a -/// world axis, a construction axis by name (followed when it is edited) or {origin, dir}. A line -/// of the sketch wins over a construction axis of the same name. +/// world axis, a construction axis by name (followed when it is edited), {origin, dir}, or an edge +/// or round face of the model ({edge|face: [x,y,z]}), which the revolve follows as the model +/// changes. A line of the sketch wins over a construction axis of the same name. pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Result { + if let Some((geo, ..)) = super::construct::model_axis_param(s, p.get("axis"), cmd)? { + return Ok(AxisRef::Model { geo }); + } if let Some(o) = p.get("axis").filter(|v| v.is_object()) { let origin = o.get("origin").and_then(vec3).unwrap_or(Vec3::ZERO); let dir = o.get("dir").and_then(vec3).ok_or_else(|| bad(cmd, "axis needs `dir`"))?; @@ -1184,7 +1188,9 @@ pub(super) fn axis_param(s: &Session, sketch: u64, p: &Value, cmd: &str) -> Resu Some(a @ ("x" | "y")) => Ok(AxisRef::SketchAxis { axis: a.into() }), Some(name) if !is_sketch_line(s, sketch, name) && is_construction_axis(s, name) => Ok(AxisRef::Construction { name: name.into() }), Some(id) => Ok(AxisRef::SketchLine { curve: id.into() }), - None => Err(bad(cmd, "`axis` must be a sketch line id, x, y (sketch axes), X, Y, Z, a construction axis or {origin, dir}")), + None => { + Err(bad(cmd, "`axis` must be a sketch line id, x, y (sketch axes), X, Y, Z, a construction axis, {origin, dir} or {edge|face: [x,y,z]}")) + } } } @@ -1773,9 +1779,19 @@ fn source_features(s: &Session, p: &Value, cmd: &str) -> Result> { Ok(names) } +/// An axis line from its parameter, with what it follows: an edge or round face of the model +/// ({edge|face: [x,y,z]}) or a construction axis by name ([`named_axis_line`]). +fn axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option, Option)> { + if let Some((geo, o, d)) = super::construct::model_axis_param(s, p.get("axis"), cmd)? { + return Ok((o, d, Some(geo), None)); + } + let (o, d, name) = named_axis_line(s, p, cmd)?; + Ok((o, d, None, name)) +} + /// An axis line from `axis`: X, Y, Z, a construction axis by name or {origin, dir}. A construction /// axis comes back where it is now, with its name. -fn axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option)> { +fn named_axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option)> { match p.get("axis") { Some(Value::String(a)) => match a.to_ascii_uppercase().as_str() { "X" => Ok((Vec3::ZERO, Vec3::X, None)), @@ -1788,7 +1804,7 @@ fn axis_line(s: &Session, p: &Value, cmd: &str) -> Result<(Vec3, Vec3, Option Err(bad(cmd, "axis must be X, Y, Z, a construction axis or {origin, dir}")), + _ => Err(bad(cmd, "axis must be X, Y, Z, a construction axis, {origin, dir} or {edge|face: [x,y,z]}")), }, Some(o @ Value::Object(_)) => { let origin = match o.get("origin") { @@ -1882,7 +1898,7 @@ fn pattern_rect(s: &mut Session, p: &Value) -> Result { fn pattern_circ(s: &mut Session, p: &Value) -> Result { let cmd = "solid.pattern.circular"; let (features, bodies) = pattern_sources(s, p, cmd)?; - let (origin, axis, axis_feature) = axis_line(s, p, cmd)?; + let (origin, axis, axis_ref, axis_feature) = axis_line(s, p, cmd)?; let count = req_expr(cmd, p, "count")?; check_expr(s, &count, Kind::Unitless, cmd, "count")?; let angle = expr(p, "angle").unwrap_or_else(|| "360 deg".into()); @@ -1894,6 +1910,7 @@ fn pattern_circ(s: &mut Session, p: &Value) -> Result { angle, alignment: super::alignment_param(p, "alignment", cmd)?, reversed: super::reversed_param(p, "reversed", cmd)?, + axis_ref, axis_feature, }; finish_pattern(s, p, features, pattern, bodies) @@ -2086,24 +2103,22 @@ fn plane_offset(s: &mut Session, p: &Value) -> Result { fn plane_angle(s: &mut Session, p: &Value) -> Result { let cmd = "construct.plane.at_angle"; - // The plane keeps the axis line as it is now. - let (axis_origin, axis_dir, _) = axis_line(s, p, cmd)?; + // The plane follows an edge or face it is on; a construction axis is kept as it is now. + let (axis_origin, axis_dir, line, _) = axis_line(s, p, cmd)?; let angle = req_expr(cmd, p, "angle")?; check_expr(s, &angle, Kind::Angle, cmd, "angle")?; + let line = line.map(Box::new); // A planar body face: attached exactly, as a sketch on that face is, so the plane follows it. if let Some(face) = p.get("base").filter(|b| b.get("face").is_some()) { let base = super::sketch::face::capture(s, face, cmd)?; super::sketch::face::capture_positions(s, &base)?; - let kind = FeatureKind::ConstructionPlane { plane: solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle } }; + let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line }; // The capture is already in the authoring frame. - return add_feature_in(s, p, kind, false); + return add_feature_in(s, p, FeatureKind::ConstructionPlane { plane }, false); } let base = plane_param(s, p.get("base"), cmd)?; - add_feature( - s, - p, - FeatureKind::ConstructionPlane { plane: solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle } }, - ) + let plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(base), axis_origin, axis_dir, angle, line }; + add_feature(s, p, FeatureKind::ConstructionPlane { plane }) } fn split_face(s: &mut Session, p: &Value) -> Result { @@ -2878,6 +2893,10 @@ fn offset_face(s: &mut Session, p: &Value) -> Result { #[path = "patterns_tests.rs"] mod patterns_tests; +#[cfg(test)] +#[path = "model_axis_tests.rs"] +mod model_axis_tests; + #[cfg(test)] #[path = "prism_local_tests.rs"] mod prism_local_tests; diff --git a/crates/engine/src/cmd/model_axis_tests.rs b/crates/engine/src/cmd/model_axis_tests.rs new file mode 100644 index 000000000..5b5ae8521 --- /dev/null +++ b/crates/engine/src/cmd/model_axis_tests.rs @@ -0,0 +1,197 @@ +//! An axis on an edge or round face of the model (`{edge|face: [x,y,z]}`): Revolve, Surface +//! Revolve, Circular Pattern and Plane at Angle turn about a circular edge's or a cylinder's +//! axis, and follow it when a parameter moves the cylinder. + +use std::f64::consts::PI; + +use serde_json::{Value, json}; +use solidcraft_geom::Vec3; + +use crate::Session; +use crate::view::construction_planes; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + match s.execute(id, &p) { + Ok(v) => v, + Err(e) => panic!("{id} {p}: {e}"), + } +} + +fn volume(s: &mut Session) -> f64 { + run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap_or(f64::NAN) +} + +fn rel(a: f64, b: f64) -> f64 { + (a - b).abs() / b.abs().max(1e-12) +} + +/// A Ø10 × 10 shaft standing on XY at x = `cx` (a parameter, 40 mm). +fn shaft() -> Session { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "cx", "expression": "40 mm"})); + run(&mut s, "solid.cylinder", json!({"base": ["cx", 0, 0], "radius": 5, "height": 10, "body_name": "Shaft"})); + s +} + +const SHAFT: f64 = PI * 25.0 * 10.0; + +/// A 2 × 6 rectangle on XZ, x 46…48, z 2…8: 6 to 8 mm from the shaft's axis. +fn ring_profile(s: &mut Session) { + run(s, "sketch.create", json!({"plane": "XZ", "name": "Profile"})); + run(s, "sketch.rectangle.two_point", json!({"p0": [46, -2], "p1": [48, -8]})); + run(s, "sketch.finish", json!({})); +} + +/// Pappus: a 2 × 6 section whose centre is `r` from the axis, turned a full turn. +fn ring(r: f64) -> f64 { + 2.0 * PI * r * 12.0 +} + +#[test] +fn revolve_about_a_circular_edge_follows_the_cylinder() { + let mut s = shaft(); + ring_profile(&mut s); + // The shaft's top rim. + run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"edge": [45, 0, 10]}, "operation": "new", "name": "Turn"})); + assert!(rel(volume(&mut s), SHAFT + ring(7.0)) < 1e-4, "turned about the shaft's axis: {}", volume(&mut s)); + run(&mut s, "parameters.change", json!({"name": "cx", "expression": "40.5 mm"})); + assert!(rel(volume(&mut s), SHAFT + ring(6.5)) < 1e-4, "follows the shaft: {}", volume(&mut s)); + // Saved and opened again it still follows. + let saved = s.doc.to_json(); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap()); + assert!(rel(volume(&mut reopened), volume(&mut s)) < 1e-9); + run(&mut reopened, "parameters.change", json!({"name": "cx", "expression": "40 mm"})); + assert!(rel(volume(&mut reopened), SHAFT + ring(7.0)) < 1e-4); +} + +#[test] +fn revolve_about_a_cylinder_wall() { + let mut s = shaft(); + ring_profile(&mut s); + run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"face": [45, 0, 5]}, "operation": "new"})); + assert!(rel(volume(&mut s), SHAFT + ring(7.0)) < 1e-4, "{}", volume(&mut s)); + let Some(solidcraft_doc::Feature { kind: solidcraft_doc::FeatureKind::Revolve { axis, .. }, .. }) = s.doc.features.last() else { + panic!("no revolve") + }; + assert!(matches!(axis, solidcraft_doc::AxisRef::Model { .. }), "kept as a reference: {axis:?}"); +} + +#[test] +fn surface_revolve_about_a_circular_edge() { + let mut s = shaft(); + ring_profile(&mut s); + run(&mut s, "surface.revolve", json!({"sketch": "Profile", "axis": {"edge": [45, 0, 0]}, "angle": "180 deg"})); + run(&mut s, "parameters.change", json!({"name": "cx", "expression": "41 mm"})); + let st = s.world_state(); + // A half turn about x = 41: the far side of the profile ends up at x = 41 − 7 ± 1. + let b = st.bodies.last().map(|b| b.mesh().bounds()).unwrap(); + assert!((b.min.x - (41.0 - 7.0)).abs() < 1e-3, "{b:?}"); + assert!((b.max.x - 48.0).abs() < 1e-3, "{b:?}"); +} + +#[test] +fn circular_pattern_about_a_boss_wall_follows_the_boss() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "cx", "expression": "100 mm"})); + run(&mut s, "solid.box", json!({"length": 200, "width": 200, "height": 5, "corner": [0, 0, 0], "body_name": "Plate"})); + run(&mut s, "solid.cylinder", json!({"base": ["cx", 100, 0], "radius": 10, "height": 20, "operation": "join", "targets": ["Plate"]})); + run(&mut s, "solid.hole", json!({"position": [130, 100, 5], "diameter": 2, "name": "Hole"})); + run(&mut s, "solid.pattern.circular", json!({"features": ["Hole"], "axis": {"face": [110, 100, 10]}, "count": 4, "name": "Ring"})); + let holes = |s: &Session, cx: f64, r: f64| { + let st = s.world_state(); + let body = &st.bodies[0].body; + [(r, 0.0), (0.0, r), (-r, 0.0), (0.0, -r)].iter().all(|(dx, dy)| !body.contains(Vec3::new(cx + dx, 100.0 + dy, 2.5))) + }; + assert!(holes(&s, 100.0, 30.0), "four holes round the boss"); + run(&mut s, "parameters.change", json!({"name": "cx", "expression": "90 mm"})); + assert!(holes(&s, 90.0, 40.0), "the copies turn about the boss where it is now"); + let st = s.world_state(); + assert!(st.bodies[0].body.contains(Vec3::new(100.0, 130.0, 2.5)), "not where the boss was"); +} + +#[test] +fn plane_at_angle_about_a_cylinder_axis_follows_it() { + let mut s = shaft(); + run(&mut s, "construct.plane.at_angle", json!({"base": "XZ", "axis": {"face": [45, 0, 5]}, "angle": "90 deg", "name": "Square"})); + let plane = |s: &Session| construction_planes(s).into_iter().find(|p| p.1 == "Square").map(|p| p.2).unwrap(); + let pl = plane(&s); + assert!(pl.normal().cross(Vec3::X).len() < 1e-9, "turned square to XZ about Z: {pl:?}"); + assert!(pl.height(Vec3::new(40.0, 0.0, 0.0)).abs() < 1e-6, "through the shaft's axis: {pl:?}"); + run(&mut s, "parameters.change", json!({"name": "cx", "expression": "25 mm"})); + assert!(plane(&s).height(Vec3::new(25.0, 0.0, 0.0)).abs() < 1e-6, "follows the shaft"); +} + +#[test] +fn plane_at_angle_on_a_face_about_an_edge_follows_both() { + let mut s = Session::default(); + run(&mut s, "parameters.add", json!({"name": "h", "expression": "20 mm"})); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": "h", "name": "Base"})); + // The top face, turned 45° about its front edge (y = 0, along X). + run( + &mut s, + "construct.plane.at_angle", + json!({"base": {"face": [5, 5, 20]}, "axis": {"edge": [20, 0, 20]}, "angle": "45 deg", "name": "Slanted"}), + ); + let feature = s.doc.find_feature("Slanted").unwrap(); + let solidcraft_doc::FeatureKind::ConstructionPlane { plane: solidcraft_doc::PlaneRef::AtAngle { base, line, .. } } = &feature.kind else { + panic!("at_angle plane: {:?}", feature.kind) + }; + assert!(matches!(base.as_ref(), solidcraft_doc::PlaneRef::Face { anchor: Some(_), .. }), "{base:?}"); + assert!(line.is_some(), "the edge is kept as a model reference"); + let plane = |s: &Session| construction_planes(s).into_iter().find(|p| p.1 == "Slanted").map(|p| p.2).unwrap(); + let half = 0.5_f64.sqrt(); + let pl = plane(&s); + assert!(pl.height(Vec3::new(20.0, 0.0, 20.0)).abs() < 1e-6, "through the edge: {pl:?}"); + assert!((pl.normal().z.abs() - half).abs() < 1e-9 && pl.normal().x.abs() < 1e-9, "45° to the top: {pl:?}"); + // A taller box: the face and the edge both move up. + run(&mut s, "parameters.change", json!({"name": "h", "expression": "30 mm"})); + let pl = plane(&s); + assert!(pl.height(Vec3::new(20.0, 0.0, 30.0)).abs() < 1e-6, "follows the edge: {pl:?}"); + assert!((pl.normal().z.abs() - half).abs() < 1e-9, "{pl:?}"); +} + +#[test] +fn the_axis_keeps_its_turn_whichever_way_the_edge_runs() { + // The top and bottom rims run opposite ways round the shaft; a quarter turn about either + // lands in the same place. + let quarter = |edge: [f64; 3]| { + let mut s = shaft(); + ring_profile(&mut s); + run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": {"edge": edge}, "angle": "90 deg", "operation": "new"})); + let st = s.world_state(); + st.bodies.last().map(|b| b.mesh().bounds()).unwrap() + }; + let (top, bottom) = (quarter([45.0, 0.0, 10.0]), quarter([45.0, 0.0, 0.0])); + assert!(top.min.dist(bottom.min) < 1e-6 && top.max.dist(bottom.max) < 1e-6, "{top:?} vs {bottom:?}"); +} + +#[test] +fn hostile_model_axes_are_refused_without_panicking() { + let mut s = shaft(); + ring_profile(&mut s); + let before = s.doc.to_json(); + for axis in [ + json!({"edge": [1e9, 0, 0]}), + json!({"face": [1e300, -1e300, 0]}), + json!({"edge": "top"}), + json!({"face": [45, 0]}), + // The flat top: no axis. + json!({"face": [40, 0, 10]}), + // The shaft's axis doesn't lie in a sketch on XY. + ] { + for (cmd, p) in [ + ("solid.revolve", json!({"sketch": "Profile", "axis": axis})), + ("surface.revolve", json!({"sketch": "Profile", "axis": axis})), + ("solid.pattern.circular", json!({"bodies": ["Shaft"], "axis": axis, "count": 3})), + ("construct.plane.at_angle", json!({"base": "XZ", "axis": axis, "angle": "10 deg"})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!(s.doc.to_json(), before, "{cmd} {p} left the design as it was"); + } + } + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Flat"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [46, 2], "p1": [48, 8]})); + run(&mut s, "sketch.finish", json!({})); + let e = s.execute("solid.revolve", &json!({"sketch": "Flat", "axis": {"face": [45, 0, 5]}})).unwrap_err().to_string(); + assert!(e.contains("does not lie in the sketch plane"), "{e}"); +} diff --git a/crates/engine/src/cmd/sketch_face_tests.rs b/crates/engine/src/cmd/sketch_face_tests.rs index 2ee90b9d8..d7d720174 100644 --- a/crates/engine/src/cmd/sketch_face_tests.rs +++ b/crates/engine/src/cmd/sketch_face_tests.rs @@ -391,7 +391,13 @@ fn angled_attachment_tracks_source_plane_and_reopens() { let id = run(&mut s, "sketch.create", json!({"plane":pick,"project_edges":false}))["sketch"].as_u64().unwrap(); run(&mut s, "sketch.finish", json!({})); let solidcraft_doc::FeatureKind::Sketch { plane, .. } = &mut s.doc_mut().feature_mut(id).unwrap().kind else { panic!("not sketch") }; - *plane = solidcraft_doc::PlaneRef::AtAngle { base: Box::new(plane.clone()), axis_origin: Vec3::ZERO, axis_dir: Vec3::X, angle: "90 deg".into() }; + *plane = solidcraft_doc::PlaneRef::AtAngle { + base: Box::new(plane.clone()), + axis_origin: Vec3::ZERO, + axis_dir: Vec3::X, + angle: "90 deg".into(), + line: None, + }; s.refresh(); let height = s.doc.find_feature("BaseFeature").unwrap().param_names[2].clone(); run(&mut s, "parameters.change", json!({"name":height,"expression":"20 mm"})); diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index f2c488641..8cab8a8ba 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -43,7 +43,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.revolve", "Surface Revolve", surface_revolve) .at("SURFACE", "CREATE") .icon("surface_revolve") - .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|construction axis name|{origin, dir}; angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), + .params("sketch?: id|name; curves?: [curve ids] and/or profiles? (as surface.extrude); axis: sketch line id|x|y|X|Y|Z|construction axis name|{origin, dir} | {edge|face: [x,y,z]} (a straight or circular edge, or a cylinder, cone or torus face: about its axis, followed as the model changes); angle?: expr (default 360 deg); angle2?: expr (the other side); symmetric?: bool; name?, body_name? (a surface body, no caps; a solid where a full turn closes it)"), CommandSpec::new("surface.sweep", "Surface Sweep", surface_sweep) .at("SURFACE", "CREATE") .icon("surface_sweep") diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 298aec974..fa1f8a1d8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,7 +15,8 @@ use solidcraft_engine::geom::{Aabb3, Vec3}; use crate::SolveApp; use crate::selection::{ - self, AXES, Accept, BODIES, CURVES, EDGES, FACES, PLANAR_FACES, PLANES, PROFILES, SelInput, SelectionExt as _, point_value as pt, polyline_mid, + self, AXES, AXIS_PICKS, Accept, BODIES, CURVES, EDGES, FACES, PLANAR_FACES, PLANES, PROFILES, SelInput, SelectionExt as _, point_value as pt, + polyline_mid, }; use crate::theme::Tokens; use crate::tool_modifiers::{Audit, Scope, ToolModifiers}; @@ -110,7 +111,7 @@ crate::dialog_descriptor::dialog_descriptors! { FeatureKind::ConstructionPlane { plane: PlaneRef::Offset { distance, .. } }) { offset: String = "0 mm".into() => distance.to_string(), } => json!({"offset": offset}); - AnglePlane("construct.plane.at_angle", "PLANE AT ANGLE", [("Plane", PLANES | PLANAR_FACES, false), ("Axis", AXES, false)], + AnglePlane("construct.plane.at_angle", "PLANE AT ANGLE", [("Plane", PLANES | PLANAR_FACES, false), ("Axis", AXIS_PICKS, false)], FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { angle, .. } }) { angle: String = "45 deg".into() => angle.to_string(), } => json!({"angle": angle}); @@ -704,7 +705,7 @@ impl Dialog { ), "solid.revolve" => Dialog::new( Kind::Revolve { angle: "360 deg".into(), operation: 0, axis: None }, - vec![SelInput::new("Profile", PROFILES | PLANAR_FACES, true), SelInput::new("Axis", AXES, false)], + vec![SelInput::new("Profile", PROFILES | PLANAR_FACES, true), SelInput::new("Axis", AXIS_PICKS, false)], ), "solid.fillet" => Dialog::new(fillet_kind(&length_default(s, "2"), false), vec![SelInput::new("Edges", EDGES | FACES, true)]), "solid.chamfer" => Dialog::new(fillet_kind(&length_default(s, "1"), true), vec![SelInput::new("Edges", EDGES | FACES, true)]), @@ -799,7 +800,7 @@ impl Dialog { ), "solid.pattern.circular" => Dialog::new( Kind::PatternCirc { count: "6".into(), angle: "360 deg".into() }, - vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXES, false)], + vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXIS_PICKS, false)], ), "solid.loft" => Dialog::new(Kind::Loft { operation: usize::from(has_bodies), rail_fit: 0 }, { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); @@ -917,7 +918,10 @@ impl Dialog { _ => true, }; let takes = |i: &SelInput| { - fits(i.accept, sel) && (i.multi || i.items.is_empty()) && (planar_ok || i.accept & FACES != 0 || !matches!(sel, Sel::Face { .. })) + fits(i.accept, sel) + && (i.multi || i.items.is_empty()) + && (planar_ok || i.accept & FACES != 0 || !matches!(sel, Sel::Face { .. })) + && (i.accept != AXIS_PICKS || takes_as_axis(s, sel)) }; if let Some(inp) = d.inputs.iter_mut().find(|i| takes(i)) { if matches!(d.kind, Kind::Fillet { .. }) { @@ -1142,6 +1146,14 @@ impl Dialog { self.inputs.get(self.active) } + /// Whether a round edge kept in `inp` stands for its centre: a construction point's input, + /// or Move's pivot and points (`dialogs_move::sel_point`). Other point inputs take the + /// centre as a vertex (`circle_centre_pick`). + pub(crate) fn edge_is_centre(&self, inp: &SelInput) -> bool { + inp.accept != selection::AXIS_PICKS + && (matches!(self.kind, Kind::Move { .. }) || (matches!(self.kind, Kind::Construct { .. }) && inp.accept & selection::VERTICES != 0)) + } + /// Everything the inputs hold (for highlighting). pub fn items(&self) -> Vec { self.inputs.iter().flat_map(|i| i.items.iter().cloned()).collect() @@ -1201,8 +1213,8 @@ impl Dialog { } /// The face under the cursor (the nearest face the pick ray meets, first among `hits`), looked - /// up once for all the sketch points among `hits` when the active input snaps face places to - /// them (the Single hole's); `None` otherwise. + /// up once for all the sketch points and round edges' centres among `hits` when the active + /// input snaps face places to them (the Single hole's); `None` otherwise. pub(crate) fn face_snap(&self, s: &Session, hits: &[Hit]) -> Option { if !self.active_input().is_some_and(|i| snaps_to_points(i.accept)) { return None; @@ -1213,6 +1225,7 @@ impl Dialog { .iter() .filter_map(|h| match h { Hit::SketchPoint { sketch, at, .. } => st.sketch(*sketch).map(|ss| ss.plane.to_world(*at)), + Hit::Edge { body, index, .. } => edge_circle_in(&st, body, *index).map(|(c, ..)| c), _ => None, }) .collect(); @@ -1246,8 +1259,37 @@ impl Dialog { let snap = snap?; return snap.place_at(s.world_state().sketch(*sketch)?.plane.to_world(*at)); } + if let Some(sel) = self.circle_centre_pick(s, inp, h, snap) { + return Some(sel); + } // The snap looked the face under the cursor up already, planar or not. - inp.accepts(h, s.active_sketch, |body, face| snap.and_then(|f| f.planar(body, face)).unwrap_or_else(|| planar_face(s, body, face).is_some())) + let sel = inp.accepts(h, s.active_sketch, |body, face| { + snap.and_then(|f| f.planar(body, face)).unwrap_or_else(|| planar_face(s, body, face).is_some()) + })?; + (inp.accept != AXIS_PICKS || takes_as_axis(s, &sel)).then_some(sel) + } + + /// A round edge where a 3D point is wanted stands for its centre: a construction point's + /// input keeps the edge (its centre is found again as the model changes), a face place + /// (a hole's) is taken at the centre when it lies on the face under the cursor, and any other + /// point input takes the centre as a point. Inputs that take edges themselves keep the edge + /// (Move's points find its centre, `dialogs_move::sel_point`). + fn circle_centre_pick(&self, s: &Session, inp: &SelInput, h: &Hit, snap: Option<&FaceSnap>) -> Option { + let Hit::Edge { body, index, mid } = h else { return None }; + let a = inp.accept; + let places = snaps_to_points(a); + if a & EDGES != 0 || (a & selection::VERTICES == 0 && !places) { + return None; + } + let (centre, ..) = edge_circle(s, body, *index)?; + if places { + return snap?.place_at(centre); + } + Some(if matches!(self.kind, Kind::Construct { .. }) { + Sel::Edge { body: body.clone(), index: *index, point: *mid } + } else { + Sel::Vertex { body: body.clone(), point: centre } + }) } /// With automatic To Object enabled and profiles picked, a face or vertex off their plane, @@ -1890,6 +1932,8 @@ fn hint(inp: &SelInput) -> &'static str { let a = inp.accept; if a & PROFILES != 0 { "click profiles in the view" + } else if a == AXIS_PICKS { + "click an axis, a sketch line, a straight or circular edge, or a cylinder face" } else if a & EDGES != 0 { "click edges or faces" } else if a & PLANES != 0 { @@ -2036,7 +2080,7 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, session: &Session) { ), 1 => ( Kind::PatternCirc { count: "6".into(), angle: "360 deg".into() }, - vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXES, false)], + vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXIS_PICKS, false)], ), _ => ( Kind::PathPattern { count: "4".into(), spacing: length_default(session, "20") }, @@ -2068,13 +2112,23 @@ fn placement_row(d: &mut Dialog, ui: &mut egui::Ui, session: &Session) { } } -fn selection_label(s: &Session, item: &Sel) -> String { +/// A picked item as its chip shows it. A round edge or face says what it stands for in `inp`: +/// its axis in an axis input, a circle's centre in a point input. +pub(crate) fn selection_label(s: &Session, d: &Dialog, inp: &SelInput, item: &Sel) -> String { + let axis = inp.accept == selection::AXIS_PICKS && round_axis(s, item).is_some(); match item { Sel::SketchCurve { id, .. } => id.clone(), Sel::SketchPoint { id } => crate::sketch_modify_ui::point_id(s, item).unwrap_or(id).to_string(), Sel::Plane { name } | Sel::Axis { name } | Sel::ConstructionPoint { name } | Sel::Body { name } => name.clone(), + Sel::Face { body, index, .. } if axis => format!("{body} · face {index} axis"), Sel::Face { body, index, .. } => format!("{body} · face {index}"), + Sel::Edge { body, .. } if axis => format!("{body} · circle axis"), + Sel::Edge { body, index, .. } if d.edge_is_centre(inp) && edge_circle(s, body, *index).is_some() => { + format!("{body} · circle centre") + } Sel::Edge { body, index, .. } => format!("{body} · edge {index}"), + // A point of the model: a vertex, or the centre a round edge stands for. + Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), Sel::Vertex { body, point } if body.is_empty() => { let state = s.world_state(); @@ -2134,7 +2188,7 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, r RichText::new(if custom_axis || stored_reference.is_some() { crate::i18n::tr("dialog.custom_axis").into() } else if !inp.multi { - inp.items.first().map(|item| selection_label(s, item)).unwrap_or_default() + inp.items.first().map(|item| selection_label(s, d, inp, item)).unwrap_or_default() } else { let count = if i == 0 { shell_count.unwrap_or(inp.items.len()) } else { inp.items.len() }; crate::i18n::format("dialog.selected_count", &[("count", &count.to_string())]) @@ -2158,11 +2212,15 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, r reference.to_string() } else if custom_axis { if let Some(axis) = stored_revolve_axis(&d.kind) { - format!( - "Custom axis\nOrigin: {}\nDirection: {}\nClick to select a replacement axis", - axis.get("origin").map(ToString::to_string).unwrap_or_default(), - axis.get("dir").map(ToString::to_string).unwrap_or_default() - ) + match axis.get("at") { + // A kept edge or face of the model (one no longer found). + Some(at) => format!("Custom axis\nThe edge or face at {at}\nClick to select a replacement axis"), + None => format!( + "Custom axis\nOrigin: {}\nDirection: {}\nClick to select a replacement axis", + axis.get("origin").map(ToString::to_string).unwrap_or_default(), + axis.get("dir").map(ToString::to_string).unwrap_or_default() + ), + } } else { hint(inp).to_string() } @@ -2187,7 +2245,7 @@ pub(crate) fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, r }); if matches!(d.kind, Kind::SketchModify(_)) && inp.multi { for (index, item) in inp.items.iter().enumerate() { - if crate::ui_kit::list_row(ui, &format!("{}:{index}", inp.label), &selection_label(s, item)).clicked() { + if crate::ui_kit::list_row(ui, &format!("{}:{index}", inp.label), &selection_label(s, d, inp, item)).clicked() { remove = Some((i, index)); } } @@ -3583,7 +3641,8 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S let axis = match sels(d, 1).first() { Some(Sel::Axis { name }) => json!(name), Some(Sel::SketchCurve { id, .. }) => json!(id), - _ => stored_axis.clone().ok_or("select an axis")?, + Some(x) => axis_param(app, x)?, + None => stored_axis.clone().ok_or("select an axis")?, }; let (sketch, idx) = profiles(); let mut p = json!({"axis": axis, "angle": angle, "operation": OPS.get(*operation).copied().unwrap_or("new")}); @@ -3730,11 +3789,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, "objects")?; let axis = match sels(d, 1).first() { None if d.extra.contains_key("axis") => d.extra.get("axis").cloned().unwrap_or(Value::Null), - Some(Sel::Axis { name }) => json!(name), - Some(x) => { - let (o, dir) = axis_of(app, x).ok_or("the axis must be an origin axis or a sketch line")?; - json!({"origin": pt(o), "dir": pt(dir)}) - } + Some(x) => axis_param(app, x)?, None => return Err("select an axis".into()), }; let mut p = json!({"axis": axis, "count": count, "angle": angle}); @@ -3848,11 +3903,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S need(0, "a plane")?; let base = plane_arg(app, sels(d, 0).first())?; let axis = match sels(d, 1).first() { - Some(Sel::Axis { name }) => json!(name), - Some(x) => { - let (o, dir) = axis_of(app, x).ok_or("the axis must be an origin axis or a sketch line")?; - json!({"origin": pt(o), "dir": pt(dir)}) - } + Some(x) => axis_param(app, x)?, None => d.extra.get("axis").cloned().ok_or("pick an axis")?, }; ("construct.plane.at_angle", json!({"base": base, "axis": axis})) @@ -4351,25 +4402,115 @@ pub fn axis_of(app: &SolveApp, sel: &Sel) -> Option<(Vec3, Vec3)> { }; Some((pa, (pb - pa).normalized()?)) } - // A straight model edge, along it. + // A straight model edge, along it; a circular one, about its axis. Sel::Edge { body, index, .. } => { let b = app.session.world_state().body(body).cloned()?; let m = b.mesh(); let e = m.edges.get(*index)?; let (a, z) = (*e.first()?, *e.last()?); - let dir = (z - a).normalized()?; + let Some(dir) = (z - a).normalized() else { return round_axis(&app.session, sel) }; let tol = 1e-6 * a.dist(z).max(1.0); if !e.iter().all(|p| (*p - a).cross(dir).len() < tol) { - return None; + return round_axis(&app.session, sel); } // An edge along an origin axis points the way the axis does (as picking the axis). let axis = [Vec3::X, Vec3::Y, Vec3::Z].into_iter().find(|x| dir.dot(*x).abs() > 1.0 - 1e-9); Some((a, axis.unwrap_or(dir))) } + // A cylinder, cone or torus face: its axis. + Sel::Face { .. } => round_axis(&app.session, sel), _ => None, } } +/// The circle a picked edge lies on, from its exact curve, when the drawn edge lies on it: +/// (centre, unit normal, radius). A round edge stands for its circle wherever a 3D pick wants +/// an axis (through the centre, along the normal) or a point (the centre). +pub(crate) fn edge_circle(s: &Session, body: &str, index: usize) -> Option<(Vec3, Vec3, f64)> { + edge_circle_in(&s.world_state(), body, index) +} + +/// [`edge_circle`] in a given model state (a dialog editing a feature looks at the model before it). +pub(crate) fn edge_circle_in(st: &solidcraft_engine::doc::ModelState, body: &str, index: usize) -> Option<(Vec3, Vec3, f64)> { + let b = st.body(body)?; + let c = solidcraft_engine::kernel::edge_circle(&b.body, index)?; + let tol = (b.body.size() * 1e-6).max(1e-9) * 10.0; + let on = |p: &Vec3| (p.dist(c.center) - c.radius).abs() <= tol && (*p - c.center).dot(*c.axis).abs() <= tol; + b.mesh().edges.get(index)?.iter().all(on).then_some((c.center, *c.axis, c.radius)) +} + +/// The axis of a circular edge (through its centre, along its normal) or of a cylinder, cone or +/// torus face, pointing the way the command will find it (`construct::canonical_dir`). `None` +/// for any other pick: those have no axis of their own. +pub(crate) fn round_axis(s: &Session, sel: &Sel) -> Option<(Vec3, Vec3)> { + use solidcraft_engine::kernel::{self, FaceSurface}; + let (o, d) = match sel { + Sel::Edge { body, index, .. } => edge_circle(s, body, *index).map(|(c, n, _)| (c, n))?, + Sel::Face { body, index, .. } => { + let st = s.world_state(); + let b = st.body(body)?; + match kernel::guard("axis of a face", || Ok(kernel::face_surface(&b.body, *index))).ok().flatten()? { + FaceSurface::Cylinder { origin, axis, .. } => (origin, *axis), + FaceSurface::Cone { apex, axis, .. } => (apex, *axis), + FaceSurface::Torus { center, axis, .. } => (center, *axis), + _ => return None, + } + } + _ => return None, + }; + o.is_finite().then(|| (o, solidcraft_engine::doc::construct::canonical_dir(d))) +} + +/// An axis pick that the command keeps as a reference to the model (`{edge|face: [x,y,z]}`), so +/// the feature follows the edge or face: a circular edge, or a cylinder, cone or torus face. +/// Straight edges stay a fixed line, as they always have. +fn round_axis_ref(app: &SolveApp, sel: &Sel) -> Option { + round_axis(&app.session, sel)?; + match sel { + Sel::Edge { .. } if !is_straight_edge(&app.session, sel) => construct_ref(app, sel).ok(), + Sel::Face { .. } => construct_ref(app, sel).ok(), + _ => None, + } +} + +fn is_straight_edge(s: &Session, sel: &Sel) -> bool { + let Sel::Edge { body, index, .. } = sel else { return false }; + let Some(b) = s.world_state().body(body).cloned() else { return false }; + let m = b.mesh(); + let Some(e) = m.edges.get(*index) else { return false }; + let (Some(a), Some(z)) = (e.first().copied(), e.last().copied()) else { return false }; + let Some(dir) = (z - a).normalized() else { return false }; + let tol = 1e-6 * a.dist(z).max(1.0); + e.iter().all(|p| (*p - a).cross(dir).len() < tol) +} + +/// Whether an axis input (`selection::AXIS_PICKS`) takes this pick: an edge or face only where +/// it has an axis (a straight or circular edge, a cylinder, cone or torus face). +pub(crate) fn takes_as_axis(s: &Session, sel: &Sel) -> bool { + match sel { + Sel::Edge { .. } => is_straight_edge(s, sel) || round_axis(s, sel).is_some(), + Sel::Face { .. } => round_axis(s, sel).is_some(), + _ => true, + } +} + +/// An axis input's pick as a command's `axis`: a world axis or construction axis by name, a +/// circular edge or round face by reference, anything else (a sketch line, a straight edge) as +/// its line. +pub(crate) fn axis_param(app: &SolveApp, sel: &Sel) -> Result { + if let Sel::Axis { name } = sel { + return Ok(json!(name)); + } + if let Some(r) = round_axis_ref(app, sel) { + return Ok(r); + } + let (o, dir) = axis_of(app, sel).ok_or(AXIS_PICK)?; + Ok(json!({"origin": pt(o), "dir": pt(dir)})) +} + +const AXIS_PICK: &str = + "the axis must be an origin or construction axis, a sketch line, a straight or circular edge, or a cylinder, cone or torus face"; + /// Which profiles of a sketch a profile selection means. pub(crate) fn profile_indices(ss: &solidcraft_engine::doc::SolvedSketch, sel: &ProfileSel) -> Vec { let ps = &ss.profiles; @@ -4637,6 +4778,18 @@ fn point_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Opti } } +/// A feature's axis on an edge or round face of the model back into a dialog pick: the edge or +/// face where it is now. +pub(crate) fn model_axis_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Option { + use solidcraft_engine::doc::construct::GeoRef; + let at = g.picked_point(&s.world_state())?; + match g { + GeoRef::Edge { .. } => edge_sel(s, at), + GeoRef::Face { .. } => face_sel(s, at), + _ => None, + } +} + /// A stored construction reference back into a dialog pick. fn geo_sel(s: &Session, g: &solidcraft_engine::doc::construct::GeoRef) -> Option { match g { @@ -4754,6 +4907,8 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option serde_json::to_value(geo).ok(), _ => None, }; d.kind = Kind::Revolve { angle: angle.to_string(), operation: op_index(operation), axis: stored_axis }; @@ -4778,8 +4933,9 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option Some(Sel::Axis { name: axis.to_ascii_uppercase() }), AxisRef::SketchAxis { axis } => Some(Sel::Axis { name: axis.to_ascii_lowercase() }), AxisRef::SketchLine { curve } => Some(crate::selection::curve_pick(curve, sketch.0, s.active_sketch)), + AxisRef::Model { geo } => model_axis_sel(s, geo), AxisRef::Construction { name } => Some(Sel::Axis { name: name.to_string() }), - _ => None, + AxisRef::Line { .. } => None, }; if let Some(inp) = d.inputs.get_mut(1) { inp.items = ax.into_iter().collect(); @@ -5192,20 +5348,29 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + PatternKind::Circular { origin, axis, count, angle, alignment, reversed, axis_ref, axis_feature } => { let mut d = start("solid.pattern.circular")?; d.extra.insert("alignment".into(), json!(alignment)); d.extra.insert("reversed".into(), json!(reversed)); d.kind = Kind::PatternCirc { count: count.to_string(), angle: angle.to_string() }; - // The construction axis it turns about, else an origin axis or its line. - let named = axis_feature.as_ref().map(|n| n.to_string()); - match named.or_else(|| world_axis(axis.0).filter(|_| origin.len() < 1e-9)) { - Some(name) => { + // The edge or face it turns about, else its construction axis, else an origin + // axis or its line. + let pick = match (axis_ref, axis_feature) { + (Some(g), _) => model_axis_sel(s, g), + (None, Some(name)) => Some(Sel::Axis { name: name.to_string() }), + (None, None) => world_axis(axis.0).filter(|_| origin.len() < 1e-9).map(|name| Sel::Axis { name }), + }; + match (pick, axis_ref) { + (Some(pick), _) => { if let Some(inp) = d.inputs.get_mut(1) { - inp.items = vec![Sel::Axis { name }]; + inp.items = vec![pick]; } } - None => { + // An edge or face that is gone stays the reference until another is picked. + (None, Some(g)) => { + d.extra.insert("axis".into(), serde_json::to_value(g).unwrap_or(Value::Null)); + } + (None, None) => { d.extra.insert("axis".into(), json!({"origin": pt3(origin.0), "dir": pt3(axis.0)})); } } @@ -5316,19 +5481,26 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { base, axis_origin, axis_dir, line, .. } } => { let mut d = start("construct.plane.at_angle")?; d.kind = Kind::simple_restore(&f.kind)?; if let Some(inp) = d.inputs.first_mut() { inp.items = plane_sel(s, base).into_iter().collect(); } - match world_axis(*axis_dir).filter(|_| axis_origin.len() < 1e-9) { - Some(name) => { + let pick = match line { + Some(g) => model_axis_sel(s, g), + None => world_axis(*axis_dir).filter(|_| axis_origin.len() < 1e-9).map(|name| Sel::Axis { name }), + }; + match (pick, line) { + (Some(pick), _) => { if let Some(inp) = d.inputs.get_mut(1) { - inp.items = vec![Sel::Axis { name }]; + inp.items = vec![pick]; } } - None => { + (None, Some(g)) => { + d.extra.insert("axis".into(), serde_json::to_value(g).unwrap_or(Value::Null)); + } + (None, None) => { d.extra.insert("axis".into(), json!({"origin": pt3(*axis_origin), "dir": pt3(*axis_dir)})); } } diff --git a/crates/ui-egui/src/dialogs_move.rs b/crates/ui-egui/src/dialogs_move.rs index c19f22d6f..87c98d81e 100644 --- a/crates/ui-egui/src/dialogs_move.rs +++ b/crates/ui-egui/src/dialogs_move.rs @@ -12,7 +12,7 @@ use solidcraft_engine::geom::Vec3; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; use crate::gizmo::{self, Change, Drag}; -use crate::selection::{AXES, BODIES, EDGES, FACES, ORIGIN, SelInput, VERTICES}; +use crate::selection::{AXIS_PICKS, BODIES, EDGES, FACES, ORIGIN, SelInput, VERTICES}; pub const TYPES: [&str; 5] = ["Free Move", "Translate", "Rotate", "Point to Point", "Point to Position"]; pub const FREE: usize = 0; @@ -34,7 +34,7 @@ pub fn inputs(mode: usize) -> Vec { let mut v = vec![SelInput::new("Bodies", BODIES, true)]; match mode { FREE => v.push(SelInput::new("Pivot", POINTS, false)), - ROTATE => v.push(SelInput::new("Axis", AXES | EDGES, false)), + ROTATE => v.push(SelInput::new("Axis", AXIS_PICKS, false)), POINT_TO_POINT => { v.push(SelInput::new("From", POINTS, false)); v.push(SelInput::new("To", POINTS, false)); @@ -92,9 +92,19 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Kind) -> bool { enter } -fn sel_point(s: Option<&Sel>) -> Option { +/// Where a point pick is: a round edge stands for its centre, where the model is before this +/// move, in the world (a body of a placed component where its occurrence puts it, as it was +/// picked); any other pick is where it was picked. +fn sel_point(app: &SolveApp, d: &Dialog, s: Option<&Sel>) -> Option { match s? { - Sel::Vertex { point, .. } | Sel::Face { point, .. } | Sel::Edge { point, .. } => Some(*point), + Sel::Edge { body, index, point } => { + let st = match d.editing { + Some((id, _)) => std::sync::Arc::new(solidcraft_engine::doc::world_state(&app.session.doc, &app.session.model.state_before(id))), + None => app.session.world_state(), + }; + Some(crate::dialogs::edge_circle_in(&st, body, *index).map_or(*point, |(c, ..)| c)) + } + Sel::Vertex { point, .. } | Sel::Face { point, .. } => Some(*point), _ => None, } } @@ -127,7 +137,7 @@ fn bodies_center(app: &SolveApp, d: &Dialog) -> Option { /// What a Free Move turns about: the picked pivot, else the kept one (editing), else the /// bodies' centre. fn pivot(app: &SolveApp, d: &Dialog) -> Option { - if let Some(p) = sel_point(items(d, 1).first()) { + if let Some(p) = sel_point(app, d, items(d, 1).first()) { return Some(p); } if let Some(a) = d.extra.get("pivot").and_then(|v| serde_json::from_value::<[f64; 3]>(v.clone()).ok()) { @@ -167,7 +177,7 @@ pub fn params(app: &SolveApp, d: &Dialog) -> Result { if bodies.is_empty() { return Err("select bodies first".into()); } - let need_point = |i: usize, what: &str| sel_point(items(d, i).first()).ok_or(format!("select {what} first")); + let need_point = |i: usize, what: &str| sel_point(app, d, items(d, i).first()).ok_or(format!("select {what} first")); let num = |t: Vec3| json!([mm(t.x), mm(t.y), mm(t.z)]); let mut p = json!({ "bodies": bodies }); match *mode { @@ -204,7 +214,10 @@ pub fn params(app: &SolveApp, d: &Dialog) -> Result { } } ROTATE => { - let (o, a) = items(d, 1).first().and_then(|s| axis_line(app, s)).ok_or("select an axis or a straight edge first")?; + let (o, a) = items(d, 1) + .first() + .and_then(|s| axis_line(app, s)) + .ok_or("select an axis, a straight or circular edge, or a cylinder, cone or torus face first")?; let th = ang(app, angle)?; let r = gizmo::rotation(a, th); p["translate"] = num(o - gizmo::apply(&r, o)); @@ -227,7 +240,8 @@ pub fn params(app: &SolveApp, d: &Dialog) -> Result { Ok(p) } -/// An axis line: origin axes and sketch lines, or a straight body edge. +/// An axis line: origin axes and sketch lines, a straight or circular body edge, or a cylinder, +/// cone or torus face (`dialogs::axis_of`), or a straight edge of a body where it was modelled. fn axis_line(app: &SolveApp, s: &Sel) -> Option<(Vec3, Vec3)> { if let Some(a) = crate::dialogs::axis_of(app, s) { return Some(a); diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 58bf3e729..d1f14ac4b 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -12,7 +12,9 @@ use solidcraft_engine::geom::Vec3; use crate::SolveApp; use crate::dialogs::{Kind, OP_LABELS, OPS, combo, form_row, op_index}; -use crate::selection::{AXES, BODIES, CURVES, EDGES, FACES, PLANES, PROFILES, SelInput, SelectionExt as _, VERTICES, items, point_value as pt}; +use crate::selection::{ + AXES, AXIS_PICKS, BODIES, CURVES, EDGES, FACES, PLANES, PROFILES, SelInput, SelectionExt as _, VERTICES, items, point_value as pt, +}; use crate::ui_kit; crate::dialog_descriptor::dialog_descriptors! { @@ -158,7 +160,7 @@ const RULED_MODES: [(&str, &str); 4] = [("Normal", "normal"), ("Tangent", "tange fn inputs(k: &Surf) -> Vec { match k { Surf::Extrude { .. } => vec![SelInput::new("Profiles or curves", PROFILES | CURVES, true)], - Surf::Revolve { .. } => vec![SelInput::new("Profiles or curves", PROFILES | CURVES, true), SelInput::new("Axis", AXES, false)], + Surf::Revolve { .. } => vec![SelInput::new("Profiles or curves", PROFILES | CURVES, true), SelInput::new("Axis", AXIS_PICKS, false)], Surf::Sweep(_) => { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); vec![ @@ -493,7 +495,8 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map json!(name), Some(Sel::SketchCurve { id, .. }) => json!(id), - _ => axis.clone().ok_or("select an axis")?, + Some(x) => crate::dialogs::axis_param(app, x)?, + None => axis.clone().ok_or("select an axis")?, }; p["angle"] = json!(angle); if *symmetric { @@ -818,6 +821,11 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K "dir": pt(solidcraft_engine::doc::apply_vector(frame, dir.0)) })), ), + // An edge or face that is gone stays the reference until another is picked. + AxisRef::Model { geo } => match crate::dialogs::model_axis_sel(s, geo) { + Some(pick) => (Some(pick), None), + None => (None, serde_json::to_value(geo).ok()), + }, }; let mut extra = Map::new(); if let Some(a2) = angle2 { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 209a840b7..ea743ee07 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -195,6 +195,8 @@ pub mod render_workspace; mod revolve_edit_tests; #[cfg(test)] mod revolve_manipulator_tests; +#[cfg(test)] +mod round_pick_tests; mod rule_editor; #[cfg(test)] mod rule_editor_tests; diff --git a/crates/ui-egui/src/round_pick_tests.rs b/crates/ui-egui/src/round_pick_tests.rs new file mode 100644 index 000000000..7a5552763 --- /dev/null +++ b/crates/ui-egui/src/round_pick_tests.rs @@ -0,0 +1,296 @@ +//! A round edge or face picked in 3D stands for its circle: an axis input (Revolve, Circular +//! Pattern, Plane at Angle, Move's Rotate) takes a circular edge or a cylinder wall as its axis, +//! kept as a reference so the feature follows it; a point input takes a circle's centre; and +//! hovering one draws the axis or centre as construction geometry. + +use serde_json::{Value, json}; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::{AxisRef, FeatureKind, PatternKind, PlaneRef}; +use solidcraft_engine::geom::Vec3; + +use crate::dialogs::Kind; +use crate::scenario::Harness; +use crate::viewport::Hit; + +/// A Ø10 × 10 shaft at x = `cx` (40 mm) and a 2 × 6 profile on XZ beside it. +fn shaft() -> Harness { + let mut h = Harness::new(); + h.app.run("parameters.add", json!({"name": "cx", "expression": "40 mm"})).unwrap(); + h.app.run("solid.cylinder", json!({"base": ["cx", 0, 0], "radius": 5, "height": 10, "body_name": "Shaft"})).unwrap(); + h.app.run("sketch.create", json!({"plane": "XZ", "name": "Profile"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [46, -2], "p1": [48, -8]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.frames(2); + h +} + +/// The shaft's wall, top rim and top cap, as picks. +fn picks(h: &Harness) -> (Sel, Sel, Sel) { + use solidcraft_engine::kernel::{FaceSurface, face_surface}; + let st = h.app.session.world_state(); + let b = st.body("Shaft").unwrap(); + let face = |want: fn(&FaceSurface) -> bool, point: Vec3| { + let index = (0..b.body.face_count()).find(|i| face_surface(&b.body, *i).is_some_and(|f| want(&f))).unwrap(); + Sel::Face { body: "Shaft".into(), index, point } + }; + let wall = face(|f| matches!(f, FaceSurface::Cylinder { .. }), Vec3::new(45.0, 0.0, 5.0)); + let cap = face(|f| matches!(f, FaceSurface::Plane { normal, .. } if normal.z > 0.5), Vec3::new(40.0, 0.0, 10.0)); + let rim = b + .mesh() + .edges + .iter() + .enumerate() + .find_map(|(index, e)| { + let c = solidcraft_engine::kernel::edge_circle(&b.body, index)?; + (c.center.z > 9.0).then(|| Sel::Edge { body: "Shaft".into(), index, point: e[0] }) + }) + .unwrap(); + (wall, rim, cap) +} + +fn hit(sel: &Sel) -> Hit { + match sel { + Sel::Face { body, index, point } => Hit::Face { body: body.clone(), index: *index, point: *point }, + Sel::Edge { body, index, point } => Hit::Edge { body: body.clone(), index: *index, mid: *point }, + _ => panic!("not a model pick"), + } +} + +fn along_z_through(axis: (Vec3, Vec3), x: f64) -> bool { + let (o, d) = axis; + d.cross(Vec3::Z).len() < 1e-9 && (o.x - x).abs() < 1e-6 && o.y.abs() < 1e-6 +} + +/// The command the open dialog runs, with `sel` in input `input`. +fn command_with(h: &mut Harness, cmd: &str, input: usize, sel: &Sel, setup: impl Fn(&mut crate::dialogs::Dialog)) -> Value { + h.app.start(cmd); + let mut d = h.app.dialog.clone().unwrap(); + setup(&mut d); + d.active = input; + d.inputs[input].items = vec![sel.clone()]; + let cmds = crate::dialogs::apply_commands(&h.app, &d).unwrap(); + h.app.dialog = None; + cmds.into_iter().find(|(c, _)| c == cmd).map(|(_, p)| p).unwrap() +} + +fn profile(h: &Harness) -> Sel { + Sel::Profile { sketch: h.app.session.doc.find_feature("Profile").unwrap().id, index: 0 } +} + +#[test] +fn a_circular_edge_or_cylinder_wall_is_an_axis_and_a_flat_face_is_not() { + let h = shaft(); + let (wall, rim, cap) = picks(&h); + for sel in [&wall, &rim] { + let axis = crate::dialogs::axis_of(&h.app, sel).unwrap(); + assert!(along_z_through(axis, 40.0), "{sel:?}: {axis:?}"); + assert!(axis.1.z > 0.0, "oriented the way the command finds it"); + } + assert!(crate::dialogs::axis_of(&h.app, &cap).is_none()); +} + +#[test] +fn axis_inputs_take_only_edges_and_faces_that_have_an_axis() { + let mut h = shaft(); + let (wall, rim, cap) = picks(&h); + for cmd in ["solid.revolve", "solid.pattern.circular", "construct.plane.at_angle", "surface.revolve"] { + h.app.start(cmd); + let mut d = h.app.dialog.clone().unwrap(); + d.active = 1; + assert_eq!(d.inputs[1].accept, crate::selection::AXIS_PICKS, "{cmd}"); + assert_eq!(d.candidate(&h.app.session, &hit(&wall)), Some(wall.clone()), "{cmd} takes the wall"); + assert_eq!(d.candidate(&h.app.session, &hit(&rim)), Some(rim.clone()), "{cmd} takes the rim"); + assert_eq!(d.candidate(&h.app.session, &hit(&cap)), None, "{cmd} refuses the flat cap"); + h.app.dialog = None; + } + // Move's Rotate too. + h.app.start("solid.move"); + let mut d = h.app.dialog.clone().unwrap(); + d.kind = crate::dialogs_move::kind(crate::dialogs_move::ROTATE, &h.app.session.doc); + d.inputs = crate::dialogs_move::inputs(crate::dialogs_move::ROTATE); + d.active = 1; + assert_eq!(d.candidate(&h.app.session, &hit(&wall)), Some(wall)); + assert_eq!(d.candidate(&h.app.session, &hit(&cap)), None); +} + +#[test] +fn revolve_keeps_a_round_pick_as_a_reference_and_reopens_it() { + let mut h = shaft(); + let (_, rim, _) = picks(&h); + let p = profile(&h); + let mut params = command_with(&mut h, "solid.revolve", 1, &rim, |d| d.inputs[0].items = vec![p.clone()]); + assert!(params["axis"].get("edge").is_some(), "{params}"); + params["name"] = json!("Turn"); + h.app.run("solid.revolve", params).unwrap(); + let revolve_axis = |h: &Harness| match &h.app.session.doc.find_feature("Turn").unwrap().kind { + FeatureKind::Revolve { axis, .. } => axis.clone(), + _ => panic!("revolve"), + }; + assert!(matches!(revolve_axis(&h), AxisRef::Model { .. })); + // The cylinder moves; editing the revolve shows the rim where it is now and keeps the reference. + h.app.run("parameters.change", json!({"name": "cx", "expression": "41 mm"})).unwrap(); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": "Turn"}})).unwrap(); + h.frames(4); + let d = h.app.dialog.as_ref().unwrap(); + let picked = d.inputs[1].items.first().cloned().unwrap(); + assert!(along_z_through(crate::dialogs::axis_of(&h.app, &picked).unwrap(), 41.0), "{picked:?}"); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(matches!(revolve_axis(&h), AxisRef::Model { .. })); +} + +#[test] +fn circular_pattern_and_angle_plane_keep_a_cylinder_wall() { + let mut h = shaft(); + let (wall, ..) = picks(&h); + let params = command_with(&mut h, "solid.pattern.circular", 1, &wall, |d| d.inputs[0].items = vec![Sel::Body { name: "Shaft".into() }]); + assert!(params["axis"].get("face").is_some(), "{params}"); + h.app.run("solid.pattern.circular", params).unwrap(); + assert!( + h.app + .session + .doc + .features + .iter() + .any(|f| matches!(f.kind, FeatureKind::Pattern { pattern: PatternKind::Circular { axis_ref: Some(_), .. }, .. })) + ); + let params = command_with(&mut h, "construct.plane.at_angle", 1, &wall, |d| d.inputs[0].items = vec![Sel::Plane { name: "XZ".into() }]); + assert!(params["axis"].get("face").is_some(), "{params}"); + h.app.run("construct.plane.at_angle", params).unwrap(); + assert!( + h.app + .session + .doc + .features + .iter() + .any(|f| matches!(&f.kind, FeatureKind::ConstructionPlane { plane: PlaneRef::AtAngle { line: Some(_), .. } })) + ); +} + +#[test] +fn move_rotates_about_a_cylinder_wall_and_moves_from_a_circle_centre() { + use crate::dialogs_move::{POINT_TO_POINT, ROTATE, inputs, kind, params}; + let mut h = shaft(); + h.app.run("solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [60, 0, 0], "body_name": "Lug"})).unwrap(); + let (wall, rim, _) = picks(&h); + h.app.start("solid.move"); + let mut d = h.app.dialog.clone().unwrap(); + d.kind = kind(ROTATE, &h.app.session.doc); + d.inputs = inputs(ROTATE); + d.inputs[0].items = vec![Sel::Body { name: "Lug".into() }]; + d.inputs[1].items = vec![wall.clone()]; + let p = params(&h.app, &d).unwrap(); + let a: Vec = serde_json::from_value(p["axis"].clone()).unwrap(); + assert!((a[2].abs() - 1.0).abs() < 1e-9, "about the shaft's axis: {a:?}"); + // The chips say what the round picks stand for. + let label = |d: &crate::dialogs::Dialog, i: usize, sel: &Sel| crate::dialogs::selection_label(&h.app.session, d, &d.inputs[i], sel); + let wall_label = label(&d, 1, &wall); + assert!(wall_label.starts_with("Shaft · face ") && wall_label.ends_with(" axis"), "{wall_label}"); + assert!(label(&d, 1, &rim).ends_with("· circle axis"), "{}", label(&d, 1, &rim)); + // Point to Point from the rim: from its centre. + d.kind = kind(POINT_TO_POINT, &h.app.session.doc); + d.inputs = inputs(POINT_TO_POINT); + d.inputs[0].items = vec![Sel::Body { name: "Lug".into() }]; + assert!(label(&d, 1, &rim).ends_with("· circle centre"), "{}", label(&d, 1, &rim)); + d.inputs[1].items = vec![rim]; + d.inputs[2].items = vec![Sel::Vertex { body: String::new(), point: Vec3::ZERO }]; + let p = params(&h.app, &d).unwrap(); + assert_eq!(p["translate"], json!(["-40 mm", "0 mm", "-10 mm"]), "the rim's centre onto the origin"); +} + +#[test] +fn move_takes_the_centre_of_a_circle_in_a_placed_component_where_it_is_shown() { + use crate::dialogs_move::{POINT_TO_POINT, inputs, kind, params}; + let mut h = shaft(); + h.app.run("solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": [60, 0, 0], "body_name": "Lug"})).unwrap(); + h.app.run("component.from_bodies", json!({"bodies": ["Shaft"]})).unwrap(); + let occ = h.app.session.doc.occurrences[0].id; + // A design's first part is grounded when it is made. + h.app.run("occurrence.ground", json!({"occurrence": occ, "grounded": false})).unwrap(); + h.app.run("occurrence.move", json!({"occurrence": occ, "translate": [0, 30, 0]})).unwrap(); + h.frames(2); + // The rim as picked in the viewport: on the shaft where the occurrence puts it. + let (_, rim, _) = picks(&h); + let Sel::Edge { point, .. } = &rim else { panic!("{rim:?}") }; + assert!((point.y - 30.0).abs() < 5.0 + 1e-6, "picked in the world: {point:?}"); + h.app.start("solid.move"); + let mut d = h.app.dialog.clone().unwrap(); + d.kind = kind(POINT_TO_POINT, &h.app.session.doc); + d.inputs = inputs(POINT_TO_POINT); + d.inputs[0].items = vec![Sel::Body { name: "Lug".into() }]; + d.inputs[1].items = vec![rim]; + d.inputs[2].items = vec![Sel::Vertex { body: String::new(), point: Vec3::ZERO }]; + let p = params(&h.app, &d).unwrap(); + assert_eq!(p["translate"], json!(["-40 mm", "-30 mm", "-10 mm"]), "the centre where the component shows it"); +} + +#[test] +fn point_inputs_take_a_circles_centre() { + let mut h = shaft(); + let (_, rim, _) = picks(&h); + // A construction point keeps the edge, and lands on its centre. + h.app.start("construct.point.vertex"); + let d = h.app.dialog.clone().unwrap(); + let got = d.candidate(&h.app.session, &hit(&rim)).unwrap(); + assert!(matches!(got, Sel::Edge { .. }), "{got:?}"); + let mut d = d; + d.inputs[0].items = vec![got]; + let cmds = crate::dialogs::apply_commands(&h.app, &d).unwrap(); + h.app.dialog = None; + for (c, p) in cmds { + h.app.run(&c, p).unwrap(); + } + let points = solidcraft_engine::view::construction_points(&h.app.session); + assert!(points.iter().any(|p| p.2.dist(Vec3::new(40.0, 0.0, 10.0)) < 1e-6), "{points:?}"); + // Revolve's To Object takes the centre as a point. + h.app.start("solid.revolve"); + let mut d = h.app.dialog.clone().unwrap(); + d.inputs.push(crate::selection::SelInput::new("To Object", crate::selection::FACES | crate::selection::VERTICES, false)); + d.active = d.inputs.len() - 1; + let got = d.candidate(&h.app.session, &hit(&rim)); + let Some(Sel::Vertex { body, point }) = &got else { panic!("{got:?}") }; + assert_eq!(body, "Shaft"); + assert!(point.dist(Vec3::new(40.0, 0.0, 10.0)) < 1e-6, "{point:?}"); + h.app.dialog = None; + // A hole placed from the top rim goes at its centre, on the cap under the cursor. + let (_, _, cap) = picks(&h); + h.app.start("solid.hole"); + let d = h.app.dialog.clone().unwrap(); + let hits = [hit(&rim), hit(&cap)]; + let snap = d.face_snap(&h.app.session, &hits); + let Some(Sel::Face { point, .. }) = d.candidate_on(&h.app.session, &hit(&rim), snap.as_ref()) else { panic!("no place") }; + assert!(point.dist(Vec3::new(40.0, 0.0, 10.0)) < 1e-6, "{point:?}"); +} + +#[test] +fn hovering_a_round_pick_draws_its_axis_or_centre() { + let mut h = shaft(); + let (wall, rim, cap) = picks(&h); + h.app.start("solid.revolve"); + if let Some(d) = h.app.dialog.as_mut() { + d.active = 1; + } + for (sel, lines) in [(&wall, 1), (&rim, 1), (&cap, 0)] { + h.app.viewport.hover = Some(hit(sel)); + let (axes, centres) = crate::viewport::round_pick_feedback(&h.app); + assert_eq!(axes.len(), lines, "{sel:?}"); + assert!(centres.is_empty()); + for (a, b) in axes { + assert!(along_z_through((a, (b - a).normalized().unwrap()), 40.0), "{a:?} {b:?}"); + } + } + // With the axis picked, it stays drawn. + h.app.viewport.hover = None; + if let Some(d) = h.app.dialog.as_mut() { + d.inputs[1].items = vec![rim.clone()]; + } + assert_eq!(crate::viewport::round_pick_feedback(&h.app).0.len(), 1); + // In a point input a circle shows its centre. + h.app.dialog = None; + h.app.start("construct.point.vertex"); + h.app.viewport.hover = Some(hit(&rim)); + let (axes, centres) = crate::viewport::round_pick_feedback(&h.app); + assert!(axes.is_empty()); + assert_eq!(centres.len(), 1); + assert!(centres[0].dist(Vec3::new(40.0, 0.0, 10.0)) < 1e-6); + assert!(!matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::Revolve { .. }))); +} diff --git a/crates/ui-egui/src/selection.rs b/crates/ui-egui/src/selection.rs index 5fd6a04ac..2d4652c47 100644 --- a/crates/ui-egui/src/selection.rs +++ b/crates/ui-egui/src/selection.rs @@ -69,6 +69,11 @@ pub const SKETCH_LINES: Accept = 8192; pub const EXTERNAL_POINTS: Accept = 16384; /// Named construction points. pub const CONSTRUCTION_POINTS: Accept = 32768; +/// What a 3D axis input takes (Revolve, Circular Pattern, Plane at Angle, Move's Rotate): an +/// origin or construction axis, a straight sketch line, and an edge or face of the model that +/// has an axis (a straight or circular edge, a cylinder, cone or torus face; the dialog takes +/// only those, `Dialog::candidate_on`). +pub const AXIS_PICKS: Accept = AXES | EDGES | FACES; /// One selection input of a command dialog ("Profiles", "Edges", "Plane", ...). #[derive(Clone, Debug, PartialEq)] diff --git a/crates/ui-egui/src/sketch_attachment_ui_tests.rs b/crates/ui-egui/src/sketch_attachment_ui_tests.rs index c0b1a60ee..12dc0b8ef 100644 --- a/crates/ui-egui/src/sketch_attachment_ui_tests.rs +++ b/crates/ui-egui/src/sketch_attachment_ui_tests.rs @@ -291,6 +291,7 @@ fn nested_anchor_saved_fixed_conversion_preserves_rotated_second_author_plane() axis_origin: Vec3::ZERO, axis_dir: Vec3::X, angle: "15 deg".into(), + line: None, }; h.app.session = solidcraft_engine::Session::new(document); let raw = h.app.session.doc.sketch(id).unwrap().clone(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 89710c324..f2505a365 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1382,28 +1382,66 @@ pub fn construction_axis_segments(app: &SolveApp) -> Vec<(String, Vec3, Vec3)> { if axes.is_empty() { return Vec::new(); } - let h = origin_size(app.cam.half_height()) * AXIS_LEN; let bb = view_bounds(app); axes.into_iter() .map(|(_, name, o, d)| { - let (mut lo, mut hi) = (-h, h); - if !bb.is_empty() { - for i in 0..8 { - let c = Vec3::new( - if i & 1 == 0 { bb.min.x } else { bb.max.x }, - if i & 2 == 0 { bb.min.y } else { bb.max.y }, - if i & 4 == 0 { bb.min.z } else { bb.max.z }, - ); - let t = (c - o).dot(d); - lo = lo.min(t - h * 0.3); - hi = hi.max(t + h * 0.3); - } - } - (name, o + d * lo, o + d * hi) + let (a, b) = axis_span(app, &bb, o, d); + (name, a, b) }) .collect() } +/// How far an axis through `o` along `d` is drawn: across the model's box `bb` where it passes +/// it (a little past it either side), at least the origin axes' length around `o`. +fn axis_span(app: &SolveApp, bb: &solidcraft_engine::geom::Aabb3, o: Vec3, d: Vec3) -> (Vec3, Vec3) { + let h = origin_size(app.cam.half_height()) * AXIS_LEN; + let (mut lo, mut hi) = (-h, h); + if !bb.is_empty() { + for i in 0..8 { + let c = Vec3::new( + if i & 1 == 0 { bb.min.x } else { bb.max.x }, + if i & 2 == 0 { bb.min.y } else { bb.max.y }, + if i & 4 == 0 { bb.min.z } else { bb.max.z }, + ); + let t = (c - o).dot(d); + lo = lo.min(t - h * 0.3); + hi = hi.max(t + h * 0.3); + } + } + (o + d * lo, o + d * hi) +} + +/// What a round edge or face stands for in the open dialog's active input, drawn as construction +/// geometry while it is under the cursor or picked: the axis an axis input takes (a dashed line +/// through a circle's centre along its normal, or along a cylinder's, cone's or torus's axis), +/// or the centre a point input takes from a circular edge (a small star). +pub(crate) fn round_pick_feedback(app: &SolveApp) -> (Vec<(Vec3, Vec3)>, Vec) { + let (mut lines, mut centres): (Vec<(Vec3, Vec3, Vec3, Vec3)>, Vec) = (Vec::new(), Vec::new()); + let Some(d) = app.dialog.as_ref() else { return (Vec::new(), centres) }; + let Some(inp) = d.active_input() else { return (Vec::new(), centres) }; + let s = &app.session; + let hovered = app.viewport.hover.as_ref().and_then(|h| d.candidate(s, h)); + if inp.accept == crate::selection::AXIS_PICKS { + let bb = view_bounds(app); + for sel in hovered.iter().chain(inp.items.iter()) { + if let Some((o, dir)) = crate::dialogs::round_axis(s, sel) + && !lines.iter().any(|(_, _, q, e)| q.dist(o) < 1e-9 && e.cross(dir).len() < 1e-9) + { + let (a, b) = axis_span(app, &bb, o, dir); + lines.push((a, b, o, dir)); + } + } + } else if let (Some(Hit::Edge { body, index, .. }), Some(sel)) = (app.viewport.hover.as_ref(), hovered.as_ref()) { + // Where the round edge is taken as its centre (`Dialog::circle_centre_pick`, Move's points). + if (matches!(sel, Sel::Vertex { .. }) || d.edge_is_centre(inp)) + && let Some((c, ..)) = crate::dialogs::edge_circle(s, body, *index) + { + centres.push(c); + } + } + (lines.into_iter().map(|(a, b, ..)| (a, b)).collect(), centres) +} + /// Construction points shown: (name, position). pub fn construction_points(app: &SolveApp) -> Vec<(String, Vec3)> { solidcraft_engine::view::construction_points(&app.session) @@ -2590,6 +2628,8 @@ fn highlight_geometry_key(app: &SolveApp) -> u64 { app.ui.pick_bodies.hash(&mut h); app.session.active_sketch.hash(&mut h); (app.dialog.is_some(), app.tool.is_some()).hash(&mut h); + // Which input is active decides what a round edge or face under the cursor stands for. + app.dialog.as_ref().and_then(|d| d.active_input()).map(|i| i.accept).hash(&mut h); crate::theme::is_dark().hash(&mut h); crate::theme::vision().hash(&mut h); // Two themes may share a light/dark base while drawing different geometry colours. @@ -2818,6 +2858,26 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene { sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), col, 2.0, true); } } + // A round edge or face under the cursor (or picked) in an axis input shows its axis, and a + // circle in a point input its centre, as construction geometry. The axis runs through the + // solid it belongs to, so it is drawn over the model. + let (round_axes, round_centres) = round_pick_feedback(app); + for (a, b) in round_axes { + let len = a.dist(b); + let dash = size * 0.08; + let mut s = 0.0; + while s < len { + let e = (s + dash).min(len); + sc.line(a.lerp(b, s / len).to_f32(), a.lerp(b, e / len).to_f32(), c4(t.construction_geom), 2.0, true); + s += dash * 1.6; + } + } + for p in round_centres { + let r = size * 0.04; + for d in [Vec3::X, Vec3::Y, Vec3::Z] { + sc.line((p - d * r).to_f32(), (p + d * r).to_f32(), c4(t.construction_geom), 2.0, true); + } + } // Reference widgets follow zoom; the often much larger world-space feedback does not. let projected = sel.iter().any(|s| matches!(s, Sel::Profile { .. } | Sel::SketchCurve { .. } | Sel::ExternalSketchCurve { .. })) || matches!(hover, Some(Hit::Profile { .. })); diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index 2421ba7ad..3fdfffe7e 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -65,7 +65,7 @@ radius of a curve it follows on the inside is refused. Spline walls follow the e within 0.0001 mm. Editing an extrusion retains its signed distances, From/To Object inputs, taper expressions -and explicit body targets. Revolve edits retain world, sketch and explicit-line axes, both +and explicit body targets. Revolve edits retain world, sketch, explicit-line and model-edge or face axes, both angle expressions and To Object targets. An unchanged **All profiles** selection continues to include profiles added later. Cancel restores the complete timeline; a successful edit is one undo step, including downstream parameter changes. Editing a placed component previews the @@ -208,12 +208,34 @@ samples them finer, at the cost of time. ## Editing a feature from a script -For `solid.pattern.circular`, `axis` accepts `X`, `Y`, `Z`, or `{origin, dir}`. +For `solid.pattern.circular`, `axis` accepts `X`, `Y`, `Z`, `{origin, dir}`, or an edge or +round face of the model, `{edge: [x, y, z]}` or `{face: [x, y, z]}` (a point on it). An explicit origin must contain three finite numeric coordinates in millimetres (`[x, y, z]` or `{x, y, z}`); omitting it uses the world origin. Expressions and construction-axis references are not supported. Invalid origins are rejected rather than silently replaced with zero. +## Axes and points on round edges and faces + +Wherever a 3D command takes an axis (Revolve, Surface Revolve, Circular Pattern, Plane at +Angle, and Move's Rotate) you can pick a circular edge, which gives the axis through its centre +along its normal, or a cylinder, cone or torus face, which gives that surface's axis. Hovering +one in an axis input draws the axis as a dashed construction line, and the line stays drawn once +the axis is picked. Flat faces and edges that are neither straight nor circular can't be picked +there. + +Revolve, Surface Revolve, Circular Pattern and Plane at Angle keep the picked edge or face as a +reference (`{edge: [x, y, z]}` or `{face: [x, y, z]}` from a script), found again by its +persistent name every time the design is evaluated. If a parameter moves the cylinder, the +feature turns about it where it is now. The axis always points the same way, with its largest +component positive, so a rebuild that reverses the edge doesn't flip the turn. Straight edges +picked as axes keep working as before, as a fixed line. + +Where a 3D command takes a point (the construction points, axes and planes built from points, +Revolve and Extrude's To Object, a surface patch's pass-through points, and Move's pivot and +points), a circular edge stands for its centre. A hovered circle shows a small star at its centre. +A construction point keeps the edge, so it follows the circle's centre as the model changes. + `timeline.inspect {feature}` returns a feature's `definition`: the fields `timeline.edit` changes, with their current values. `timeline.edit {feature, set}` merges `set` into that definition (objects are merged field by field, anything else replaces the value), rebuilds the feature and diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index a8a58452f..e533f9733 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -82,7 +82,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim | `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. | -| `solid.pattern.circular` | `features`, `axis` (`"Z"` or `{origin, dir}`), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | +| `solid.pattern.circular` | `features`, `axis` (`"Z"`, `{origin, dir}`, or `{face: [x,y,z]}` / `{edge: [x,y,z]}` on a cylinder wall or circular edge, which the pattern follows), `count` | `angle` defaults to 360 deg. A full pattern keeps the COM on the axis, so check its radius with a top-view screenshot. | | `solid.mirror` | `features:[names]` or `bodies:[names]`, `plane` (`XY`/`XZ`/`YZ`, a construction plane, or `{origin, normal}` whose origin may use length expressions) | Follows parameters. A mirror or pattern feature cannot be listed in `features` of another mirror or pattern, but `bodies` can mirror the body it made. The mirror is a new body with the first free default name: `Body1`, `Body2` from `features`, and `Side (2)`, `Side (3)` from `bodies:["Side"]`. Read the name from `created_bodies`. With `combine:true`, a mirror that overlaps the original joins it and makes no new body. `features` copies only the features listed, so a later cut is left out unless you list it too. `bodies` copies the finished body. To name the mirror, use `body.rename {"body":"Side (2)","name":"Side_L"}`. The new name stays when parameters change. | - **Names:** name every feature (`"name":"Standoff"`) and keep names unique across sketches and features. `timeline.roll_to {"feature":"Plate"}` picks the first match, which can be the sketch.