Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

IO: sketch.export_dxf - units, layers and joined LWPOLYLINE loops (#12725) (#12726)

Albert Shambazov395679015f4b
diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs
index 1ef7b05057..89ea53d570 100644
--- a/crates/engine/src/cmd/sketch_import.rs
+++ b/crates/engine/src/cmd/sketch_import.rs
@@ -5,7 +5,7 @@ use std::collections::HashMap;
use serde_json::{Value, json};
use solidcore_record::Vec2;
-use solidcraft_io::{Geom2, MAX_DRAWING_BYTES};
+use solidcraft_io::{DxfEntity, DxfLayer, Geom2, MAX_DRAWING_BYTES};
use solidcraft_sketch::{CurveKind, LinkKind, LinkSource, Sketch};
use super::CommandSpec;
@@ -29,7 +29,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params("path | text: SVG or DXF (by `format`: \"svg\" | \"dxf\", default by the file name, else SVG); returns min, max, width and height in the file's own size"),
CommandSpec::new("sketch.export_dxf", "Save As DXF", export_dxf).icon("sketch_dxf")
.noundo()
- .params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned)"),
+ .params("sketch?: id|name (default active); path?: file to write (else the DXF text is returned); units?: \"design\" | \"in\" | \"inch\" | \"mm\" | \"cm\" | \"m\" | \"ft\" (default mm); layer?: profile layer name (default \"0\"); layers?: \"single\" | \"roles\" (default \"single\": all on `layer`; \"roles\": outer on \"OUTLINE\", holes on \"CUT\"); join?: bool (default false: R12 LINE/ARC; true: closed loops as LWPOLYLINE with arc bulges)"),
];
/// The sketch import command for a drawing file name, regardless of extension case.
@@ -290,39 +290,248 @@ fn insert_svg(s: &mut Session, p: &Value) -> Result<Value> {
insert(s, p, "sketch.insert_svg", true)
}
+fn sorted_curve_ids<'a>(ids: &'a [String]) -> Vec<&'a str> {
+ let mut v: Vec<&'a str> = ids.iter().map(String::as_str).collect();
+ v.sort_unstable();
+ v
+}
+
fn export_dxf(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.export_dxf";
let id = sketch_store::target(s, p, cmd)?;
let st = s.model.state();
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("that sketch is not evaluated".into()))?;
let sk = &ss.sketch;
- let mut geom = Vec::new();
- for (i, c) in sk.curves.iter().enumerate() {
- if c.construction {
- continue;
- }
- let pt = |k: usize| sk.point(k).unwrap_or_default();
- match &c.kind {
- CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
- CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
- CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
- _ => {
- let poly = sk.polyline(i);
- geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
+
+ let units_val = p.get("units").filter(|v| !v.is_null());
+ if let Some(v) = units_val
+ && !v.is_string()
+ {
+ return Err(bad(cmd, "`units` must be a string"));
+ }
+ let units_param = str_(p, "units").map(str::to_ascii_lowercase);
+ let (insunits, scale) = match units_param.as_deref() {
+ None => (4, 1.0),
+ Some("design") => {
+ let doc_units = solidcraft_doc::expr::length_unit_or_mm(&s.doc.units);
+ match doc_units.to_ascii_lowercase().as_str() {
+ "in" | "inch" => (1, 1.0 / 25.4),
+ "ft" => (2, 1.0 / 304.8),
+ "cm" => (5, 0.1),
+ "m" => (6, 0.001),
+ _ => (4, 1.0),
}
}
+ Some("in" | "inch") => (1, 1.0 / 25.4),
+ Some("ft") => (2, 1.0 / 304.8),
+ Some("mm") => (4, 1.0),
+ Some("cm") => (5, 0.1),
+ Some("m") => (6, 0.001),
+ Some(other) => {
+ return Err(bad(cmd, format!("unsupported unit `{other}` (use \"design\", \"mm\", \"in\", \"cm\", \"m\", or \"ft\")")));
+ }
+ };
+
+ let layer_val = p.get("layer").filter(|v| !v.is_null());
+ if let Some(v) = layer_val
+ && !v.is_string()
+ {
+ return Err(bad(cmd, "`layer` must be a string"));
+ }
+ let custom_layer = str_(p, "layer").map(str::trim).filter(|s| !s.is_empty());
+
+ let layers_val = p.get("layers").filter(|v| !v.is_null());
+ if let Some(v) = layers_val
+ && !v.is_string()
+ {
+ return Err(bad(cmd, "`layers` must be \"single\" or \"roles\""));
+ }
+ let roles_layers = match str_(p, "layers").map(str::to_ascii_lowercase).as_deref() {
+ None | Some("single") => false,
+ Some("roles") => true,
+ Some(_) => return Err(bad(cmd, "`layers` must be \"single\" or \"roles\"")),
+ };
+
+ let join = match p.get("join").filter(|v| !v.is_null()) {
+ None => false,
+ Some(Value::Bool(b)) => *b,
+ Some(_) => return Err(bad(cmd, "`join` must be true or false")),
+ };
+
+ let path_val = p.get("path").filter(|v| !v.is_null());
+ if let Some(v) = path_val
+ && !v.is_string()
+ {
+ return Err(bad(cmd, "`path` must be a string"));
}
- let text = solidcraft_io::write_dxf(&geom);
+
+ let is_default = units_val.is_none() && layer_val.is_none() && layers_val.is_none() && !join;
+
+ let (text, entity_count) = if is_default {
+ let mut geom = Vec::new();
+ for (i, c) in sk.curves.iter().enumerate() {
+ if c.construction {
+ continue;
+ }
+ let pt = |k: usize| sk.point(k).unwrap_or_default();
+ match &c.kind {
+ CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
+ CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
+ CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
+ _ => {
+ let poly = sk.polyline(i);
+ geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
+ }
+ }
+ }
+ let count = geom.len();
+ (solidcraft_io::write_dxf(&geom), count)
+ } else if !join {
+ let hole_keys: std::collections::HashSet<Vec<&str>> =
+ ss.profiles.iter().flat_map(|p| p.hole_curves.iter().map(|h| sorted_curve_ids(h))).collect();
+
+ let mut outline_ids = std::collections::HashSet::new();
+ let mut cut_ids = std::collections::HashSet::new();
+ if roles_layers {
+ for prof in &ss.profiles {
+ for holes in &prof.hole_curves {
+ for id in holes {
+ cut_ids.insert(id.as_str());
+ }
+ }
+ if !hole_keys.contains(&sorted_curve_ids(&prof.outer_curves)) {
+ for id in &prof.outer_curves {
+ outline_ids.insert(id.as_str());
+ }
+ }
+ }
+ }
+ let base_layer = custom_layer.unwrap_or("0");
+ let mut entities = Vec::new();
+ for (i, c) in sk.curves.iter().enumerate() {
+ if c.construction {
+ continue;
+ }
+ let layer = if roles_layers {
+ if cut_ids.contains(c.id.as_str()) {
+ "CUT"
+ } else if outline_ids.contains(c.id.as_str()) {
+ "OUTLINE"
+ } else {
+ base_layer
+ }
+ } else {
+ base_layer
+ };
+ let pt = |k: usize| sk.point(k).unwrap_or_default() * scale;
+ match &c.kind {
+ CurveKind::Line { a, b } => entities.push((layer, Geom2::Line(pt(*a), pt(*b)))),
+ CurveKind::Circle { c, r } => entities.push((layer, Geom2::Circle(pt(*c), *r * scale))),
+ CurveKind::Arc { c, a, b } => entities.push((layer, Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) })),
+ _ => {
+ let poly = sk.polyline(i);
+ for w in poly.windows(2) {
+ entities.push((layer, Geom2::Line(w[0] * scale, w[1] * scale)));
+ }
+ }
+ }
+ }
+ let count = entities.len();
+ (solidcraft_io::write_dxf_entities(&entities, insunits), count)
+ } else {
+ // join: true -> emit closed loops as LWPOLYLINE with bulges for arcs
+ let hole_keys: std::collections::HashSet<Vec<&str>> =
+ ss.profiles.iter().flat_map(|p| p.hole_curves.iter().map(|h| sorted_curve_ids(h))).collect();
+
+ let mut outline_ids = std::collections::HashSet::new();
+ let mut cut_ids = std::collections::HashSet::new();
+ for prof in &ss.profiles {
+ for id in &prof.outer_curves {
+ outline_ids.insert(id.as_str());
+ }
+ for holes in &prof.hole_curves {
+ for id in holes {
+ cut_ids.insert(id.as_str());
+ }
+ }
+ }
+ let base_layer = custom_layer.unwrap_or("0");
+ let mut entities = Vec::new();
+ for prof in &ss.profiles {
+ if hole_keys.contains(&sorted_curve_ids(&prof.outer_curves)) {
+ continue;
+ }
+ let outer_layer = if roles_layers { "OUTLINE" } else { base_layer };
+ let shape = solidcraft_io::loop_lwpolyline_scaled(&prof.region.outer, scale);
+ entities.push(DxfEntity { layer: outer_layer.into(), shape });
+
+ for hole in &prof.region.holes {
+ let hole_layer = if roles_layers { "CUT" } else { base_layer };
+ let shape = solidcraft_io::loop_lwpolyline_scaled(hole, scale);
+ entities.push(DxfEntity { layer: hole_layer.into(), shape });
+ }
+ }
+ // Preserve any non-profile open curves as disconnected entities so nothing is lost
+ for (i, c) in sk.curves.iter().enumerate() {
+ if c.construction || outline_ids.contains(c.id.as_str()) || cut_ids.contains(c.id.as_str()) {
+ continue;
+ }
+ let pt = |k: usize| sk.point(k).unwrap_or_default() * scale;
+ match &c.kind {
+ CurveKind::Line { a, b } => {
+ entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Line(pt(*a), pt(*b)) })
+ }
+ CurveKind::Circle { c, r } => {
+ entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Circle { c: pt(*c), r: *r * scale } })
+ }
+ CurveKind::Arc { c, a, b } => {
+ let center = pt(*c);
+ let pa = pt(*a);
+ let pb = pt(*b);
+ let r = center.dist(pa);
+ let a0 = (pa - center).angle().to_degrees().rem_euclid(360.0);
+ let a1 = (pb - center).angle().to_degrees().rem_euclid(360.0);
+ entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Arc { c: center, r, a0, a1 } });
+ }
+ _ => {
+ let poly = sk.polyline(i);
+ let points: Vec<Vec2> = poly.into_iter().map(|p| p * scale).collect();
+ entities.push(DxfEntity { layer: base_layer.into(), shape: solidcraft_io::DxfShape::Polyline { points } });
+ }
+ }
+ }
+ let mut layer_names = std::collections::BTreeSet::new();
+ if roles_layers {
+ layer_names.insert("OUTLINE".to_string());
+ layer_names.insert("CUT".to_string());
+ }
+ for e in &entities {
+ layer_names.insert(e.layer.clone());
+ }
+ let layers: Vec<DxfLayer> = layer_names
+ .iter()
+ .map(|name| match name.as_str() {
+ "OUTLINE" => DxfLayer::new(name, 7),
+ "CUT" => DxfLayer::new(name, 4),
+ _ => DxfLayer::new(name, 7),
+ })
+ .collect();
+ let count = entities.len();
+ (solidcraft_io::write_dxf_drawing_units(&layers, &entities, insunits)?, count)
+ };
+
if let Some(path) = str_(p, "path").filter(|x| !x.trim().is_empty()) {
solidcraft_io::vfs::write(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- return Ok(json!({"path": path, "entities": geom.len()}));
+ return Ok(json!({"path": path, "entities": entity_count}));
}
- Ok(json!({"dxf": text, "entities": geom.len()}))
+ Ok(json!({"dxf": text, "entities": entity_count}))
}
#[cfg(test)]
mod tests {
use serde_json::json;
+ use solidcraft_geom::prelude::*;
+ use solidcraft_io::Geom2;
use crate::Session;
@@ -495,4 +704,197 @@ mod tests {
assert!(s.execute("sketch.insert_svg", &p).is_err(), "{bad}");
}
}
+
+ #[test]
+ fn export_dxf_default_is_byte_identical_to_before() {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [40, 30]})).unwrap();
+ s.execute("sketch.circle.center", &json!({"center": [15, 15], "radius": 5})).unwrap();
+
+ let out = s.execute("sketch.export_dxf", &json!({})).unwrap();
+ let text = out["dxf"].as_str().unwrap();
+
+ // Build expected R12 DXF exactly as before
+ let st = s.model.state();
+ let ss = st.sketch(1).unwrap();
+ let sk = &ss.sketch;
+ let mut geom = Vec::new();
+ for (i, c) in sk.curves.iter().enumerate() {
+ if c.construction {
+ continue;
+ }
+ let pt = |k: usize| sk.point(k).unwrap_or_default();
+ match &c.kind {
+ solidcraft_sketch::CurveKind::Line { a, b } => geom.push(Geom2::Line(pt(*a), pt(*b))),
+ solidcraft_sketch::CurveKind::Circle { c, r } => geom.push(Geom2::Circle(pt(*c), *r)),
+ solidcraft_sketch::CurveKind::Arc { c, a, b } => geom.push(Geom2::Arc { c: pt(*c), a: pt(*a), b: pt(*b) }),
+ _ => {
+ let poly = sk.polyline(i);
+ geom.extend(poly.windows(2).map(|w| Geom2::Line(w[0], w[1])));
+ }
+ }
+ }
+ let expected = solidcraft_io::write_dxf(&geom);
+ assert_eq!(text, expected, "default output must be byte-identical to previous write_dxf output");
+
+ // Null options must be treated as omitted (default behavior)
+ for null_params in [
+ json!({"units": null}),
+ json!({"layer": null}),
+ json!({"layers": null}),
+ json!({"join": null}),
+ json!({"path": null}),
+ json!({"units": null, "layer": null, "layers": null, "join": null, "path": null}),
+ ] {
+ let out_null = s.execute("sketch.export_dxf", &null_params).unwrap();
+ assert_eq!(out_null["dxf"].as_str().unwrap(), expected, "null options must behave identically to default options");
+ assert_eq!(out_null["entities"], out["entities"]);
+ }
+
+ // Hostile inputs
+ assert!(s.execute("sketch.export_dxf", &json!({"units": 123})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"units": "unknown_unit"})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"layer": 456})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"layers": 123})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"layers": "all"})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"join": "true"})).is_err());
+ assert!(s.execute("sketch.export_dxf", &json!({"path": 123})).is_err());
+ }
+
+ #[test]
+ fn export_dxf_layers_present() {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [50, 50]})).unwrap();
+ s.execute("sketch.circle.center", &json!({"center": [25, 25], "radius": 10})).unwrap();
+
+ // 1. Single custom layer
+ let out_cut = s.execute("sketch.export_dxf", &json!({"layer": "CUT"})).unwrap();
+ let dxf_cut = out_cut["dxf"].as_str().unwrap();
+ assert!(dxf_cut.contains("\n8\nCUT\n"));
+ assert!(!dxf_cut.contains("\n8\n0\n"));
+
+ // 2. Roles layers (OUTLINE for outer profile, CUT for holes)
+ let out_roles = s.execute("sketch.export_dxf", &json!({"layers": "roles"})).unwrap();
+ let dxf_roles = out_roles["dxf"].as_str().unwrap();
+ assert!(dxf_roles.contains("\n8\nOUTLINE\n"));
+ assert!(dxf_roles.contains("\n8\nCUT\n"));
+
+ // 3. Roles layers with join: true
+ let out_joined_roles = s.execute("sketch.export_dxf", &json!({"join": true, "layers": "roles"})).unwrap();
+ assert_eq!(out_joined_roles["entities"], 2);
+ let dxf_joined = out_joined_roles["dxf"].as_str().unwrap();
+ assert!(dxf_joined.contains("AcDbPolyline"));
+ assert!(dxf_joined.contains("\n 8\nOUTLINE\n") || dxf_joined.contains("\n8\nOUTLINE\n"));
+ assert!(dxf_joined.contains("\n 8\nCUT\n") || dxf_joined.contains("\n8\nCUT\n"));
+ }
+
+ #[test]
+ fn export_dxf_join_does_not_duplicate_holes() {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [100, 80]})).unwrap();
+ s.execute("sketch.circle.center", &json!({"center": [30, 40], "radius": 5})).unwrap();
+ s.execute("sketch.circle.center", &json!({"center": [70, 40], "radius": 8})).unwrap();
+
+ // With join: true, layers: "roles": exactly 3 entities (1 outer outline, 2 hole cuts)
+ let out_roles = s.execute("sketch.export_dxf", &json!({"join": true, "layers": "roles"})).unwrap();
+ assert_eq!(out_roles["entities"], 3, "expected 1 outer outline and 2 hole cuts, got {}", out_roles["entities"]);
+ let dxf_roles = out_roles["dxf"].as_str().unwrap();
+ let lwpolyline_count = dxf_roles.lines().filter(|l| l.trim() == "LWPOLYLINE").count();
+ assert_eq!(lwpolyline_count, 3, "expected exactly 3 LWPOLYLINE entities in DXF");
+
+ // Without roles (single layer): still exactly 3 entities
+ let out_single = s.execute("sketch.export_dxf", &json!({"join": true})).unwrap();
+ assert_eq!(out_single["entities"], 3, "entities without roles must also be exactly 3");
+ }
+
+ #[test]
+ fn export_dxf_join_closed_lwpolyline_with_bulge() {
+ let mut s = Session::default();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ // Quarter-pie shape: center at (0, 0), arc from (10, 0) to (0, 10), and lines to (0, 0)
+ s.execute("sketch.line", &json!({"points": [[0, 0], [10, 0]]})).unwrap();
+ s.execute("sketch.arc.center_point", &json!({"center": [0, 0], "start": [10, 0], "end": [0, 10]})).unwrap();
+ s.execute("sketch.line", &json!({"points": [[0, 10], [0, 0]]})).unwrap();
+
+ let out = s.execute("sketch.export_dxf", &json!({"join": true})).unwrap();
+ let dxf = out["dxf"].as_str().unwrap();
+ assert!(dxf.contains("LWPOLYLINE"));
+ // 70: bit 1 (closed) + bit 128 (plinegen) = 129
+ assert!(dxf.contains("\n 70\n129\n") || dxf.contains("\n70\n129\n"));
+ // Bulge: 90° arc has sweep = pi/2, bulge = tan(sweep / 4) = tan(pi / 8) = sqrt(2) - 1 ≈ 0.414213562373
+ let expected_bulge = (std::f64::consts::FRAC_PI_2 / 4.0).tan();
+ let has_bulge = dxf
+ .lines()
+ .zip(dxf.lines().skip(1))
+ .any(|(k, v)| k.trim() == "42" && (v.trim().parse::<f64>().unwrap_or(0.0).abs() - expected_bulge).abs() < 1e-6);
+ assert!(has_bulge, "DXF must contain group 42 bulge approx {expected_bulge}");
+
+ // Re-import the joined DXF into a new sketch and verify round-trip profile area
+ s.execute("sketch.finish", &json!({})).unwrap();
+ let r = s.execute("sketch.insert_dxf", &json!({"text": dxf, "at": [100, 0]})).unwrap();
+ let id = r["sketch"].as_u64().unwrap();
+ let ss = s.model.state().sketch(id).unwrap().clone();
+ assert_eq!(ss.profiles.len(), 1);
+ let expected_area = std::f64::consts::PI * 100.0 / 4.0; // quarter circle of radius 10
+ assert!((ss.profiles[0].area - expected_area).abs() < 1e-4, "area was {}", ss.profiles[0].area);
+ }
+
+ #[test]
+ fn export_dxf_inch_design_round_trip() {
+ let mut s = Session::default();
+ s.doc_mut().units = "in".to_string();
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap();
+ // A 2 in by 3 in rectangle in an inch design (stored internally as 50.8 mm by 76.2 mm)
+ s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [50.8, 76.2]})).unwrap();
+
+ // 1. Export with units: "design"
+ let out = s.execute("sketch.export_dxf", &json!({"units": "design"})).unwrap();
+ let dxf = out["dxf"].as_str().unwrap();
+ // $INSUNITS must be 1 (inches)
+ assert!(dxf.contains("\n$INSUNITS\n70\n1\n"));
+ // Sizes in inches: 2.0 and 3.0
+ assert!(dxf.contains("2.000000000"));
+ assert!(dxf.contains("3.000000000"));
+
+ // Round-trip through read_dxf: reads $INSUNITS=1, scales by 25.4 to mm
+ let geom = solidcraft_io::read_dxf(dxf).unwrap();
+ let mut widths = Vec::new();
+ let mut heights = Vec::new();
+ for g in &geom {
+ if let Geom2::Line(a, b) = g {
+ let dx = (b.x - a.x).abs() / 25.4;
+ let dy = (b.y - a.y).abs() / 25.4;
+ if dx > 0.1 {
+ widths.push(dx);
+ }
+ if dy > 0.1 {
+ heights.push(dy);
+ }
+ }
+ }
+ for w in widths {
+ assert!((w - 2.0).abs() < 1e-8, "width in inches was {w}");
+ }
+ for h in heights {
+ assert!((h - 3.0).abs() < 1e-8, "height in inches was {h}");
+ }
+
+ // 2. Export with join: true and explicit units: "in"
+ let out_join = s.execute("sketch.export_dxf", &json!({"join": true, "units": "in"})).unwrap();
+ let dxf_join = out_join["dxf"].as_str().unwrap();
+ assert!(dxf_join.contains("LWPOLYLINE"));
+ assert!(dxf_join.contains("\n$INSUNITS\n 70\n1\n") || dxf_join.contains("\n$INSUNITS\n70\n1\n"));
+
+ let geom_join = solidcraft_io::read_dxf(dxf_join).unwrap();
+ assert_eq!(geom_join.len(), 4);
+ for g in &geom_join {
+ if let Geom2::Line(a, b) = g {
+ let len_in = a.dist(*b) / 25.4;
+ assert!((len_in - 2.0).abs() < 1e-8 || (len_in - 3.0).abs() < 1e-8, "edge length {len_in}");
+ }
+ }
+ }
}
diff --git a/crates/io/src/dxf.rs b/crates/io/src/dxf.rs
index d046035296..8ba1669975 100644
--- a/crates/io/src/dxf.rs
+++ b/crates/io/src/dxf.rs
@@ -397,8 +397,23 @@ fn polyline(verts: &[(Vec2, f64)], closed: bool, out: &mut Vec<Geom2>) {
}
}
-/// Write 2D geometry (millimetres) as an R12-style ASCII DXF.
-pub fn write_dxf(geom: &[Geom2]) -> String {
+/// Options for writing an R12-style ASCII DXF.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DxfWriteOptions {
+ /// DXF $INSUNITS: 1 in, 2 ft, 4 mm (default), 5 cm, 6 m.
+ pub insunits: i32,
+ /// Default layer name (default "0").
+ pub layer: String,
+}
+
+impl Default for DxfWriteOptions {
+ fn default() -> Self {
+ DxfWriteOptions { insunits: 4, layer: "0".to_string() }
+ }
+}
+
+/// Write 2D geometry with per-entity layer names as an R12-style ASCII DXF.
+pub fn write_dxf_entities(entities: &[(&str, Geom2)], insunits: i32) -> String {
let mut s = String::new();
let mut w = |c: i32, v: &str| {
s.push_str(&format!("{c}\n{v}\n"));
@@ -406,22 +421,24 @@ pub fn write_dxf(geom: &[Geom2]) -> String {
w(0, "SECTION");
w(2, "HEADER");
w(9, "$INSUNITS");
- w(70, "4");
+ let insunits_str = insunits.to_string();
+ w(70, &insunits_str);
w(0, "ENDSEC");
w(0, "SECTION");
w(2, "ENTITIES");
let f = |x: f64| format!("{x:.9}");
- for g in geom {
+ for (layer, g) in entities {
+ let lyr = if layer.trim().is_empty() { "0" } else { layer.trim() };
match g {
Geom2::Point(p) => {
w(0, "POINT");
- w(8, "0");
+ w(8, lyr);
w(10, &f(p.x));
w(20, &f(p.y));
}
Geom2::Line(a, b) => {
w(0, "LINE");
- w(8, "0");
+ w(8, lyr);
w(10, &f(a.x));
w(20, &f(a.y));
w(11, &f(b.x));
@@ -429,14 +446,14 @@ pub fn write_dxf(geom: &[Geom2]) -> String {
}
Geom2::Circle(c, r) => {
w(0, "CIRCLE");
- w(8, "0");
+ w(8, lyr);
w(10, &f(c.x));
w(20, &f(c.y));
w(40, &f(*r));
}
Geom2::Arc { c, a, b } => {
w(0, "ARC");
- w(8, "0");
+ w(8, lyr);
w(10, &f(c.x));
w(20, &f(c.y));
w(40, &f(c.dist(*a)));
@@ -445,7 +462,7 @@ pub fn write_dxf(geom: &[Geom2]) -> String {
}
Geom2::Text { text, at, height, angle } => {
w(0, "TEXT");
- w(8, "0");
+ w(8, lyr);
w(10, &f(at.x));
w(20, &f(at.y));
w(40, &f(*height));
@@ -461,6 +478,18 @@ pub fn write_dxf(geom: &[Geom2]) -> String {
s
}
+/// Write 2D geometry as an R12-style ASCII DXF with options.
+pub fn write_dxf_opts(geom: &[Geom2], opts: &DxfWriteOptions) -> String {
+ let layer = if opts.layer.trim().is_empty() { "0" } else { opts.layer.as_str() };
+ let entities: Vec<(&str, Geom2)> = geom.iter().cloned().map(|g| (layer, g)).collect();
+ write_dxf_entities(&entities, opts.insunits)
+}
+
+/// Write 2D geometry (millimetres) as an R12-style ASCII DXF.
+pub fn write_dxf(geom: &[Geom2]) -> String {
+ write_dxf_opts(geom, &DxfWriteOptions::default())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -643,4 +672,28 @@ mod tests {
let g = read_dxf(&array).unwrap_or_default();
assert!(g.is_empty(), "an empty block has no geometry to place");
}
+
+ #[test]
+ fn write_dxf_opts_and_entities_round_trip() {
+ let geom = vec![Geom2::Line(Vec2::ZERO, Vec2::new(25.4, 0.0)), Geom2::Circle(Vec2::new(12.7, 12.7), 6.35)];
+
+ // Default write_dxf: byte-identical check with write_dxf_opts default
+ let d0 = write_dxf(&geom);
+ let d1 = write_dxf_opts(&geom, &DxfWriteOptions::default());
+ assert_eq!(d0, d1);
+ assert!(d0.contains("\n8\n0\n"));
+ assert!(d0.contains("\n70\n4\n"));
+
+ // Custom layer and inch units (insunits = 1)
+ let opts = DxfWriteOptions { insunits: 1, layer: "CUT".to_string() };
+ let d_inch = write_dxf_opts(&geom, &opts);
+ assert!(d_inch.contains("\n8\nCUT\n"));
+ assert!(d_inch.contains("\n70\n1\n"));
+
+ // Per-entity layers with write_dxf_entities
+ let ents = vec![("OUTLINE", Geom2::Line(Vec2::ZERO, Vec2::new(10.0, 0.0))), ("CUT", Geom2::Circle(Vec2::new(5.0, 5.0), 2.0))];
+ let d_roles = write_dxf_entities(&ents, 4);
+ assert!(d_roles.contains("\n8\nOUTLINE\n"));
+ assert!(d_roles.contains("\n8\nCUT\n"));
+ }
}
diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs
index 56d12dbcd4..63ea6647c6 100644
--- a/crates/io/src/dxf_out.rs
+++ b/crates/io/src/dxf_out.rs
@@ -68,6 +68,12 @@ pub enum DxfShape {
Polyline {
points: Vec<Vec2>,
},
+ /// A lightweight polyline (AutoCAD `LWPOLYLINE`) with bulges for arc segments.
+ /// Each entry in `verts` is `(position, bulge)`, where bulge is `tan(sweep / 4)`.
+ LwPolyline {
+ verts: Vec<(Vec2, f64)>,
+ closed: bool,
+ },
Circle {
c: Vec2,
r: f64,
@@ -153,6 +159,54 @@ pub fn loop_shapes(lp: &Loop2) -> Vec<DxfShape> {
lp.segs.iter().map(seg_shape).collect()
}
+/// The closed loop as one AutoCAD `LWPOLYLINE` entity, with circular arc segments represented
+/// by their DXF bulge (tan of a quarter of the included angle). Free-form curves are sampled as lines.
+pub fn loop_lwpolyline_scaled(lp: &Loop2, scale: f64) -> DxfShape {
+ let mut verts: Vec<(Vec2, f64)> = Vec::new();
+ for s in &lp.segs {
+ match *s {
+ Seg2::Line { a, .. } => {
+ verts.push((a * scale, 0.0));
+ }
+ Seg2::Arc { center, radius, start, sweep } => {
+ if (sweep.abs() - TAU).abs() < 1e-9 {
+ // Full circle: split into two 180° semicircles.
+ let b = if sweep >= 0.0 { 1.0 } else { -1.0 };
+ let p0 = (center + Vec2::from_angle(start) * radius) * scale;
+ let p1 = (center + Vec2::from_angle(start + std::f64::consts::PI) * radius) * scale;
+ verts.push((p0, b));
+ verts.push((p1, b));
+ } else if sweep.abs() > std::f64::consts::PI + 1e-9 {
+ // Arc larger than 180°: split into two pieces.
+ let half = sweep * 0.5;
+ let b = (half / 4.0).tan();
+ let p0 = (center + Vec2::from_angle(start) * radius) * scale;
+ let p1 = (center + Vec2::from_angle(start + half) * radius) * scale;
+ verts.push((p0, b));
+ verts.push((p1, b));
+ } else {
+ let b = (sweep / 4.0).tan();
+ let p0 = (center + Vec2::from_angle(start) * radius) * scale;
+ verts.push((p0, b));
+ }
+ }
+ _ => {
+ let poly = s.polyline(0.01);
+ let count = poly.len().saturating_sub(1);
+ for p in poly.iter().take(count) {
+ verts.push((*p * scale, 0.0));
+ }
+ }
+ }
+ }
+ DxfShape::LwPolyline { verts, closed: true }
+}
+
+/// [`loop_lwpolyline_scaled`] at scale 1.0 (millimetres).
+pub fn loop_lwpolyline(lp: &Loop2) -> DxfShape {
+ loop_lwpolyline_scaled(lp, 1.0)
+}
+
/// A parameter reduced to [0, 2π); one within 1e-12 of a full turn is 0.
fn wrap(t: f64) -> f64 {
let r = t.rem_euclid(TAU);
@@ -221,6 +275,30 @@ impl DxfShape {
match self {
DxfShape::Line(a, b) => out.extend([*a, *b]),
DxfShape::Polyline { points } => out.extend(points.iter().copied()),
+ DxfShape::LwPolyline { verts, closed } => {
+ for (i, (p0, b)) in verts.iter().enumerate() {
+ out.push(*p0);
+ if b.abs() > 1e-12 {
+ let next_idx = if i + 1 < verts.len() {
+ Some(i + 1)
+ } else if *closed {
+ Some(0)
+ } else {
+ None
+ };
+ if let Some(next) = next_idx
+ && let Some((p1, _)) = verts.get(next)
+ {
+ let chord = *p1 - *p0;
+ let mid = (*p0 + *p1) * 0.5;
+ let arc_mid = mid + chord.perp() * (*b * 0.5);
+ if arc_mid.x.is_finite() && arc_mid.y.is_finite() {
+ out.push(arc_mid);
+ }
+ }
+ }
+ }
+ }
DxfShape::Circle { c, r } => out.extend([*c - Vec2::new(*r, *r), *c + Vec2::new(*r, *r)]),
DxfShape::Arc { c, r, a0, a1 } => {
let sweep = (a1 - a0).rem_euclid(360.0);
@@ -349,6 +427,11 @@ fn text_value(s: &str) -> Result<String> {
/// (layer `0` is always there). A TEXT character beyond U+FFFF returns an error naming the
/// character, its position, the entity and its layer; no drawing is returned on failure.
pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result<String> {
+ write_dxf_drawing_units(layers, entities, 4)
+}
+
+/// [`write_dxf_drawing`], with explicit DXF `$INSUNITS` (1 in, 2 ft, 4 mm, 5 cm, 6 m).
+pub fn write_dxf_drawing_units(layers: &[DxfLayer], entities: &[DxfEntity], insunits: i32) -> Result<String> {
let mut pts = Vec::new();
for e in entities {
e.shape.sample(&mut pts);
@@ -507,7 +590,7 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result<
for (index, e) in entities.iter().enumerate() {
let kind = match &e.shape {
DxfShape::Line(..) => "LINE",
- DxfShape::Polyline { .. } => "LWPOLYLINE",
+ DxfShape::Polyline { .. } | DxfShape::LwPolyline { .. } => "LWPOLYLINE",
DxfShape::Circle { .. } => "CIRCLE",
DxfShape::Arc { .. } => "ARC",
DxfShape::Ellipse { .. } => "ELLIPSE",
@@ -531,6 +614,19 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result<
o.num(20, p.y);
}
}
+ DxfShape::LwPolyline { verts, closed } => {
+ o.code(100, "AcDbPolyline");
+ o.code(90, verts.len());
+ // Autodesk DXF reference: bit 1 closed, bit 128 (PLINEGEN) continues dash pattern.
+ o.code(70, 128 + if *closed { 1 } else { 0 });
+ for (p, b) in verts {
+ o.num(10, p.x);
+ o.num(20, p.y);
+ if b.abs() > 1e-12 {
+ o.num(42, *b);
+ }
+ }
+ }
DxfShape::Line(a, b) => {
o.code(100, "AcDbLine");
o.point(10, *a);
@@ -632,9 +728,9 @@ pub fn write_dxf_drawing(layers: &[DxfLayer], entities: &[DxfEntity]) -> Result<
head.code(9, "$HANDSEED");
head.code(5, format!("{:X}", o.next));
head.code(9, "$INSUNITS");
- head.code(70, 4);
+ head.code(70, insunits);
head.code(9, "$MEASUREMENT");
- head.code(70, 1);
+ head.code(70, if insunits == 1 || insunits == 2 { 0 } else { 1 });
head.code(9, "$EXTMIN");
head.point(10, lo);
head.code(9, "$EXTMAX");
@@ -1128,4 +1224,62 @@ mod tests {
assert_eq!(&after("$EXTMIN")[..2], &[(10, "27.0".to_string()), (20, "6.0".to_string())]);
assert_eq!(&after("$EXTMAX")[..2], &[(10, "30.0".to_string()), (20, "18.0".to_string())]);
}
+
+ #[test]
+ fn lwpolyline_with_bulge_and_units_round_trip() {
+ // Closed loop with a line and a 90° arc segment (bulge tan(pi / 8)).
+ let sweep = FRAC_PI_2;
+ let bulge = (sweep / 4.0).tan();
+ let loop2 = Loop2 {
+ segs: vec![
+ Seg2::Line { a: Vec2::new(10.0, 0.0), b: Vec2::new(0.0, 0.0) },
+ Seg2::Line { a: Vec2::new(0.0, 0.0), b: Vec2::new(0.0, 10.0) },
+ Seg2::Arc { center: Vec2::ZERO, radius: 10.0, start: FRAC_PI_2, sweep: -FRAC_PI_2 },
+ ],
+ };
+ let shape = loop_lwpolyline(&loop2);
+ let DxfShape::LwPolyline { ref verts, closed } = shape else { panic!("expected LwPolyline") };
+ assert!(closed);
+ assert_eq!(verts.len(), 3);
+ // Third segment is clockwise (-90°), bulge is negative
+ assert!((verts[2].1 - (-bulge)).abs() < 1e-12, "bulge was {}", verts[2].1);
+
+ // Write with inch units (insunits = 1)
+ let dxf = write_dxf_drawing_units(
+ &[DxfLayer::new("CUT", 4)],
+ &[DxfEntity { layer: "CUT".into(), shape: loop_lwpolyline_scaled(&loop2, 1.0 / 25.4) }],
+ 1,
+ )
+ .unwrap();
+ assert!(dxf.contains("LWPOLYLINE"));
+ assert!(dxf.contains("\n 8\nCUT\n") || dxf.contains("\n8\nCUT\n"));
+ assert!(dxf.contains("\n 70\n1\n") || dxf.contains("\n70\n1\n")); // $INSUNITS 1
+
+ // Read back via read_dxf: should scale from inches back to mm
+ let geom = read_dxf(&dxf).unwrap();
+ assert_eq!(geom.len(), 3);
+ // Arcs and lines should be recovered in millimetres
+ let Some((c, a, b)) = geom.iter().find_map(|g| match *g {
+ Geom2::Arc { c, a, b } => Some((c, a, b)),
+ _ => None,
+ }) else {
+ panic!("arc not recovered");
+ };
+ assert!(c.dist(Vec2::ZERO) < 1e-6);
+ assert!((c.dist(a) - 10.0).abs() < 1e-6);
+ assert!((c.dist(b) - 10.0).abs() < 1e-6);
+ }
+
+ #[test]
+ fn lwpolyline_open_sampling_does_not_wrap_around() {
+ // Unclosed polyline with 2 vertices: (0, 0) and (10, 0), with a bulge on the last vertex.
+ // For an unclosed polyline, the last vertex cannot form an arc segment to vertex 0.
+ let shape = DxfShape::LwPolyline { verts: vec![(Vec2::new(0.0, 0.0), 0.0), (Vec2::new(10.0, 0.0), 1.0)], closed: false };
+ let mut pts = Vec::new();
+ shape.sample(&mut pts);
+ // Only the two vertices should be sampled, not an arc chord back to (0, 0)
+ assert_eq!(pts.len(), 2);
+ assert_eq!(pts[0], Vec2::new(0.0, 0.0));
+ assert_eq!(pts[1], Vec2::new(10.0, 0.0));
+ }
}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 4216e8ff8b..603c073807 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -39,8 +39,11 @@ mod threemf;
pub mod urdf;
pub mod vfs;
-pub use dxf::{read_dxf, write_dxf};
-pub use dxf_out::{DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_shapes, seg_shape, write_dxf_drawing};
+pub use dxf::{DxfWriteOptions, read_dxf, write_dxf, write_dxf_entities, write_dxf_opts};
+pub use dxf_out::{
+ DxfEntity, DxfLayer, DxfLinetype, DxfShape, loop_lwpolyline, loop_lwpolyline_scaled, loop_shapes, seg_shape, write_dxf_drawing,
+ write_dxf_drawing_units,
+};
pub use legacy_dir::{APP_ID, LEGACY_APP_ID, PREVIOUS_APP_IDS, adopt_legacy_dir, legacy_flatpak_paths};
pub use safe_write::{backup_path, write_atomic};
pub use sketch2d::{Geom2, MAX_DRAWING_BYTES};