From 98abb249c4478f1aa47689cd9958a4dd3723d0d1 Mon Sep 17 00:00:00 2001 From: tr1pp4 <38721264+tr1pp4@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:28:22 +0000 Subject: [PATCH] Cylinder: place by distances from reference edges, like Hole (#6380) (#6381) * claim: #6380 * Cylinder: place by distances from reference edges, like Hole (#6380) A Cylinder standing on a flat face can take up to two straight edges of that face as references, each with the distance of its base centre from the edge's line, measured in the face's plane, as a Single hole does (#37). `solid.cylinder` takes them as `references: [{edge, distance}]` with a numeric `base`; the edges are found again by their persistent names, else their points, so the cylinder follows them when the part changes, and each distance is a parameter (an input of Inspect Feature). A cylinder without references stays at its base, as before. In the Cylinder window, started on a picked face, Reference 1 and 2 take the edges, each with its Distance measured from the pick, so it works with the mouse alone; the canvas shows each distance with a box to type it in, and Edit Feature picks the edges again. Co-Authored-By: Claude Opus 5.5 * Cylinder: Edit Feature shows each reference edge input once (#6380) A face selected when Edit Feature opened the window had already added the reference inputs; the edit added them a second time. Co-Authored-By: Claude Opus 5.5 * Cylinder references: the measured-once cost test's cylinder has none (#6380) Co-Authored-By: Claude Opus 5.5 * Cylinder: pick the face it stands on in its window, then the edges (#6380) The Cylinder window took its place only from a face selected before it opened, so started first it stood at the origin and offered no reference edges. It now has a Face input before Reference 1 and 2, as the Hole window does: start Cylinder, click the face, click the edges, OK. Co-Authored-By: Claude Opus 5.5 * Glossary: reference edge, and "Reference" among the words with more than one meaning (#6380) Co-Authored-By: Claude Opus 5.5 * Cylinder edge references: the Cone dialog (#6250) gets the references field too The Cone primitive landed on main after this branch began; its dialog initialisers lacked the `refs` field the Primitive kind gained here. The dense form check for Cylinder fills only its fields: its face and reference edges place it, which the reference tests cover. Co-Authored-By: Claude Opus 5.5 * Cylinder: declare references in its contract; reference-placed cylinders are not placement-independent Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- crates/doc/src/document.rs | 5 + crates/doc/src/eval.rs | 24 ++- crates/doc/src/eval_cost_tests.rs | 2 + crates/doc/src/feature_walk_tests/fixtures.rs | 8 + .../src/feature_walk_tests/golden_exprs.txt | 7 + .../feature_walk_tests/golden_geometry.txt | 3 + .../src/feature_walk_tests/golden_refs.txt | 1 + .../pending/cylinder-reference-edges.rs | 5 + crates/doc/src/hole_reference.rs | 8 + crates/doc/src/placement_reuse.rs | 4 +- crates/doc/src/tests.rs | 1 + crates/engine/src/cmd/edit.rs | 7 + crates/engine/src/cmd/features.rs | 56 ++++-- crates/engine/src/hole_reference_tests.rs | 120 ++++++++++++- crates/engine/src/large_assembly_tests.rs | 1 + crates/engine/src/schema/features.rs | 6 + crates/engine/src/schema/features_tests.rs | 2 +- crates/io/src/lib.rs | 1 + crates/ui-egui/src/canvas.rs | 7 + crates/ui-egui/src/dialogs.rs | 57 +++++- crates/ui-egui/src/dialogs_all_tests.rs | 3 + crates/ui-egui/src/dialogs_dense.rs | 11 +- crates/ui-egui/src/hole_refs.rs | 162 ++++++++++++------ crates/ui-egui/src/hole_refs_ui_tests.rs | 89 ++++++++++ docs/book/src/guide/features.md | 9 +- docs/book/src/reference/glossary.md | 19 ++ skills/solidcraft-modeling/reference.md | 2 +- 27 files changed, 523 insertions(+), 97 deletions(-) create mode 100644 crates/doc/src/format/pending/cylinder-reference-edges.rs diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 1a9fcd0d8..bf6266ad5 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -693,6 +693,11 @@ pub enum FeatureKind { height: Expr, #[serde(default)] operation: Operation, + /// Up to two straight edges of the face it stands on (#6380), as a Single hole's + /// references: the base centre sits at each one's distance from its edge, in the face's + /// plane, and follows the edges when the part changes. `base` keeps where it was placed. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + references: Vec, }, Sphere { #[serde(with = "point_expr")] diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 159390769..fab66f79c 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4457,17 +4457,24 @@ fn single_hole_position( Ok(ss.plane.to_world(p.pos)) } -/// A hole's reference edges (#37); none for any other feature. +/// A hole's (#37) or a cylinder's (#6380) reference edges; none for any other feature. fn hole_references(f: &Feature) -> &[crate::HoleReference] { match &f.kind { - FeatureKind::Hole { references, .. } => references, + FeatureKind::Hole { references, .. } | FeatureKind::Cylinder { references, .. } => references, _ => &[], } } -/// Where a Single hole with reference edges (#37) is drilled: at its distances from the edges' -/// lines, in the plane of the face at `at` (on the surface), the edges found by their names, else -/// their points. A hole without reference edges stays at `at`. +/// Where a cylinder stands: its base, or with reference edges (#6380) at their distances in the +/// plane of the flat face at its base, square to its axis. +fn cylinder_base(vals: &BTreeMap, st: &ModelState, f: &Feature, base: &crate::PointExpr, axis: Vec3) -> Result { + let at = point(vals, base)?; + with_references(vals, st, f, at, -axis) +} + +/// Where a Single hole (or a cylinder) with reference edges (#37) is placed: at its distances +/// from the edges' lines, in the plane of the face at `at` (on the surface), the edges found by +/// their names, else their points. A feature without reference edges stays at `at`. fn with_references(vals: &BTreeMap, st: &ModelState, f: &Feature, at: Vec3, dir: Vec3) -> Result { let references = hole_references(f); if references.is_empty() { @@ -5774,7 +5781,7 @@ fn feature_tools_with_constructor( Ok(vec![crate::lineage::box_tool(kernel::box_solid(corner, corner + s)?)]) } FeatureKind::Cylinder { base, axis, radius, height, .. } => Ok(vec![crate::lineage::cylinder_tool(kernel::cylinder( - point(vals, base)?, + cylinder_base(vals, st, f, base, axis.0)?, axis.0, val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?, @@ -7676,8 +7683,9 @@ fn eval_feature(doc: &Document, vals: &BTreeMap, f: &Feature, st: } apply_traced(doc, st, f, tools, *operation, &[]) } - FeatureKind::Cylinder { base, axis, radius, height, operation } => { - let (base, radius, height) = (point(vals, base)?, val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?); + FeatureKind::Cylinder { base, axis, radius, height, operation, .. } => { + let base = cylinder_base(vals, st, f, base, axis.0)?; + let (radius, height) = (val(vals, radius, Kind::Length)?, val(vals, height, Kind::Length)?); let b = kernel::cylinder(base, axis.0, radius, height)?; let b = if matches!(operation, Operation::NewBody | Operation::Join) { b.with_cylinder_certificate(f.id)? } else { b }; let prism = more::PrimitivePrism::Cylinder { base, axis: axis.0, radius, height }; diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs index d4a82fe4b..c2af067f9 100644 --- a/crates/doc/src/eval_cost_tests.rs +++ b/crates/doc/src/eval_cost_tests.rs @@ -59,6 +59,7 @@ fn joint_face_measurements_are_shared_across_motion_samples_and_snap_kinds() { radius: "2".into(), height: "10".into(), operation: Operation::NewBody, + references: Vec::new(), }, None, ) @@ -433,6 +434,7 @@ fn a_body_is_measured_once_while_it_stays_the_same() { radius: "2".into(), height: "10".into(), operation: Operation::NewBody, + references: Vec::new(), }; doc.add_feature(kind, None).unwrap(); }; diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index 3d52ce028..27037f33e 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -56,6 +56,11 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> { ), ("box", json!({"type": "box", "corner": ["box.x", "box.y", "box.z"], "length": "box.length", "width": "box.width", "height": "box.height"})), ("cylinder", json!({"type": "cylinder", "base": ["cyl.x", "cyl.y", "cyl.z"], "radius": "cyl.radius", "height": "cyl.height"})), + ( + "cylinder_references", + json!({"type": "cylinder", "base": o, "radius": "cyl.radius", "height": "cyl.height", + "references": [{"edge": o, "distance": "cyl.reference1"}, {"edge": o, "distance": "cyl.reference2"}]}), + ), ("sphere", json!({"type": "sphere", "center": ["sph.x", "sph.y", "sph.z"], "radius": "sph.radius"})), ("torus", json!({"type": "torus", "center": ["tor.x", "tor.y", "tor.z"], "major": "tor.major", "minor": "tor.minor"})), ( @@ -286,6 +291,9 @@ pub(super) fn with_points(name: &str, mut v: Value) -> Value { "surface_revolve" => json!({"axis": line}), "hole_simple" => json!({"points": null, "to": p(4.0)}), "hole_drilled" | "hole_counterbore" | "hole_countersink" => json!({"to": p(4.0)}), + "cylinder_references" => { + json!({"references": [{"edge": p(11.0), "distance": "cyl.reference1"}, {"edge": p(12.0), "distance": "cyl.reference2"}]}) + } "hole_references" => { json!({"references": [{"edge": p(11.0), "distance": "hole.reference1"}, {"edge": p(12.0), "distance": "hole.reference2"}]}) } diff --git a/crates/doc/src/feature_walk_tests/golden_exprs.txt b/crates/doc/src/feature_walk_tests/golden_exprs.txt index 43da6a37f..fc766b6a5 100644 --- a/crates/doc/src/feature_walk_tests/golden_exprs.txt +++ b/crates/doc/src/feature_walk_tests/golden_exprs.txt @@ -73,6 +73,13 @@ cylinder Radius = cyl.radius (Length) Height = cyl.height (Length) expressions: cyl.radius, cyl.height, cyl.x, cyl.y, cyl.z +cylinder_references + inputs: + Radius = cyl.radius (Length) + Height = cyl.height (Length) + Reference distance = cyl.reference1 (Length) + Reference distance = cyl.reference2 (Length) + expressions: cyl.radius, cyl.height, cyl.reference1, cyl.reference2, 0, 0, 0 sphere inputs: Radius = sph.radius (Length) diff --git a/crates/doc/src/feature_walk_tests/golden_geometry.txt b/crates/doc/src/feature_walk_tests/golden_geometry.txt index 30add0647..ce58eadb2 100644 --- a/crates/doc/src/feature_walk_tests/golden_geometry.txt +++ b/crates/doc/src/feature_walk_tests/golden_geometry.txt @@ -30,6 +30,9 @@ box cylinder moves: axis[0], axis[2], base[0], base[1], base[2] placement: cyl.x, cyl.y, cyl.z +cylinder_references + moves: axis[0], axis[2], base[0], base[1], base[2], references[0].edge[0], references[0].edge[1], references[0].edge[2], references[1].edge[0], references[1].edge[1], references[1].edge[2] + placement: 0, 0, 0 sphere moves: center[0], center[1], center[2] placement: sph.x, sph.y, sph.z diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 48bc04e7f..303007b9d 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -29,6 +29,7 @@ chamfer remap_bodies: body box cylinder +cylinder_references sphere torus cone diff --git a/crates/doc/src/format/pending/cylinder-reference-edges.rs b/crates/doc/src/format/pending/cylinder-reference-edges.rs new file mode 100644 index 000000000..de0756ad4 --- /dev/null +++ b/crates/doc/src/format/pending/cylinder-reference-edges.rs @@ -0,0 +1,5 @@ +//! A Cylinder can be placed by distances from up to two straight edges of the face it stands on +//! (`references`: each `{"edge": [x, y, z], "distance": "…"}`, the edges' persistent names in the +//! feature's `edge_names`, #6380), as a Single hole is: its base centre sits where those +//! distances hold, measured in the face's plane, and follows the edges when the part changes. +//! Older designs need no transformation: a cylinder without `references` stays at its `base`. diff --git a/crates/doc/src/hole_reference.rs b/crates/doc/src/hole_reference.rs index 187a1971f..9241104f1 100644 --- a/crates/doc/src/hole_reference.rs +++ b/crates/doc/src/hole_reference.rs @@ -152,6 +152,14 @@ pub fn reference_edge_names(st: &ModelState, at: Vec3, edges: &[Vec3]) -> Vec Vec { + let [x, y, z] = base.clone().map(|c| c.parse::().unwrap_or(0.0)); + let edges: Vec = references.iter().map(|r| r.edge.0).collect(); + reference_edge_names(st, Vec3::new(x, y, z), &edges) +} + /// The (non-mesh) body whose surface is nearest `p`. fn body_at(st: &ModelState, p: Vec3) -> Option<&ModelBody> { st.bodies diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index 865451ca3..af5a3f10e 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -70,8 +70,10 @@ pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap return false; } match &f.kind { + // A cylinder placed by reference edges follows the body it stands on. + FeatureKind::Cylinder { references, .. } if !references.is_empty() => false, FeatureKind::Box { corner: _, length: _, width: _, height: _, operation: Operation::NewBody } - | FeatureKind::Cylinder { base: _, axis: _, radius: _, height: _, operation: Operation::NewBody } + | FeatureKind::Cylinder { base: _, axis: _, radius: _, height: _, operation: Operation::NewBody, references: _ } | FeatureKind::Sphere { center: _, radius: _, operation: Operation::NewBody } | FeatureKind::Torus { center: _, major: _, minor: _, operation: Operation::NewBody } | FeatureKind::Import { file: _, step: _, components: _, skip: _ } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 9f338af0c..556179d96 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -436,6 +436,7 @@ fn primitives_and_combine() { radius: "2".into(), height: "20".into(), operation: Operation::NewBody, + references: Vec::new(), }, None, ) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 43eafdc34..518e6944f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1143,6 +1143,13 @@ fn edit_feature(s: &mut Session, p: &Value) -> Result { nf.edge_names = solidcraft_doc::hole_reference::reference_edge_names(&s.model.state_before(id), position.0, &edges(a)); } } + // New reference edges for a cylinder (#6380): likewise. + if let (FeatureKind::Cylinder { references: a, base, .. }, FeatureKind::Cylinder { references: b, .. }) = (&nf.kind, &f.kind) { + let edges = |r: &[solidcraft_doc::HoleReference]| r.iter().map(|x| x.edge.0).collect::>(); + if edges(a) != edges(b) { + nf.edge_names = solidcraft_doc::hole_reference::cylinder_edge_names(&s.model.state_before(id), base, a); + } + } // New bend edges for a conversion: the names of the body's edges there now. if let (FeatureKind::SheetConvert { bends: a, body, .. }, FeatureKind::SheetConvert { bends: b, body: was, .. }) = (&nf.kind, &f.kind) && (a != b || body != was) diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 7ff7c1e15..dd52429e1 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -55,7 +55,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("cylinder") .contract(&CYLINDER_CONTRACT) .output(output_schema_for::) - .params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); operation?, targets?: [body], name?, body_name?"), + .params("radius | diameter, height: expr; base?: [x,y,z] (centre of the bottom: numbers in mm or length expressions; default: the origin); axis?: X|Y|Z|[x,y,z] (default Z); references?: [{edge: [x,y,z] on a straight edge of the face it stands on, distance: expr}] (at most two, as solid.hole's: the base centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric base only); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.sphere", "Sphere", crate::checked!("solid.sphere", prim_sphere)) .at("SOLID", "CREATE") .icon("sphere") @@ -680,6 +680,10 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) -> let edges: Vec = references.iter().map(|r| r.edge.0).collect(); (Vec::new(), solidcraft_doc::hole_reference::reference_edge_names(&s.model.state(), position.0, &edges)) } + // A cylinder's reference edges (#6380) are edges of the body it stands on. + FeatureKind::Cylinder { base, references, .. } if !references.is_empty() => { + (Vec::new(), solidcraft_doc::hole_reference::cylinder_edge_names(&s.model.state(), base, references)) + } // A conversion's bend edges are edges of the body it converts. FeatureKind::SheetConvert { body, bends, .. } if !bends.is_empty() => { (Vec::new(), solidcraft_doc::sheet::bend_edge_names(&s.model.state(), body, &solidcraft_doc::plain(bends))) @@ -1392,7 +1396,19 @@ fn prim_cylinder(s: &mut Session, p: &Value) -> Result { check_expr(s, &height, Kind::Length, cmd, "height")?; let base = point_param(s, p, "base", cmd)?.unwrap_or_else(|| point_expr(Vec3::ZERO)); let axis = axis_dir_param(p, cmd)?; - add_feature(s, p, FeatureKind::Cylinder { base, axis: Dir(axis), radius, height, operation: operation(p, cmd)? }) + // Reference edges (#6380), as a Single hole's: the base centre sits at these distances from + // straight edges of the face it stands on, and `base` keeps where those put it. + let references = hole_reference_params(s, p, cmd)?; + let base = if references.is_empty() { + base + } else { + let at = p + .get("base") + .and_then(vec3) + .ok_or_else(|| bad(cmd, "`references` place a cylinder by its `base` given as numbers, not length expressions"))?; + point_expr(referenced_centre(s, cmd, &references, at, -axis)?) + }; + add_feature(s, p, FeatureKind::Cylinder { base, axis: Dir(axis), radius, height, operation: operation(p, cmd)?, references }) } fn prim_sphere(s: &mut Session, p: &Value) -> Result { @@ -2506,22 +2522,7 @@ fn hole(s: &mut Session, p: &Value) -> Result { }; // Placed by its reference edges: drilled where their distances put it, which `position` // then keeps. The edges must be straight edges at the given points, and cross. - let position = if references.is_empty() { - position - } else { - let st = s.model.state(); - let mut distances = Vec::with_capacity(references.len()); - for r in &references { - distances.push(s.doc.eval(&r.distance, Kind::Length).map_err(|e| bad(cmd, format!("`references`: {e}")))?); - } - let edges: Vec<(Vec3, Option<&str>)> = references.iter().map(|r| (r.edge.0, None)).collect(); - let frame = solidcraft_doc::hole_reference::reference_frame(&st, position, direction, &edges, true).map_err(|e| bad(cmd, e.to_string()))?; - let centre = frame.place(position, &distances).map_err(|e| bad(cmd, e.to_string()))?; - if !solidcraft_doc::hole_reference::on_reference_face(&st, &frame, centre) { - return Err(bad(cmd, "the reference distances put the hole's centre off its face")); - } - centre - }; + let position = if references.is_empty() { position } else { referenced_centre(s, cmd, &references, position, direction)? }; // The diameter: given, or a metric-estimate/Unified-table tap drill, or an ISO 273 // clearance hole for a bolt size (close, normal or loose fit). let diameter = match (expr(p, "diameter"), &thread, str_(p, "clearance")) { @@ -2606,6 +2607,25 @@ fn hole(s: &mut Session, p: &Value) -> Result { ) } +/// Where reference edges (#37) put a hole's (or a cylinder's) centre picked at `at` on a flat +/// face, `dir` into it: at their distances from the edges, which must be straight edges at the +/// given points, and cross. +fn referenced_centre(s: &Session, cmd: &str, references: &[solidcraft_doc::HoleReference], at: Vec3, dir: Vec3) -> Result { + let st = s.model.state(); + let mut distances = Vec::with_capacity(references.len()); + for r in references { + distances.push(s.doc.eval(&r.distance, Kind::Length).map_err(|e| bad(cmd, format!("`references`: {e}")))?); + } + let edges: Vec<(Vec3, Option<&str>)> = references.iter().map(|r| (r.edge.0, None)).collect(); + let frame = solidcraft_doc::hole_reference::reference_frame(&st, at, dir, &edges, true).map_err(|e| bad(cmd, e.to_string()))?; + let centre = frame.place(at, &distances).map_err(|e| bad(cmd, e.to_string()))?; + if !solidcraft_doc::hole_reference::on_reference_face(&st, &frame, centre) { + let what = if cmd == "solid.cylinder" { "cylinder's base" } else { "hole's centre" }; + return Err(bad(cmd, format!("the reference distances put the {what} off its face"))); + } + Ok(centre) +} + /// A hole's reference edges (#37): `references: [{edge: [x, y, z], distance: expr}]`, at most /// two, each distance a length. fn hole_reference_params(s: &Session, p: &Value, cmd: &str) -> Result> { diff --git a/crates/engine/src/hole_reference_tests.rs b/crates/engine/src/hole_reference_tests.rs index da8ac53a6..48d437e72 100644 --- a/crates/engine/src/hole_reference_tests.rs +++ b/crates/engine/src/hole_reference_tests.rs @@ -1,7 +1,7 @@ //! A Single hole placed by distances from reference edges (#37): the centre sits at the typed //! distances from straight edges of its face, measured in the face's plane, follows the edges //! when the part changes (also after the design is saved and reopened), and a bad reference is -//! refused with an error. +//! refused with an error. A cylinder takes the same references for its base (#6380). use std::f64::consts::PI; @@ -165,3 +165,121 @@ fn hostile_references_never_panic() { } assert!(panicked.is_empty(), "solid.hole panicked:\n{}", panicked.join("\n")); } + +/// The last feature's base and reference edges. +fn cylinder(s: &Session) -> (solidcraft_doc::PointExpr, Vec) { + match &s.doc.features.last().map(|f| &f.kind) { + Some(FeatureKind::Cylinder { base, references, .. }) => (base.clone(), references.clone()), + other => panic!("the last feature is not a cylinder: {other:?}"), + } +} + +/// A Ø6 × 5 cylinder joined onto the plate's top (z = 10), picked at (30, 25), with these +/// references. +fn standing(references: Value) -> Value { + json!({"base": [30, 25, 10], "axis": [0, 0, 1], "radius": 3, "height": 5, "operation": "join", "name": "C", "references": references}) +} + +/// The cylinder (Ø6, from z = 10 to 15) stands about (x, y): solid on its axis and up to 2 mm +/// from it, empty 4 mm from it in every direction. +fn pin_at(s: &Session, x: f64, y: f64) { + let at = Vec3::new(x, y, 12.5); + for k in 0..8 { + let a = PI / 4.0 * f64::from(k); + let p = |r: f64| at + Vec3::new(a.cos(), a.sin(), 0.0) * r; + assert!(solid_at(s, p(0.0)) && solid_at(s, p(2.0)), "the cylinder about ({x}, {y}) is solid {a} rad from +x"); + assert!(!solid_at(s, p(4.0)), "beside the cylinder about ({x}, {y}) is empty {a} rad from +x"); + } +} + +#[test] +fn a_cylinder_follows_its_edges_when_the_plate_changes() { + let mut s = plate(); + // 10 mm from the far edge (x = len), 12 mm from the front edge (y = 0). + let refs = json!([{"edge": [50, 20, 10], "distance": 10}, {"edge": [25, 0, 10], "distance": "12 mm"}]); + run(&mut s, "solid.cylinder", standing(refs.clone())); + let (base, references) = cylinder(&s); + assert_eq!(base.map(|c| c.to_string()), ["40", "12", "10"].map(String::from), "the base keeps where the distances put it"); + assert_eq!(references.len(), 2); + pin_at(&s, 40.0, 12.0); + let f = s.doc.find_feature("C").unwrap(); + let id = f.id; + assert_eq!(f.edge_names.len(), 2, "each reference edge keeps its persistent name"); + // The distances are inputs (Inspect Feature lists them) and parameters. + let inspected = run(&mut s, "timeline.inspect", json!({"feature": "C"})); + let labels: Vec<&str> = inspected["inputs"].as_array().unwrap().iter().filter_map(|i| i["label"].as_str()).collect(); + assert_eq!(labels.iter().filter(|l| **l == "Reference distance").count(), 2, "{labels:?}"); + // The plate grows: the cylinder stays 10 mm from its far edge. + run(&mut s, "parameters.change", json!({"name": "len", "expression": "80 mm"})); + assert!(s.model.result(id).is_some_and(|r| r.error.is_none()), "{:?}", s.model.result(id).map(|r| &r.error)); + pin_at(&s, 70.0, 12.0); + assert!(!solid_at(&s, Vec3::new(40.0, 12.0, 12.5)), "nothing stands at the old spot"); + // A distance changed as a parameter moves it. + let d = s.doc.find_feature("C").unwrap().param_names.last().cloned().unwrap(); + run(&mut s, "parameters.change", json!({"name": d, "expression": "20 mm"})); + pin_at(&s, 70.0, 20.0); + // Undo and redo. + run(&mut s, "edit.undo", json!({})); + pin_at(&s, 70.0, 12.0); + run(&mut s, "edit.redo", json!({})); + pin_at(&s, 70.0, 20.0); + // Saved and reopened, it keeps its references and its place. + let mut t = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + t.refresh(); + pin_at(&t, 70.0, 20.0); + assert_eq!(cylinder(&t).1, cylinder(&s).1); + run(&mut t, "parameters.change", json!({"name": "len", "expression": "60 mm"})); + pin_at(&t, 50.0, 20.0); +} + +#[test] +fn a_cylinder_without_references_stays_at_its_base() { + let mut s = plate(); + run(&mut s, "solid.cylinder", standing(json!([]))); + assert!(cylinder(&s).1.is_empty()); + assert!(!s.doc.to_json().contains("references"), "a cylinder without references is saved as before"); + pin_at(&s, 30.0, 25.0); + run(&mut s, "parameters.change", json!({"name": "len", "expression": "80 mm"})); + pin_at(&s, 30.0, 25.0); + // One reference: it moves square to that edge and keeps its place along it. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "solid.cylinder", standing(json!([{"edge": [0, 20, 10], "distance": 10}]))); + pin_at(&s, 10.0, 25.0); +} + +#[test] +fn a_bad_cylinder_reference_is_refused() { + let mut s = plate(); + let before = s.doc.features.len(); + let edge = |p: [f64; 3], d: Value| json!({"edge": p, "distance": d}); + for (refs, why) in [ + (json!([edge([25.0, 30.0, 10.0], json!(5))]), "no edge"), + (json!([edge([0.0, 20.0, 10.0], json!(5)), edge([50.0, 20.0, 10.0], json!(5))]), "parallel"), + (json!([edge([0.0, 20.0, 10.0], json!(5)), edge([25.0, 0.0, 10.0], json!(5)), edge([50.0, 20.0, 10.0], json!(5))]), "at most 2"), + (json!([edge([0.0, 20.0, 10.0], json!("-5 mm"))]), "0 or more"), + (json!([edge([0.0, 20.0, 10.0], json!(500))]), "off its face"), + (json!([edge([0.0, 20.0, 10.0], json!("5 deg"))]), "references"), + ] { + match s.execute("solid.cylinder", &standing(refs.clone())) { + Err(EngineError::Internal(..)) | Ok(_) => panic!("{refs} is refused"), + Err(e) => assert!(e.to_string().contains(why), "{refs}: {e}"), + } + assert_eq!(s.doc.features.len(), before, "{refs} adds nothing"); + } + let p = json!({"base": ["30 mm", "25 mm", "10 mm"], "radius": 3, "height": 5, "references": [edge([0.0, 20.0, 10.0], json!(5))]}); + assert!(s.execute("solid.cylinder", &p).is_err(), "not with a base given as expressions"); + let values = crate::tests::hostile_values(); + let mut panicked = Vec::new(); + for v in &values { + for refs in [v.clone(), json!([v]), json!([{"edge": v, "distance": 5}]), json!([{"edge": [0, 20, 10], "distance": v}])] { + for base in [json!([30, 25, 10]), json!([1e300, 0, 10]), v.clone()] { + let p = json!({"base": base, "radius": 3, "height": 5, "references": refs}); + if let Err(EngineError::Internal(id, msg)) = s.execute("solid.cylinder", &p) { + panicked.push(format!("{id} {p}: {msg}")); + } + } + } + } + assert!(panicked.is_empty(), "solid.cylinder panicked:\n{}", panicked.join("\n")); +} diff --git a/crates/engine/src/large_assembly_tests.rs b/crates/engine/src/large_assembly_tests.rs index 3fc50e339..cf256f5ce 100644 --- a/crates/engine/src/large_assembly_tests.rs +++ b/crates/engine/src/large_assembly_tests.rs @@ -38,6 +38,7 @@ fn generated_assembly(parts: usize) -> Document { radius: mm(1.5), height: mm(4.0 + k as f64), operation: Operation::NewBody, + references: Vec::new(), }; made.push((i, doc.add_feature(pin, Some(&format!("Pin {i}.{k}"))).unwrap())); } diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs index 78a04f321..7ca08762b 100644 --- a/crates/engine/src/schema/features.rs +++ b/crates/engine/src/schema/features.rs @@ -189,6 +189,12 @@ pub struct CylinderParams { #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] #[schemars(with = "AxisDir")] pub axis: Option, + /// Up to two straight edges of the face it stands on, each `{edge: [x, y, z], distance: expr}` + /// (as `solid.hole`'s): the base centre goes that far from each edge's line, in the face's + /// plane, and follows the edges. With a numeric `base` only. + #[serde(default)] + #[schemars(with = "Option>")] + pub references: Option, /// How the cylinder combines with existing bodies. Default: new. #[serde(default)] pub operation: Option, diff --git a/crates/engine/src/schema/features_tests.rs b/crates/engine/src/schema/features_tests.rs index e3e1679bb..05d5255d4 100644 --- a/crates/engine/src/schema/features_tests.rs +++ b/crates/engine/src/schema/features_tests.rs @@ -49,7 +49,7 @@ fn schemas_and_the_key_check_agree() { ); assert_keys( input_schema_for::(), - &["axis", "base", "body_name", "body_names", "diameter", "height", "name", "operation", "participants", "radius", "targets"], + &["axis", "base", "body_name", "body_names", "diameter", "height", "name", "operation", "participants", "radius", "references", "targets"], ); assert_keys( input_schema_for::(), diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a4abc38a4..fa0c98622 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -1059,6 +1059,7 @@ mod tests { radius: "6".into(), height: "15".into(), operation: Operation::NewBody, + references: Vec::new(), }, None, ) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1dec97603..4172878fd 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -361,6 +361,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj app.dialog = Some(d); return; } + // A cylinder's values are typed in its window; its distances from its reference edges + // (#6380) are shown and typed on the canvas, as a hole's. + if matches!(d.kind, Kind::Primitive { cmd: "solid.cylinder", .. }) { + crate::hole_refs::canvas(app, ui, painter, proj, &mut d); + app.dialog = Some(d); + return; + } if let Some((base, dir)) = anchor(app, &d) && let Some(bs) = proj.to_screen(base) { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0cf0bdc37..dc01b723c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -329,6 +329,8 @@ crate::dialog_descriptor::dialog_descriptors! { /// face is planar. `None` keeps the command's own placement (the origin, or the edited /// feature's). at: Option<(Vec3, Option)>, + /// A Cylinder's reference edge distances on that face (`hole_refs`, #6380). + refs: Box, }, Combine { operation: usize, @@ -932,6 +934,7 @@ impl Dialog { fields: vec![("length", length_default(s, "20")), ("width", length_default(s, "20")), ("height", length_default(s, "20"))], operation: 0, at: None, + refs: Default::default(), }, crate::primitive_placement::inputs("solid.box"), ), @@ -941,11 +944,18 @@ impl Dialog { fields: vec![("diameter", length_default(s, "20")), ("height", length_default(s, "20"))], operation: 0, at: None, + refs: Default::default(), }, - vec![], + crate::hole_refs::cylinder_inputs(), ), "solid.sphere" => Dialog::new( - Kind::Primitive { cmd: "solid.sphere", fields: vec![("diameter", length_default(s, "20"))], operation: 0, at: None }, + Kind::Primitive { + cmd: "solid.sphere", + fields: vec![("diameter", length_default(s, "20"))], + operation: 0, + at: None, + refs: Default::default(), + }, vec![], ), "solid.torus" => Dialog::new( @@ -954,6 +964,7 @@ impl Dialog { fields: vec![("major", length_default(s, "20")), ("minor", length_default(s, "5"))], operation: 0, at: None, + refs: Default::default(), }, vec![], ), @@ -967,6 +978,7 @@ impl Dialog { ], operation: 0, at: None, + refs: Default::default(), }, vec![], ), @@ -981,6 +993,7 @@ impl Dialog { ], operation: 0, at: None, + refs: Default::default(), }, vec![SelInput::new("Profile", PROFILES, false)], ), @@ -4474,7 +4487,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S } return Ok(out); } - Kind::Primitive { cmd, fields, operation, at } => { + Kind::Primitive { cmd, fields, operation, at, .. } => { let mut p = serde_json::Map::new(); for (k, v) in fields { p.insert((*k).into(), json!(v)); @@ -4497,6 +4510,11 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S if let Some(n) = normal { p.insert("axis".into(), pt(n)); } + // Reference edges (#6380) place the base by its distances from them. + let references = crate::hole_refs::params(d); + if !references.is_empty() { + p.insert("references".into(), json!(references)); + } } _ => { p.insert("center".into(), pt(point)); @@ -5467,26 +5485,50 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Cylinder { base, axis, radius, height, operation, references } => { let mut d = start("solid.cylinder")?; d.kind = Kind::Primitive { cmd: "solid.cylinder", fields: vec![("radius", stored_length(s, radius)), ("height", stored_length(s, height))], operation: op_index(operation), at: None, + refs: Default::default(), }; d.extra.insert("base".into(), pt_expr(base)); d.extra.insert("axis".into(), pt3(axis.0)); + // Standing on a flat face (a base of numbers there, square to it): placed there, so it + // can take reference edges of that face (#6380), with its own picked again. Not the + // picks a selection made when the window opened. + d.inputs = crate::hole_refs::cylinder_inputs(); + let [x, y, z] = base.clone().map(|c| c.parse::().ok()); + if let (Some(x), Some(y), Some(z)) = (x, y, z) + && let Some(face @ Sel::Face { .. }) = face_sel(s, Vec3::new(x, y, z)) + && let Sel::Face { body, index, .. } = &face + && planar_face(s, body, *index).is_some_and(|(_, n)| n.dot(axis.0) > 1.0 - 1e-9) + && let Kind::Primitive { at, .. } = &mut d.kind + { + *at = Some((Vec3::new(x, y, z), Some(axis.0))); + if let Some(inp) = d.inputs.first_mut() { + inp.items = vec![face]; + } + crate::hole_refs::restore(s, &mut d, references, &f.edge_names); + } d } FeatureKind::Sphere { center, radius, operation } => { let mut d = start("solid.sphere")?; - d.kind = - Kind::Primitive { cmd: "solid.sphere", fields: vec![("radius", stored_length(s, radius))], operation: op_index(operation), at: None }; + d.kind = Kind::Primitive { + cmd: "solid.sphere", + fields: vec![("radius", stored_length(s, radius))], + operation: op_index(operation), + at: None, + refs: Default::default(), + }; d.extra.insert("center".into(), pt_expr(center)); d } @@ -5497,6 +5539,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option) -> Option) -> Option Dialog { if command == "solid.coil" { continue; // an empty Profile input keeps the primitive section, which this form checks } + if command == "solid.cylinder" { + continue; // its face and reference edges place it (cylinder reference tests); this form checks its fields + } if matches!(input.label, "Rail" | "Second Rail" | "Pass through" | "Direction" | "Roller (optional)" | "Tip (optional)") { continue; } diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 708b7c345..b26ddbcbe 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -184,8 +184,8 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: ui_kit::text(ui, tr(key), ui_kit::Text::Hint("manage")); } placement_row(d, ui, &app.session); - if matches!(&d.kind, Kind::Hole { opts, .. } if !opts.multiple) { - // Each reference edge with its distance (#37). + if crate::hole_refs::takes(d) { + // Each reference edge with its distance (#37, #6380). enter |= crate::hole_refs::input_rows(d, ui, &app.session); } else { input_rows(d, ui, &app.session); @@ -793,7 +793,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo enter |= crate::dialogs_move::rows(ui, k); extra_options(ui, "move_options", &mut d.extra, &[("Create Copy", "copy")]); } - Kind::Primitive { cmd, fields, operation, at } => { + Kind::Primitive { cmd, fields, operation, at, .. } => { let from_sketch = *cmd == "solid.coil" && d.inputs.first().is_some_and(|i| i.accept & selection::PROFILES != 0 && !i.items.is_empty()); for (k, v) in fields.iter_mut() { if from_sketch && (*k == "diameter" || *k == "section_size") { @@ -811,7 +811,10 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo form_row(ui, "Position", |ui| { ui.horizontal(|ui| { ui.label(format!("{:.2}, {:.2}, {:.2}", p.x, p.y, p.z)); - if ui_kit::button(ui, "×", ui_kit::Button::Small).on_hover_text(tr("Place at the origin instead")).clicked() { + // A cylinder's place is its Face pick, cleared there. + if *cmd != "solid.cylinder" + && ui_kit::button(ui, "×", ui_kit::Button::Small).on_hover_text(tr("Place at the origin instead")).clicked() + { *at = None; } }); diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs index fafe8d461..b2477da0b 100644 --- a/crates/ui-egui/src/hole_refs.rs +++ b/crates/ui-egui/src/hole_refs.rs @@ -5,7 +5,9 @@ //! there; moving the hole (another pick, or dragging its handle) measures the distances again. //! The canvas shows each distance as a dimension from its edge to the hole's centre. OK sends the //! edges and distances as `solid.hole`'s `references`, so the hole follows its edges when the -//! part changes; Edit Feature picks the edges again where they are now. +//! part changes; Edit Feature picks the edges again where they are now. A Cylinder takes the same +//! references for its base centre (#6380): its window picks the face it stands on (or takes the +//! one selected before it opened), then the edges. use egui::{Color32, Pos2, Stroke, vec2}; use serde_json::{Value, json}; @@ -17,7 +19,7 @@ use solidcraft_engine::{Sel, Session}; use crate::SolveApp; use crate::dialogs::{Dialog, Kind}; -use crate::selection::{EDGES, SelInput}; +use crate::selection::{EDGES, FACES, PLANAR_FACES, SelInput, VERTICES}; use crate::theme::Tokens; use crate::viewport::Proj; @@ -60,19 +62,75 @@ pub(crate) fn inputs() -> [SelInput; 2] { REFERENCES.map(|label| SelInput::new(label, EDGES, false)) } -/// Is `d` a Single hole's dialog? -fn single(d: &Dialog) -> bool { - matches!(&d.kind, Kind::Hole { opts, .. } if !opts.multiple) +/// The Cylinder window's inputs: where it stands (a face, or a vertex), then the reference edges. +pub(crate) fn cylinder_inputs() -> Vec { + let mut v = vec![SelInput::new("Face", PLANAR_FACES | FACES | VERTICES, false)]; + v.extend(inputs()); + v } -/// The hole's place: the first face pick (its index in the face input, and the point). -fn place(d: &Dialog) -> Option<(usize, Vec3)> { - d.inputs.first()?.items.iter().enumerate().find_map(|(i, x)| match x { - Sel::Face { point, .. } => Some((i, *point)), +/// Does `d` take reference edges: a Single hole's dialog, or a Cylinder's? +pub(crate) fn takes(d: &Dialog) -> bool { + match &d.kind { + Kind::Hole { opts, .. } => !opts.multiple, + Kind::Primitive { cmd, .. } => *cmd == "solid.cylinder", + _ => false, + } +} + +/// A Cylinder stands where its Face input is picked: on a planar face, along its normal (as it +/// stood when it is the place it already has); nowhere picked, at the origin. +fn cylinder_place(s: &Session, d: &mut Dialog) { + let picked = d.inputs.first().and_then(|i| i.items.first()).cloned(); + let Kind::Primitive { cmd: "solid.cylinder", at, .. } = &mut d.kind else { return }; + let to = match picked { + Some(Sel::Face { body, index, point }) => Some((point, crate::dialogs::planar_face(s, &body, index).map(|(_, n)| n))), + Some(Sel::Vertex { point, .. }) => Some((point, None)), + _ => None, + }; + if to.map(|(p, _)| p) != at.map(|(p, _)| p) { + *at = to; + } +} + +/// The dialog's reference distances and what they were worked out for. +fn refs(d: &Dialog) -> Option<&Refs> { + match &d.kind { + Kind::Hole { opts, .. } => Some(opts.refs.as_ref()), + Kind::Primitive { refs, .. } => Some(refs.as_ref()), + _ => None, + } +} + +fn refs_mut(d: &mut Dialog) -> Option<&mut Refs> { + match &mut d.kind { + Kind::Hole { opts, .. } => Some(opts.refs.as_mut()), + Kind::Primitive { refs, .. } => Some(refs.as_mut()), + _ => None, + } +} + +/// The place: the cylinder's base, else the hole's first face pick. +fn place(d: &Dialog) -> Option { + if let Kind::Primitive { at, .. } = &d.kind { + return at.map(|(p, _)| p); + } + d.inputs.first()?.items.iter().find_map(|x| match x { + Sel::Face { point, .. } => Some(*point), _ => None, }) } +/// Move the place (see [`place`]) to `p`: the face pick, and a cylinder's base with it. +fn set_place(d: &mut Dialog, p: Vec3) { + if let Kind::Primitive { at: Some((point, _)), .. } = &mut d.kind { + *point = p; + } + if let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.iter_mut().find(|x| matches!(x, Sel::Face { .. }))) { + *point = p; + } +} + /// A point on each reference edge picked, by input. fn edges(d: &Dialog) -> [Option; 2] { REFERENCES.map(|label| { @@ -90,21 +148,24 @@ fn vec3(v: &Value) -> Option { (a.len() == 3).then(|| Some(Vec3::new(c(0)?, c(1)?, c(2)?))).flatten() } -/// The way the hole drills at `at`: as it was made (editing), else into the face there. +/// The way the hole drills at `at`: as it was made (editing), else into the face there. A +/// cylinder's: into the face it stands on, against its axis. fn direction(s: &Session, d: &Dialog, at: Vec3) -> Option { + if let Kind::Primitive { at: Some((_, normal)), .. } = &d.kind { + return normal.map(|n| -n); + } d.extra.get("direction").and_then(vec3).or_else(|| solidcraft_engine::doc::hole_direction_at(&s.world_state(), at)) } /// The face's frame at the place for the picked edges (and which reference inputs they are), found /// again only when the design, the place or the edges change. fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec)> { - let (_, at) = place(d)?; + let at = place(d)?; let edges = edges(d); if edges.iter().all(Option::is_none) { return None; } - let Kind::Hole { opts, .. } = &d.kind else { return None }; - if let Some(f) = &opts.refs.frame + if let Some(f) = &refs(d)?.frame && f.revision == s.revision && f.place == at && f.edges == edges @@ -116,8 +177,8 @@ fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec)> { let pts: Vec<(Vec3, Option<&str>)> = picked.iter().map(|(_, p)| (*p, None)).collect(); reference_frame(&s.world_state(), at, dir, &pts, true).ok().map(|f| (f, picked.iter().map(|(k, _)| *k).collect())) }); - if let Kind::Hole { opts, .. } = &mut d.kind { - opts.refs.frame = Some(Framed { revision: s.revision, place: at, edges, frame: found.clone() }); + if let Some(refs) = refs_mut(d) { + refs.frame = Some(Framed { revision: s.revision, place: at, edges, frame: found.clone() }); } found } @@ -126,19 +187,19 @@ fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec)> { /// typed distance moves the place there (when it stays on the face). Run before the dialog's /// commands are made. pub(crate) fn sync(s: &Session, d: &mut Dialog) { - if !single(d) { + if !takes(d) { return; } + cylinder_place(s, d); let edges = edges(d); - let Some((i, at)) = place(d) else { - if let Kind::Hole { opts, .. } = &mut d.kind { - opts.refs.seen = None; + let Some(at) = place(d) else { + if let Some(refs) = refs_mut(d) { + refs.seen = None; } return; }; let framed = frame(s, d); - let Kind::Hole { opts, .. } = &mut d.kind else { return }; - let refs = &mut opts.refs; + let Some(refs) = refs_mut(d) else { return }; let mut to = at; if let Some((f, picked)) = &framed { let same = refs.seen.as_ref().filter(|sn| sn.place == at && sn.edges == edges); @@ -170,15 +231,13 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { } } refs.seen = Some(Seen { place: to, edges, distance: refs.distance.clone() }); - if to != at - && let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.get_mut(i)) - { - *point = to; + if to != at { + set_place(d, to); } } -/// The Single hole's selection rows, each reference edge with its distance on the row below it -/// once it is picked. Whether Enter was pressed in a distance. +/// The Single hole's (or the Cylinder's) selection rows, each reference edge with its distance on +/// the row below it once it is picked. Whether Enter was pressed in a distance. pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) -> bool { let mut enter = false; for i in 0..d.inputs.len() { @@ -186,8 +245,8 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) -> bool let Some(k) = d.inputs.get(i).filter(|inp| !inp.items.is_empty()).and_then(|inp| REFERENCES.iter().position(|l| *l == inp.label)) else { continue; }; - if let Kind::Hole { opts, .. } = &mut d.kind - && let (Some(label), Some(value)) = (DISTANCES.get(k), opts.refs.distance.get_mut(k)) + if let Some(refs) = refs_mut(d) + && let (Some(label), Some(value)) = (DISTANCES.get(k), refs.distance.get_mut(k)) { enter |= crate::ui_kit::expr_row(ui, label, value); } @@ -198,24 +257,17 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session) -> bool /// The `references` OK sends: each picked edge (a point on it) with its distance. pub(crate) fn params(d: &Dialog) -> Vec { - let Kind::Hole { opts, .. } = &d.kind else { return Vec::new() }; - if opts.multiple { - return Vec::new(); - } - edges(d) - .iter() - .zip(&opts.refs.distance) - .filter_map(|(e, distance)| e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()}))) - .collect() + let Some(refs) = refs(d).filter(|_| takes(d)) else { return Vec::new() }; + edges(d).iter().zip(&refs.distance).filter_map(|(e, distance)| e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()}))).collect() } -/// Editing a hole with reference edges: the edges picked again where they are now, their -/// distances, and the place where those distances put the hole now. +/// Editing a hole (or a cylinder) with reference edges: the edges picked again where they are +/// now, their distances, and the place where those distances put it now. pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String]) { if references.is_empty() { return; } - let Some((i, at)) = place(d) else { return }; + let Some(at) = place(d) else { return }; let st = s.world_state(); let edges: Vec<(Vec3, Option<&str>)> = references.iter().enumerate().map(|(k, r)| (r.edge.0, names.get(k).map(String::as_str))).collect(); let found = direction(s, d, at).and_then(|dir| reference_frame(&st, at, dir, &edges, false).ok()); @@ -233,8 +285,8 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], { inp.items = vec![sel]; } - if let Kind::Hole { opts, .. } = &mut d.kind - && let Some(slot) = opts.refs.distance.get_mut(k) + if let Some(refs) = refs_mut(d) + && let Some(slot) = refs.distance.get_mut(k) { *slot = r.distance.to_string(); } @@ -242,19 +294,17 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], // The hole where its distances put it now (the part may have changed since it was placed). let mut to = at; if let Some(f) = &found - && let Kind::Hole { opts, .. } = &d.kind + && let Some(refs) = refs(d) { - let values: Option> = opts.refs.distance.iter().take(f.lines.len()).map(|e| s.doc.eval(e, ValueKind::Length).ok()).collect(); + let values: Option> = refs.distance.iter().take(f.lines.len()).map(|e| s.doc.eval(e, ValueKind::Length).ok()).collect(); if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&st, f, *c)) { to = c; } } - if let Some(Sel::Face { point, .. }) = d.inputs.first_mut().and_then(|inp| inp.items.get_mut(i)) { - *point = to; - } + set_place(d, to); let edges = self::edges(d); - if let Kind::Hole { opts, .. } = &mut d.kind { - opts.refs.seen = Some(Seen { place: to, edges, distance: opts.refs.distance.clone() }); + if let Some(refs) = refs_mut(d) { + refs.seen = Some(Seen { place: to, edges, distance: refs.distance.clone() }); } } @@ -273,10 +323,10 @@ fn nearest_edge(s: &Session, at: Vec3, p: Vec3) -> Option { /// box beside it to type the distance in. Whether a box took the keyboard (a newly picked edge's), /// which the dialog's main value then leaves to it. pub(crate) fn canvas(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj, d: &mut Dialog) -> bool { - if !single(d) { + if !takes(d) { return false; } - let Some((_, at)) = place(d) else { return false }; + let Some(at) = place(d) else { return false }; let Some((f, picked)) = frame(&app.session, d) else { return false }; let mut took = false; let t = Tokens::get(); @@ -291,13 +341,13 @@ pub(crate) fn canvas(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, painter.line_segment([e0, e1], Stroke::new(1.2, t.dimension)); } dimension(painter, a, b, t.dimension); - let (Some(label), Kind::Hole { opts, .. }) = (DISTANCES.get(*k), &mut d.kind) else { continue }; - let focus = opts.refs.focus == Some(*k); + let (Some(label), Some(refs)) = (DISTANCES.get(*k), refs_mut(d)) else { continue }; + let focus = refs.focus == Some(*k); if focus { - opts.refs.focus = None; + refs.focus = None; took = true; } - let Some(value) = opts.refs.distance.get_mut(*k) else { continue }; + let Some(value) = refs.distance.get_mut(*k) else { continue }; let at = box_beyond(a, b); let r = crate::canvas::value_box_in( ui, diff --git a/crates/ui-egui/src/hole_refs_ui_tests.rs b/crates/ui-egui/src/hole_refs_ui_tests.rs index f65f691f8..bdc410305 100644 --- a/crates/ui-egui/src/hole_refs_ui_tests.rs +++ b/crates/ui-egui/src/hole_refs_ui_tests.rs @@ -2,6 +2,7 @@ //! face, pick two edges (each distance is measured from the pick), type the distances (one in //! the dialog, one in its box on the canvas), OK. The hole sits at those distances; Edit Feature //! picks the edges again with their distances, and moving the hole's place measures them again. +//! A Cylinder standing on a picked face takes reference edges the same way (#6380). use serde_json::json; use solidcraft_engine::Sel; @@ -160,3 +161,91 @@ fn a_number_typed_after_an_edge_pick_sets_its_distance() { let Some(Kind::Hole { diameter, .. }) = h.app.dialog.as_ref().map(|d| &d.kind) else { panic!("the hole dialog") }; assert_eq!(diameter, "5 mm", "the diameter is left as it was"); } + +/// The open Cylinder dialog's reference distances and where it stands. +fn cylinder_dialog(h: &Harness) -> ([String; 2], Vec3) { + match h.app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Primitive { cmd: "solid.cylinder", refs, at: Some((p, _)), .. }) => (refs.distance.clone(), *p), + other => panic!("the cylinder dialog is open on a face: {other:?}"), + } +} + +/// With the mouse alone: pick the top face, start Cylinder, pick two edges (each distance +/// measured from the pick), OK. Typing a distance moves the base; Edit Feature picks the edges +/// again. +#[test] +fn a_cylinder_is_placed_by_its_distances_from_two_edges() { + let mut h = plate(); + let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0)); + h.step(&json!({"click": at})).unwrap(); + h.step(&json!({"start": "solid.cylinder"})).unwrap(); + h.frames(2); + let (_, picked) = cylinder_dialog(&h); + assert!(picked.dist(Vec3::new(30.0, 25.0, 10.0)) < 0.5, "it stands where the face was picked: {picked:?}"); + // Reference 1 takes the first edge picked, Reference 2 the next. + let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0)); + h.step(&json!({"click": left})).unwrap(); + let front = screen(&mut h, Vec3::new(25.0, 0.0, 10.0)); + h.step(&json!({"click": front})).unwrap(); + h.frames(2); + assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 1")); + assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 2")); + let (measured, _) = cylinder_dialog(&h); + let value = |s: &str| h.app.session.doc.eval(s, solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((value(&measured[0]) - picked.x).abs() < 1e-3 && (value(&measured[1]) - picked.y).abs() < 1e-3, "{measured:?} from {picked:?}"); + assert!(h.at(&json!({"handle": "canvas:Distance 1"})).is_ok() && h.at(&json!({"handle": "canvas:Distance 2"})).is_ok()); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "OK closed the dialog: {:?}", h.app.dialog.as_ref().map(|d| &d.error)); + let f = h.app.session.doc.features.last().unwrap().clone(); + let FeatureKind::Cylinder { references, .. } = &f.kind else { panic!("the last feature is a cylinder: {}", f.kind.type_name()) }; + assert_eq!(references.len(), 2); + assert_eq!(f.edge_names.len(), 2); + assert!(h.app.session.model.result(f.id).is_some_and(|r| r.error.is_none())); + + // Edit Feature (with the face selected): the edges again with their distances, each input + // once; a typed distance moves the base. + let top = crate::dialogs::face_sel(&h.app.session, Vec3::new(45.0, 35.0, 10.0)).unwrap(); + h.app.session.selection = vec![top]; + h.step(&json!({"call": "ui.editFeature", "params": {"feature": f.id}})).unwrap(); + h.frames(4); + let labels: Vec<&str> = h.app.dialog.as_ref().unwrap().inputs.iter().map(|i| i.label).collect(); + assert_eq!(labels, ["Face", "Reference 1", "Reference 2"]); + assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 1")); + assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 2")); + assert_eq!(cylinder_dialog(&h).0, measured); + type_into(&mut h, "dialog:Distance 1", "10 mm"); + type_into(&mut h, "canvas:Distance 2", "12 mm"); + assert!(cylinder_dialog(&h).1.dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "{:?}", cylinder_dialog(&h).1); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error)); + assert!(solid_at(&h, Vec3::new(10.0, 12.0, 12.0)) && !solid_at(&h, Vec3::new(picked.x, picked.y, 12.0)), "the edit moved it to (10, 12)"); +} + +/// Started with nothing selected, the Cylinder stands at the origin until a face is clicked; +/// then its edges are picked, all with the mouse. +#[test] +fn a_cylinder_started_first_takes_its_face_then_its_edges() { + let mut h = plate(); + h.step(&json!({"start": "solid.cylinder"})).unwrap(); + h.frames(2); + let d = h.app.dialog.as_ref().unwrap(); + let labels: Vec<&str> = d.inputs.iter().map(|i| i.label).collect(); + assert_eq!(labels, ["Face", "Reference 1", "Reference 2"]); + assert!(matches!(d.kind, Kind::Primitive { at: None, .. }), "nothing picked: at the origin"); + let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0)); + h.step(&json!({"click": at})).unwrap(); + h.frames(2); + let (_, picked) = cylinder_dialog(&h); + assert!(picked.dist(Vec3::new(30.0, 25.0, 10.0)) < 0.5, "it stands where the face was clicked: {picked:?}"); + let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0)); + h.step(&json!({"click": left})).unwrap(); + let front = screen(&mut h, Vec3::new(25.0, 0.0, 10.0)); + h.step(&json!({"click": front})).unwrap(); + h.frames(2); + assert!(picked_edge(&h, "Reference 1").is_some() && picked_edge(&h, "Reference 2").is_some()); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error)); + let f = h.app.session.doc.features.last().unwrap(); + let FeatureKind::Cylinder { references, .. } = &f.kind else { panic!("the last feature is a cylinder") }; + assert_eq!(references.len(), 2); +} diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index adecfcd96..d70c6fc44 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -114,6 +114,13 @@ measured in the face's plane. Moving the hole measures the distances again. The distances when the part changes: it follows its edges, and the distances are parameters like its diameter. +A **Cylinder** placed on a planar face takes reference edges the same way. Select the face, then +start **Cylinder**: it stands where you clicked, and the window has **Reference 1** and +**Reference 2**. Pick one or two straight edges of that face; each gets a **Distance**, measured +from where you clicked, which you can also type in the window or in its box on the canvas. The +cylinder's base centre then follows the edges when the part changes, and the distances are +parameters like its radius. Edit Feature picks the edges again. + A **Hole** with **Single** placement drills where you pick a planar face. A pick on or near a point of a shown sketch that lies on that face, such as a circle's centre, places the hole exactly at that point, as **Multiple** placement picks it; **Select Other** (press and hold) also @@ -271,7 +278,7 @@ still be added through `set`. The fields of the common features: | Fillet | `radius`, `edges` (a point on each edge), `body`, `style` | | Chamfer | `distance`, `distance2` or `angle`, `flip`, `edges`, `body` | | Box | `length`, `width`, `height`, `corner`, `operation` | -| Cylinder | `radius`, `height`, `base`, `axis`, `operation` | +| Cylinder | `radius`, `height`, `base`, `axis`, `operation`, `references` (an `edge` point and a `distance` each, as a hole's) | | Hole | `diameter`, `depth`, `position`, `direction`, `hole` (simple, drilled, counterbore, countersink), `thread`, `to`, `references` (an `edge` point and a `distance` each) | | Shell | `thickness`, `faces`, `direction`, `body`, `tangent_chain` | | Draft | `angle`, `faces`, `neutral`, `pull`, `body` | diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index 300cc2d09..211cb5803 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -258,6 +258,22 @@ The first instance is the original. - **Elsewhere:** instance, element, occurrence. - **For translators:** not an occurrence of a component. +### reference edge + +A straight edge of a flat face that a Single hole's centre or a cylinder's base centre keeps a +set distance from, measured in that face's plane. + +Up to two reference edges place one hole or cylinder. Each distance is a parameter, and the +feature follows its edges when the part changes. + +- **In SolidCraft:** the `references` parameter of `solid.hole` and `solid.cylinder` (each + `{edge, distance}`); the windows' Reference 1, Reference 2 and Distance 1, Distance 2 rows; the + "Reference distance" input (`ui.reference_1`, `ui.reference_2`, `ui.reference_distance`). +- **Don't use:** datum edge, anchor edge. +- **Elsewhere:** reference edge, edge offset, distance from edge. +- **For translators:** an edge of a body, not a construction axis or a reference plane; the + distance is a length, not a reference value for light or material. + ### rollback marker The marker in the timeline after which no feature is computed. @@ -351,6 +367,9 @@ share a catalogue entry. Each meaning below gets its own term and, in time, its | | the middle display quality | normal (quality) | `ui.display_quality_normal` | | Quantity | the number of pattern instances | count | the pattern dialogs' Quantity rows, `ui.quantity` | | | what the motion plot shows: value, velocity or acceleration | plotted quantity | the motion study's Quantity row, `motion.plot_quantity` | +| Reference | an edge a hole or cylinder keeps its distance from | *reference edge* | `references` of `solid.hole` and `solid.cylinder`, `ui.reference_1` | +| | the measured values a material is checked against | reference (material) | `material.editor.reference` | +| | the distance a light's intensity is given for | reference distance (light) | `render.cpu_light_reference` | Some translations show the clash today: Japanese and Chinese show a hole's flat bottom with the word for "unfold" or "plane", Chinese shows "Round" as "fillet", and Chinese and Russian show the diff --git a/skills/solidcraft-modeling/reference.md b/skills/solidcraft-modeling/reference.md index e533f9733..b2f877472 100644 --- a/skills/solidcraft-modeling/reference.md +++ b/skills/solidcraft-modeling/reference.md @@ -76,7 +76,7 @@ Distances are unsigned. Draw the geometry on the correct side first, and the dim |---|---|---| | `solid.extrude` | `distance` | `profiles` defaults to **every region**, with a region inside another as a hole in it: two concentric circles give a ring. Pick regions with `[{"point":[x,y]}]` or `[index]`. Other options: `operation` (new/join/cut/intersect/auto), `direction` (positive/negative/symmetric), `through_all: true`, `start_offset`. A cut that misses reports success. | | `solid.box` | `length`, `width`, `height` | `center:[x,y,z]` or `corner`. The quickest way to block out a part. `body_name` names the body it makes. With `operation:"cut"`, `targets:["Top"]` cuts only the bodies listed, so the cutter can pass through other bodies. | -| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. | +| `solid.cylinder` | `radius` or `diameter`, `height` | `base` is the centre of the bottom (default origin), `axis` defaults to `Z`. Expressions work in `base`. To tie a cylinder standing on a flat face to the part, give `base` as numbers on that face and add `references: [{edge:[x,y,z], distance}]` (up to two straight edges of the face, as for `solid.hole`): the base centre then sits at those distances from the edges and follows them. Always pass `operation`. `body_name` and `targets` work as for `solid.box`. | | `sketch.slot.overall` / `sketch.slot.center_to_center` | `p0`, `p1` (overall ends / arc centres), `width` | Ids and dof are in the "Ids" section above. | | `solid.fillet` / `solid.chamfer` | `edges:[[x,y,z]]`, `radius` / `distance` | The pick snaps to the **nearest** edge. A pick farther than 5% of the body's size from every edge is refused, so check that the face count changed. One pick takes the whole tangent chain: a rounded rim needs 1 point, not 8. | | `solid.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`. |