From 9f833f3d16dee22e32f552500a772fbaf5e1ec9d Mon Sep 17 00:00:00 2001 From: SBaksa Date: Sun, 18 Oct 2026 12:46:06 +1100 Subject: [PATCH] UCS: ortho, snap, grid, polar and object snap tracking, and DIMLINEAR follow the current UCS (part of #1106) The drafting aids worked along the world axes whatever the UCS; now they work along the current UCS's. - Ortho (and direct distance entry with it, and TK tracking) along the UCS axes; the isometric axes turn with the UCS. Settings::ucs_angle, filled in by drafting_settings(), carries the UCS rotation. - Grid and grid snap in the UCS: SNAPBASE is a UCS point and SNAPANG an angle from its X axis (snap::grid_frame_in). The rectangular grid is drawn in that frame, so it also honours SNAPANG and SNAPBASE now (its snap already did); the red and green axes are the UCS's. - Polar tracking measured from ANGBASE off the UCS X axis; object snap tracking's orthogonal paths along the UCS axes; the tracking tooltip reads the angle in the UCS. - DIMLINEAR horizontal and vertical (automatic and the keywords) along the UCS axes at the command line; JSON stays in world coordinates. - Ortho at the cursor keeps the full drafting settings (isometric snap steps), not the copy grid snap hands back. Tests: ortho through the cursor and direct distance entry, grid snap and the grid frame with SNAPBASE/SNAPANG, polar tracking and the tracking configuration, isometric axes, DIMLINEAR, and the World UCS unchanged. --- crates/engine/src/cmd/annotate.rs | 39 +++++- crates/engine/src/lib.rs | 7 + crates/engine/src/lisp/ucs_tests.rs | 27 ++++ crates/engine/src/pointmod.rs | 4 +- crates/engine/src/snap.rs | 27 +++- crates/engine/src/snap/iso.rs | 10 +- crates/engine/src/snap/tracking.rs | 20 +-- crates/engine/tests/ucs_drafting.rs | 206 ++++++++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 71 ++++++---- docs/ui-parity.md | 6 +- 10 files changed, 362 insertions(+), 55 deletions(-) create mode 100644 crates/engine/tests/ucs_drafting.rs diff --git a/crates/engine/src/cmd/annotate.rs b/crates/engine/src/cmd/annotate.rs index 48254955a..97717d854 100644 --- a/crates/engine/src/cmd/annotate.rs +++ b/crates/engine/src/cmd/annotate.rs @@ -149,8 +149,15 @@ fn auto_rotation(p1: Vec2, p2: Vec2, at: Vec2) -> f64 { if outside_x && !outside_y { std::f64::consts::FRAC_PI_2 } else { 0.0 } } -fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, aligned: bool) -> DimKind { - if aligned { DimKind::Aligned } else { DimKind::Linear { rotation: rotation.unwrap_or_else(|| auto_rotation(p1, p2, at)) } } +/// A linear or aligned dimension's kind; without a rotation, horizontal or vertical along axes turned +/// `ucs` radians (the current UCS's at the command line; the world's for JSON). +fn linear_kind(p1: Vec2, p2: Vec2, at: Vec2, rotation: Option, aligned: bool, ucs: f64) -> DimKind { + if aligned { + return DimKind::Aligned; + } + let ucs = if ucs.is_finite() { ucs } else { 0.0 }; + let auto = || auto_rotation(p1.rotate(-ucs), p2.rotate(-ucs), at.rotate(-ucs)) + ucs; + DimKind::Linear { rotation: rotation.unwrap_or_else(auto) } } /// Add a dimension. With DIMASSOC on, definition points that sit on object endpoints, @@ -219,7 +226,7 @@ fn run_linear(s: &mut Session, p: &Value) -> Result { }; let at = point_req("dimlinear", p, "at")?; let rot = p.get("rotation").and_then(Value::as_f64).map(f64::to_radians); - let k = dim(s, linear_kind(a, b, at, rot, false), at, a, b, Vec2::ZERO, Vec2::ZERO, str_param(p, "text").unwrap_or("")); + let k = dim(s, linear_kind(a, b, at, rot, false, 0.0), at, a, b, Vec2::ZERO, Vec2::ZERO, str_param(p, "text").unwrap_or("")); Ok(json!({ "handle": add_dim(s, k)?.hex() })) } @@ -1056,7 +1063,16 @@ impl Interactive for LinearM { } (_, Input::Point(at)) => { let (Some(&a), Some(&b)) = (self.pts.first(), self.pts.get(1)) else { return Ok(Step::Continue) }; - let k = self.text.apply(dim(s, linear_kind(a, b, at, self.rotation, self.aligned), at, a, b, Vec2::ZERO, Vec2::ZERO, "")); + let k = self.text.apply(dim( + s, + linear_kind(a, b, at, self.rotation, self.aligned, s.input_ucs().rotation()), + at, + a, + b, + Vec2::ZERO, + Vec2::ZERO, + "", + )); add_dim(s, k)?; if let Some(EntityKind::Dimension(d)) = s.last_dim.and_then(|h| s.doc().ok()?.entity(h).map(|e| e.kind.clone())) { let st = s.doc()?.dim_style(&d.style).cloned().unwrap_or_default(); @@ -1067,8 +1083,8 @@ impl Interactive for LinearM { } (_, Input::Keyword(k)) => { match k.as_str() { - "Horizontal" => self.rotation = Some(0.0), - "Vertical" => self.rotation = Some(std::f64::consts::FRAC_PI_2), + "Horizontal" => self.rotation = Some(s.input_ucs().rotation()), + "Vertical" => self.rotation = Some(s.input_ucs().rotation() + std::f64::consts::FRAC_PI_2), "Rotated" => self.rotating = true, other => { self.text.keyword(other); @@ -1083,7 +1099,16 @@ impl Interactive for LinearM { fn preview(&self, s: &Session, c: Vec2) -> Vec { match self.pts.as_slice() { [a] => vec![super::helpers::line(*a, c)], - [a, b] => vec![self.text.apply(dim(s, linear_kind(*a, *b, c, self.rotation, self.aligned), c, *a, *b, Vec2::ZERO, Vec2::ZERO, ""))], + [a, b] => vec![self.text.apply(dim( + s, + linear_kind(*a, *b, c, self.rotation, self.aligned, s.input_ucs().rotation()), + c, + *a, + *b, + Vec2::ZERO, + Vec2::ZERO, + "", + ))], _ => Vec::new(), } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2c927ba6f..7e89db59c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -452,6 +452,10 @@ pub struct Settings { pub polarsnap: bool, /// POLARDIST: the PolarSnap step; 0 uses the snap X spacing. pub polardist: f64, + /// The current UCS's X axis, radians from world +X: ortho, polar and object snap tracking + /// work along the UCS axes. Filled in by [`Session::drafting_settings`]; not a setting. + #[serde(skip)] + pub ucs_angle: f64, } impl Default for Settings { @@ -510,6 +514,7 @@ impl Default for Settings { polaraddang: Vec::new(), polarsnap: false, polardist: 0.0, + ucs_angle: 0.0, } } } @@ -796,6 +801,8 @@ impl Session { settings.snapunit = d.header.snap_unit(); settings.gridunit = d.header.grid_unit(); } + let a = self.input_ucs().rotation(); + settings.ucs_angle = if a.is_finite() { a } else { 0.0 }; settings } /// The space commands act on (model space while working inside a layout viewport). diff --git a/crates/engine/src/lisp/ucs_tests.rs b/crates/engine/src/lisp/ucs_tests.rs index f03b27a42..8bb71103f 100644 --- a/crates/engine/src/lisp/ucs_tests.rs +++ b/crates/engine/src/lisp/ucs_tests.rs @@ -145,3 +145,30 @@ fn getangle_and_getdist_measure_in_the_ucs() { assert!(close(pt(&ok(&mut s, "(getvar \"UCSXDIR\")")), [0.0, 1.0, 0.0])); assert_eq!(ok(&mut s, "(getvar \"WORLDUCS\")"), "0"); } + +#[test] +fn entsel_and_getcorner_answer_in_the_ucs() { + let mut s = session(); + s.execute("line", &json!({"points": [[100, 60], [100, 80]]})).unwrap(); + turned(&mut s); + // entsel: the object, and the pick point in the UCS. + s.cmdline("(setq e (entsel))").unwrap(); + s.input(crate::Input::Point(Vec2::new(100.0, 70.0))).unwrap(); + let v = to_text(&s.lisp_var("E"), true); + assert!(v.contains(" { // Each point after the first goes straight across or up from the last one. - let q = last.map_or(p, |l| crate::snap::ortho(l, p)); + let q = last.map_or(p, |l| crate::snap::ortho_at(l, p, self.drafting_settings().ucs_angle)); self.point_mods.push(Frame::Track { last: Some(q) }); self.last_point = q; return Ok(()); diff --git a/crates/engine/src/snap.rs b/crates/engine/src/snap.rs index 3b38b976f..3a17982a5 100644 --- a/crates/engine/src/snap.rs +++ b/crates/engine/src/snap.rs @@ -974,6 +974,17 @@ pub fn ortho(base: Vec2, p: Vec2) -> Vec2 { if d.x.abs() >= d.y.abs() { Vec2::new(p.x, base.y) } else { Vec2::new(base.x, p.y) } } +/// [`ortho`] along axes turned by `angle` radians (the current UCS's). +pub fn ortho_at(base: Vec2, p: Vec2, angle: f64) -> Vec2 { + if !angle.is_finite() || angle == 0.0 { + return ortho(base, p); + } + let d = (p - base).rotate(-angle); + let along = if d.x.abs() >= d.y.abs() { Vec2::new(d.x, 0.0) } else { Vec2::new(0.0, d.y) }; + let r = base + along.rotate(angle); + if r.is_finite() { r } else { p } +} + /// Polar tracking: if the direction base→p is within `tol` radians of a multiple of `inc`, /// return the point projected onto that ray and the angle. pub fn polar(base: Vec2, p: Vec2, inc: f64, tol: f64) -> Option<(Vec2, f64)> { @@ -1007,12 +1018,26 @@ pub fn grid_snap(p: Vec2, unit: Vec2, origin: Vec2, angle: f64) -> Vec2 { if s.is_finite() { s } else { p } } -/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing. +/// The snap grid's origin (SNAPBASE) and rotation in radians (SNAPANG, in degrees) of a drawing, +/// as stored: in the UCS ([`grid_frame_in`] places them in the world). pub fn grid_frame(d: &Drawing) -> (Vec2, f64) { let base = d.header.point("SNAPBASE").map(|p| p.xy()).filter(|p| p.is_finite()).unwrap_or(Vec2::ZERO); (base, d.header.f64("SNAPANG", 0.0).to_radians()) } +/// The snap grid's origin and rotation in world coordinates, for `space`: SNAPBASE is a point of +/// the current UCS and SNAPANG is measured from its X axis, so the grid and grid snap lie in the +/// UCS (in the World UCS while it is tilted out of the XY plane). +pub fn grid_frame_in(d: &Drawing, space: &Space) -> (Vec2, f64) { + let (base, angle) = grid_frame(d); + let (ucs, _) = crate::ucs::current(d, space); + if !ucs.is_planar() { + return (base, angle); + } + let (o, a) = (ucs.to_wcs(base), ucs.rotation() + angle); + if o.is_finite() && a.is_finite() { (o, a) } else { (base, angle) } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/snap/iso.rs b/crates/engine/src/snap/iso.rs index 9f1688b93..a4469a925 100644 --- a/crates/engine/src/snap/iso.rs +++ b/crates/engine/src/snap/iso.rs @@ -118,11 +118,11 @@ pub fn lattice_snap(p: Vec2, d: f64, origin: Vec2, angle: f64) -> Vec2 { /// isometric lattice, and the settings with grid snap off so the rectangular grid leaves it be. /// Otherwise both unchanged, also when PolarSnap (SNAPTYPE 1) is the snap type: snap mode then /// steps along the tracking paths instead. -pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, mut s: Settings, p: Vec2) -> (Vec2, Settings) { +pub(crate) fn grid_snap(doc: &cadcraft_doc::Drawing, space: &cadcraft_doc::Space, mut s: Settings, p: Vec2) -> (Vec2, Settings) { if !(s.snapmode && s.isodraft) || s.polarsnap { return (p, s); } - let (origin, angle) = super::grid_frame(doc); + let (origin, angle) = super::grid_frame_in(doc, space); s.snapmode = false; (lattice_snap(p, s.snapunit.y, origin, angle), s) } @@ -144,10 +144,12 @@ fn nearest_axis(plane: IsoPlane, d: Vec2) -> Vec2 { /// Ortho without snapping: `p` constrained relative to `base` to the nearest axis of the current /// isometric plane (or to horizontal/vertical when isometric drafting is off). pub fn constrain(s: &Settings, base: Vec2, p: Vec2) -> Vec2 { + // Along the current UCS's axes (`s.ucs_angle`), the isometric ones turned with it. if !s.isodraft { - return super::ortho(base, p); + return super::ortho_at(base, p, s.ucs_angle); } - let dir = nearest_axis(s.isoplane, p - base); + let a = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 }; + let dir = nearest_axis(s.isoplane, (p - base).rotate(-a)).rotate(a); let r = base + dir * (p - base).dot(dir); if r.is_finite() { r } else { p } } diff --git a/crates/engine/src/snap/tracking.rs b/crates/engine/src/snap/tracking.rs index e0740d7be..4fb9113bb 100644 --- a/crates/engine/src/snap/tracking.rs +++ b/crates/engine/src/snap/tracking.rs @@ -259,12 +259,14 @@ impl TrackConfig { /// direction (radians) of the last segment when the base point ends it. pub fn relative_to(s: &crate::Settings, angbase: f64, last: Option) -> Self { let additional: &[f64] = if s.polar_flags & polarmode::ADDITIONAL != 0 { &s.polaraddang } else { &[] }; - let absolute = polar_angles(s.polarang, additional, angbase); + // Measured in the current UCS: from ANGBASE off its X axis. + let ucs = if s.ucs_angle.is_finite() { s.ucs_angle } else { 0.0 }; + let absolute = polar_angles(s.polarang, additional, angbase + ucs); let polar = match last.filter(|a| a.is_finite() && s.polar_flags & polarmode::RELATIVE != 0) { Some(a) => polar_angles(s.polarang, additional, a), None => absolute.clone(), }; - let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal() }; + let track_angles = if s.polar_flags & polarmode::TRACK_POLAR != 0 { absolute } else { orthogonal(ucs) }; TrackConfig { otrack: s.otrack, osmode: s.osmode, @@ -279,9 +281,9 @@ impl TrackConfig { } } -/// Horizontal and vertical, both ways. -fn orthogonal() -> Vec { - vec![0.0, PI / 2.0, PI, 1.5 * PI] +/// Along the UCS axes (turned `ucs` radians from the world's), both ways. +fn orthogonal(ucs: f64) -> Vec { + [0.0, PI / 2.0, PI, 1.5 * PI].iter().map(|a| norm_angle(a + ucs)).collect() } /// Every multiple of the increment `inc` (POLARANG) around the circle, plus the `additional` @@ -803,10 +805,10 @@ impl crate::Session { return CursorSnap { point: h.point, snap: Some(h), track: None, wait }; } // Isometric snap (SNAPSTYL 1): its lattice in place of the rectangular grid. - let (raw, s) = super::iso::grid_snap(&doc, s, raw); + let (raw, s) = super::iso::grid_snap(&doc, &space, s, raw); let mut p = raw; if s.snapmode && !s.polarsnap { - let (origin, angle) = super::grid_frame(&doc); + let (origin, angle) = super::grid_frame_in(&doc, &space); p = super::grid_snap(p, doc.header.snap_unit(), origin, angle); } if let Some(mut t) = self.tracking.track(&doc, &space, p, q.aperture, q.tol, &cfg, q.base) { @@ -825,7 +827,9 @@ impl crate::Session { && s.orthomode && !q.corner { - p = super::iso::ortho(&self.settings, b, p); + // The drafting settings as they are (`s` has grid snap turned off once the isometric + // lattice took it), with the UCS axes. + p = super::iso::ortho(&self.drafting_settings(), b, p); } CursorSnap { point: p, snap: None, track: None, wait } } diff --git a/crates/engine/tests/ucs_drafting.rs b/crates/engine/tests/ucs_drafting.rs new file mode 100644 index 000000000..036d97775 --- /dev/null +++ b/crates/engine/tests/ucs_drafting.rs @@ -0,0 +1,206 @@ +//! The drafting aids follow the current UCS (#1106): ortho and direct distance entry along its +//! axes, grid snap in its XY plane (SNAPBASE from its origin, SNAPANG from its X axis), polar and +//! object snap tracking measured from its X axis, isometric axes turned with it, and DIMLINEAR's +//! horizontal and vertical along its axes. In the World UCS everything is as before. + +use cadcraft_engine::Session; +use cadcraft_engine::doc::{DimKind, EntityKind}; +use cadcraft_engine::geom::{Vec2, Vec3}; +use cadcraft_engine::snap::tracking::{CursorQuery, TrackConfig}; +use cadcraft_engine::snap::{self, iso}; +use serde_json::json; + +const DEG: f64 = std::f64::consts::PI / 180.0; + +fn session() -> Session { + let mut s = Session::new(); + s.new_drawing(false); + // Nothing running that would snap the cursor elsewhere. + s.settings.osmode = 0; + s.settings.otrack = false; + s.settings.polarmode = false; + s.settings.orthomode = false; + s.settings.snapmode = false; + s +} + +/// The UCS at (5, 5) turned `deg` degrees. +fn turned(s: &mut Session, deg: f64) { + s.execute("ucs", &json!({"option": "origin", "origin": [5, 5]})).unwrap(); + s.execute("ucs", &json!({"option": "z", "angle": deg})).unwrap(); +} + +fn query(base: Option) -> CursorQuery { + CursorQuery { base, deferred: false, corner: false, aperture: 0.01, tol: 1.0, now: 0.0, shift: false } +} + +fn near(a: Vec2, x: f64, y: f64) -> bool { + a.dist(Vec2::new(x, y)) < 1e-9 +} + +fn ang_eq(a: f64, b: f64) -> bool { + let d = (a - b).rem_euclid(std::f64::consts::TAU); + d < 1e-9 || std::f64::consts::TAU - d < 1e-9 +} + +#[test] +fn ortho_follows_the_ucs_axes() { + let mut s = session(); + s.settings.orthomode = true; + // World UCS: horizontal. + let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point; + assert!(near(p, 10.0, 0.0), "{p:?}"); + // Turned 30°: along the UCS X axis, as far as the cursor reaches along it. + turned(&mut s, 30.0); + let p = s.snap_cursor(Vec2::new(10.0, 4.0), &query(Some(Vec2::ZERO))).point; + let along = 10.0 * (30.0 * DEG).cos() + 4.0 * (30.0 * DEG).sin(); + assert!(near(p, along * (30.0 * DEG).cos(), along * (30.0 * DEG).sin()), "{p:?}"); + // And along its Y axis when the cursor is nearer that. + let p = s.snap_cursor(Vec2::new(-4.0, 9.0), &query(Some(Vec2::ZERO))).point; + let d = p - Vec2::ZERO; + assert!(ang_eq(d.angle(), 120.0 * DEG) || ang_eq(d.angle(), 300.0 * DEG), "{:?}", d.angle() / DEG); +} + +#[test] +fn direct_distance_with_ortho_goes_along_the_ucs_axis() { + let mut s = session(); + turned(&mut s, 30.0); + s.settings.orthomode = true; + s.cmdline("line 0,0").unwrap(); + // The cursor a little off the UCS X axis: 10 along it. + s.cursor = s.input_ucs().to_wcs(Vec2::new(8.0, 1.0)); + s.cmdline("10").unwrap(); + s.cmdline("").unwrap(); + let l = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap(); + let u = s.input_ucs(); + assert!(l.a.xy().dist(u.to_wcs(Vec2::ZERO)) < 1e-9 && l.b.xy().dist(u.to_wcs(Vec2::new(10.0, 0.0))) < 1e-9, "{l:?}"); +} + +#[test] +fn grid_snap_lies_in_the_ucs() { + let mut s = session(); + cadcraft_engine::sysvars::set(&mut s, "SNAPUNIT", &json!([1, 1])).unwrap(); + s.settings.snapmode = true; + let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point; + assert!(near(p, 5.0, 7.0), "World: {p:?}"); + // Turned 90° at (5, 5): the lattice through (5, 5) along the turned axes; with SNAPBASE and + // SNAPANG measured in the UCS. + turned(&mut s, 90.0); + let p = s.snap_cursor(Vec2::new(5.3, 6.8), &query(None)).point; + assert!(near(p, 5.0, 7.0), "{p:?}"); + s.execute("ucs", &json!({"option": "z", "angle": -45})).unwrap(); + let u = s.input_ucs(); + let p = s.snap_cursor(u.to_wcs(Vec2::new(2.2, -0.9)), &query(None)).point; + assert!(u.to_ucs(p).dist(Vec2::new(2.0, -1.0)) < 1e-9, "UCS {:?}", u.to_ucs(p)); + let d = s.doc().unwrap(); + let (o, a) = snap::grid_frame_in(d, &s.space()); + assert!(near(o, 5.0, 5.0) && ang_eq(a, 45.0 * DEG), "{o:?} {}", a / DEG); + // SNAPBASE is a UCS point, SNAPANG an angle from its X axis. + cadcraft_engine::sysvars::set(&mut s, "SNAPBASE", &json!([1, 0])).unwrap_or(()); + s.doc_mut().unwrap().header.set("SNAPBASE", cadcraft_engine::doc::HVal::Point(Vec3::new(1.0, 0.0, 0.0))); + s.doc_mut().unwrap().header.set_f64("SNAPANG", 10.0); + let (o, a) = snap::grid_frame_in(s.doc().unwrap(), &s.space()); + assert!(o.dist(u.to_wcs(Vec2::new(1.0, 0.0))) < 1e-9 && ang_eq(a, 55.0 * DEG), "{o:?} {}", a / DEG); + // The stored values are unchanged (they are UCS values). + assert_eq!(snap::grid_frame(s.doc().unwrap()), (Vec2::new(1.0, 0.0), 10.0 * DEG)); +} + +#[test] +fn polar_tracking_is_measured_from_the_ucs_x_axis() { + let mut s = session(); + s.settings.polarmode = true; + s.settings.polarang = 90.0 * DEG; + let base = Vec2::ZERO; + let at32 = Vec2::from_angle(32.0 * DEG) * 10.0; + // World UCS, 90° steps: 32° is on no path. + assert!(s.snap_cursor(at32, &query(Some(base))).track.is_none()); + // Turned 30°: the path at 30° catches it. + turned(&mut s, 30.0); + let snapped = s.snap_cursor(at32, &query(Some(base))); + let t = snapped.track.expect("on the 30° path"); + let d = t.point - base; + assert!(ang_eq(d.angle(), 30.0 * DEG), "{}", d.angle() / DEG); + // The configuration itself: polar angles and the orthogonal tracking paths turn with the UCS. + let st = s.drafting_settings(); + let cfg = TrackConfig::new(&st, 0.0); + for want in [30.0, 120.0, 210.0, 300.0] { + assert!( + cfg.polar_angles.iter().any(|a| ang_eq(*a, want * DEG)), + "{want}: {:?}", + cfg.polar_angles.iter().map(|a| a / DEG).collect::>() + ); + assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG)), "{want}"); + } + // ANGBASE adds to it. + let cfg = TrackConfig::new(&st, 15.0 * DEG); + assert!(cfg.polar_angles.iter().any(|a| ang_eq(*a, 45.0 * DEG))); +} + +#[test] +fn the_world_ucs_drafts_as_before() { + let s = session(); + let st = s.drafting_settings(); + assert_eq!(st.ucs_angle, 0.0); + for (b, p) in [(Vec2::ZERO, Vec2::new(10.0, 4.0)), (Vec2::new(3.0, 3.0), Vec2::new(1.0, 20.0)), (Vec2::ZERO, Vec2::new(-5.0, 5.0))] { + assert_eq!(snap::ortho_at(b, p, 0.0), snap::ortho(b, p)); + assert_eq!(iso::constrain(&st, b, p), snap::ortho(b, p)); + } + let cfg = TrackConfig::new(&st, 0.0); + for want in [0.0, 90.0, 180.0, 270.0] { + assert!(cfg.track_angles.iter().any(|a| ang_eq(*a, want * DEG))); + } + assert_eq!(snap::grid_frame_in(s.doc().unwrap(), &s.space()), snap::grid_frame(s.doc().unwrap())); + // Hostile angles fall back to the world axes. + assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::NAN), Vec2::new(3.0, 0.0)); + assert_eq!(snap::ortho_at(Vec2::ZERO, Vec2::new(3.0, 1.0), f64::INFINITY), Vec2::new(3.0, 0.0)); +} + +#[test] +fn isometric_axes_turn_with_the_ucs() { + let mut s = session(); + s.settings.isodraft = true; + let st0 = s.drafting_settings(); + turned(&mut s, 40.0); + let st = s.drafting_settings(); + for v in [Vec2::new(10.0, 3.0), Vec2::new(-2.0, 9.0), Vec2::new(4.0, -7.0)] { + let base = Vec2::new(1.0, 2.0); + let r = iso::constrain(&st, base, base + v.rotate(40.0 * DEG)) - base; + let want = iso::constrain(&st0, Vec2::ZERO, v).rotate(40.0 * DEG); + assert!(r.dist(want) < 1e-9, "{v:?}: {r:?} vs {want:?}"); + } +} + +fn last_dim_rotation(s: &Session) -> f64 { + let d = s.doc().unwrap(); + let r = d.model.iter().filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm.kind) } else { None }).last(); + match r { + Some(DimKind::Linear { rotation }) => rotation, + other => panic!("not a linear dimension: {other:?}"), + } +} + +#[test] +fn dimlinear_horizontal_and_vertical_follow_the_ucs() { + let mut s = session(); + turned(&mut s, 30.0); + // Placed above the points (in the UCS): horizontal along the UCS X axis. + s.cmdline("dimlinear 0,0 10,0 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG), "{}", last_dim_rotation(&s) / DEG); + // Beside them: vertical along its Y axis. + s.cmdline("dimlinear 0,0 0,10 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG), "{}", last_dim_rotation(&s) / DEG); + // The keywords. + s.cmdline("dimlinear 0,0 10,10 h 5,20").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 30.0 * DEG)); + s.cmdline("dimlinear 0,0 10,10 v 20,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 120.0 * DEG)); + // JSON stays in world coordinates: horizontal is world horizontal. + s.execute("dimlinear", &json!({"p1": [0, 0], "p2": [10, 0], "at": [5, 5]})).unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 0.0)); + // World UCS: as before. + s.execute("ucs", &json!({"option": "world"})).unwrap(); + s.cmdline("dimlinear 0,0 10,0 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 0.0)); + s.cmdline("dimlinear 0,0 0,10 5,5").unwrap(); + assert!(ang_eq(last_dim_rotation(&s), 90.0 * DEG)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4bf102510..e85493b0c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -668,40 +668,41 @@ fn draw_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { let unit = if s.gridunit.x == 0.0 { s.snapunit.x } else { s.gridunit.x }; let minor = adaptive(unit, xf.scale, 8.0); let major = minor * major_n; + // The grid lies in the snap frame: SNAPBASE and SNAPANG in the current UCS. + let space = app.session.space(); + let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0)); + let to_world = |q: Vec2| origin + q.rotate(angle); + // The view's corners in grid coordinates bound the lines needed. + let corners = [wb.min, Vec2::new(wb.max.x, wb.min.y), wb.max, Vec2::new(wb.min.x, wb.max.y)].map(|c| (c - origin).rotate(-angle)); + let lo = Vec2::new(corners.iter().map(|c| c.x).fold(f64::INFINITY, f64::min), corners.iter().map(|c| c.y).fold(f64::INFINITY, f64::min)); + let hi = + Vec2::new(corners.iter().map(|c| c.x).fold(f64::NEG_INFINITY, f64::max), corners.iter().map(|c| c.y).fold(f64::NEG_INFINITY, f64::max)); + let (x0, x1) = ((lo.x / minor).floor(), (hi.x / minor).ceil()); + let (y0, y1) = ((lo.y / minor).floor(), (hi.y / minor).ceil()); let mut lines = Vec::new(); - let x0 = (wb.min.x / minor).floor() as i64; - let x1 = (wb.max.x / minor).ceil() as i64; - let y0 = (wb.min.y / minor).floor() as i64; - let y1 = (wb.max.y / minor).ceil() as i64; - if (x1 - x0) < 2000 && (y1 - y0) < 2000 { - for i in x0..=x1 { + if [x0, x1, y0, y1].iter().all(|v| v.is_finite()) && (x1 - x0) < 2000.0 && (y1 - y0) < 2000.0 { + let is_major = |v: f64| ((v / major) - (v / major).round()).abs() < 1e-6; + let stroke = |m: bool| Stroke::new(1.0, if m { t.grid_major } else { t.grid_minor }); + for i in (x0 as i64)..=(x1 as i64) { let x = i as f64 * minor; - let is_major = (x / major).round() * major - x == 0.0 || ((x / major) - (x / major).round()).abs() < 1e-6; - let sx = xf.to_screen(Vec2::new(x, 0.0)).x; - lines.push(Shape::line_segment( - [pos2(sx, xf.rect.top()), pos2(sx, xf.rect.bottom())], - Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), - )); + let (a, b) = (to_world(Vec2::new(x, lo.y)), to_world(Vec2::new(x, hi.y))); + lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(x)))); } - for j in y0..=y1 { + for j in (y0 as i64)..=(y1 as i64) { let y = j as f64 * minor; - let is_major = ((y / major) - (y / major).round()).abs() < 1e-6; - let sy = xf.to_screen(Vec2::new(0.0, y)).y; - lines.push(Shape::line_segment( - [pos2(xf.rect.left(), sy), pos2(xf.rect.right(), sy)], - Stroke::new(1.0, if is_major { t.grid_major } else { t.grid_minor }), - )); + let (a, b) = (to_world(Vec2::new(lo.x, y)), to_world(Vec2::new(hi.x, y))); + lines.push(Shape::line_segment([xf.to_screen(a), xf.to_screen(b)], stroke(is_major(y)))); } } p.extend(lines); } - // Axes through the origin. - let o = xf.to_screen(Vec2::ZERO); - if xf.rect.y_range().contains(o.y) { - p.line_segment([pos2(xf.rect.left(), o.y), pos2(xf.rect.right(), o.y)], Stroke::new(1.0, t.axis_x)); - } - if xf.rect.x_range().contains(o.x) { - p.line_segment([pos2(o.x, xf.rect.top()), pos2(o.x, xf.rect.bottom())], Stroke::new(1.0, t.axis_y)); + // The current UCS's X and Y axes through its origin. + let u = app.session.input_ucs(); + let o = u.origin.xy(); + for (dir, color) in [(u.x.xy(), t.axis_x), (u.y.xy(), t.axis_y)] { + if let Some(seg) = clip_infinite(xf, o, dir, false) { + p.line_segment(seg, Stroke::new(1.0, color)); + } } } @@ -718,7 +719,9 @@ fn draw_iso_grid(app: &CadApp, p: &egui::Painter, xf: &Xf) { } d *= 5.0; } - let (origin, angle) = app.session.doc().map(cadcraft_engine::snap::grid_frame).unwrap_or((Vec2::ZERO, 0.0)); + // In the current UCS (SNAPBASE from its origin, SNAPANG from its X axis). + let space = app.session.space(); + let (origin, angle) = app.session.doc().map(|d| cadcraft_engine::snap::grid_frame_in(d, &space)).unwrap_or((Vec2::ZERO, 0.0)); let lines = iso::grid_lines(xf.world_bounds(), d, origin, angle, s.gridmajor); p.extend( lines.into_iter().map(|l| { @@ -1114,7 +1117,8 @@ fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) { /// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor /// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°"). -fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) { +/// `ucs`: the current UCS's X axis (radians), which the tooltips measure angles from. +fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64, ucs: f64) { use snap::tracking::{Acquired, PathShape}; let t = Tokens::get(); let st = Stroke::new(1.0, t.snap); @@ -1151,7 +1155,7 @@ fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquire p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0)); let (distance, angle) = ( cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4), - (path.from.angle_to(tr.point).to_degrees().round() as i64).rem_euclid(360), + ((path.from.angle_to(tr.point) - ucs).to_degrees().round() as i64).rem_euclid(360), ); tips.push(if path.name == "Polar" { crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle) @@ -1819,7 +1823,14 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { } // Acquired tracking points and the polar / tracking paths under the cursor. if app.canvas.cursor.is_some() { - draw_tracking(&painter, &xf, &app.session.tracking.acquired, app.canvas.track.as_ref(), view.height * 4.0); + draw_tracking( + &painter, + &xf, + &app.session.tracking.acquired, + app.canvas.track.as_ref(), + view.height * 4.0, + app.session.input_ucs().rotation(), + ); } if let (Some(hit), Some(_)) = (app.canvas.snap, app.canvas.cursor) { draw_snap_marker(&painter, xf.to_screen(hit.point), &hit); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4d31efc47..fcd57cd92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -83,12 +83,12 @@ ignored; there are no context menus. Remaining: **≈ 110–170 Opus 5.5 hours** | Feature | AutoCAD | CADCraft | |---|---|---| -| Ortho (F8) | yes | yes (`snap.rs:503`) | -| Polar tracking increment | yes | yes, measured from ANGBASE; dotted path and "Polar: d < a°" tooltip (`snap/tracking.rs`, `canvas.rs` `draw_tracking`) | +| Ortho (F8) | yes | yes, along the current UCS's axes (`snap::ortho_at`) | +| Polar tracking increment | yes | yes, measured from ANGBASE off the current UCS's X axis; dotted path and "Polar: d < a°" tooltip (`snap/tracking.rs`, `canvas.rs` `draw_tracking`) | | Additional polar angles, relative to last segment | yes | additional angles yes (POLARADDANG with POLARMODE 4); **relative to the last segment no** | | Polar distance snap (PolarSnap) | yes | **no** | | **Object snap tracking** (acquire points, alignment paths, intersections of paths) | yes, F11 | yes (#379): resting on a snap point acquires it (`+`), resting again releases it, seven at most; horizontal/vertical paths, or every polar angle with POLARMODE 2; Shift to acquire with POLARMODE 8; crossings of two paths, a path and an object, and a path and a polar path snap; tooltip names each path; a typed distance (direct distance entry) runs along the path the cursor is on, measured from the point the path comes from. Engine: `Session::snap_cursor`, `snap/tracking.rs`; AUTOSNAP bits 8 and 16 | -| Grid (rectangular, major lines, adaptive, limits) | yes | rectangular and isometric (30°, 90° and 150° lines), major lines, adaptive display | +| Grid (rectangular, major lines, adaptive, limits) | yes | rectangular and isometric (30°, 90° and 150° lines), major lines, adaptive display; grid and grid snap in the current UCS (SNAPBASE from its origin, SNAPANG from its X axis), the red and green axes along its X and Y | | Snap (rectangular, isometric, polar snap) | yes | rectangular and isometric (SNAPSTYL 1: the snap Y spacing along the isometric axes), from SNAPBASE turned by SNAPANG | | Isometric drafting (ISODRAFT, isoplanes F5) | yes | yes (#556): ISODRAFT and the status-bar toggle set SNAPSTYL and the plane; ISOPLANE / F5 / Ctrl+E cycle Left, Top, Right (SNAPISOPAIR); ortho, direct distance entry and the crosshair follow the plane's axes; ELLIPSE Isocircle (radius or Diameter, also for elliptical arcs); Drafting Settings snap style radio. Engine: `snap/iso.rs`, `cmd/settings/iso.rs` | | Drafting Settings dialog | yes | yes (`dialogs.rs:36-80`) |