diff --git a/ROADMAP.md b/ROADMAP.md index 6f102acf5..327201486 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -57,7 +57,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings. | M5 | Persistent naming of faces and edges (docs/book/src/dev/naming.md): faces named from their exact kernel-reported history (sketch curve sides, caps, revolve sections, primitive sides, blends, shell inner walls, pattern/mirror copies; split pieces told apart by the faces around them, lumps of a cut body named after their faces), edges by their faces; fillets/chamfers, sketches on faces, shell/draft/offset/replace faces, hole placements, joint origins and face appearances resolve by name first and warn when the entity split or vanished: done. sheet metal edges by base sketch line and flange side, shell inner faces, sweep and loft roles: done. kernel-reported face history: done (merged faces answer to every name; operations without history yet fall back to geometric names, flagged unverified; format 14 keeps older designs' geometric names). Left: history through sheet metal, plastic, surface and emboss features; FaceSource certificates through history | in progress | 20 | | M6 | UI depth: selection feedback and origin (done), timeline editing (done: hover and selection highlight modifier faces, including fillets and chamfers; edit feature, history marker drag, dependency-checked single and multi-item reorder, suppress, rename, delete with dependents, re-resolved references; redefining selections refreshes persistent edge/face references while retaining feature identity and dimension names; optional compact named left feature history with rollback bar, multi-selection and persistent folders above the parts browser), right-docked dialogs (done), live previews for every feature dialog (done), keyboard-first commands with on-canvas value boxes and sketch inline dimensions (done), drag manipulators with automatic join/cut (done: extrude incl. two sides, fillet, shell, hole depth, move, pattern spacing, revolve rotator, extrude taper), dark theme (done), right-click menu with Repeat (done), measure tool (done), section analysis (done), selection filter (done), drag-solve of sketch points (done); appearance controls now preserve body/face/component targeting, named transparent looks, reuse/search and override removal; preferences | in progress | 6 | | M7 | Thin extrude (walls along open or closed curves: centre, inside, outside or two sides; mitred corners, crossing walls joined; #721), sweep, loft (incl. to a point), rib and web (to next / depth), emboss (planar faces and exact radial emboss/deboss of bounded orthogonal profiles on complete exterior cylinders/sleeves), thread (cosmetic, and modelled M3–M20 outside and inside: the ISO profile screwed in as a faceted cut), coil (smooth B-spline helical walls), pipe, pattern on path, patterns of bodies and components, replace face (parallel), align, remove, feature copy/paste: done. Unique eligible cylindrical targets are inferred for new Emboss features. Left: general curved-face emboss and exact (unfaceted) modelled threads | in progress | 12 | -| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown. Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), loft guide rails (#201; sweep guide rails and two-rail sweeps are done, #771), and every remaining #757–#772 item | deferred | — | +| M8 | Surface workspace (#772). Done: Patch (sketch regions; edge loops filled G0, plus `crown`), Stitch, Thicken (planes and cylinders), Extend (straight edges of planar surfaces), Trim (by a plane, a face or sketch curves swept onto the surface, keeping a side or the picked regions; mutual trim of two surfaces, extended to meet and stitched, #767), Delete Face (healing), Boundary Fill, zebra/draft/curvature-map analysis, Surface Extrude/Revolve/Sweep/Loft from open and closed curves, Offset, Unstitch and Reverse Normal; the continuity-driven core (`kernel/src/bridge.rs`, G0–G3 Hermite rows) with **Blend** (`surface.blend`, #764), **Match** (`surface.match`), **Boundary** (`surface.boundary`, #763 — two sketch curves exact with G0–G3, three or four as the flat patch of their loop, and curve networks: Coons and Gordon surfaces through sketch, 3D-sketch or edge curves, a point for a three-sided side, G1/G2 against the faces along one direction's edges, joined into their body on request; G1/G2 on two sides that meet at a corner waits for the Gregory-type corner), **Fair** (`surface.fair`, CV fairing), **continuity analysis** (`inspect.continuity`, #770; a toolbar tool with edge markers and a legend, and curvature combs along face isocurves) and a multi-section **loft** with per-end continuity and crown, and guide rails on solid and surface lofts (one or two, scaling or stretching the sections between; #201). Also in the Class-A pass: G1…G4 blend curves in the sketch, chord and variable-radius fillets on curved edges (with honest refusals where the fit cannot hold), and a G2 corner patch where filleted edges meet (kernel; the command refuses until the patch's sections can be sewn to the blends' contacts). Left: bias/form-factor fillet sections (design recorded), a Gregory-type corner, surface Fillet between separate surface bodies (#769), Ruled (#762), Untrim (#761), curved-face Extend (#760), and every remaining #757–#772 item | deferred | — | | M9 | Components and assemblies: New Component / Create Components from Bodies, active component, per-component origin/bodies/sketches/timeline entries, occurrences with transforms, Copy/Paste vs Paste New, nested Browser tree with visibility and isolate; Ground, Move/Copy of occurrences, joints (rigid, revolute, slider, cylindrical, pin-slot, planar, ball) by joint origins with limits and Drive Joints, closed kinematic loops (four-bar, slider-crank: the loop's other joints follow the driven one on its branch, and driving stops where a loop can no longer close), cams (`joint.cam`: a revolute cam drives a slider or revolute follower along a closed sketch profile or the cam's edges, knife, roller or flat followers, worked out again when the profile changes; drives, studies, closed loops, contact sets), As-built Joint, Rigid Group, Contact Sets (driving and motion studies stop where bodies in a set would pass through each other), Motion Study (joint values keyed along a timeline, playback, export of occurrence positions as JSON/CSV), motion analysis (joint values and a point's path charted over a study as value, velocity and acceleration; the parts that collide along a study, with the steps where they do), Exploded views (automatic or by hand, shown without changing placements); interference, per-component physical properties; STEP with assembly structure; URDF export for robot simulators (links with meshes, mass and inertia; joint chains whose values match Drive Joints; docs/urdf.md). Physical properties now measure material-aware component/occurrence placements, descendants and repeated instances, including pending moves and body reassignment offsets; contact geometry and automatic exploded centres respect those offsets. Groundwork done: component tree, occurrences with transforms (instances, Paste New), world placement, active component as authoring frame, ground, Capture/Revert Position, moving bodies and sketches. UI: ASSEMBLE panel dialogs for New Component, Joint (snaps on faces, edges, circles and vertices; animated motion preview; offsets, flip, limits), As-built Joint, Joint Origin, Rigid Group, Drive Joints (live slider), Motion Link, Cam and Interference (overlaps shown red); joints in the timeline and the Browser | in progress | 32 | | M10 | Sheet metal: flange (base, edge, contour), hem, unfold/refold, convert, flat pattern + DXF, rules: done. PLASTIC enclosure subset: Boss, Rib, Web, Lip/Groove, Snap Fit, Rest, Plastic Rules (library, edit, assign; rule draft and clearance as feature defaults): done, tested against hand-computed geometry. UI: SHEET METAL and PLASTIC tabs with dialogs (live preview, Edit Feature, pre-selection) for Flange, Hem, Unfold/Refold, Convert, Sheet Metal Rules, Create Flat Pattern (flat view with bend lines, bend table CSV/JSON and DXF export with exact circle/arc/line cutouts), Boss, Lip/Groove, Snap Fit, Rest, Manage and Assign Plastic Rules; Fold (bend along a sketch line); flanges meeting at a corner closed at any angle with the rule's gap; edge flanges with their own angle and height per edge in one feature; corner reliefs (notch, round, rectangular, tear) chosen by the rule; Convert to Sheet Metal from a solid or shelled body by its bend edges (flat faces, sharp bends) | in progress | 36 | | M11 | 2D drawings | deferred | — | diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 76e9a2f5b..6e4906c86 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -301,8 +301,8 @@ impl SweepOrientation { } } -/// A sweep's guide rail: a chain of curves of a sketch, followed from the end nearest the path's -/// start. +/// A sweep's or a loft's guide rail: a chain of curves of a sketch, followed from the end nearest +/// the path's start (the loft's first section). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)] pub struct SweepRail { pub sketch: SketchId, @@ -742,6 +742,12 @@ pub enum FeatureKind { operation: Operation, #[serde(default, skip_serializing_if = "Vec::is_empty")] targets: Vec, + /// Guide rails (one or two) the loft follows between its sections. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + rails: Vec, + /// How the rails reshape the sections between. + #[serde(default, skip_serializing_if = "RailFit::is_scale")] + rail_fit: RailFit, }, /// Sweep profiles along a chain of sketch curves. Sweep { @@ -1374,6 +1380,12 @@ pub enum FeatureKind { continuity: [Continuity; 2], #[serde(default, skip_serializing_if = "loft_crown_is_plain")] crown: [f64; 2], + /// Guide rails (one or two) the loft follows between its sections. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + rails: Vec, + /// How the rails reshape the sections between. + #[serde(default, skip_serializing_if = "RailFit::is_scale")] + rail_fit: RailFit, }, /// The faces at `faces` copied out at a signed `distance` along their normals as a new /// surface body (0 copies them); `chain` takes each pick's whole smooth chain of faces; diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 3c254beb5..4d7a7c69e 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1071,23 +1071,26 @@ fn placement_digest(doc: &Document, f: &Feature) -> u64 { }; let wired = |id: &crate::SketchId| doc.sketch(id.0).is_ok_and(|sketch| !sketch.wires.is_empty()); let rails: &[crate::SweepRail] = match &f.kind { - FeatureKind::Sweep { rails, .. } | FeatureKind::SurfaceSweep { rails, .. } => rails, + FeatureKind::Sweep { rails, .. } + | FeatureKind::SurfaceSweep { rails, .. } + | FeatureKind::Loft { rails, .. } + | FeatureKind::SurfaceLoft { rails, .. } => rails, _ => &[], }; - if let Some(path) = path - && (wired(&path) || rails.iter().any(|r| wired(&r.sketch))) - { + if path.as_ref().is_some_and(wired) || rails.iter().any(|r| wired(&r.sketch)) { let mut hash = std::collections::hash_map::DefaultHasher::new(); - let owner = doc.feature(path.0).map(|feature| feature.component).unwrap_or(0); + let owner = path.and_then(|path| doc.feature(path.0)).map(|feature| feature.component).unwrap_or(0); for frame in [doc.component_transform(f.component), doc.component_transform(owner)] { frame.iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); } - if let FeatureKind::Sweep { sketch, rails, .. } | FeatureKind::SurfaceSweep { sketch, rails, .. } = &f.kind { - // The profile's and the rails' components place them too. - for sketch in std::iter::once(sketch).chain(rails.iter().map(|r| &r.sketch)) { - let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0); - doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); - } + // A sweep's profile and the rails' components place them too. + let profile = match &f.kind { + FeatureKind::Sweep { sketch, .. } | FeatureKind::SurfaceSweep { sketch, .. } => Some(sketch), + _ => None, + }; + for sketch in profile.into_iter().chain(rails.iter().map(|r| &r.sketch)) { + let owner = doc.feature(sketch.0).map(|feature| feature.component).unwrap_or(0); + doc.component_transform(owner).iter().flatten().for_each(|value| value.to_bits().hash(&mut hash)); } return hash.finish(); } @@ -3769,8 +3772,11 @@ fn feature_tools_with_constructor( let m = crate::rigid(Vec3::ZERO, origin_w, axis_w, -start); regions.iter().zip(bodies).map(|(r, body)| Ok(tool(r, kernel::transform_matrix(&body, m)?, Some(&body)))).collect() } - FeatureKind::Loft { sections, .. } if sections.iter().any(|s| s.point.is_some()) => { + FeatureKind::Loft { sections, rails, .. } if sections.iter().any(|s| s.point.is_some()) => { // A profile lofted to a sketch point (an apex). + if !rails.is_empty() { + return Err(DocError::Invalid("not supported yet: guide rails on a loft to a point".into())); + } let [a, b] = §ions[..] else { return Err(DocError::Invalid("not supported yet: a point section in a loft of more than two".into())) }; let (prof, pt) = if a.point.is_some() { (b, a) } else { (a, b) }; let ss = st.sketch(prof.sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {}", prof.sketch)))?; @@ -3823,7 +3829,7 @@ fn feature_tools_with_constructor( let pitch = if *clockwise { -p } else { p }; Ok(unnamed(vec![kernel::sweep_helix(&plane, ®ion, *base, axis, pitch, n)?])) } - FeatureKind::Loft { sections, .. } => { + FeatureKind::Loft { sections, rails, rail_fit, .. } => { let mut secs = Vec::new(); let mut sketches = Vec::new(); for sec in sections { @@ -3837,7 +3843,19 @@ fn feature_tools_with_constructor( } // Its caps are the first and last sections, its sides named by the curves they run // between. - let body = kernel::loft_regions(&secs)?; + let body = if rails.is_empty() { + kernel::loft_regions(&secs)? + } else { + // Rails shape the sections' outlines; sections with holes wait for rails that + // carry the holes too. + if secs.iter().any(|(_, r)| !r.holes.is_empty()) { + return Err(DocError::Invalid("not supported yet: guide rails on a loft whose sections have holes".into())); + } + let outlines: Vec<_> = secs.iter().map(|(p, r)| (*p, r.outer.clone())).collect(); + // The rails run from the end at the first section. + let start = outlines.first().and_then(|(p, lp)| lp.segs.first().map(|seg| p.to_world(seg.start()))).unwrap_or_default(); + kernel::loft_with_rails(&outlines, &rail_polylines(doc, st, rails, f.component, start)?, kernel_rail_fit(*rail_fit))? + }; let roles = crate::lineage::SectionRoles { sections: sketches.into_iter().zip(secs.iter().map(|(_, r)| std::iter::once(&r.outer).chain(&r.holes).collect())).collect(), }; @@ -3950,20 +3968,24 @@ pub(crate) fn sweep_control( Some(k) => val(vals, k, Kind::Unitless)?, None => 1.0, }; - let rail_fit = match rail_fit { - crate::RailFit::Scale => kernel::RailFit::Scale, - crate::RailFit::Stretch => kernel::RailFit::Stretch, - }; - let ctl = kernel::SweepControl { orientation, twist, scale, rails, rail_fit }; + let ctl = kernel::SweepControl { orientation, twist, scale, rails, rail_fit: kernel_rail_fit(rail_fit) }; ctl.check()?; Ok(ctl) } -/// A sweep's guide rails as polylines in the feature's frame, each a chain of its sketch's curves -/// (planar or 3D) from the end nearest `start`, the start of the path. +/// How guide rails reshape a sweep's profile or a loft's sections, for the kernel. +pub(crate) fn kernel_rail_fit(fit: crate::RailFit) -> kernel::RailFit { + match fit { + crate::RailFit::Scale => kernel::RailFit::Scale, + crate::RailFit::Stretch => kernel::RailFit::Stretch, + } +} + +/// A sweep's or a loft's guide rails as polylines in the feature's frame, each a chain of its sketch's curves +/// (planar or 3D) from the end nearest `start` (the start of the path, the loft's first section). pub(crate) fn rail_polylines(doc: &Document, st: &ModelState, rails: &[crate::SweepRail], consumer: u64, start: Vec3) -> Result>> { if rails.len() > 2 { - return Err(DocError::Invalid("a sweep takes one or two guide rails".into())); + return Err(DocError::Invalid("a sweep or a loft takes one or two guide rails".into())); } rails .iter() diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rs index c8c3145fb..b9d53cfc8 100644 --- a/crates/doc/src/eval_surface.rs +++ b/crates/doc/src/eval_surface.rs @@ -388,11 +388,14 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, push_sheet(st, f, traced); Ok(()) } - FeatureKind::SurfaceLoft { sections, continuity, crown } => { + FeatureKind::SurfaceLoft { sections, continuity, crown, rails, rail_fit } => { // A loft with edge chains for sections, or one that has to leave its ends a particular // way, is built through `loft_blend` from the frames of every section; the plain one // (sketch chains only, both ends G0) is the loft of old. if *continuity != [kernel::Continuity::G0, kernel::Continuity::G0] || sections.iter().any(|s| s.body.is_some()) { + if !rails.is_empty() { + return Err(DocError::Invalid("not supported yet: guide rails on a loft with edge sections or end continuity".into())); + } return loft_blend(st, f, sections, *continuity, *crown, doc); } let mut secs = Vec::with_capacity(sections.len()); @@ -417,7 +420,14 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap, f: &Feature, secs.push((ss.plane, chain)); sketches.push(ss); } - let body = kernel::loft_sheet(&secs)?; + let body = if rails.is_empty() { + kernel::loft_sheet(&secs)? + } else { + // The rails run from the end at the first section. + let start = secs.first().and_then(|(p, c)| c.first().map(|seg| p.to_world(seg.start()))).unwrap_or_default(); + let rails = crate::eval::rail_polylines(doc, st, rails, f.component, start)?; + kernel::loft_sheet_with_rails(&secs, &rails, crate::eval::kernel_rail_fit(*rail_fit))? + }; // Each wall named by the section curves it runs between, as a loft's sides are. let loops: Vec = secs.iter().map(|(_, c)| solidcraft_geom::Loop2 { segs: c.clone() }).collect(); let traced = crate::lineage::SectionRoles { sections: sketches.iter().zip(&loops).map(|(s, lp)| (s, vec![lp])).collect() }.tool(body); diff --git a/crates/doc/src/feature_walk_tests/fixtures.rs b/crates/doc/src/feature_walk_tests/fixtures.rs index ba9d31fdb..28c2da3e6 100644 --- a/crates/doc/src/feature_walk_tests/fixtures.rs +++ b/crates/doc/src/feature_walk_tests/fixtures.rs @@ -220,10 +220,11 @@ pub(super) fn with_refs(name: &str, mut v: Value) -> Value { "combine" => json!({"target": "B", "tools": ["B"]}), "pattern_rectangular" | "pattern_circular" | "pattern_path" | "mirror" => json!({"bodies": ["B"]}), "hole_simple" | "hole_drilled" | "hole_counterbore" | "hole_countersink" => json!({"points": {"sketch": 3, "ids": ["p"]}}), - "loft" => json!({"sections": [{"sketch": 4, "profiles": {"type": "all"}}, {"sketch": 5, "profiles": {"type": "all"}}], "targets": ["B"]}), + "loft" => json!({"sections": [{"sketch": 4, "profiles": {"type": "all"}}, {"sketch": 5, "profiles": {"type": "all"}}], "targets": ["B"], + "rails": [{"sketch": 6, "curves": ["l1"]}]}), "split" | "surface_trim" => json!({"tool": tool}), "split_line" => json!({"sketch": 6, "line": "l1"}), - "surface_loft" => json!({"sections": [{"sketch": 4}, {"sketch": 5}]}), + "surface_loft" => json!({"sections": [{"sketch": 4}, {"sketch": 5}], "rails": [{"sketch": 6, "curves": ["l1"]}]}), "split_face" => json!({"body": "B", "tool": tool, "sketch": 6}), "emboss" => json!({"face": {"body": "B", "at": o}, "targets": ["B"]}), "sheet_fold" => json!({"sketch": 7, "body": "B"}), diff --git a/crates/doc/src/feature_walk_tests/golden_refs.txt b/crates/doc/src/feature_walk_tests/golden_refs.txt index 5eeaff421..e6c3fcbdf 100644 --- a/crates/doc/src/feature_walk_tests/golden_refs.txt +++ b/crates/doc/src/feature_walk_tests/golden_refs.txt @@ -60,8 +60,8 @@ hole_countersink remap_refs: points.sketch thread loft - sketches: [4, 5] - remap_refs: sections[0].sketch, sections[1].sketch + sketches: [4, 5, 6] + remap_refs: rails[0].sketch, sections[0].sketch, sections[1].sketch remap_bodies: targets[0] sweep sketches: [1, 2] @@ -171,8 +171,8 @@ surface_sweep_options sketches: [1, 2] remap_refs: path_sketch, sketch surface_loft - sketches: [4, 5] - remap_refs: sections[0].sketch, sections[1].sketch + sketches: [4, 5, 6] + remap_refs: rails[0].sketch, sections[0].sketch, sections[1].sketch surface_blend remap_bodies: from.body surface_offset diff --git a/crates/doc/src/format/pending/loft-guide-rails.rs b/crates/doc/src/format/pending/loft-guide-rails.rs new file mode 100644 index 000000000..ab9457533 --- /dev/null +++ b/crates/doc/src/format/pending/loft-guide-rails.rs @@ -0,0 +1,3 @@ +//! Lofts (`Loft`, `SurfaceLoft`) take guide rails: `rails` (one or two `{sketch, curves}` chains, +//! as a sweep's) and `rail_fit` (`scale` or `stretch`). Both default to none and `scale`, so older +//! designs read unchanged. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index bfe0f3c91..4d5c01f8d 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -27,7 +27,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("sweep") .params("sketch: profile sketch; profiles?; path_sketch: sketch; path: [curve ids in order]; orientation?: perpendicular (default: square to the path, turning with it) | parallel (as drawn: the profile moves without turning; the path must keep crossing its plane) | [x,y,z] (square to the path, its turn about the path fixed by this direction); twist?: angle expr (the profile turns this much about the path over its length; within 4 turns); scale?: expr (the profile's scale at the end, linear along the path; 0.01…100); rails?: [{sketch?: sketch (default path_sketch), curves: [curve ids in order]}] (guide rails, one or two, each meeting every plane square to the path once along it, from the end nearest the path's start: one rail turns the profile so its point where the rail starts stays on the rail and scales it with the rail's distance from the path; two rails carry it between them, its points where they start staying on both; rails take the default orientation, no twist and no scale, and a path without sharp corners); rail_fit?: scale (default: the profile grows and shrinks evenly) | stretch (only across to the rail, between the rails); operation?, targets?, name?, body_name?"), - CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); operation?, targets?, name?, body_name?"), + CommandSpec::new("solid.loft", "Loft", loft).at("SOLID", "CREATE").icon("loft").params("sections: [{sketch, profiles?} | {sketch, point: id} (an apex)] (2…50, in order; matching hole counts, no holes at an apex); rails?: [{sketch, curves: [ids in order]}] (one or two guide rails from the first section to the last, through every section's outline: the loft follows them between the sections; not with sections that have holes); rail_fit?: scale|stretch (default scale: with one rail the sections grow evenly with the rail's distance from their middle, with two with the distance between the rails; stretch: only that way); operation?, targets?, name?, body_name?"), CommandSpec::new("solid.box", "Box", prim_box).at("SOLID", "CREATE").icon("box").params("length, width, height: expr; corner?: [x,y,z] | center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), CommandSpec::new("solid.cylinder", "Cylinder", prim_cylinder).at("SOLID", "CREATE").icon("cylinder").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?"), CommandSpec::new("solid.sphere", "Sphere", prim_sphere).at("SOLID", "CREATE").icon("sphere").params("radius | diameter: expr; center?: [x,y,z] (numbers in mm or length expressions; default: the origin); operation?, targets?: [body], name?, body_name?"), @@ -1985,6 +1985,20 @@ pub(super) fn sweep_options(s: &Session, p: &Value, cmd: &str) -> Result<(SweepO /// rails, each a sketch (default: the path's) and 1…1000 of its curves; a fit of scale or /// stretch; and no orientation, twist or scale besides, since the rails set those. pub(super) fn sweep_rails(s: &Session, p: &Value, cmd: &str, path_sketch: u64) -> Result<(Vec, RailFit)> { + let (rails, rail_fit) = guide_rails(s, p, cmd, "sweep", Some(path_sketch))?; + if !rails.is_empty() { + for key in ["orientation", "twist", "scale"] { + if p.get(key).is_some_and(|v| !v.is_null()) { + return Err(bad(cmd, format!("guide rails set the profile's turn and size along the path: leave out `{key}`"))); + } + } + } + Ok((rails, rail_fit)) +} + +/// A sweep's or a loft's (`what`) `rails` (one or two `{sketch?, curves}`, each rail's sketch +/// `default_sketch` when it names none) and `rail_fit` (scale | stretch). +pub(super) fn guide_rails(s: &Session, p: &Value, cmd: &str, what: &str, default_sketch: Option) -> Result<(Vec, RailFit)> { let rail_fit = match p.get("rail_fit") { None | Some(Value::Null) => RailFit::Scale, Some(Value::String(f)) if f.eq_ignore_ascii_case("scale") => RailFit::Scale, @@ -1994,21 +2008,17 @@ pub(super) fn sweep_rails(s: &Session, p: &Value, cmd: &str, path_sketch: u64) - let given = match p.get("rails") { None | Some(Value::Null) => return Ok((Vec::new(), rail_fit)), Some(Value::Array(a)) => a, - Some(_) => return Err(bad(cmd, "`rails` must list one or two rails: [{sketch?, curves: [ids]}]")), + Some(_) => return Err(bad(cmd, "`rails` must list one or two rails: [{sketch, curves: [ids]}]")), }; if !(1..=2).contains(&given.len()) { - return Err(bad(cmd, "a sweep takes one or two guide rails")); - } - for key in ["orientation", "twist", "scale"] { - if p.get(key).is_some_and(|v| !v.is_null()) { - return Err(bad(cmd, format!("guide rails set the profile's turn and size along the path: leave out `{key}`"))); - } + return Err(bad(cmd, format!("a {what} takes one or two guide rails"))); } let mut rails = Vec::with_capacity(given.len()); for rail in given { - let sketch = match rail.get("sketch") { - None | Some(Value::Null) => path_sketch, - Some(_) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?, + let sketch = match (rail.get("sketch").filter(|v| !v.is_null()), default_sketch) { + (None, Some(sketch)) => sketch, + (None, None) => return Err(bad(cmd, "each rail needs the `sketch` its curves are in")), + (Some(_), _) => sketch_id(s, rail.get("sketch"), cmd, "rails[].sketch")?, }; let curves = string_list(rail, "curves"); if curves.is_empty() || curves.len() > 1000 { @@ -2043,10 +2053,17 @@ fn loft(s: &mut Session, p: &Value) -> Result { } sections.push(solidcraft_doc::LoftSection { sketch: SketchId(sketch), profiles: profiles(sec, cmd)?, point: None }); } + let (rails, rail_fit) = guide_rails(s, p, cmd, "loft", None)?; add_feature( s, p, - FeatureKind::Loft { sections, operation: operation(p, cmd)?, targets: string_list(p, "targets").into_iter().map(BodyName).collect() }, + FeatureKind::Loft { + sections, + operation: operation(p, cmd)?, + targets: string_list(p, "targets").into_iter().map(BodyName).collect(), + rails, + rail_fit, + }, ) } @@ -2160,6 +2177,10 @@ mod patterns_tests; #[path = "prism_local_tests.rs"] mod prism_local_tests; +#[cfg(test)] +#[path = "loft_rails_tests.rs"] +mod loft_rails_tests; + #[cfg(test)] #[path = "revolve_convention_tests.rs"] mod revolve_convention_tests; diff --git a/crates/engine/src/cmd/loft_rails_tests.rs b/crates/engine/src/cmd/loft_rails_tests.rs new file mode 100644 index 000000000..eca940d01 --- /dev/null +++ b/crates/engine/src/cmd/loft_rails_tests.rs @@ -0,0 +1,163 @@ +//! Guide rails through the loft commands (#201): solid.loft and surface.loft with a rail, +//! scaling or stretching, checked against analytic values; editing, naming, saving and hostile +//! values. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::f64::consts::PI; + +use serde_json::{Value, json}; + +use crate::Session; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// The arc rail's radius (chord 40, bulging 5) and where its centre sits off the Z axis: the +/// rail is at x = r(z) = C + √(R² − (z − 20)²), from 10 at both ends to 15 halfway. (The sketch +/// hands the arc on as chords within 0.01 mm, hence the 2e-3 on the measures.) +const R: f64 = 42.5; +const C: f64 = 15.0 - R; + +/// ∫ √(R² − u²) du over the rail's height (u from −20 to 20). +fn root_integral() -> f64 { + 20.0 * (R * R - 400.0).sqrt() + R * R * (20.0 / R).asin() +} + +/// Circles `Base` (z = 0) and `Top` (z = 40) of radius 10, lines `Low` and `High` across them +/// from x = −10 to 10, rings `RingLow` and `RingHigh` (radius 10 round a hole of 5) there, and +/// in `Rail` on XZ the arc `arc` from (10, 0, 0) to (10, 0, 40) bulging out to x = 15 halfway, +/// and a straight `short` one that stops at z = 30. +fn setup() -> Session { + let mut s = Session::default(); + for (name, z) in [("Base", 0), ("Top", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10, "id": "c"})); + run(&mut s, "sketch.finish", json!({})); + } + for (name, z) in [("Low", 0), ("High", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["l"]})); + run(&mut s, "sketch.finish", json!({})); + } + for (name, z) in [("RingLow", 0), ("RingHigh", 40)] { + run(&mut s, "sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10})); + run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 5})); + run(&mut s, "sketch.finish", json!({})); + } + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Rail"})); + // The XZ sketch's y runs down world Z. + run(&mut s, "sketch.arc.three_point", json!({"start": [10, 0], "end": [10, -40], "through": [15, -20], "id": "arc"})); + run(&mut s, "sketch.line", json!({"points": [[-10, 0], [-10, -30]], "ids": ["short"]})); + run(&mut s, "sketch.finish", json!({})); + s +} + +fn measure(s: &Session, body: &str) -> solidcraft_kernel::BodyMeasure { + solidcraft_kernel::measure(&s.world_state().body(body).unwrap().body).unwrap() +} + +fn loft(s: &mut Session, body: &str, extra: Value) -> Result { + let mut p = json!({"sections": [{"sketch": "Base"}, {"sketch": "Top"}], "operation": "new", "body_name": body}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + s.execute("solid.loft", &p).map_err(|e| e.to_string()) +} + +fn face_names(s: &mut Session, body: &str) -> Vec { + let f = run(s, "model.faces", json!({ "body": body })); + let mut n: Vec = f["faces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|x| x["name"].as_str()) + .map(|x| x.split_once(':').map_or(x, |(_, rest)| rest).to_string()) + .collect(); + n.sort(); + n +} + +/// The arc rail turns the loft between the circles into the arc's solid of revolution +/// (π∫r² dz); its faces keep the plain loft's names; the rail is saved with the feature; and +/// switching the fit to stretch is an edit (the circles then widen only toward the rail, into +/// ellipses π · 10 · r). +#[test] +fn a_rail_turns_a_loft_into_its_solid_of_revolution_and_stretching_is_an_edit() { + let mut s = setup(); + let rail = json!([{"sketch": "Rail", "curves": ["arc"]}]); + loft(&mut s, "Plain", json!({})).unwrap(); + loft(&mut s, "Vase", json!({"rails": rail, "name": "Railed"})).unwrap(); + let volume = PI * (40.0 * C * C + 2.0 * C * root_integral() + 40.0 * R * R - 2.0 * 8000.0 / 3.0); + let m = measure(&s, "Vase"); + assert!((m.volume - volume).abs() < 2e-3 * volume, "volume {} vs {volume}", m.volume); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2, "{:?}", m.bbox); + assert_eq!(face_names(&mut s, "Plain"), face_names(&mut s, "Vase")); + + let doc = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap(); + let reopened = Session::new(doc); + assert!((measure(&reopened, "Vase").volume - m.volume).abs() < 1e-9 * volume); + + run(&mut s, "timeline.edit", json!({"feature": "Railed", "set": {"rail_fit": "stretch"}})); + let stretched = measure(&s, "Vase"); + let elliptic = 10.0 * PI * (40.0 * C + root_integral()); + assert!((stretched.volume - elliptic).abs() < 2e-3 * elliptic, "stretched {} vs {elliptic}", stretched.volume); + assert!((stretched.bbox.max.y - 10.0).abs() < 1e-3, "{:?}", stretched.bbox); +} + +/// A sheet lofted between the two lines with the arc rail from one end: the lines between grow +/// about their middles, 2r long; area 2∫r dz. +#[test] +fn a_surface_loft_follows_its_rail() { + let mut s = setup(); + run( + &mut s, + "surface.loft", + json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}], "rails": [{"sketch": "Rail", "curves": ["arc"]}], "body_name": "Sail"}), + ); + let m = measure(&s, "Sail"); + let area = 2.0 * (40.0 * C + root_integral()); + assert!((m.area - area).abs() < 2e-3 * area, "area {} vs {area}", m.area); + assert!((m.bbox.min.x + 15.0).abs() < 1e-2, "{:?}", m.bbox); +} + +/// Hostile rails are refused with an error and leave the design as it was. +#[test] +fn hostile_rails_are_refused() { + let mut s = setup(); + let before = s.doc.features.len(); + let rail = json!([{"sketch": "Rail", "curves": ["arc"]}]); + for bad in [ + json!({"rails": "arc"}), + json!({"rails": []}), + json!({"rails": [{"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}]}), + json!({"rails": [{"sketch": "Rail", "curves": []}]}), + // A loft has no path whose sketch a rail could default to. + json!({"rails": [{"curves": ["arc"]}]}), + json!({"rails": [{"sketch": "Rail", "curves": ["nope"]}]}), + json!({"rails": [{"sketch": "Nowhere", "curves": ["arc"]}]}), + json!({"rails": rail, "rail_fit": "wobble"}), + // A rail that stops short of the top section. + json!({"rails": [{"sketch": "Rail", "curves": ["short"]}]}), + // Two rails meeting the sections at one point. + json!({"rails": [{"sketch": "Rail", "curves": ["arc"]}, {"sketch": "Rail", "curves": ["arc"]}]}), + ] { + assert!(loft(&mut s, "Bad", bad.clone()).is_err(), "{bad}"); + let mut p = json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}]}); + p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone()); + assert!(s.execute("surface.loft", &p).is_err(), "surface {bad}"); + } + // Rails on what the railed loft does not build yet. + let apex = json!({"sections": [{"sketch": "Base"}, {"sketch": "Rail", "point": "arc.start"}], "rails": rail}); + assert!(s.execute("solid.loft", &apex).is_err()); + // Rings (a circle with a hole) loft without rails, not with them yet. + let ring = |name: &str| json!({"sketch": name, "profiles": [{"point": [7.5, 0]}]}); + let rings = json!({"sections": [ring("RingLow"), ring("RingHigh")], "operation": "new", "rails": rail}); + let refused = s.execute("solid.loft", &rings).unwrap_err().to_string(); + assert!(refused.contains("not supported yet") && refused.contains("holes"), "{refused}"); + let g1 = + json!({"sections": [{"sketch": "Low", "curves": ["l"]}, {"sketch": "High", "curves": ["l"]}], "rails": rail, "continuity": ["g1", "g0"]}); + let refused = s.execute("surface.loft", &g1).unwrap_err().to_string(); + assert!(refused.contains("not supported yet"), "{refused}"); + assert_eq!(s.doc.features.len(), before, "nothing was added"); +} diff --git a/crates/engine/src/cmd/surface.rs b/crates/engine/src/cmd/surface.rs index 32fb50bc1..e12b6aea6 100644 --- a/crates/engine/src/cmd/surface.rs +++ b/crates/engine/src/cmd/surface.rs @@ -51,7 +51,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("surface.loft", "Surface Loft", surface_loft) .at("SURFACE", "CREATE") .icon("surface_loft") - .params("sections: [{sketch, curves?: [curve ids], profiles?} | {body, edges: [[x,y,z]]}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed; a body edge chain takes the face the chain bounds as the surface the end repeats); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g0: how much of the surface at the first and last section the loft repeats — the tangent plane, the curvature, or how that curvature changes); crown?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"), + .params("sections: [{sketch, curves?: [curve ids], profiles?} | {body, edges: [[x,y,z]]}] (2…50 in order; each one chain: a profile without holes, or curves meeting end to end; all open or all closed; a body edge chain takes the face the chain bounds as the surface the end repeats); continuity?: [g0|g1|g2|g3, g0|g1|g2|g3] (each end, default g0: how much of the surface at the first and last section the loft repeats — the tangent plane, the curvature, or how that curvature changes); crown?: [number, number] (default 0: how full each end leaves, -0.9 flattest to 3 fullest); rails?, rail_fit? (as solid.loft; sketch sections only, both ends g0); name?, body_name? (a surface body: ruled between two sections, smooth through three or more; no caps)"), CommandSpec::new("surface.offset", "Offset Surface", offset) .at("SURFACE", "CREATE") .icon("surface_offset") @@ -431,7 +431,8 @@ fn surface_loft(s: &mut Session, p: &Value) -> Result { [one(list.first())?, one(list.get(1))?] } }; - add_feature(s, p, FeatureKind::SurfaceLoft { sections, continuity, crown }) + let (rails, rail_fit) = super::features::guide_rails(s, p, cmd, "loft", None)?; + add_feature(s, p, FeatureKind::SurfaceLoft { sections, continuity, crown, rails, rail_fit }) } fn offset(s: &mut Session, p: &Value) -> Result { diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index a1c097df6..e781e7f37 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -8,6 +8,7 @@ use crate::body::{Body, Solid, from_p3, p3, v3}; use crate::history::FaceProv; use crate::numbered::{self, NumberedLoop, NumberedRegion}; use crate::record::{self, Side}; +use crate::sweep_path::RailFit; use crate::{KernelError, Result, guard}; const MAX_SEGS: usize = 20_000; @@ -1797,21 +1798,34 @@ pub(crate) fn close_sweep(sides: Vec) -> Result { /// Ruled loft through two or more planar sections (outer loops only). The sections and the /// same sections in reverse order give the same body. pub fn loft(sections: &[(Plane, Loop2)]) -> Result { + loft_with_rails(sections, &[], RailFit::Scale) +} + +/// [`loft`] following one or two guide rails (polylines from the first section to the last, +/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the +/// sections between. Without rails, the plain loft. +pub fn loft_with_rails(sections: &[(Plane, Loop2)], rails: &[Vec], fit: RailFit) -> Result { let (wires, edge_sources, reversed) = loft_wires(sections)?; + let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("loft: sections".into())) }; + let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); + if reversed { + planes.reverse(); + } + let all = guard("loft", || crate::loft_rails::railed_wires(&planes, &wires, true, rails, fit))?; // The wires run from the first section given, or (turned round) the last. - // Three sections or more: one smooth surface through them all for each segment. - if wires.len() >= 3 - && let Ok(b) = guard("loft", || { - let faces = smooth_loft_faces(&wires, &edge_sources, true)?; - let (Some(w0), Some(w1)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("smooth loft: sections".into())) }; - cap_and_close(faces, std::slice::from_ref(w0), std::slice::from_ref(w1), reversed) - }) - { - return Ok(b); + // Three wires or more: one smooth surface through them all for each segment. A plain loft + // falls back to ruled faces where that fails; a railed one has to follow its rails. + if all.len() >= 3 { + let smooth = guard("loft", || { + let faces = smooth_loft_faces(&all, &edge_sources, true)?; + cap_and_close(faces, std::slice::from_ref(first), std::slice::from_ref(last), reversed) + }); + if smooth.is_ok() || !rails.is_empty() { + return smooth; + } } guard("loft", || { let sides = ruled_loft_faces(&wires, &edge_sources)?; - let (Some(first), Some(last)) = (wires.first(), wires.last()) else { return Err(KernelError::Failed("loft".into())) }; cap_and_close(sides, std::slice::from_ref(first), std::slice::from_ref(last), reversed) }) } @@ -2039,7 +2053,7 @@ pub(crate) fn ruled_loft_faces(wires: &[mt::Wire], edge_sources: &[Vec Option> { +pub(crate) fn across(pts: &[Vec3], u: &[f64]) -> Option> { match pts { [a, b, c] => { // The quadratic Bezier through `b` at t = u[1]. @@ -2059,7 +2073,7 @@ fn across(pts: &[Vec3], u: &[f64]) -> Option> { /// them. At a uniform parameter a section close to its neighbour makes the surface overshoot /// between the others (by several times the section's size when the spacing differs tenfold). /// Evenly spaced sections give the uniform parameters. -fn section_parameters(edges: &[Vec]) -> Vec { +pub(crate) fn section_parameters(edges: &[Vec]) -> Vec { let m = edges.len(); let uniform = || (0..m).map(|i| i as f64 / (m.max(2) - 1) as f64).collect::>(); let corners: Vec> = edges.iter().map(|es| es.iter().map(|e| from_p3(e.front().point())).collect()).collect(); diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs index e01cf5ee6..1051cae30 100644 --- a/crates/kernel/src/curveblend.rs +++ b/crates/kernel/src/curveblend.rs @@ -2243,7 +2243,7 @@ fn curve_blend_sized(solid: &Solid, ids: &[mt::EdgeID], size: f64, size_law: Siz #[path = "curvecorner.rs"] mod corner; -pub(crate) use corner::corner_blend_style; +pub(crate) use corner::{corner_blend_style, param_on}; // The planar corner builder the G2 corner work left in place of `corner_blend_style`'s sphere. #[allow(unused_imports)] pub(crate) use corner::corner_blend; diff --git a/crates/kernel/src/curvecorner.rs b/crates/kernel/src/curvecorner.rs index affabdaab..a3dbc8892 100644 --- a/crates/kernel/src/curvecorner.rs +++ b/crates/kernel/src/curvecorner.rs @@ -214,7 +214,9 @@ fn radius_along(e: &mt::Edge, axis: Vec3, tol: f64) -> Option { (0..=16).map(|i| at(i as f64 / 16.0)).all(|p| (p.dist(o) - rho).abs() <= tol).then_some(rho) } -fn param_on(c: &mt::Curve, x: Vec3) -> Option { +/// The parameter of `c`'s point nearest `x`: the nearest of 65 samples, refined where that +/// comes nearer. +pub(crate) fn param_on(c: &mt::Curve, x: Vec3) -> Option { use mt::{BoundedCurve, ParametricCurve, SearchNearestParameter}; let (lo, hi) = c.range_tuple(); let d = |t: f64| from_p3(c.subs(t)).dist(x); diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index a49cb3ced..6f852793d 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -81,6 +81,9 @@ mod issue_871_tests; mod join_between_caps_tests; mod lip; pub mod loft_blend; +mod loft_rails; +#[cfg(test)] +mod loft_rails_tests; #[cfg(test)] mod loft_region_tests; mod loopblend; @@ -160,7 +163,7 @@ pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDG pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid}; pub use build::{ PathSeg, box_solid, canonical_revolve_axis, cylinder, extrude, extrude_tapered, extrude_tapered_between, extrude_whole_sides, loft, loft_regions, - path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, + loft_with_rails, path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus, }; pub use clearance::{Clearance, Occupancy}; pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap}; @@ -209,8 +212,8 @@ pub use surface_ruled::{Ruled, RuledCorners, RuledMode, ruled_surface}; pub use surface_trim::{TrimKeep, mutual_trim, trim, trim_keep}; pub use surface_untrim::{UntrimHoles, untrim}; pub use surfaces::{ - copy_faces, extend, extrude_sheet, loft_sheet, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, stitch, sweep_sheet, - sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, + copy_faces, extend, extrude_sheet, loft_sheet, loft_sheet_with_rails, patch_edges, patch_region, remove_faces, reverse_faces, revolve_sheet, + stitch, sweep_sheet, sweep_sheet_points, sweep_sheet_points_with, sweep_sheet_with, thicken, unstitch, }; pub use sweep_path::{RailFit, SweepControl, SweepOrientation, sweep_path, sweep_path_with}; pub use topo::{CylinderFace, cylinder_end_at, cylinder_face, cylinder_face_at}; diff --git a/crates/kernel/src/loft_rails.rs b/crates/kernel/src/loft_rails.rs new file mode 100644 index 000000000..72acd5e6e --- /dev/null +++ b/crates/kernel/src/loft_rails.rs @@ -0,0 +1,349 @@ +//! Guide rails for a loft (#201): curves the loft follows between its sections. A rail runs from +//! the first section to the last and passes through every section's curve. Between each two +//! sections, stations are added: each is the plain loft there, moved so that the point of it a +//! rail guides lands on the rail. With one rail the station turns about the loft's direction +//! there and grows or shrinks about its middle (stretches across to the rail, with +//! [`RailFit::Stretch`]), shifted along the loft as far as the rail leads or lags; with two it +//! moves with the first rail, turns with the line between the rails and sizes with their distance +//! (stretches along that line), leaning to follow the second. At the sections the move is none, +//! so the sections and the loft's caps stay exactly as drawn; the loft's smooth surfaces then run +//! through the sections and the stations together. + +use mt::{BoundedCurve, ParametricCurve}; +use solidcraft_geom::{Plane, Vec3}; +use truck_modeling as mt; + +use crate::body::{from_p3, p3}; +use crate::sweep_path::RailFit; +use crate::{KernelError, Result}; + +/// Most wires a railed loft is skinned through, sections and stations together. +const MAX_WIRES: usize = 33; +/// Most stations between two sections. +const MAX_PER_SPAN: usize = 15; + +type Curve = mt::BSplineCurve; + +/// Where a rail meets a section: the point of the section's wire it guides (as a wire parameter: +/// the edge's index plus how far along the edge), that point, how far it is from where the rail +/// crosses the section's plane (the nudge onto it), and how far along the rail that crossing is +/// (segment and fraction). +struct Anchor { + g: f64, + on: Vec3, + nudge: Vec3, + at: (usize, f64), +} + +/// A rail as a polyline from the first section, and where it meets each section. +struct Rail { + pts: Vec, + anchors: Vec, +} + +/// An affine move: `x` goes to `to + m·(x − from)` (`m` by columns). +struct Affine { + from: Vec3, + to: Vec3, + m: [Vec3; 3], +} + +impl Affine { + fn apply(&self, x: Vec3) -> Vec3 { + let d = x - self.from; + self.to + self.m[0] * d.x + self.m[1] * d.y + self.m[2] * d.z + } +} + +/// The loft's wires with stations added between the sections so that the loft follows `rails` +/// (polylines; see the module notes). `planes` are the sections' planes, `wires` their matched +/// wires (as [`crate::build::loft_wires`] or a sheet loft makes them: the k-th edges of every +/// wire are B-splines on one knot vector), both in loft order; `closed` whether the wires close. +/// Without rails the wires come back as they are. +pub(crate) fn railed_wires(planes: &[Plane], wires: &[mt::Wire], closed: bool, rails: &[Vec], fit: RailFit) -> Result> { + if rails.is_empty() { + return Ok(wires.to_vec()); + } + if rails.len() > 2 { + return Err(KernelError::Invalid("a loft takes one or two guide rails".into())); + } + let fail = |m: &str| KernelError::Failed(format!("loft rails: {m}")); + let count = wires.len(); + if count < 2 || planes.len() != count { + return Err(fail("sections")); + } + // Each section's edge curves, and the knot vector the k-th edges share. + let curves: Vec> = wires + .iter() + .map(|w| { + w.edge_iter() + .map(|e| match e.curve() { + mt::Curve::BSplineCurve(c) if e.orientation() => Some(c), + _ => None, + }) + .collect::>>() + }) + .collect::>() + .ok_or_else(|| fail("section curves"))?; + let first = curves.first().ok_or_else(|| fail("sections"))?; + let n = first.len(); + let knots: Vec = first.iter().map(|c| c.knot_vec().clone()).collect(); + let sizes: Vec = first.iter().map(|c| c.control_points().len()).collect(); + if n == 0 + || curves + .iter() + .any(|cs| cs.len() != n || cs.iter().zip(&knots).zip(&sizes).any(|((c, k), m)| c.knot_vec() != k || c.control_points().len() != *m)) + { + return Err(fail("sections parameterised differently")); + } + let ctrl: Vec>> = + curves.iter().map(|cs| cs.iter().map(|c| c.control_points().iter().map(|p| from_p3(*p)).collect()).collect()).collect(); + let edges: Vec> = wires.iter().map(|w| w.edge_iter().cloned().collect()).collect(); + let along = crate::build::section_parameters(&edges); + let mut bounds = solidcraft_geom::Aabb3::EMPTY; + for p in ctrl.iter().flatten().flatten() { + if !p.is_finite() { + return Err(fail("sections")); + } + bounds.add(*p); + } + let size = bounds.diagonal(); + let tol = (size * 1e-4).max(1e-6); + let start = centroid(ctrl.first().ok_or_else(|| fail("sections"))?); + let rails: Vec = rails.iter().map(|r| rail(r, start, planes, &curves, tol)).collect::>()?; + if let [a, b] = &rails[..] + && a.anchors.iter().zip(&b.anchors).any(|(p, q)| p.on.dist(q.on) <= tol) + { + return Err(KernelError::Invalid("the two guide rails meet a section at the same point".into())); + } + // The plain loft between the sections: each control point across them, straight between two + // sections, the smooth loft's curve through three or more. + let across: Vec>> = if count == 2 { + Vec::new() + } else { + (0..n) + .map(|k| { + (0..sizes.get(k).copied().unwrap_or(0)) + .map(|j| { + let pts: Vec = ctrl.iter().filter_map(|s| s.get(k).and_then(|e| e.get(j)).copied()).collect(); + crate::build::across(&pts, &along) + }) + .collect() + }) + .collect() + }; + let plain = |v: f64| -> Result>> { + let (Some(a), Some(b)) = (ctrl.first(), ctrl.last()) else { return Err(fail("sections")) }; + if count == 2 { + return Ok(a.iter().zip(b).map(|(ea, eb)| ea.iter().zip(eb).map(|(p, q)| p.lerp(*q, v)).collect()).collect()); + } + across.iter().map(|cs| cs.iter().map(|c| c.as_ref().map(|c| from_p3(c.subs(v))).ok_or_else(|| fail("the plain loft"))).collect()).collect() + }; + // The middle of the plain loft (the middles of the sections' control points, across them as + // the control points are: the middle is linear in them) and its direction. + let middles: Vec = ctrl.iter().map(|s| centroid(s)).collect(); + let middle_curve = if count == 2 { None } else { Some(crate::build::across(&middles, &along).ok_or_else(|| fail("the plain loft"))?) }; + let middle = |v: f64| -> Result<(Vec3, Vec3)> { + let (p, d) = match (&middle_curve, middles.first(), middles.last()) { + (Some(c), ..) => { + let d = c.der(v); + (from_p3(c.subs(v)), Vec3::new(d.x, d.y, d.z)) + } + (None, Some(a), Some(b)) => (a.lerp(*b, v), *b - *a), + _ => return Err(fail("sections")), + }; + let d = d.normalized().ok_or_else(|| KernelError::Invalid("two loft sections sit on top of each other".into()))?; + Ok((p, d)) + }; + // The sections' normals, turned to agree with the first's. + let mut normals: Vec = Vec::with_capacity(count); + for p in planes { + let n = p.normal(); + let prev = normals.last().copied().unwrap_or(n); + normals.push(if n.dot(prev) < 0.0 { n * -1.0 } else { n }); + } + let spans = count - 1; + let per = (MAX_WIRES.saturating_sub(count) / spans).clamp(1, MAX_PER_SPAN); + let mut out = Vec::with_capacity(count + spans * per); + for i in 0..spans { + out.push(wires.get(i).cloned().ok_or_else(|| fail("sections"))?); + let (Some(&v0), Some(&v1), Some(&n0), Some(&n1)) = (along.get(i), along.get(i + 1), normals.get(i), normals.get(i + 1)) else { + return Err(fail("sections")); + }; + // Each rail's anchors at the span's two sections, and where its walk has got to. + let mut spans_of: Vec<(&Rail, &Anchor, &Anchor, (usize, f64))> = Vec::with_capacity(rails.len()); + for r in &rails { + let (Some(a0), Some(a1)) = (r.anchors.get(i), r.anchors.get(i + 1)) else { return Err(fail("rail")) }; + spans_of.push((r, a0, a1, a0.at)); + } + for q in 1..=per { + let f = q as f64 / (per + 1) as f64; + let v = v0 + f * (v1 - v0); + let station = plain(v)?; + let (mid, dir) = middle(v)?; + // The station's plane turns from one section's to the next's. + let normal = n0.lerp(n1, f).normalized().ok_or_else(|| fail("section planes"))?; + let mut pairs = Vec::with_capacity(rails.len()); + for (r, a0, a1, cursor) in &mut spans_of { + let anchor = wire_point(&station, &knots, interpolate_g(a0.g, a1.g, f, n, closed))?; + // Where the rail crosses the station's plane through the point it guides, nudged + // so that at each section it is the section's own point (a rail drawn a hair off + // a section moves nothing there). + let Some((hit, at)) = crate::sweep_path::rail_crossing(&r.pts, anchor, normal, *cursor, tol) else { + return Err(KernelError::Invalid(format!( + "a guide rail turns back between sections {} and {}: it has to run on from one section to the next", + i + 1, + i + 2 + ))); + }; + *cursor = at; + let target = hit + a0.nudge * (1.0 - f) + a1.nudge * f; + pairs.push((anchor, target)); + } + let map = station_map(&pairs, mid, dir, fit, size)?; + let moved: Vec> = station.iter().map(|e| e.iter().map(|p| map.apply(*p)).collect()).collect(); + out.push(wire_of(&moved, &knots, closed)?); + } + } + out.push(wires.last().cloned().ok_or_else(|| fail("sections"))?); + Ok(out) +} + +/// The rail `pts` from its end nearer `start` (the first section's middle), where it meets each +/// section: across the section's plane, on the section's curve within `tol`. +fn rail(pts: &[Vec3], start: Vec3, planes: &[Plane], curves: &[Vec], tol: f64) -> Result { + let mut pts = + crate::sweep_path::clean(pts).map_err(|_| KernelError::Invalid("a guide rail needs 2…100000 finite points along its length".into()))?; + if let (Some(a), Some(b)) = (pts.first(), pts.last()) + && b.dist(start) < a.dist(start) + { + pts.reverse(); + } + let mut cursor = (0usize, 0.0f64); + let mut anchors = Vec::with_capacity(planes.len()); + for (i, (plane, section)) in planes.iter().zip(curves).enumerate() { + let Some((hit, at)) = crate::sweep_path::rail_crossing(&pts, plane.origin, plane.normal(), cursor, tol) else { + return Err(KernelError::Invalid(format!( + "a guide rail does not reach section {}: a rail has to run from the first section to the last, through every one", + i + 1 + ))); + }; + cursor = at; + let (g, on, d) = nearest_on(section, hit).ok_or_else(|| KernelError::Failed("loft rails: section".into()))?; + if d > tol { + return Err(KernelError::Invalid(format!( + "a guide rail crosses section {}'s plane {d:.3} mm from its curves: a rail has to pass through every section", + i + 1 + ))); + } + anchors.push(Anchor { g, on, nudge: on - hit, at }); + } + Ok(Rail { pts, anchors }) +} + +/// The point of a section's wire (its edge curves) nearest `p`: as a wire parameter, the point, +/// and how far it is. +fn nearest_on(section: &[Curve], p: Vec3) -> Option<(f64, Vec3, f64)> { + let mut best: Option<(f64, Vec3, f64)> = None; + for (k, c) in section.iter().enumerate() { + let (t0, t1) = c.range_tuple(); + let t = crate::curveblend::param_on(&mt::Curve::BSplineCurve(c.clone()), p)?; + let q = from_p3(c.subs(t)); + let d = q.dist(p); + if best.as_ref().is_none_or(|b| d < b.2) { + best = Some((k as f64 + (t - t0) / (t1 - t0).max(1e-300), q, d)); + } + } + best +} + +/// A wire parameter `f` of the way from `g0` to `g1`; round a closed wire of `n` edges the +/// shorter way. +fn interpolate_g(g0: f64, g1: f64, f: f64, n: usize, closed: bool) -> f64 { + let n = n as f64; + if !closed { + return (g0 + f * (g1 - g0)).clamp(0.0, n); + } + let mut d = g1 - g0; + if d > n / 2.0 { + d -= n; + } else if d < -n / 2.0 { + d += n; + } + (g0 + f * d).rem_euclid(n) +} + +/// The point at wire parameter `g` of a wire given by its edges' control points on `knots`. +fn wire_point(ctrl: &[Vec], knots: &[mt::KnotVec], g: f64) -> Result { + let n = ctrl.len(); + let k = (g.floor().max(0.0) as usize).min(n.saturating_sub(1)); + let (Some(pts), Some(kv)) = (ctrl.get(k), knots.get(k)) else { return Err(KernelError::Failed("loft rails: wire".into())) }; + let c = edge_curve(kv, pts)?; + let (t0, t1) = c.range_tuple(); + let f = (g - k as f64).clamp(0.0, 1.0); + Ok(from_p3(c.subs(t0 + (t1 - t0) * f))) +} + +/// The middle of a wire's control points. +fn centroid(ctrl: &[Vec]) -> Vec3 { + let (sum, n) = ctrl.iter().flatten().fold((Vec3::ZERO, 0usize), |(s, n), p| (s + *p, n + 1)); + sum * (1.0 / n.max(1) as f64) +} + +/// The move that puts a station's guided points onto the rails (`pairs`: each point with its +/// rail's point), the station's middle `middle`, the loft's direction there `dir` (unit); `size` +/// the loft's size. One rail: turned about `dir` and sized about the middle, shifted along `dir`; +/// two: carried with the first, turned and sized with the line between them, leaning along `dir`. +fn station_map(pairs: &[(Vec3, Vec3)], middle: Vec3, dir: Vec3, fit: RailFit, size: f64) -> Result { + let (from, to, a, r, two) = match pairs { + [(p, q)] => (middle, middle, *p - middle, *q - middle, false), + [(p1, q1), (p2, q2)] => (*p1, *q1, *p2 - *p1, *q2 - *q1, true), + _ => return Err(KernelError::Invalid("a loft takes one or two guide rails".into())), + }; + let flat = |v: Vec3| v - dir * v.dot(dir); + let (ap, rp) = (flat(a), flat(r)); + let tiny = 1e-6 * size.max(1e-9); + let (Some(u0), Some(u1)) = (ap.normalized().filter(|_| ap.len() > tiny), rp.normalized().filter(|_| rp.len() > tiny)) else { + return Err(KernelError::Invalid(if two { + "the two guide rails come together between the sections: the loft would shrink to nothing".into() + } else { + "a guide rail runs through the middle of the loft: it has to guide a point of the sections away from their middle".into() + })); + }; + // Turned about the loft's direction and sized as the sweep's rails size its profile. + let mut m = crate::sweep_path::rail_frame(dir, u0, dir, u1, rp.len() / ap.len(), fit); + // Whatever the rails ask along the loft: one rail shifts the station that far, two lean it, + // in step with the way across. + let lead = (r - a).dot(dir); + if two { + let lean = lead / ap.len(); + for (col, e) in m.iter_mut().zip([Vec3::X, Vec3::Y, Vec3::Z]) { + *col += dir * (lean * e.dot(u0)); + } + } + let shift = if two { Vec3::ZERO } else { dir * lead }; + Ok(Affine { from, to: to + shift, m }) +} + +/// A wire of B-spline edges with these control points on these knots, joined end to end +/// (closing back on its first edge's start when `closed`). +fn wire_of(ctrl: &[Vec], knots: &[mt::KnotVec], closed: bool) -> Result { + let fail = || KernelError::Failed("loft rails: station".into()); + let n = ctrl.len(); + let mut verts: Vec = ctrl.iter().map(|e| e.first().map(|p| mt::Vertex::new(p3(*p)))).collect::>().ok_or_else(fail)?; + if !closed { + verts.push(mt::Vertex::new(p3(*ctrl.last().and_then(|e| e.last()).ok_or_else(fail)?))); + } + let mut edges = Vec::with_capacity(n); + for (i, (pts, kv)) in ctrl.iter().zip(knots).enumerate() { + let (Some(a), Some(b)) = (verts.get(i), verts.get(if closed { (i + 1) % n } else { i + 1 })) else { return Err(fail()) }; + let c = edge_curve(kv, pts)?; + edges.push(mt::Edge::new(a, b, mt::Curve::BSplineCurve(c))); + } + Ok(edges.into()) +} + +/// An edge's B-spline from its control points on its knots. +fn edge_curve(kv: &mt::KnotVec, pts: &[Vec3]) -> Result { + Curve::try_new(kv.clone(), pts.iter().map(|p| p3(*p)).collect()).map_err(|e| KernelError::Failed(format!("loft rails: {e}"))) +} diff --git a/crates/kernel/src/loft_rails_tests.rs b/crates/kernel/src/loft_rails_tests.rs new file mode 100644 index 000000000..4755dfee2 --- /dev/null +++ b/crates/kernel/src/loft_rails_tests.rs @@ -0,0 +1,169 @@ +//! Guide rails on lofts (#201), checked against analytic solids: a rail bulging out from a loft +//! between two equal circles makes the solid of revolution of the rail, a stretching rail widens +//! squares one way only, two rails carry the sections between them, a sheet loft of lines follows +//! its rail; and rails the loft cannot follow are refused. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::f64::consts::PI; + +use solidcraft_geom::{Loop2, Plane, Seg2, Vec2, Vec3}; + +use crate::{KernelError, RailFit, loft, loft_sheet_with_rails, loft_with_rails, measure}; + +fn at(z: f64) -> Plane { + Plane { origin: Vec3::new(0.0, 0.0, z), x: Vec3::X, y: Vec3::Y } +} + +fn circle(r: f64) -> Loop2 { + Loop2::circle(Vec2::ZERO, r) +} + +fn square(h: f64) -> Loop2 { + Loop2::polygon(&[Vec2::new(-h, -h), Vec2::new(h, -h), Vec2::new(h, h), Vec2::new(-h, h)]) +} + +/// The bulge of the rails: 0 at both ends, 1 halfway up the 40 mm loft. +fn bulge(z: f64) -> f64 { + (PI * z / 40.0).sin() +} + +/// A rail in the XZ plane at `x(z)`, from z = 0 to z = 40. +fn rail(x: impl Fn(f64) -> f64) -> Vec { + (0..=80).map(|i| f64::from(i) * 0.5).map(|z| Vec3::new(x(z), 0.0, z)).collect() +} + +fn close(a: f64, b: f64, rel: f64) -> bool { + (a - b).abs() <= rel * b.abs() +} + +/// The body's volume from a fine mesh. +fn volume(b: &crate::Body) -> f64 { + b.volume_at(1e-4).unwrap() +} + +/// How far `p` is from the nearest face of the body. +fn off(b: &crate::Body, p: Vec3) -> f64 { + use truck_modeling::{ParametricSurface, SearchNearestParameter}; + b.solid + .face_iter() + .filter_map(|f| { + let s = f.surface(); + let (u, v) = s.search_nearest_parameter(crate::body::p3(p), None, 100)?; + Some(crate::body::from_p3(s.subs(u, v)).dist(p)) + }) + .fold(f64::INFINITY, f64::min) +} + +/// A rail straight up the side of a loft between equal circles changes nothing: the plain loft +/// (the cylinder, to the accuracy of its fitted circles). +#[test] +fn a_straight_rail_up_a_cylinder_leaves_it_a_cylinder() { + let sections = [(at(0.0), circle(10.0)), (at(40.0), circle(10.0))]; + let b = loft_with_rails(§ions, &[rail(|_| 10.0)], RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + let plain = measure(&loft(§ions).unwrap()).unwrap(); + assert!(close(m.volume, 4000.0 * PI, 1e-3), "volume {} vs {}", m.volume, 4000.0 * PI); + assert!(close(m.volume, plain.volume, 1e-6), "{} vs the plain loft's {}", m.volume, plain.volume); +} + +/// A rail bulging out to radius 15 halfway up turns the loft into the rail's solid of +/// revolution: circles of radius r = 10 + 5 sin(πz/40), volume π∫r² = 4500π + 8000. The sections +/// stay exactly as drawn, and three sections give the same solid. +#[test] +fn a_bulging_rail_makes_the_solid_of_revolution_of_the_rail() { + let want = 4500.0 * PI + 8000.0; + let r = rail(|z| 10.0 + 5.0 * bulge(z)); + for sections in + [vec![(at(0.0), circle(10.0)), (at(40.0), circle(10.0))], vec![(at(0.0), circle(10.0)), (at(20.0), circle(15.0)), (at(40.0), circle(10.0))]] + { + let b = loft_with_rails(§ions, std::slice::from_ref(&r), RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + assert!(close(volume(&b), want, 1e-4), "{} sections: volume {} vs {want}", sections.len(), volume(&b)); + // The loft runs through the rail. + let worst = r.iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "{} sections: the rail is {worst} mm off the loft", sections.len()); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2 && (m.bbox.max.y - 15.0).abs() < 1e-2, "{:?}", m.bbox); + assert!(m.bbox.min.z.abs() < 1e-9 && (m.bbox.max.z - 40.0).abs() < 1e-9, "{:?}", m.bbox); + } + // The sections given the other way round: the same solid. + let flipped = [(at(40.0), circle(10.0)), (at(0.0), circle(10.0))]; + let v = volume(&loft_with_rails(&flipped, &[r], RailFit::Scale).unwrap()); + assert!(close(v, want, 1e-4), "reversed: volume {v} vs {want}"); +} + +/// A rail from the middle of a square's side bulging out by 5: stretching widens the squares +/// only across to the rail (sections 2w × 10 with w = 5 + 5 sin, volume 4000 + 8000/π); scaling +/// grows them both ways (sections (2w)², volume 6000 + 16000/π). +#[test] +fn a_stretching_rail_widens_squares_one_way_and_a_scaling_one_both() { + let sections = [(at(0.0), square(5.0)), (at(40.0), square(5.0))]; + let r = rail(|z| 5.0 + 5.0 * bulge(z)); + let b = loft_with_rails(§ions, std::slice::from_ref(&r), RailFit::Stretch).unwrap(); + let stretched = measure(&b).unwrap(); + let want = 4000.0 + 8000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "stretched: volume {} vs {want}", volume(&b)); + assert!((stretched.bbox.max.x - 10.0).abs() < 1e-2 && (stretched.bbox.max.y - 5.0).abs() < 1e-6, "{:?}", stretched.bbox); + let b = loft_with_rails(§ions, &[r], RailFit::Scale).unwrap(); + let scaled = measure(&b).unwrap(); + let want = 6000.0 + 16000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "scaled: volume {} vs {want}", volume(&b)); + assert!((scaled.bbox.max.y - 10.0).abs() < 1e-2, "{:?}", scaled.bbox); +} + +/// Two rails, one straight up a square's side and one bulging out from the opposite side: the +/// sections run between them, 10 + 5 sin wide. Stretching keeps their depth (volume +/// 4000 + 4000/π); scaling sizes it too (sections (10 + 5 sin)², volume 4500 + 8000/π). +#[test] +fn two_rails_carry_the_sections_between_them() { + let sections = [(at(0.0), square(5.0)), (at(40.0), square(5.0))]; + let rails = [rail(|_| -5.0), rail(|z| 5.0 + 5.0 * bulge(z))]; + let b = loft_with_rails(§ions, &rails, RailFit::Stretch).unwrap(); + let stretched = measure(&b).unwrap(); + let want = 4000.0 + 4000.0 / PI; + assert!(close(volume(&b), want, 1e-4), "stretched: volume {} vs {want}", volume(&b)); + for r in &rails { + let worst = r.iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "a rail is {worst} mm off the loft"); + } + assert!((stretched.bbox.min.x + 5.0).abs() < 1e-6 && (stretched.bbox.max.x - 10.0).abs() < 1e-2, "{:?}", stretched.bbox); + let v = volume(&loft_with_rails(§ions, &rails, RailFit::Scale).unwrap()); + let want = 4500.0 + 8000.0 / PI; + assert!(close(v, want, 1e-4), "scaled: volume {v} vs {want}"); +} + +/// A sheet lofted between two 20 mm lines with a rail from one end bulging out by 5: the lines +/// between grow about their middles, 2(10 + 5 sin) long; area 800 + 800/π. +#[test] +fn a_sheet_loft_of_lines_follows_its_rail() { + let line = vec![Seg2::Line { a: Vec2::new(-10.0, 0.0), b: Vec2::new(10.0, 0.0) }]; + let sections = [(at(0.0), line.clone()), (at(40.0), line)]; + let b = loft_sheet_with_rails(§ions, &[rail(|z| 10.0 + 5.0 * bulge(z))], RailFit::Scale).unwrap(); + let m = measure(&b).unwrap(); + let want = 800.0 + 800.0 / PI; + let worst = rail(|z| 10.0 + 5.0 * bulge(z)).iter().map(|p| off(&b, *p)).fold(0.0, f64::max); + assert!(worst < 1e-3, "the rail is {worst} mm off the sheet"); + assert!(close(m.area, want, 1e-3), "area {} vs {want}", m.area); + assert!((m.bbox.max.x - 15.0).abs() < 1e-2 && (m.bbox.min.x + 15.0).abs() < 1e-2, "{:?}", m.bbox); +} + +/// Rails the loft cannot follow are refused, saying why: one that starts off the first section, +/// one that stops short of the last, three rails, and one up the middle of a sheet loft's lines. +#[test] +fn rails_the_loft_cannot_follow_are_refused() { + let sections = [(at(0.0), circle(10.0)), (at(40.0), circle(10.0))]; + let refused = |rails: &[Vec]| match loft_with_rails(§ions, rails, RailFit::Scale) { + Err(KernelError::Invalid(m)) => m, + other => panic!("{other:?}"), + }; + assert!(refused(&[rail(|_| 12.0)]).contains("section 1"), "{}", refused(&[rail(|_| 12.0)])); + let short: Vec = rail(|_| 10.0).into_iter().filter(|p| p.z <= 30.0).collect(); + let m = refused(&[short]); + assert!(m.contains("does not reach section 2"), "{m}"); + assert!(refused(&[rail(|_| 10.0), rail(|_| -10.0), rail(|_| 10.0)]).contains("one or two")); + let line = vec![Seg2::Line { a: Vec2::new(-10.0, 0.0), b: Vec2::new(10.0, 0.0) }]; + match loft_sheet_with_rails(&[(at(0.0), line.clone()), (at(40.0), line)], &[rail(|_| 0.0)], RailFit::Scale) { + Err(KernelError::Invalid(m)) => assert!(m.contains("middle"), "{m}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/kernel/src/surfaces.rs b/crates/kernel/src/surfaces.rs index e625b775f..f47fd0d0d 100644 --- a/crates/kernel/src/surfaces.rs +++ b/crates/kernel/src/surfaces.rs @@ -324,6 +324,13 @@ fn far_wire(swept: &mt::Shell, start: &mt::Wire, map: &dyn Fn(Vec3) -> Vec3) -> /// split to the same number of segments (longest first) and each turned to run the way the one /// before it does. Walls only, no caps; the history has no operands: every face is new. pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { + loft_sheet_with_rails(sections, &[], crate::RailFit::Scale) +} + +/// [`loft_sheet`] following one or two guide rails (polylines from the first section to the last, +/// through every section's curve; see [`crate::loft_rails`]), `fit` saying how they reshape the +/// sections between. Without rails, the plain sheet loft. +pub fn loft_sheet_with_rails(sections: &[(Plane, Vec)], rails: &[Vec], fit: crate::RailFit) -> Result { if sections.len() < 2 || sections.len() > 50 { return Err(KernelError::Invalid("a loft needs 2…50 sections".into())); } @@ -345,10 +352,9 @@ pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { } crate::build::chain_wire(plane, chain)?; } - let (wires, sources) = if all_closed { + let (wires, sources, reversed) = if all_closed { let loops: Vec<(Plane, solidcraft_geom::Loop2)> = sections.iter().map(|(p, c)| (*p, solidcraft_geom::Loop2 { segs: c.clone() })).collect(); - let (wires, sources, _) = crate::build::loft_wires(&loops)?; - (wires, sources) + crate::build::loft_wires(&loops)? } else { let n = sections.iter().map(|(_, c)| c.len()).max().unwrap_or(0); let mut wires = Vec::with_capacity(sections.len()); @@ -378,13 +384,21 @@ pub fn loft_sheet(sections: &[(Plane, Vec)]) -> Result { wires.push(crate::build::uniform_chain_wire(plane, &pieces, false)?); sources.push(segs.iter().map(|(_, k)| vec![*k]).collect::>()); } - (wires, sources) + (wires, sources, false) }; + let mut planes: Vec = sections.iter().map(|(p, _)| *p).collect(); + if reversed { + planes.reverse(); + } let faces = guard("surface loft", || { - let smooth = if wires.len() >= 3 { crate::build::smooth_loft_faces(&wires, &sources, all_closed).ok() } else { None }; + let all = crate::loft_rails::railed_wires(&planes, &wires, all_closed, rails, fit)?; + // A plain loft falls back to ruled faces where the smooth one fails; a railed one has to + // follow its rails. + let smooth = if all.len() >= 3 { Some(crate::build::smooth_loft_faces(&all, &sources, all_closed)) } else { None }; match smooth { - Some(f) => Ok(f), - None => crate::build::ruled_loft_faces(&wires, &sources), + Some(Ok(f)) => Ok(f), + Some(Err(e)) if !rails.is_empty() => Err(e), + _ => crate::build::ruled_loft_faces(&wires, &sources), } })?; sheet_body(faces) diff --git a/crates/kernel/src/sweep_path.rs b/crates/kernel/src/sweep_path.rs index f2e9292fb..08fb3a95b 100644 --- a/crates/kernel/src/sweep_path.rs +++ b/crates/kernel/src/sweep_path.rs @@ -152,7 +152,7 @@ impl Station { } } -fn clean(path: &[Vec3]) -> Result> { +pub(crate) fn clean(path: &[Vec3]) -> Result> { if path.len() < 2 || path.len() > MAX_PATH_POINTS { return Err(KernelError::Invalid("a sweep path needs 2…100000 points".into())); } @@ -365,7 +365,7 @@ fn controlled_stations(plane: &Plane, pts: &[Vec3], tangents: &[Vec3], mitre: &[ /// after `from` (segment index and fraction along it), with the position it was found at, so a /// walk along the path finds each rail point after the last. Within `tol` of the plane a rail's /// first and last points count as on it (a rail drawn to end where the path ends). -fn rail_crossing(rail: &[Vec3], p: Vec3, t: Vec3, from: (usize, f64), tol: f64) -> Option<(Vec3, (usize, f64))> { +pub(crate) fn rail_crossing(rail: &[Vec3], p: Vec3, t: Vec3, from: (usize, f64), tol: f64) -> Option<(Vec3, (usize, f64))> { let f = |q: Vec3| (q - p).dot(t); let (k0, u0) = from; if k0 == 0 && u0 == 0.0 && rail.first().is_some_and(|q| f(*q).abs() <= tol) { @@ -437,10 +437,7 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> "the two guide rails start at the same point".into() })); } - let (u0, w0) = { - let u = d0.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; - (u, t0.cross(u)) - }; + let u0 = d0.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; let mut out = Vec::with_capacity(pts.len()); for ((anchor, d), t) in across.iter().zip(tangents) { if near(*d) { @@ -450,17 +447,8 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> format!("the guide rails meet near ({:.3}, {:.3}, {:.3}): the profile would shrink to nothing", anchor.x, anchor.y, anchor.z) })); } - let k = d.len() / d0.len(); - let k_other = match ctl.rail_fit { - RailFit::Scale => k, - RailFit::Stretch => 1.0, - }; let u = d.normalized().ok_or_else(|| KernelError::Invalid("guide rail".into()))?; - let w = t.cross(u); - // Along the path stays along it; across to the rail turns onto the rail and sizes with - // it; the third way follows, scaled evenly or kept. - let map = |v: Vec3| *t * v.dot(t0) + u * (k * v.dot(u0)) + w * (k_other * v.dot(w0)); - let m = [map(Vec3::X), map(Vec3::Y), map(Vec3::Z)]; + let m = rail_frame(t0, u0, *t, u, d.len() / d0.len(), ctl.rail_fit); let st = Station { at: Vec3::default(), m }; // The anchor's start position lands on the anchor. out.push(Station { at: *anchor - st.apply(a0 - s0), m }); @@ -468,6 +456,20 @@ fn railed_stations(pts: &[Vec3], tangents: &[Vec3], mitre: &[Option<(Vec3, f64)> Ok(out) } +/// How guide rails turn and size a section (by columns): the way `along` (unit) turns onto +/// `along_to`, the way across to the rail `across` (unit, square to `along`) turns onto +/// `across_to` and sizes by `k`; the third way follows, sized by `k` as well ([`RailFit::Scale`]) +/// or kept ([`RailFit::Stretch`]). A sweep's stations and a loft's share it. +pub(crate) fn rail_frame(along: Vec3, across: Vec3, along_to: Vec3, across_to: Vec3, k: f64, fit: RailFit) -> [Vec3; 3] { + let k_other = match fit { + RailFit::Scale => k, + RailFit::Stretch => 1.0, + }; + let (w0, w1) = (along.cross(across), along_to.cross(across_to)); + let map = |v: Vec3| along_to * v.dot(along) + across_to * (k * v.dot(across)) + w1 * (k_other * v.dot(w0)); + [map(Vec3::X), map(Vec3::Y), map(Vec3::Z)] +} + /// The volume a profile of `area` on `plane` sweeps through the stations: each station's /// section area times how squarely the path crosses it, summed along the path (trapezoids). fn swept_volume(plane: &Plane, area: f64, st: &[Station], tangents: &[Vec3]) -> f64 { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 87538992e..532279f4e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -158,9 +158,11 @@ pub enum Kind { count: String, angle: String, }, - /// Loft through profiles of different sketches, in pick order. + /// Loft through profiles of different sketches, in pick order; `rail_fit` how its guide + /// rails reshape the sections (an index into the sweep dialog's rail fits). Loft { operation: usize, + rail_fit: usize, }, /// Sweep a profile along a path of sketch curves. Sweep { @@ -644,7 +646,10 @@ impl Dialog { Kind::PatternCirc { count: "6".into(), angle: "360 deg".into() }, vec![SelInput::new("Objects", BODIES, true), SelInput::new("Axis", AXES, false)], ), - "solid.loft" => Dialog::new(Kind::Loft { operation: usize::from(has_bodies) }, vec![SelInput::new("Profiles", PROFILES, true)]), + "solid.loft" => Dialog::new(Kind::Loft { operation: usize::from(has_bodies), rail_fit: 0 }, { + let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); + vec![SelInput::new("Profiles", PROFILES, true), rail, rail2] + }), "solid.sweep" => Dialog::new(Kind::Sweep { operation: usize::from(has_bodies), opts: crate::dialogs_sweep::SweepOpts::default() }, { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); vec![ @@ -2993,7 +2998,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { feature_pattern_alignment_row(ui, &mut d.extra, 0); } } - Kind::Loft { operation } => { + Kind::Loft { operation, rail_fit } => { + crate::dialogs_sweep::rail_fit_row(ui, "lf", rail_fit); row_label(ui, "Operation"); combo(ui, "lf_op", &OP_LABELS, operation); ui.end_row(); @@ -4086,7 +4092,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S pattern_objects(s, sels(d, 0), &mut p); ("solid.pattern.circular", p) } - Kind::Loft { operation } => { + Kind::Loft { operation, rail_fit } => { need(0, "profiles of two or more sketches")?; // One section per sketch, in the order the sketches were first picked. let mut sections: Vec<(u64, Vec)> = Vec::new(); @@ -4102,7 +4108,9 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S return Err("pick profiles in two or more sketches".into()); } let sections: Vec = sections.into_iter().map(|(sk, v)| json!({"sketch": sk, "profiles": v})).collect(); - ("solid.loft", json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")})) + let mut p = json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")}); + crate::dialogs_sweep::rail_params(app, *rail_fit, [sels(d, 1), sels(d, 2)], &mut p)?; + ("solid.loft", p) } Kind::Sweep { operation, opts } => { need(0, "a profile")?; @@ -5344,9 +5352,12 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option { + FeatureKind::Loft { sections, operation, targets, rails, rail_fit } => { let mut d = start("solid.loft")?; - d.kind = Kind::Loft { operation: op_index(operation) }; + d.kind = Kind::Loft { operation: op_index(operation), rail_fit: crate::dialogs_sweep::rail_fit_index(*rail_fit) }; + for (inp, items) in d.inputs.iter_mut().skip(1).zip(crate::dialogs_sweep::rail_sels(rails)) { + inp.items = items; + } if let Some(inp) = d.inputs.first_mut() { inp.items = sections .iter() diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index 397ce0fa8..36a23f96c 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -27,7 +27,11 @@ pub enum Surf { axis: Option, }, Sweep(crate::dialogs_sweep::SweepOpts), - Loft, + /// `rail_fit`: how the guide rails reshape the sections (an index into the sweep dialog's + /// rail fits). + Loft { + rail_fit: usize, + }, /// `continuity`: an index into [`PATCH_CONTINUITY`] (for a loop of sketch curves, how much of /// the sketch's plane each side repeats; for picked edges, how the surface meets the faces /// beside them); `join`: sew the surface into the body of its edges. @@ -86,7 +90,7 @@ impl Surf { Surf::Extrude { .. } => "SURFACE EXTRUDE", Surf::Revolve { .. } => "SURFACE REVOLVE", Surf::Sweep(_) => "SURFACE SWEEP", - Surf::Loft => "SURFACE LOFT", + Surf::Loft { .. } => "SURFACE LOFT", Surf::Boundary { .. } => "BOUNDARY SURFACE", Surf::Patch { .. } => "PATCH", Surf::Unstitch => "UNSTITCH", @@ -144,7 +148,10 @@ fn inputs(k: &Surf) -> Vec { rail2, ] } - Surf::Loft => vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true)], + Surf::Loft { .. } => { + let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); + vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true), rail, rail2] + } Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)], Surf::Patch { .. } => vec![SelInput::new("Boundary", PROFILES | EDGES, true), SelInput::new("Pass through", VERTICES | FACES, true)], Surf::Unstitch => vec![SelInput::new("Body, or faces to take out", BODIES | FACES, true)], @@ -174,7 +181,7 @@ pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "surface.extrude" => Surf::Extrude { distance: "10 mm".into(), direction: 0 }, "surface.revolve" => Surf::Revolve { angle: "360 deg".into(), symmetric: false, axis: None }, "surface.sweep" => Surf::Sweep(crate::dialogs_sweep::SweepOpts::default()), - "surface.loft" => Surf::Loft, + "surface.loft" => Surf::Loft { rail_fit: 0 }, "surface.boundary" => Surf::Boundary { continuity: 1, join: false }, "surface.patch" => Surf::Patch { continuity: 0 }, "surface.unstitch" => Surf::Unstitch, @@ -304,7 +311,8 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool { ui.end_row(); } Surf::Sweep(opts) => enter |= crate::dialogs_sweep::rows(ui, opts, "ss"), - Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal | Surf::Loft => {} + Surf::Loft { rail_fit } => crate::dialogs_sweep::rail_fit_row(ui, "sl", rail_fit), + Surf::SplitFace | Surf::Unstitch | Surf::ReverseNormal => {} } enter } @@ -510,7 +518,7 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { + Surf::Loft { rail_fit } => { need(0, "the sections, one sketch each")?; // One section per sketch, in the order the sketches were first picked. let st = app.session.world_state(); @@ -536,7 +544,9 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map>()?; - ("surface.loft", json!({ "sections": sections })) + let mut p = json!({ "sections": sections }); + crate::dialogs_sweep::rail_params(app, *rail_fit, [items(inputs, 1), items(inputs, 2)], &mut p)?; + ("surface.loft", p) } Surf::Boundary { continuity, join } => { need(0, "the curves (sketch curves or edges)")?; @@ -876,8 +886,10 @@ pub fn for_feature(app: &SolveApp, kind: &FeatureKind, frame: &Mat) -> Option<(K let index = PATCH_CONTINUITY.iter().position(|(_, w)| *w == g.as_str()).unwrap_or(0); (Surf::Boundary { continuity: index, join: *operation == solidcraft_engine::doc::Operation::Join }, vec![sels(u), sels(v)]) } - FeatureKind::SurfaceLoft { sections, .. } => { - (Surf::Loft, vec![sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect()]) + FeatureKind::SurfaceLoft { sections, rails, rail_fit, .. } => { + let [rail, rail2] = crate::dialogs_sweep::rail_sels(rails); + let picked = sections.iter().flat_map(|sec| sheet_sels(app, sec.sketch.0, sec.profiles.as_ref(), &sec.curves)).collect(); + (Surf::Loft { rail_fit: crate::dialogs_sweep::rail_fit_index(*rail_fit) }, vec![picked, rail, rail2]) } FeatureKind::SurfaceExtrude { sketch, profiles, curves, extent } => { let sels = sheet_sels(app, sketch.0, profiles.as_ref(), curves); diff --git a/crates/ui-egui/src/dialogs_sweep.rs b/crates/ui-egui/src/dialogs_sweep.rs index cc3a716e7..7528e0588 100644 --- a/crates/ui-egui/src/dialogs_sweep.rs +++ b/crates/ui-egui/src/dialogs_sweep.rs @@ -1,6 +1,6 @@ //! The options Sweep and Surface Sweep share (#771): how the profile turns along the path, a //! twist over the path's length, the profile's scale at the end, and guide rails with how they -//! reshape the profile. +//! reshape the profile. Loft and Surface Loft take the same guide rails (#201). use serde_json::{Value, json}; use solidcraft_engine::Sel; @@ -55,7 +55,7 @@ impl SweepOpts { let mut o = SweepOpts { twist: twist.as_ref().map_or_else(|| NO_TWIST.into(), |t| t.to_string()), scale: scale.as_ref().map_or_else(|| NO_SCALE.into(), |k| k.to_string()), - rail_fit: usize::from(rail_fit == RailFit::Stretch), + rail_fit: rail_fit_index(rail_fit), ..SweepOpts::default() }; let mut pick = None; @@ -110,17 +110,25 @@ pub fn rows(ui: &mut egui::Ui, o: &mut SweepOpts, id: &str) -> bool { row_label(ui, "End Scale"); enter |= field(ui, &mut o.scale); ui.end_row(); - row_label(ui, "Rail Fit"); - combo(ui, &format!("{id}_rail_fit"), &RAIL_FITS, &mut o.rail_fit); - ui.end_row(); + rail_fit_row(ui, id, &mut o.rail_fit); enter } -/// The options as command parameters, added to `p`: the orientation, and the twist and end -/// scale when they change anything; with rails picked, the rails (each in the sketch its curves -/// are in) and the fit instead. `picked` is the direction input's selection, `rails` the rail -/// inputs'. -pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel]; 2], p: &mut Value) -> Result<(), String> { +/// The Rail Fit row: `fit` an index into [`RAIL_FITS`]. +pub fn rail_fit_row(ui: &mut egui::Ui, id: &str, fit: &mut usize) { + row_label(ui, "Rail Fit"); + combo(ui, &format!("{id}_rail_fit"), &RAIL_FITS, fit); + ui.end_row(); +} + +/// A stored rail fit as an index into [`RAIL_FITS`]. +pub fn rail_fit_index(fit: RailFit) -> usize { + usize::from(fit == RailFit::Stretch) +} + +/// The picked rails (each in the sketch its curves are in) and the fit (`fit`, an index into +/// [`RAIL_FITS`]), added to `p`; whether any rail was picked. +pub fn rail_params(app: &SolveApp, fit: usize, rails: [&[Sel]; 2], p: &mut Value) -> Result { let mut given = Vec::new(); for sels in rails { let curves: Vec = sels.iter().filter_map(|x| if let Sel::SketchCurve { id } = x { Some(id.clone()) } else { None }).collect(); @@ -130,12 +138,23 @@ pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel let sketch = crate::dialogs::curves_sketch(app, &curves, None).ok_or("each rail's curves must be in one sketch")?; given.push(json!({"sketch": sketch, "curves": curves})); } - if !given.is_empty() { - // Rails set the profile's turn and size: the other options don't apply. - p["rails"] = json!(given); - if o.rail_fit == 1 { - p["rail_fit"] = json!("stretch"); - } + if given.is_empty() { + return Ok(false); + } + p["rails"] = json!(given); + if fit == 1 { + p["rail_fit"] = json!("stretch"); + } + Ok(true) +} + +/// The options as command parameters, added to `p`: the orientation, and the twist and end +/// scale when they change anything; with rails picked, the rails (each in the sketch its curves +/// are in) and the fit instead. `picked` is the direction input's selection, `rails` the rail +/// inputs'. +pub fn params(app: &SolveApp, o: &SweepOpts, picked: Option<&Sel>, rails: [&[Sel]; 2], p: &mut Value) -> Result<(), String> { + // Rails set the profile's turn and size: the other options don't apply. + if rail_params(app, o.rail_fit, rails, p)? { return Ok(()); } match o.orientation { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 799369a19..595a674c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -72,6 +72,8 @@ pub mod issue_report; pub mod joint_drag; pub mod keymap; mod linked_source; +#[cfg(test)] +mod loft_rails_dialog_tests; mod material_card_review; #[cfg(test)] mod measurement_ui_tests; diff --git a/crates/ui-egui/src/loft_rails_dialog_tests.rs b/crates/ui-egui/src/loft_rails_dialog_tests.rs new file mode 100644 index 000000000..03076e087 --- /dev/null +++ b/crates/ui-egui/src/loft_rails_dialog_tests.rs @@ -0,0 +1,85 @@ +//! The Loft and Surface Loft dialogs' guide rails (#201): rails picked in the dialog reach the +//! commands with their sketches and the fit, and editing the loft brings them back and keeps them. +use crate::dialogs::Kind; +use crate::dialogs_surface::Surf; +use crate::scenario::Harness; +use serde_json::json; +use solidcraft_engine::Sel; +use solidcraft_engine::doc::{FeatureKind, RailFit, SketchId, SweepRail}; + +/// Circles `Base` (z = 0) and `Top` (z = 40) and in `R` on XZ a rail `out` from (10, 0, 0) out to +/// x = 15 halfway and back to (10, 0, 40); the circles' and the rail's sketch ids. +fn setup(h: &mut Harness) -> (u64, u64, u64) { + for (name, z) in [("Base", 0), ("Top", 40)] { + h.app.run("sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})).unwrap(); + h.app.run("sketch.circle.center", json!({"center": [0, 0], "radius": 10})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.app.run("sketch.create", json!({"plane": "XZ", "name": "R"})).unwrap(); + h.app.run("sketch.arc.three_point", json!({"start": [10, 0], "end": [10, -40], "through": [15, -20], "id": "out"})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + let id = |h: &Harness, n: &str| h.app.session.doc.find_feature(n).unwrap().id; + (id(h, "Base"), id(h, "Top"), id(h, "R")) +} + +fn ok(h: &mut Harness) { + h.frames(2); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?} {:?}", h.app.dialog.as_ref().map(|d| &d.error), h.app.session.log); +} + +#[test] +fn a_rail_picked_in_the_loft_dialog_is_kept_through_an_edit() { + let mut h = Harness::new(); + let (base, top, rail_sketch) = setup(&mut h); + h.step(&json!({"call":"ui.start","params":{"command":"solid.loft"}})).unwrap(); + h.frames(3); + assert!(h.widget("Rail").is_some() && h.widget("Rail Fit").is_some()); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: base, index: 0 }, Sel::Profile { sketch: top, index: 0 }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "out".into() }]; + let Kind::Loft { rail_fit, .. } = &mut d.kind else { panic!("{:?}", d.kind) }; + *rail_fit = 1; + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + let rails = |h: &Harness| match &h.app.session.doc.find_feature(&name).unwrap().kind { + FeatureKind::Loft { rails, rail_fit, .. } => (rails.clone(), *rail_fit), + k => panic!("{k:?}"), + }; + let (stored, fit) = rails(&h); + assert_eq!(stored, vec![SweepRail { sketch: SketchId(rail_sketch), curves: vec!["out".into()] }]); + assert_eq!(fit, RailFit::Stretch); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let d = h.app.dialog.as_ref().unwrap(); + assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "out".into() }]); + assert!(matches!(d.kind, Kind::Loft { rail_fit: 1, .. }), "{:?}", d.kind); + ok(&mut h); + assert_eq!(rails(&h), (stored, fit)); +} + +#[test] +fn a_rail_picked_in_the_surface_loft_dialog_is_kept_through_an_edit() { + let mut h = Harness::new(); + let (base, top, rail_sketch) = setup(&mut h); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + assert!(h.widget("Rail").is_some() && h.widget("Rail Fit").is_some()); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: base, index: 0 }, Sel::Profile { sketch: top, index: 0 }]; + d.inputs[1].items = vec![Sel::SketchCurve { id: "out".into() }]; + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + let rails = |h: &Harness| match &h.app.session.doc.find_feature(&name).unwrap().kind { + FeatureKind::SurfaceLoft { rails, rail_fit, .. } => (rails.clone(), *rail_fit), + k => panic!("{k:?}"), + }; + assert_eq!(rails(&h), (vec![SweepRail { sketch: SketchId(rail_sketch), curves: vec!["out".into()] }], RailFit::Scale)); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let d = h.app.dialog.as_ref().unwrap(); + assert!(matches!(d.kind, Kind::Surface(Surf::Loft { rail_fit: 0 })), "{:?}", d.kind); + assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: "out".into() }]); + ok(&mut h); + assert_eq!(rails(&h).0.len(), 1); +}