diff --git a/crates/dwg/src/lib.rs b/crates/dwg/src/lib.rs index 037aa26b51..5f3a6271fd 100644 --- a/crates/dwg/src/lib.rs +++ b/crates/dwg/src/lib.rs @@ -249,9 +249,24 @@ mod native { table_merges(doc); table_style_rows(doc, false); keep_sort_handles(doc); + jog_angles(doc); drop_orphaned_dgn_components(doc) } + /// Dimension styles' jog angles in a DWG older than 2007 (AC1021), whose DIMSTYLE objects + /// have no DIMJOGANG (ODA DWG specification, DIMSTYLE: R2007+). acadrust 0.6.6 leaves 0 + /// there, and its DXF writer then gives every style a group 50 of 5° (0 clamped to the + /// shortest jog) that isn't in the file. Its default, 45°, is left out of the DXF instead, so + /// a style's jog angle comes from its xdata or the reader's default. + fn jog_angles(doc: &mut acadrust::CadDocument) { + if doc.version >= acadrust::DxfVersion::AC1021 { + return; + } + for s in doc.dim_styles.iter_mut() { + s.dimjogang = std::f64::consts::FRAC_PI_4; + } + } + /// Runs `f`, turning a panic into an error (the reader and writer are guarded the same way). fn guarded(f: impl FnOnce() -> R + std::panic::UnwindSafe) -> Result { std::panic::catch_unwind(f).map_err(|_| ()) diff --git a/crates/io/src/dxf_ext.rs b/crates/io/src/dxf_ext.rs index 392ee14002..06af840021 100644 --- a/crates/io/src/dxf_ext.rs +++ b/crates/io/src/dxf_ext.rs @@ -62,7 +62,8 @@ pub(crate) enum K { Block, /// Handle of an LTYPE record (DIMLTYPE, DIMLTEX1, DIMLTEX2); "" (ByBlock) isn't written. Linetype, - /// An angle: degrees in the style, radians in the file (DIMJOGANG). + /// The jog angle (DIMJOGANG): degrees in the style and in DIMSTYLE groups, radians in xdata. + /// Read in either unit ([`jog_degrees`]). Angle, } @@ -187,10 +188,14 @@ pub(crate) fn canonical(field: &str, v: &Value) -> Option { serde_json::to_value(&st).ok()?.get(field).cloned() } -/// A dimension variable encoded for a group: real, integer, string or handle. +/// A dimension variable encoded for a group: real, angle, integer, string or handle. #[derive(Clone, Debug, PartialEq)] pub(crate) enum DimVal { Real(f64), + /// Degrees. A DIMSTYLE group holds degrees (AutoCAD and the DWG bridge read group 50 so); + /// xdata holds radians, like the xdata of AutoCAD's own R2000 DIMSTYLE records and every + /// CADCraft version so far. + Angle(f64), Int(i64), Str(String), Handle(String), @@ -214,10 +219,24 @@ pub(crate) fn encode(kind: K, v: &Value, style: Lookup, block: Lookup, ltype: Lo DimVal::Handle(if name.trim().is_empty() { "0".to_string() } else { block(name)? }) } K::Linetype => DimVal::Handle(ltype(v.as_str().filter(|n| !n.trim().is_empty())?)?), - K::Angle => DimVal::Real(v.as_f64().filter(|x| x.is_finite())?.to_radians()), + K::Angle => DimVal::Angle(v.as_f64().filter(|x| x.is_finite())?), }) } +/// The jog angles (degrees) a [`DimStyle`] takes. +const JOG_DEGREES: std::ops::RangeInclusive = 5.0..=90.0; + +/// A DIMJOGANG value from a file in degrees, or `None` when it is no jog angle a style takes. +/// The DIMSTYLE group (50) holds degrees (AutoCAD and the DWG bridge, acadrust, read and write it +/// so), but CADCraft 0.7.0 and earlier wrote radians there, and xdata and `$DIMJOGANG` hold +/// radians. Usable angles don't overlap in the two units (5 to 90 degrees, 0.087 to 1.571 +/// radians), so the value says which it is. NaN and infinities are in neither range. +pub(crate) fn jog_degrees(x: f64) -> Option { + // Rounded so that whole degrees come back whole from either unit. + let round = |deg: f64| (deg * 1e9).round() / 1e9; + [round(x), round(x.to_degrees())].into_iter().find(|deg| JOG_DEGREES.contains(deg)) +} + /// Decode a group value into the JSON a [`DimStyle`] field takes. `styles` / `blocks` / /// `ltypes` map upper-case handles to names. pub(crate) fn decode( @@ -249,14 +268,7 @@ pub(crate) fn decode( let h = t.str().trim().to_ascii_uppercase(); if h.is_empty() || h == "0" { Value::String(String::new()) } else { Value::String(ltypes.get(&h)?.clone()) } } - K::Angle => { - // Rounded so that whole degrees come back whole. - let x = (t.f64().to_degrees() * 1e9).round() / 1e9; - if !x.is_finite() { - return None; - } - serde_json::json!(x) - } + K::Angle => serde_json::json!(jog_degrees(t.f64())?), }) } @@ -892,6 +904,24 @@ mod tests { } } + #[test] + fn jog_angle_in_either_unit() { + use std::f64::consts::FRAC_PI_4; + // Degrees (a round trip through radians comes back whole), then radians. + let degrees = [(45.0, 45.0), (5.0, 5.0), (90.0, 90.0), (37.5, 37.5), (30f64.to_radians().to_degrees(), 30.0)]; + let radians = [(FRAC_PI_4, 45.0), (5f64.to_radians(), 5.0), (90f64.to_radians(), 90.0)]; + for (file, deg) in degrees.into_iter().chain(radians) { + assert_eq!(jog_degrees(file), Some(deg), "{file}"); + } + for file in [0.0, 0.05, 2.0, 4.99, 90.01, -45.0, -0.5, 1e300, f64::MAX, f64::MIN_POSITIVE, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!(jog_degrees(file), None, "{file}"); + } + // The range is the one the style takes. + let takes = |deg: f64| canonical("jogAngle", &serde_json::json!(deg)).is_some(); + assert!(takes(*JOG_DEGREES.start()) && takes(*JOG_DEGREES.end())); + assert!(!takes(JOG_DEGREES.start() - 1e-6) && !takes(JOG_DEGREES.end() + 1e-6)); + } + #[test] fn arrow_names() { assert_eq!(arrow_block_name("_DOT").map(|x| x.0).as_deref(), Some("_DOT")); diff --git a/crates/io/src/dxf_read/tables.rs b/crates/io/src/dxf_read/tables.rs index 8a57f7f9e9..7bc7d9cdcb 100644 --- a/crates/io/src/dxf_read/tables.rs +++ b/crates/io/src/dxf_read/tables.rs @@ -45,8 +45,12 @@ pub(super) fn header(tags: &[Tag], d: &mut Drawing) { Some(c) => HVal::Str(c.to_string()), None => continue, }, - // $DIMJOGANG is in radians; the variable (like the style) holds degrees. - HVal::Real(r) if name == "DIMJOGANG" => HVal::Real((r.to_degrees() * 1e9).round() / 1e9), + // $DIMJOGANG is in radians (degrees are taken too); the variable, like the style, + // holds degrees. A value no style takes is dropped. + HVal::Real(r) if name == "DIMJOGANG" => match crate::dxf_ext::jog_degrees(r) { + Some(deg) => HVal::Real(deg), + None => continue, + }, // $ANGBASE is in degrees (a drawing measured from north has 90.0); the variable // holds radians. HVal::Real(r) if name == "ANGBASE" => HVal::Real(r.to_radians()), diff --git a/crates/io/src/dxf_write.rs b/crates/io/src/dxf_write.rs index 8eb3ab91f9..64a7c4584d 100644 --- a/crates/io/src/dxf_write.rs +++ b/crates/io/src/dxf_write.rs @@ -84,6 +84,8 @@ impl W { fn dimval(&mut self, code: i32, v: DimVal, xdata: bool) { match v { DimVal::Real(x) => self.f(if xdata { 1040 } else { code }, x), + DimVal::Angle(a) if xdata => self.f(1040, a.to_radians()), + DimVal::Angle(a) => self.f(code, a), DimVal::Int(i) => self.i(if xdata { 1070 } else { code }, i), DimVal::Str(t) => { if xdata || !t.is_empty() { diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 354c293c89..f3cd9f1b0f 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -77,6 +77,11 @@ fn dim_header_vars(w: &mut W, d: &Drawing) { w.s(9, format!("${var}")); w.f(40, x); } + // $DIMJOGANG holds radians (the DIMSTYLE group holds degrees). + Some(DimVal::Angle(a)) => { + w.s(9, format!("${var}")); + w.f(40, a.to_radians()); + } Some(DimVal::Int(i)) if i16::try_from(i).is_ok() => { w.s(9, format!("${var}")); w.i(70, i); diff --git a/crates/io/src/tests.rs b/crates/io/src/tests.rs index 977a7c1842..7977733415 100644 --- a/crates/io/src/tests.rs +++ b/crates/io/src/tests.rs @@ -1675,8 +1675,8 @@ fn extension_sample_roundtrips_and_can_be_exported() { fn dwg_roundtrip_keeps_extension_data() { let d = extension_sample(); let back = read(&write(&d, "x.dwg").unwrap(), "x.dwg").unwrap(); - // The bridge loses DIMFXL and DIMJOGANG (0 and its 5° minimum come back). - let norm = |s: Option<&DimStyle>| s.cloned().map(|s| DimStyle { fixed_ext_length: 1.0, jog_angle: 45.0, ..s }); + // The bridge loses DIMFXL (0 comes back). + let norm = |s: Option<&DimStyle>| s.cloned().map(|s| DimStyle { fixed_ext_length: 1.0, ..s }); assert_eq!(norm(back.dim_style("Mech")), norm(d.dim_style("Mech"))); assert_eq!(back.constraints, d.constraints); assert_eq!(back.parametric, d.parametric); diff --git a/crates/io/tests/it/dimstyle_vars_roundtrip.rs b/crates/io/tests/it/dimstyle_vars_roundtrip.rs index 061054bbc2..d6d3846e04 100644 --- a/crates/io/tests/it/dimstyle_vars_roundtrip.rs +++ b/crates/io/tests/it/dimstyle_vars_roundtrip.rs @@ -1,11 +1,12 @@ //! The dimension variables added for fit, suppression, fixed extension lines, tolerance //! justification, angular zeros, arc symbols, leader arrows, linetypes, lineweights and the jog //! angle survive DXF: in DIMSTYLE records (group codes of the DXF Reference) and as per-dimension -//! `ACAD` DSTYLE overrides. Linetypes are LTYPE handles; DIMJOGANG is in radians in the file. +//! `ACAD` DSTYLE overrides. Linetypes are LTYPE handles. DIMJOGANG is in degrees in DIMSTYLE +//! group 50, as AutoCAD reads it, and in radians in xdata and `$DIMJOGANG`; either unit reads. -use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, Linetype, Space}; +use cadcraft_doc::{Common, DimKind, DimStyle, Dimension, Drawing, EntityKind, HVal, Linetype, Space}; use cadcraft_geom::Vec3; -use cadcraft_io::{read_dxf, write_dxf}; +use cadcraft_io::{SaveOptions, Version, read_dxf, write_dxf}; fn styled() -> DimStyle { DimStyle { @@ -131,3 +132,144 @@ fn header_jog_angle_is_read_in_degrees_and_hostile_values_are_dropped() { assert_eq!((st.dim_linetype.as_str(), st.jog_angle, st.fit), ("", 45.0, 3), "{st:?}"); assert_eq!(st.ext_linetype1, "CENTER"); } + +fn dxf(d: &Drawing, v: Version) -> String { + String::from_utf8(cadcraft_io::write_with(d, "x.dxf", &SaveOptions { version: Some(v), binary: false }).unwrap()).unwrap() +} + +/// `d` saved (2018) and opened again. +fn reopened(d: &Drawing) -> Drawing { + read_dxf(dxf(d, Version::R2018).as_bytes()).unwrap() +} + +/// The line holding the value of group `code` in the DIMSTYLE record `name`. +fn style_group(lines: &[&str], name: &str, code: &str) -> Option { + let pair = |i: usize, c: &str, v: &str| lines.get(i).is_some_and(|l| l.trim() == c) && lines.get(i + 1).is_some_and(|l| l.trim() == v); + let table = (0..lines.len()).step_by(2).find(|&i| pair(i, "2", "DIMSTYLE"))?; + let rec = (table..lines.len()).step_by(2).find(|&i| pair(i, "2", name))?; + (rec..lines.len()).step_by(2).take_while(|&i| lines[i].trim() != "0").find(|&i| lines[i].trim() == code).map(|i| i + 1) +} + +/// `text` with the value of group `code` in the DIMSTYLE record `name` replaced by `value`. +fn with_style_group(text: &str, name: &str, code: &str, value: &str) -> String { + let mut lines: Vec<&str> = text.lines().collect(); + let at = style_group(&lines, name, code).unwrap(); + lines[at] = value; + lines.join("\r\n") +} + +#[test] +fn jog_angle_is_degrees_in_dimstyle_groups() { + // AutoCAD reads group 50 as degrees: given 0.7853981633974483 (45° in radians), it took the + // jog angle as 0.785°. + let d = drawing(); + for v in [Version::R2004, Version::R2018] { + let text = dxf(&d, v); + let lines: Vec<&str> = text.lines().collect(); + for (name, want) in [("Standard", "45.0"), ("Detail", "30.0")] { + let at = style_group(&lines, name, "50").unwrap(); + assert_eq!(lines[at].trim(), want, "{v:?} {name}"); + } + let back = read_dxf(text.as_bytes()).unwrap(); + assert_eq!(back.dim_style("Standard").unwrap(), &DimStyle::default(), "{v:?}"); + assert_eq!(back.dim_style("Detail").unwrap(), &styled(), "{v:?}"); + } +} + +#[test] +fn jog_angle_in_radians_in_a_group_still_reads() { + // CADCraft 0.7.0 and earlier wrote group 50 in radians. 5° to 90° in radians are below the 5° + // a style takes, so they can't be degrees and read as radians. + let text = dxf(&drawing(), Version::R2018); + for (file, want) in [("0.7853981633974483", 45.0), ("1.0471975511965976", 60.0), ("0.08726646259971647", 5.0), ("1.5707963267948966", 90.0)] { + let back = read_dxf(with_style_group(&text, "Detail", "50", file).as_bytes()).unwrap(); + assert_eq!(back.dim_style("Detail").unwrap().jog_angle, want, "{file}"); + // Saved again, it's degrees: the same style comes back, its linetypes too. + assert_eq!(reopened(&back).dim_style("Detail").unwrap(), &DimStyle { jog_angle: want, ..styled() }, "saved again: {file}"); + } +} + +#[test] +fn jog_angle_no_style_takes_keeps_the_default() { + let text = dxf(&drawing(), Version::R2018); + for file in ["0.0", "0.05", "2.0", "4.99", "90.5", "-30.0", "1e300", "-1e300", "NaN", "inf"] { + let back = read_dxf(with_style_group(&text, "Detail", "50", file).as_bytes()).unwrap(); + let st = back.dim_style("Detail").unwrap(); + assert_eq!(st.jog_angle, 45.0, "{file}"); + assert_eq!(DimStyle { jog_angle: 30.0, ..st.clone() }, styled(), "the rest of the style reads: {file}"); + assert_eq!(reopened(&back).dim_style("Detail").unwrap(), &DimStyle { jog_angle: 45.0, ..styled() }, "saved again: {file}"); + } +} + +#[test] +fn jog_angle_overrides_stay_radians_in_xdata() { + // Xdata keeps radians, as CADCraft's DSTYLE overrides and R2000 DIMVARS always have (AutoCAD's + // own R2000 save keeps the style's jog angle in xdata in radians too). Degrees read as well. + let mut d = drawing(); + d.add(&Space::Model, Common::default(), dimension(serde_json::json!({ "DIMJOGANG": 60 }))).unwrap(); + let text = dxf(&d, Version::R2018); + let rad = 60f64.to_radians().to_string(); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + assert!(lines.windows(4).any(|w| w == ["1070", "50", "1040", rad.as_str()]), "DSTYLE: 1070 50, 1040 {rad}"); + let jog = |text: &str| { + read_dxf(text.as_bytes()).unwrap().model.iter().find_map(|e| match &e.kind { + EntityKind::Dimension(dm) => Some(DimStyle::default().with_overrides(&dm.overrides).jog_angle), + _ => None, + }) + }; + assert_eq!(jog(&text), Some(60.0)); + let degrees = text.replacen(&format!("1040\r\n{rad}\r\n"), "1040\r\n60.0\r\n", 1); + assert_ne!(degrees, text); + assert_eq!(jog(°rees), Some(60.0)); +} + +#[test] +fn header_jog_angle_takes_degrees_too_and_drops_unusable_values() { + let d = drawing(); + // The header carries the current style's jog angle, in radians. + let text = write_dxf(&d); + let lines: Vec<&str> = text.lines().collect(); + let at = lines.iter().position(|l| l.trim() == "$DIMJOGANG").expect("$DIMJOGANG written") + 2; + assert!((lines[at].trim().parse::().unwrap() - 45f64.to_radians()).abs() < 1e-9, "{}", lines[at]); + let jog = |v: &str| { + let mut lines = lines.clone(); + lines[at] = v; + read_dxf(lines.join("\r\n").as_bytes()).unwrap().header.get("DIMJOGANG").and_then(HVal::as_f64) + }; + assert_eq!(jog("0.5235987755982988"), Some(30.0)); + assert_eq!(jog("30.0"), Some(30.0)); + for v in ["0.0", "120.0", "1e300", "NaN"] { + assert_eq!(jog(v), None, "{v}"); + } +} + +/// The DWG bridge (acadrust) reads and writes DIMSTYLE group 50 in degrees too, so a DWG whose +/// style jogs at 30° (made here by the bridge from our 2018 DXF) opens at 30°. Read as radians, +/// it was 1719° and the style fell back to 45°. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dwg_jog_angle_reads_in_degrees() { + let dwg = cadcraft_dwg::dxf_to_dwg_as(dxf(&drawing(), Version::R2018).as_bytes(), "AC1032").unwrap(); + let text = String::from_utf8(cadcraft_dwg::dwg_to_dxf(&dwg).unwrap()).unwrap(); + let lines: Vec<&str> = text.lines().collect(); + let jog: f64 = lines[style_group(&lines, "Detail", "50").unwrap()].trim().parse().unwrap(); + assert!((jog - 30.0).abs() < 1e-9, "the bridge's DXF has degrees: {jog}"); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + assert_eq!(back.dim_style("Detail").unwrap().jog_angle, 30.0); +} + +/// A DWG older than 2007 has no jog angle in its DIMSTYLE objects, and the bridge used to give +/// every style a group 50 of 5° when it read one. Read as degrees, every style then jogged at +/// 5°; now Standard keeps 45° and a style's own angle comes back from its xdata. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn older_dwg_keeps_each_styles_jog_angle() { + for version in [Version::R2000, Version::R2004] { + let opts = SaveOptions { version: Some(version), binary: false }; + let dwg = cadcraft_io::write_with(&drawing(), "x.dwg", &opts).unwrap(); + let back = cadcraft_io::read(&dwg, "x.dwg").unwrap(); + for (name, deg) in [("Standard", 45.0), ("Detail", 30.0)] { + assert_eq!(back.dim_style(name).unwrap().jog_angle, deg, "{name} in {version:?}"); + } + } +} diff --git a/crates/io/tests/it/followups_626.rs b/crates/io/tests/it/followups_626.rs index 10e355cd34..5315b498bc 100644 --- a/crates/io/tests/it/followups_626.rs +++ b/crates/io/tests/it/followups_626.rs @@ -141,7 +141,7 @@ fn newer_dimstyle_variables_are_table_groups_from_2004() { assert!(rec.chunks(2).any(|p| p[0] == code), "{v:?}: group {code}"); } let jog = rec.chunks(2).find(|p| p[0] == "50").unwrap()[1].parse::().unwrap(); - assert!((jog - 30f64.to_radians()).abs() < 1e-9, "DIMJOGANG in radians: {jog}"); + assert_eq!(jog, 30.0, "DIMJOGANG in degrees, as AutoCAD reads group 50"); let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap(); assert_eq!(back.dim_style("Detail").unwrap(), &st, "{v:?}"); }