diff --git a/crates/engine/src/cmd/hatch.rs b/crates/engine/src/cmd/hatch.rs index a362a3502..2402823a6 100644 --- a/crates/engine/src/cmd/hatch.rs +++ b/crates/engine/src/cmd/hatch.rs @@ -1,4 +1,5 @@ //! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects. +//! HATCHGENERATEBOUNDARY: polylines around existing hatches. mod patfile; pub use patfile::{PatternChoice, pattern_choices}; @@ -10,6 +11,7 @@ use cadcraft_geom::{Bounds2, PolyVertex, Polyline, Vec2, point_in_polygon}; use serde_json::{Value, json}; use super::helpers::lwpoly; +use super::machines::SelectRun; use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_param, str_param, targets}; use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step}; @@ -29,6 +31,9 @@ pub fn specs() -> Vec { CommandSpec::new("boundary", "Boundary...", run_boundary).menu(&["Draw", "Boundary..."]).alias(&["bo", "bpoly"]).params("{points: [[x,y]]}").interactive(|_| Ok(Box::new(BoundaryM { region: false }))), CommandSpec::new("region", "Region", run_region).menu(&["Draw", "Region"]).alias(&["reg"]).params("{handles?}"), CommandSpec::new("hatchedit", "Hatch Edit", edit::run_hatchedit).menu(&["Modify", "Object", "Hatch..."]).alias(&["he", "-hatchedit"]).params("{handles?, pattern?, scale?, angle?, gradient?: {name?, color1?, color2?, angle? (degrees), centered?} (makes or changes a gradient fill; `pattern` turns it back), associative?: bool (false unlinks; true links each loop to a closed object of the same shape, or to `boundary` objects), boundary?: [hex], addPoints?: [[x,y]], addBoundary?: [hex], removeLoops?: [zero-based index] (geometry edits require one hatch), style?, origin? | originMode?, separate?: true, recreate?: \"polyline\"|\"region\", associate?: bool (link to the recreated boundary)}").interactive(|s| Ok(Box::new(edit::HatchEditM::new(s)))), + CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary) + .params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles") + .interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))), CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick) .params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing") .enabled(has_doc) diff --git a/crates/engine/src/cmd/hatch/edit.rs b/crates/engine/src/cmd/hatch/edit.rs index c0f5c7440..49ddaf3b2 100644 --- a/crates/engine/src/cmd/hatch/edit.rs +++ b/crates/engine/src/cmd/hatch/edit.rs @@ -20,15 +20,49 @@ const MAX_EDITED: usize = 10_000; const MAX_LOOPS: usize = 2000; fn hatches(s: &Session, p: &Value) -> Result> { + hatches_for(s, p, "hatchedit") +} + +/// The hatches among the targets of command `cmd` (an error names `cmd` when there are none). +fn hatches_for(s: &Session, p: &Value, cmd: &str) -> Result> { let hs = targets(s, p)?; let d = s.doc()?; let out: Vec = hs.into_iter().filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(_)))).take(MAX_EDITED).collect(); if out.is_empty() { - return Err(bad("hatchedit", "select one or more hatches")); + return Err(bad(cmd, "select one or more hatches")); } Ok(out) } +/// Most polylines one HATCHGENERATEBOUNDARY call creates. +const MAX_GENERATED: usize = 10_000; + +/// HATCHGENERATEBOUNDARY: a closed polyline around every boundary loop (outer and islands) of +/// the selected hatches. The hatches are not changed: an associative hatch stays linked to its +/// own boundary objects and is not linked to the new polylines. +pub(super) fn run_hatchgenerateboundary(s: &mut Session, p: &Value) -> Result { + let hs = hatches_for(s, p, "hatchgenerateboundary")?; + let mut loops = Vec::new(); + { + let d = s.doc()?; + for h in &hs { + if let Some(EntityKind::Hatch(x)) = d.entity(*h).map(|e| &e.kind) { + loops.extend(x.loops.iter().map(|l| l.vertices.clone())); + } + } + } + // Refused before anything is added, so a refused call leaves no partial result behind. + if loops.len() > MAX_GENERATED { + return Err(bad("hatchgenerateboundary", format!("more than {MAX_GENERATED} boundary polylines in one call; select fewer hatches"))); + } + let mut created = Vec::new(); + for vs in loops { + created.push(s.add_entity(lwpoly(vs, true))?.hex()); + } + let n = created.len(); + Ok(json!({ "handles": created, "message": format!("{n} boundary polyline(s) created.") })) +} + fn outline(l: &HatchLoop) -> Vec { Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(1e-3) } diff --git a/crates/engine/tests/it/hatch_generate_boundary.rs b/crates/engine/tests/it/hatch_generate_boundary.rs new file mode 100644 index 000000000..030f35031 --- /dev/null +++ b/crates/engine/tests/it/hatch_generate_boundary.rs @@ -0,0 +1,124 @@ +//! HATCHGENERATEBOUNDARY (#2801): closed polylines around existing hatches, which stay as they are. + +use cadcraft_engine::doc::{EntityKind, Handle, Hatch, LwPolyline}; +use cadcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +fn hatch(s: &Session, h: &str) -> Hatch { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::Hatch(x) => x.clone(), + k => panic!("not a hatch: {k:?}"), + } +} + +fn poly(s: &Session, h: &str) -> LwPolyline { + match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind { + EntityKind::LwPolyline(p) => p.clone(), + k => panic!("not a polyline: {k:?}"), + } +} + +fn handle(v: &Value) -> String { + v["handle"].as_str().unwrap().to_string() +} + +fn handles(v: &Value) -> Vec { + v["handles"].as_array().unwrap().iter().map(|h| h.as_str().unwrap().to_string()).collect() +} + +fn rect(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> String { + handle(&s.execute("rectang", &json!({ "p1": a, "p2": b })).unwrap()) +} + +fn count(s: &Session) -> usize { + s.doc().unwrap().model.iter().count() +} + +#[test] +fn generates_a_closed_polyline_around_a_hatch_without_its_outline() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()] })).unwrap()); + s.execute("erase", &json!({ "handles": [r] })).unwrap(); + let before = hatch(&s, &h); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap(); + let new = handles(&v); + assert_eq!(new.len(), 1); + let p = poly(&s, &new[0]); + assert!(p.closed); + assert_eq!(p.vertices, before.loops[0].vertices); + assert_eq!(hatch(&s, &h), before, "the hatch is not changed"); + s.execute("undo", &json!({})).unwrap(); + assert_eq!(count(&s), 1, "one undo step removes what was generated"); +} + +#[test] +fn islands_get_their_own_polylines() { + let mut s = Session::new(); + rect(&mut s, [0.0, 0.0], [20.0, 20.0]); + rect(&mut s, [5.0, 5.0], [10.0, 10.0]); + let h = handle(&s.execute("hatch", &json!({ "points": [[2, 2]] })).unwrap()); + assert_eq!(hatch(&s, &h).loops.len(), 2); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h] })).unwrap(); + assert_eq!(handles(&v).len(), 2); +} + +#[test] +fn every_selected_hatch_gets_its_boundary() { + let mut s = Session::new(); + let a = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let b = rect(&mut s, [10.0, 0.0], [14.0, 2.0]); + let ha = handle(&s.execute("hatch", &json!({ "handles": [a] })).unwrap()); + let hb = handle(&s.execute("hatch", &json!({ "handles": [b] })).unwrap()); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [ha, hb] })).unwrap(); + assert_eq!(handles(&v).len(), 2); +} + +#[test] +fn an_associative_hatch_stays_linked_to_its_own_boundary() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r.clone()], "associative": true })).unwrap()); + let v = s.execute("hatchgenerateboundary", &json!({ "handles": [h.clone()] })).unwrap(); + let p = handles(&v)[0].clone(); + // Moving the generated polyline leaves the hatch where it is. + s.execute("move", &json!({ "handles": [p], "delta": [0, 10] })).unwrap(); + assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.y, 0.0); + // Moving the original rectangle still moves the hatch. + s.execute("move", &json!({ "handles": [r], "delta": [10, 0] })).unwrap(); + assert!(hatch(&s, &h).associative); + assert_eq!(hatch(&s, &h).loops[0].vertices[0].p.x, 10.0); +} + +#[test] +fn needs_a_hatch() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + assert!(s.execute("hatchgenerateboundary", &json!({ "handles": [r] })).is_err()); + assert_eq!(count(&s), 1, "nothing is added"); +} + +#[test] +fn runs_at_once_on_selected_hatches() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.set_selection(vec![Handle::parse_hex(&h).unwrap()]); + s.start("hatchgenerateboundary").unwrap(); + assert!(s.current_prompt().is_none(), "a pickfirst selection needs no prompt"); + assert_eq!(count(&s), 3); +} + +#[test] +fn asks_for_hatches_without_a_selection() { + let mut s = Session::new(); + let r = rect(&mut s, [0.0, 0.0], [4.0, 2.0]); + let h = handle(&s.execute("hatch", &json!({ "handles": [r] })).unwrap()); + s.set_selection(Vec::new()); + s.start("hatchgenerateboundary").unwrap(); + assert!(s.current_prompt().is_some()); + s.input(Input::Pick(vec![Handle::parse_hex(&h).unwrap()])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.current_prompt().is_none()); + assert_eq!(count(&s), 3); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3a1537bee..694633f92 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -58,6 +58,7 @@ mod group_selection; mod groups; mod hatch_assoc; mod hatch_dialog_helpers; +mod hatch_generate_boundary; mod hatch_numeric_validation; mod hatch_options; mod helix; diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index bbaf48df3..e93f91494 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -122,8 +122,8 @@ pub fn entries(app: &CadApp) -> Vec> { } /// The edit commands of the selected objects' type (when they are all of one type), with their -/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit, -/// Polyline Edit, Spline Edit… +/// labels: Edit Text for text, Block Editor and Edit Attributes for block references, Hatch Edit +/// and Generate Boundary for hatches, Polyline Edit, Spline Edit… fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { let Ok(d) = app.session.doc() else { return Vec::new() }; let sel = app.session.selection(); @@ -142,7 +142,7 @@ fn object_commands(app: &CadApp) -> Vec<(&'static str, Option<&'static str>)> { } v } - EntityKind::Hatch(_) => vec![("hatchedit", None)], + EntityKind::Hatch(_) => vec![("hatchedit", None), ("hatchgenerateboundary", None)], EntityKind::LwPolyline(_) | EntityKind::Polyline3d(_) => vec![("pedit", Some("Polyline Edit"))], EntityKind::Spline(_) => vec![("splinedit", Some("Spline Edit"))], EntityKind::Dimension(_) => vec![("dimtedit", None)], diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0e6471ee..b2d44f309 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -372,6 +372,7 @@ From Desde From Template... Desde plantilla... General General + Generate Boundary Generar contorno Geometric Center Centro geométrico Geometric Constraint Restricción geométrica Geometric Constraints Restricciones geométricas diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index a07b4f027..ed4b9c6b4 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -294,6 +294,7 @@ Freeze/Thaw in the current viewport 在当前视口中冻结/解冻 From 自 General 常规 + Generate Boundary 生成边界 Geometric Center 几何中心 Geometric Constraint 几何约束 Geometric Constraints 几何约束