diff --git a/Cargo.lock b/Cargo.lock index 6272ba25..1dae744f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1220,7 +1220,7 @@ checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" [[package]] name = "draftcraft" -version = "2.0.2" +version = "2.1.0" dependencies = [ "chrono", "clap", @@ -1250,7 +1250,7 @@ dependencies = [ [[package]] name = "draftcraft-cli" -version = "2.0.2" +version = "2.1.0" dependencies = [ "clap", "clap_complete", @@ -1266,14 +1266,14 @@ dependencies = [ [[package]] name = "draftcraft-color" -version = "2.0.2" +version = "2.1.0" dependencies = [ "serde", ] [[package]] name = "draftcraft-constraints" -version = "2.0.2" +version = "2.1.0" dependencies = [ "draftcraft-doc", "draftcraft-geom", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "draftcraft-doc" -version = "2.0.2" +version = "2.1.0" dependencies = [ "draftcraft-color", "draftcraft-geom", @@ -1294,7 +1294,7 @@ dependencies = [ [[package]] name = "draftcraft-dwg" -version = "2.0.2" +version = "2.1.0" dependencies = [ "acadrust", "log", @@ -1302,7 +1302,7 @@ dependencies = [ [[package]] name = "draftcraft-dxf" -version = "2.0.2" +version = "2.1.0" dependencies = [ "encoding_rs", "log", @@ -1311,7 +1311,7 @@ dependencies = [ [[package]] name = "draftcraft-engine" -version = "2.0.2" +version = "2.1.0" dependencies = [ "craft-docpath", "draftcraft-color", @@ -1333,7 +1333,7 @@ dependencies = [ [[package]] name = "draftcraft-fonts" -version = "2.0.2" +version = "2.1.0" dependencies = [ "draftcraft-geom", "encoding_rs", @@ -1345,14 +1345,14 @@ dependencies = [ [[package]] name = "draftcraft-geom" -version = "2.0.2" +version = "2.1.0" dependencies = [ "serde", ] [[package]] name = "draftcraft-io" -version = "2.0.2" +version = "2.1.0" dependencies = [ "acadrust", "craft-pdf", @@ -1375,7 +1375,7 @@ dependencies = [ [[package]] name = "draftcraft-mcp" -version = "2.0.2" +version = "2.1.0" dependencies = [ "clap", "draftcraft-engine", @@ -1389,7 +1389,7 @@ dependencies = [ [[package]] name = "draftcraft-render" -version = "2.0.2" +version = "2.1.0" dependencies = [ "draftcraft-color", "draftcraft-doc", @@ -1403,7 +1403,7 @@ dependencies = [ [[package]] name = "draftcraft-ui-egui" -version = "2.0.2" +version = "2.1.0" dependencies = [ "chrono", "craft-ui", @@ -1430,7 +1430,7 @@ dependencies = [ [[package]] name = "draftcraft-web" -version = "2.0.2" +version = "2.1.0" dependencies = [ "craft-web-host", "draftcraft-engine", @@ -6208,7 +6208,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "2.0.2" +version = "2.1.0" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 794fbd47..4ed33777 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "2.0.2" +version = "2.1.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/README.md b/README.md index d6837403..1515192d 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ DraftCraft is young and moving fast. [ROADMAP.md](ROADMAP.md) has what is missin | Annotation | DIM commands with dimension styles and associative dimensions, multileaders, tables, TrueType and SHX fonts, right-to-left text | | Hatches and blocks | Pattern, solid and gradient fills; blocks, attributes, the Block Editor, in-place editing, external references | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, parameters with expressions | -| Layouts and output | Paper-space layouts, viewports, page setups, plot styles, PLOT and EXPORTPDF, SVG and PNG export | +| Layouts and output | Paper-space layouts, viewports, page setups, plot styles, PLOT and EXPORTPDF (arcs, circles and splines kept as true curves), SVG and PNG export | | Files | DWG and DXF reading and writing at a chosen version, AUDIT and RECOVER, autosave and drawing recovery. Objects DraftCraft doesn't model yet can be lost on save | | Automation | MCP server, JSON control channel, `draftcraft-cli`, AutoLISP, scripts and alias files | diff --git a/ROADMAP.md b/ROADMAP.md index 9e582885..d364932e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,6 +1,6 @@ # DraftCraft roadmap -DraftCraft **2.0.2** is out for macOS (Apple silicon), Windows (x64 and ARM64) and Linux (x64 AppImage). It is a +DraftCraft **2.1.0** is out for macOS (Apple silicon), Windows (x64 and ARM64) and Linux (x64 AppImage). It is a young project: good for 2D drafting, dimensioning and plotting, and still missing parts of what a full CAD suite does. This page says what works today, what is known to be missing and what comes next. @@ -19,8 +19,8 @@ Something not listed here is broken, or missing something you need? | Annotation | DIM commands with dimension styles and associative dimensions, multileaders, tables, TrueType and SHX fonts, right-to-left text | | Hatches and blocks | Pattern, solid and gradient fills; blocks, attributes, the Block Editor, in-place editing, external references | | Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, parameters with expressions | -| Layouts and output | Paper-space layouts, viewports, page setups, plot styles, PLOT and EXPORTPDF, SVG and PNG export | -| Files | DWG and DXF reading and writing, at a chosen file version; AUDIT and RECOVER; autosave and drawing recovery | +| Layouts and output | Paper-space layouts, viewports, page setups, plot styles, PLOT and EXPORTPDF (arcs, circles and splines kept as true curves), SVG and PNG export | +| Files | DWG and DXF reading and writing, at a chosen file version; AUDIT and RECOVER; autosave and drawing recovery; PDF underlays and PDFIMPORT (PDF vectors to lines, arcs, circles, polylines, splines, hatches and text) | | Automation | MCP server, JSON control channel, `draftcraft-cli`, AutoLISP, scripts and alias files | ## Known gaps @@ -28,14 +28,13 @@ Something not listed here is broken, or missing something you need? - **3D** — there is no 3D modelling yet (no EXTRUDE, REVOLVE, solids or surfaces). - **File round-trips** — some objects that DraftCraft doesn't model can be lost when a DWG or DXF is saved. Keep a copy of drawings that come from other programs before saving over them. -- **Ribbon** — no contextual tabs yet (for example a Text Editor tab while editing MTEXT) and no - slide-out panels; collapsed panels open a plain list of their commands. +- **Ribbon** — no slide-out panels yet; collapsed panels open a plain list of their commands. - **Builds** — the macOS and Windows builds are not signed or notarized, there is no Linux ARM build and no Windows installer yet. ## Next -1. Contextual ribbon tabs and slide-out panels, so the ribbon behaves like Windows CAD in every state. +1. Slide-out ribbon panels, so the ribbon behaves like Windows CAD in every state. 2. Keep every object through a DWG/DXF save. 3. Signed and notarized builds, a Windows installer, and a Linux ARM build. 4. The first 3D commands. diff --git a/crates/doc/src/extents.rs b/crates/doc/src/extents.rs index c83549e1..16f1bbea 100644 --- a/crates/doc/src/extents.rs +++ b/crates/doc/src/extents.rs @@ -12,6 +12,12 @@ pub const MAX_BLOCK_DEPTH: usize = 16; /// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification /// the same way the renderer places it (the stroke font is about 0.88 of the height per character). fn text_box(t: &crate::Text, len: usize) -> Bounds2 { + Bounds2::from_points(text_quad(t, len)) +} + +/// The four corners of the box [`text_box`] bounds, turned with the text (counter-clockwise from +/// the bottom left of the text). +fn text_quad(t: &crate::Text, len: usize) -> [Vec2; 4] { use crate::{HAlign, VAlign}; let w = t.height * 0.9 * t.width_factor.abs().max(0.01) * len.max(1) as f64; // Justified text (TL, ML and BL too) hangs from its alignment point (DXF group 11). @@ -29,7 +35,7 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 { (_, VAlign::Top) => -t.height, }; let local = [Vec2::new(dx, dy), Vec2::new(dx + w, dy), Vec2::new(dx + w, dy + t.height), Vec2::new(dx, dy + t.height)]; - Bounds2::from_points(local.map(|p| origin + p.rotate(t.rotation))) + local.map(|p| origin + p.rotate(t.rotation)) } /// Whether an entity inside a block definition shows: its own invisible flag and its layer count, @@ -65,6 +71,11 @@ fn blank(s: &str) -> bool { /// Approximate box of an MTEXT, from its attachment point, width and line count. fn mtext_box(t: &crate::MText) -> Bounds2 { + Bounds2::from_points(mtext_quad(t)) +} + +/// The four corners of the box [`mtext_box`] bounds, turned with the text. +fn mtext_quad(t: &crate::MText) -> [Vec2; 4] { let lines = t.contents.split("\\P").count().max(1); let longest = t.contents.split("\\P").map(|l| l.chars().count()).max().unwrap_or(1); let estimate = t.height * 0.8 * longest as f64; @@ -87,9 +98,37 @@ fn mtext_box(t: &crate::MText) -> Bounds2 { _ => 0.0, }; let o = t.insert.xy(); - let pts = [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)] - .map(|p| o + p.rotate(t.rotation)); - Bounds2::from_points(pts) + [Vec2::new(dx, top + dy), Vec2::new(dx + w, top + dy), Vec2::new(dx + w, top - h + dy), Vec2::new(dx, top - h + dy)] + .map(|p| o + p.rotate(t.rotation)) +} + +/// The box a TEXT, MTEXT or ATTDEF takes, turned with the text: the four corners of the box whose +/// axis-aligned bounds [`entity_bounds`] gives. Picking hits text inside this box, not inside its +/// bounds, which for turned text reach far past the letters (a text at 45° covered a square around +/// it, taking picks meant for the line beside it). `None` for other objects and for text that +/// draws nothing (blank, or hidden at the current annotation scale). +pub fn text_outline(d: &Drawing, e: &Entity) -> Option<[Vec2; 4]> { + let scaled; + let e = match d.anno_draw(e) { + crate::AnnoDraw::Plain => e, + crate::AnnoDraw::Hidden => return None, + crate::AnnoDraw::Scaled(f) => { + scaled = crate::anno_scaled(e, f); + &scaled + } + }; + let upright = e.common.matches_layout_orientation(); + let quad = match &e.kind { + EntityKind::Text(t) if blank(&t.value) => return None, + EntityKind::MText(t) if blank(&t.contents) => return None, + EntityKind::Text(t) if upright => text_quad(&crate::Text { rotation: 0.0, ..t.clone() }, t.value.chars().count()), + EntityKind::MText(t) if upright => mtext_quad(&crate::MText { rotation: 0.0, ..t.clone() }), + EntityKind::Text(t) => text_quad(t, t.value.chars().count()), + EntityKind::AttDef(a) => text_quad(&a.text, a.tag.chars().count()), + EntityKind::MText(t) => mtext_quad(t), + _ => return None, + }; + quad.iter().all(|p| p.is_finite()).then_some(quad) } /// The box of what `e` draws (block contents on layers turned off left out). diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index dd8580a0..a42b34b3 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -29,7 +29,7 @@ pub use constraint::*; pub use draftcraft_color as color; pub use draftcraft_geom as geom; pub use entity::*; -pub use extents::{BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached}; +pub use extents::{BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, text_outline}; pub use format::Format; pub use gdt::*; pub use header::{HVal, Header}; diff --git a/crates/engine/src/select.rs b/crates/engine/src/select.rs index 7a63ce1a..4346cabe 100644 --- a/crates/engine/src/select.rs +++ b/crates/engine/src/select.rs @@ -1,6 +1,6 @@ //! Hit testing and window/crossing selection. -use draftcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds}; +use draftcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds, text_outline}; use draftcraft_geom::{Bounds2, Line, Vec2, point_in_polygon}; use crate::spatial::{self, SpatialIndex}; @@ -18,12 +18,19 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec> { | EntityKind::Tolerance(_) | EntityKind::MLeader(_) | EntityKind::Image(_) => { - // Text-like objects are hit inside their box. - let b = entity_bounds(d, e, 0); - if b.is_empty() { - return Vec::new(); - } - let c = b.corners(); + // Text-like objects are hit inside their box: text turned with it, not the (much + // larger) axis-aligned bounds of turned text. + let c = match text_quad(d, e) { + Some(q) => q, + None if matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)) => return Vec::new(), + None => { + let b = entity_bounds(d, e, 0); + if b.is_empty() { + return Vec::new(); + } + b.corners() + } + }; let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]]; if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) { let list = draftcraft_render::build_entities( @@ -90,7 +97,7 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min); let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_)) || matches!(e.kind, EntityKind::Tolerance(_)); - if (filled && entity_bounds(d, e, 0).contains(p)) || in_text(d, e, p) { + if (filled && in_text_box(d, e, p)) || in_text(d, e, p) { best = 0.0; } // A solid hatch fills its loops with odd parity under its island style, as it is drawn, not @@ -108,6 +115,42 @@ pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 { best } +/// The box around the letters a TEXT, MTEXT or ATTDEF draws, turned with the text: the extents +/// of its drawn strokes and glyphs along and across its baseline, as AutoCAD's text box. Spaces +/// and the room above lower-case letters are not in it, which the estimate [`text_outline`] +/// (the full height, a fixed width per character) took in; that estimate stands in when the text +/// draws nothing measurable. +fn text_quad(d: &Drawing, e: &Entity) -> Option<[Vec2; 4]> { + let est = text_outline(d, e)?; + let (a, b) = (est[0], est[1]); + let along = b - a; + let angle = if along.len() > 1e-12 { along.y.atan2(along.x) } else { 0.0 }; + // Fine enough for a box: a few hundred steps along the text's estimated size. + let size = Bounds2::from_points(est); + let tol = ((size.width() + size.height()) / 400.0).max(1e-9); + let list = draftcraft_render::build_entities( + d, + std::iter::once(e), + &draftcraft_render::Options { tolerance: tol, text: true, linetypes: false, ..Default::default() }, + ); + let ink = + Bounds2::from_points(list.prims.iter().flat_map(|p| list.points(p).iter().copied()).filter(|q| q.is_finite()).map(|q| q.rotate(-angle))); + if ink.is_empty() || (ink.width() <= 0.0 && ink.height() <= 0.0) { + return Some(est); + } + let c = ink.corners(); + Some(c.map(|q| q.rotate(angle))) +} + +/// Whether `p` is inside the box of a text-like object: around its letters, turned with the +/// text, for TEXT, MTEXT and ATTDEF ([`text_quad`]), the bounds for tables and tolerances. +fn in_text_box(d: &Drawing, e: &Entity, p: Vec2) -> bool { + match text_quad(d, e) { + Some(q) => point_in_polygon(&q, p), + None => !matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_)) && entity_bounds(d, e, 0).contains(p), + } +} + /// Whether `p` is on the text of a dimension or multileader: inside the box around its words, /// turned with the text, as plain text is hit anywhere inside its box. Their other geometry is /// hit along its lines, so without this the cursor found the object only between the letters' @@ -281,7 +324,12 @@ pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option, bx: &Bo } }); // A crossing box entirely inside a text/block bounding rectangle also selects it. - if hit || (eb.contains_box(bx) && matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_))) { + let inside_text = match &e.kind { + EntityKind::Text(_) | EntityKind::MText(_) => text_quad(d, e).is_some_and(|q| bx.corners().iter().all(|c| point_in_polygon(&q, *c))), + EntityKind::Insert(_) => eb.contains_box(bx), + _ => false, + }; + if hit || inside_text { return true; } // SOLID/TRACE are filled polygons. A crossing window wholly within the diff --git a/crates/engine/tests/it/pick_text.rs b/crates/engine/tests/it/pick_text.rs index f080faaf..9893bb25 100644 --- a/crates/engine/tests/it/pick_text.rs +++ b/crates/engine/tests/it/pick_text.rs @@ -123,3 +123,55 @@ fn a_dimension_drawn_from_its_block_is_picked_on_the_block_text() { assert_eq!(pick(d, &Space::Model, mid, 0.01), Some(dim), "on the block's text"); assert_eq!(pick(d, &Space::Model, Vec2::new(50.0, 33.0), 0.01), None, "not where the dimension would have set it"); } + +/// The case reported from the field: text turned 40° set just above a diagonal line. The text's +/// axis-aligned bounds cover the line and a wide empty corner below it; picks there must find the +/// line (or nothing), not the text, at any pickbox size. Text is hit inside its own turned box. +#[test] +fn turned_text_is_picked_inside_its_turned_box_not_its_bounds() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [100, 84]]})).unwrap(); + for (kind, params) in [ + ("text", json!({"at": [20, 22], "height": 5, "text": "dlocd", "rotation": 40})), + ("mtext", json!({"at": [20, 22], "height": 5, "text": "dlocd", "rotation": 40, "justify": "BL"})), + ] { + s.execute(kind, ¶ms).unwrap(); + let d = s.doc().unwrap(); + let line = d.model.iter().find(|e| matches!(e.kind, EntityKind::Line(_))).unwrap().handle; + let text = d.model.iter().last().unwrap().handle; + let a = 40f64.to_radians(); + let along = |u: f64, v: f64| Vec2::new(20.0, 22.0) + Vec2::new(u, v).rotate(a); + for ap in [0.05, 0.5, 1.5] { + // On the letters, in the middle of the word: the text. + assert_eq!(pick(d, &Space::Model, along(10.0, 2.5), ap), Some(text), "{kind} on its words (aperture {ap})"); + // On the line where it runs under the text's bounds: the line, not the text. + let on_line = Vec2::new(30.0, 25.2); + assert!(draftcraft_engine::doc::entity_bounds(d, d.entity(text).unwrap(), 0).contains(on_line), "{kind}: probe in the loose bounds"); + assert_eq!(pick(d, &Space::Model, on_line, ap), Some(line), "{kind} the line under the text's bounds (aperture {ap})"); + // The empty bottom-right corner of the text's bounds: nothing. + assert!(draftcraft_engine::doc::entity_bounds(d, d.entity(text).unwrap(), 0).contains(Vec2::new(35.0, 23.0))); + assert_eq!(pick(d, &Space::Model, Vec2::new(35.0, 23.0), ap), None, "{kind} the empty corner (aperture {ap})"); + } + s.execute("erase", &json!({"handles": [text.0]})).unwrap(); + } +} + +/// Text is hit around its letters, not around an estimate of the full font height and a fixed +/// width per character: above lower-case letters and past the end of the word is off the text +/// (a line drawn there is what the cursor finds). +#[test] +fn text_is_picked_around_its_letters_not_a_full_height_estimate() { + let mut s = Session::new(); + for rotation in [0.0, 40.0] { + s.execute("text", &json!({"at": [0, 0], "height": 5, "text": "zoom e", "rotation": rotation})).unwrap(); + let d = s.doc().unwrap(); + let text = d.model.iter().last().unwrap().handle; + let a = f64::to_radians(rotation); + let at = |u: f64, v: f64| Vec2::new(u, v).rotate(a); + // On the letters. + assert_eq!(pick(d, &Space::Model, at(3.0, 1.5), 0.05), Some(text), "on 'z' at {rotation}°"); + // Inside the old estimate (5 high), above the lower-case letters. + assert_eq!(pick(d, &Space::Model, at(8.0, 4.7), 0.05), None, "above the letters at {rotation}°"); + s.execute("erase", &json!({"handles": [text.0]})).unwrap(); + } +} diff --git a/crates/engine/tests/pdf_underlay.rs b/crates/engine/tests/pdf_underlay.rs index 30a68af7..a00a76d2 100644 --- a/crates/engine/tests/pdf_underlay.rs +++ b/crates/engine/tests/pdf_underlay.rs @@ -159,9 +159,8 @@ fn pdfimport_turns_a_page_into_objects() { layers.sort(); assert_eq!(layers, ["PDF_Geometry", "PDF_Solid Fills", "PDF_Text"]); // At 72 units per inch one point is one unit: the line runs from (172, 72) to (244, 72). - let line = d.model.iter().find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.clone()) } else { None }).unwrap(); - let pts: Vec<(f64, f64)> = line.vertices.iter().map(|v| (v.p.x, v.p.y)).collect(); - assert_eq!(pts, [(172.0, 72.0), (244.0, 72.0)]); + let line = d.model.iter().find_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.clone()) } else { None }).unwrap(); + assert_eq!([(line.a.x, line.a.y), (line.b.x, line.b.y)], [(172.0, 72.0), (244.0, 72.0)]); let text = d.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); assert_eq!(text.value, "Plan"); assert!((text.insert.x - 172.0).abs() < 1e-6 && (text.insert.y - 300.0).abs() < 1e-6); diff --git a/crates/geom/src/bezier.rs b/crates/geom/src/bezier.rs new file mode 100644 index 00000000..06f523d4 --- /dev/null +++ b/crates/geom/src/bezier.rs @@ -0,0 +1,300 @@ +//! Curves as cubic Bézier paths, for writers whose formats draw with Béziers (PDF, SVG): circular +//! and elliptical arcs as cubics of at most a quarter turn each (off the true curve by under +//! 0.03 % of the radius), polylines with bulges as lines and arcs, and non-rational B-splines of +//! degree 2 or 3 exactly, by Bézier decomposition. +//! +//! A path written this way keeps its curves: a reader (or DraftCraft's own PDFIMPORT) gets arcs and +//! splines back, instead of the hundreds of short lines a tessellated curve leaves. + +use std::f64::consts::FRAC_PI_2; + +use crate::{Arc, Circle, Ellipse, Mat3, Polyline, Segment, Spline, TAU, Vec2}; + +/// Most cubic pieces one path holds; a longer one is left to tessellation. +const MAX_PIECES: usize = 20_000; + +/// One piece of a path, from the end of the previous one. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PathSeg { + /// A straight segment to the point. + Line(Vec2), + /// A cubic Bézier through two control points to the last point. + Cubic(Vec2, Vec2, Vec2), +} + +impl PathSeg { + /// The point the piece ends at. + pub fn end(&self) -> Vec2 { + match self { + PathSeg::Line(p) | PathSeg::Cubic(_, _, p) => *p, + } + } + + fn map(&self, f: impl Fn(Vec2) -> Vec2) -> PathSeg { + match *self { + PathSeg::Line(p) => PathSeg::Line(f(p)), + PathSeg::Cubic(a, b, c) => PathSeg::Cubic(f(a), f(b), f(c)), + } + } +} + +/// A path: a start point and the pieces that follow it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BezierPath { + pub start: Vec2, + pub segs: Vec, +} + +impl BezierPath { + /// The point the path ends at. + pub fn end(&self) -> Vec2 { + self.segs.last().map_or(self.start, PathSeg::end) + } + + /// The path under an affine transform: exact, as a Bézier curve's image is the curve of its + /// control points' images. + pub fn transformed(&self, m: &Mat3) -> BezierPath { + BezierPath { start: m.apply(self.start), segs: self.segs.iter().map(|s| s.map(|p| m.apply(p))).collect() } + } + + /// The path with `f` applied to every point (an affine `f` keeps it exact). + pub fn mapped(&self, f: impl Fn(Vec2) -> Vec2) -> BezierPath { + BezierPath { start: f(self.start), segs: self.segs.iter().map(|s| s.map(&f)).collect() } + } + + /// Whether the path has a curved piece (else it is a polyline). + pub fn has_curves(&self) -> bool { + self.segs.iter().any(|s| matches!(s, PathSeg::Cubic(..))) + } + + /// Whether every point of the path is finite. + pub fn is_finite(&self) -> bool { + self.start.is_finite() + && self.segs.iter().all(|s| match s { + PathSeg::Line(p) => p.is_finite(), + PathSeg::Cubic(a, b, c) => a.is_finite() && b.is_finite() && c.is_finite(), + }) + } +} + +/// Cubic pieces of the unit-circle arc from angle `a0` turning by `sweep` (negative: clockwise), +/// mapped through `f` (from unit-circle coordinates to the curve's). Each piece turns at most a +/// quarter: its handles are `4/3 · tan(θ/4)` long, the usual best fit. +fn unit_arc(a0: f64, sweep: f64, f: impl Fn(Vec2) -> Vec2, out: &mut Vec) -> bool { + if !(a0.is_finite() && sweep.is_finite()) || sweep == 0.0 { + return false; + } + let n = (sweep.abs() / FRAC_PI_2).ceil().clamp(1.0, 8.0) as usize; + let step = sweep / n as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + for i in 0..n { + let (t0, t1) = (a0 + step * i as f64, a0 + step * (i + 1) as f64); + let (p0, p3) = (Vec2::new(t0.cos(), t0.sin()), Vec2::new(t1.cos(), t1.sin())); + let p1 = p0 + p0.perp() * k; + let p2 = p3 - p3.perp() * k; + out.push(PathSeg::Cubic(f(p1), f(p2), f(p3))); + } + true +} + +impl Arc { + /// The arc counter-clockwise from its start, as cubic pieces. + pub fn bezier(&self) -> Option { + let (c, r) = (self.center, self.radius); + let mut segs = Vec::new(); + unit_arc(self.start, self.sweep(), |p| c + p * r, &mut segs).then_some(())?; + Some(BezierPath { start: self.start_point(), segs }) + } +} + +impl Circle { + /// The circle counter-clockwise from angle 0 (where its tessellation starts), as four cubics. + pub fn bezier(&self) -> Option { + Arc { center: self.center, radius: self.radius, start: 0.0, end: TAU }.bezier() + } +} + +impl Ellipse { + /// The elliptical arc counter-clockwise from its start parameter, as cubic pieces: the + /// circular pieces under the affine map taking the unit circle to the ellipse (exact as such). + pub fn bezier(&self) -> Option { + let (c, u, v) = (self.center, self.major, self.minor()); + let f = |p: Vec2| c + u * p.x + v * p.y; + let mut segs = Vec::new(); + unit_arc(self.start, self.sweep(), f, &mut segs).then_some(())?; + Some(BezierPath { start: self.at_param(self.start), segs }) + } +} + +impl Segment { + /// The pieces of this segment from its start (see [`Segment::start`]). + fn bezier_into(&self, out: &mut Vec) -> bool { + match self { + Segment::Line(l) => { + out.push(PathSeg::Line(l.b)); + true + } + Segment::Arc { arc, ccw } => { + let (c, r) = (arc.center, arc.radius); + let sweep = arc.sweep(); + if *ccw { unit_arc(arc.start, sweep, |p| c + p * r, out) } else { unit_arc(arc.end, -sweep, |p| c + p * r, out) } + } + } + } + + /// The segment as a path from its start. + pub fn bezier(&self) -> Option { + let mut segs = Vec::new(); + self.bezier_into(&mut segs).then_some(())?; + Some(BezierPath { start: self.start(), segs }) + } +} + +impl Polyline { + /// The polyline's lines and arcs as one path (closed back to the start when closed). + pub fn bezier(&self) -> Option { + let segs = self.segments(); + let first = segs.first()?; + let mut out = Vec::new(); + for s in &segs { + if !s.bezier_into(&mut out) || out.len() > MAX_PIECES { + return None; + } + } + Some(BezierPath { start: first.start(), segs: out }) + } +} + +impl Spline { + /// A non-rational spline of degree 2 or 3 as its cubic Bézier pieces, exactly (degree 2 + /// raised to 3). `None` for rational splines, other degrees and broken knot vectors, which + /// are left to tessellation. + pub fn bezier(&self) -> Option { + if self.is_rational() || !(2..=3).contains(&self.degree) { + return None; + } + let (pieces, _) = self.bezier_pieces()?; + if pieces.len() > MAX_PIECES { + return None; + } + let mut start = None; + let mut segs = Vec::with_capacity(pieces.len()); + for piece in pieces { + let mut q = piece; + while q.len() < 4 { + q = crate::nurbs::elevate_bezier(&q); + } + // Non-rational: every weight is 1, so the homogeneous points are the points. + let [a, b, c, d] = q.get(..4)?.iter().map(|h| h.0).collect::>().try_into().ok()?; + start.get_or_insert(a); + segs.push(PathSeg::Cubic(b, c, d)); + } + let path = BezierPath { start: start?, segs }; + path.is_finite().then_some(path) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::PolyVertex; + + /// The point at `t` on a cubic. + fn at(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: f64) -> Vec2 { + let s = 1.0 - t; + p0 * (s * s * s) + p1 * (3.0 * s * s * t) + p2 * (3.0 * s * t * t) + p3 * (t * t * t) + } + + /// Every point sampled along the path's cubics, with its lines' ends. + fn samples(p: &BezierPath) -> Vec { + let mut out = vec![p.start]; + let mut cur = p.start; + for s in &p.segs { + match *s { + PathSeg::Line(q) => out.push(q), + PathSeg::Cubic(a, b, c) => out.extend((1..=16).map(|i| at(cur, a, b, c, f64::from(i) / 16.0))), + } + cur = s.end(); + } + out + } + + #[test] + fn a_circle_is_four_cubics_on_the_circle() { + let c = Circle::new(Vec2::new(3.0, -2.0), 5.0); + let p = c.bezier().unwrap(); + assert_eq!(p.segs.len(), 4); + assert!(p.start.near(Vec2::new(8.0, -2.0), 1e-12)); + assert!(p.end().near(p.start, 1e-9)); + for q in samples(&p) { + assert!((q.dist(c.center) - 5.0).abs() < 5.0 * 3e-4, "{q:?}"); + } + } + + #[test] + fn arcs_turn_their_way_and_end_where_they_end() { + let arc = Arc::new(Vec2::ZERO, 2.0, 0.3, 2.9); + let p = arc.bezier().unwrap(); + assert!(p.start.near(arc.start_point(), 1e-12) && p.end().near(arc.end_point(), 1e-9)); + assert_eq!(p.segs.len(), 2); + let cw = Segment::Arc { arc, ccw: false }.bezier().unwrap(); + assert!(cw.start.near(arc.end_point(), 1e-12) && cw.end().near(arc.start_point(), 1e-9)); + for q in samples(&cw) { + assert!((q.len() - 2.0).abs() < 2.0 * 3e-4); + } + } + + #[test] + fn an_ellipse_arc_stays_on_the_ellipse() { + let e = Ellipse { center: Vec2::new(1.0, 1.0), major: Vec2::new(4.0, 3.0), ratio: 0.4, start: 0.5, end: 4.0 }; + let p = e.bezier().unwrap(); + assert!(p.start.near(e.at_param(0.5), 1e-12) && p.end().near(e.at_param(4.0), 1e-9)); + // In the ellipse's own frame the samples sit on the unit circle. + let (u, v) = (e.major, e.minor()); + for q in samples(&p) { + let d = q - e.center; + let (x, y) = (d.dot(u) / u.dot(u), d.dot(v) / v.dot(v)); + assert!(((x * x + y * y).sqrt() - 1.0).abs() < 3e-4, "{q:?}"); + } + } + + #[test] + fn a_bulged_polyline_is_lines_and_arcs() { + let pl = Polyline { + vertices: vec![ + PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(0.0, 0.0)) }, + PolyVertex::new(Vec2::new(10.0, 0.0)), + PolyVertex::new(Vec2::new(10.0, 5.0)), + ], + closed: false, + }; + let p = pl.bezier().unwrap(); + assert!(p.has_curves()); + assert_eq!(p.segs.last(), Some(&PathSeg::Line(Vec2::new(10.0, 5.0)))); + // The half circle below the chord (bulge 1, counter-clockwise from (0,0) to (10,0)). + assert!(samples(&p).iter().any(|q| q.near(Vec2::new(5.0, -5.0), 1e-3))); + } + + #[test] + fn a_cubic_spline_is_its_bezier_pieces_exactly() { + let s = + Spline::from_control(vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 3.0), Vec2::new(4.0, 3.0), Vec2::new(6.0, 0.0), Vec2::new(9.0, 1.0)], 3); + let p = s.bezier().unwrap(); + assert_eq!(p.segs.len(), 2); + let pts = s.tessellate(1e-4); + for q in samples(&p) { + let d = pts.windows(2).map(|w| crate::Line::new(w[0], w[1]).dist(q)).fold(f64::INFINITY, f64::min); + assert!(d < 1e-3, "{q:?} off the spline by {d}"); + } + let mut rational = s.clone(); + rational.weights = vec![1.0, 2.0, 1.0, 1.0, 1.0]; + assert!(rational.bezier().is_none(), "rational splines stay tessellated"); + } + + #[test] + fn hostile_input_gives_none_not_a_panic() { + assert!(Arc { center: Vec2::new(f64::NAN, 0.0), radius: 1.0, start: f64::NAN, end: 1.0 }.bezier().is_none()); + assert!(Spline::from_control(vec![Vec2::ZERO], 3).bezier().is_none()); + assert!(Polyline { vertices: Vec::new(), closed: true }.bezier().is_none()); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index cfcc38be..ea9da5bd 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -7,6 +7,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +mod bezier; mod bounds; mod curve; mod fillet; @@ -18,6 +19,7 @@ mod spline; mod spline_fit; mod vec; +pub use bezier::{BezierPath, PathSeg}; pub use bounds::Bounds2; pub use curve::{ Arc, Circle, Ellipse, Line, PolyVertex, Polyline, Segment, arc_to_bulge, bulge_to_arc, point_in_polygon, polygon_centroid, shoelace, diff --git a/crates/geom/src/nurbs.rs b/crates/geom/src/nurbs.rs index 36b064b0..b9374d5b 100644 --- a/crates/geom/src/nurbs.rs +++ b/crates/geom/src/nurbs.rs @@ -21,7 +21,7 @@ const MAX_SPLIT_INSERTS: usize = 64; const MAX_DECOMPOSED: usize = 10_000; /// A homogeneous control point: (w·P, w). -type H = (Vec2, f64); +pub(crate) type H = (Vec2, f64); fn hlerp(a: H, b: H, t: f64) -> H { (a.0 * (1.0 - t) + b.0 * t, a.1 * (1.0 - t) + b.1 * t) @@ -76,7 +76,7 @@ fn bezier_knots(breaks: &[f64], p: usize) -> Vec { } /// One degree elevation of a homogeneous Bézier piece. -fn elevate_bezier(p: &[H]) -> Vec { +pub(crate) fn elevate_bezier(p: &[H]) -> Vec { let n = p.len(); let zero = (Vec2::ZERO, 0.0); (0..=n) @@ -315,7 +315,7 @@ impl Spline { /// Bézier decomposition: the homogeneous control points of each polynomial piece /// (degree + 1 each) and the parameter breaks between them (pieces + 1 values). - fn bezier_pieces(&self) -> Option<(Vec>, Vec)> { + pub(crate) fn bezier_pieces(&self) -> Option<(Vec>, Vec)> { let mut s = self.clamped()?; let p = s.degree; if p > MAX_EDIT_DEGREE { diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index eb6462ae..fe913070 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -860,6 +860,7 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts: let w = if w.is_finite() && w > 0.0 { w.min(100.0) } else { 0.0 }; let m = Mark { rgb, t, w }; match prim.kind { + Kind::Polyline if curve(s, &mut batch, p, list.curve(i), m) => {} Kind::Polyline | Kind::Infinite { .. } => polyline(s, &mut batch, p, prim, raw, m), Kind::Tris | Kind::Mask => { flush(s, &mut batch); @@ -907,6 +908,52 @@ fn polyline(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)>, } } +/// Stroke the exact curve a polyline primitive stands for (an arc, circle, ellipse, spline or +/// bulged polyline) as Bézier pieces into the open batch, so the file keeps curves rather than +/// short lines: a reader (DraftCraft's PDFIMPORT among them) gets arcs and splines back. `false` +/// when there is none or a point is out of range, for the caller to draw the polyline. +fn curve( + s: &mut Surface<'_>, + batch: &mut Option<(StrokeStyle, PathBuilder)>, + p: &SheetPage, + path: Option<&draftcraft_geom::BezierPath>, + m: Mark, +) -> bool { + use draftcraft_geom::PathSeg; + let Some(path) = path.map(|c| c.mapped(|q| p.map.pt(q))) else { return false }; + let pt = |q: Vec2| coord(q).filter(|_| p.clip_pt.expand(m.w + 1.0).contains(q)); + let Some(start) = pt(path.start) else { return false }; + let mut ops = Vec::with_capacity(path.segs.len()); + for seg in &path.segs { + let op = match *seg { + PathSeg::Line(q) => pt(q).map(|q| (None, q)), + PathSeg::Cubic(a, b, c) => match (coord(a), coord(b), pt(c)) { + (Some(a), Some(b), Some(c)) => Some((Some((a, b)), c)), + _ => None, + }, + }; + let Some(op) = op else { return false }; + ops.push(op); + } + // A curve with no extent is drawn as the polyline's dot. + if ops.iter().all(|(_, q)| *q == start) { + return false; + } + let style = StrokeStyle { rgb: m.rgb, width: m.w as f32, transparency: m.t }; + if m.t > 0 || batch.as_ref().is_some_and(|(b, _)| *b != style) { + flush(s, batch); + } + let (_, pb) = batch.get_or_insert_with(|| (style, PathBuilder::new())); + pb.move_to(start.0, start.1); + for (handles, (x, y)) in ops { + match handles { + Some(((x1, y1), (x2, y2))) => pb.cubic_to(x1, y1, x2, y2, x, y), + None => pb.line_to(x, y), + } + } + true +} + /// The page points of a polyline, or of an infinite line clipped to the plot area; `None` when /// there is nothing to draw. fn polyline_points(prim: &DPrim, raw: &[Vec2], map: &Map, clip_pt: &Bounds2) -> Option> { diff --git a/crates/io/src/pdf_read.rs b/crates/io/src/pdf_read.rs index 590d86cd..2e9c7ffb 100644 --- a/crates/io/src/pdf_read.rs +++ b/crates/io/src/pdf_read.rs @@ -3,9 +3,10 @@ //! - [`pages`]: each page's size in points (1/72 inch), as the page is shown (after its rotation). //! - [`rasterize`]: one page as pixels, on white paper, for an underlay to show. //! - [`import`]: one page's vector content as DraftCraft objects in points, the page's lower-left -//! corner at the origin and y up: stroked paths as polylines and splines (each cubic Bézier -//! exactly), filled areas as solid hatches, and text as single-line text. Images, shadings and -//! clipping are not imported. +//! corner at the origin and y up: stroked paths as lines, arcs, circles and polylines (with arc +//! segments) where their curves are circular arcs, as CAD programs write arcs, DraftCraft +//! included; other curves as splines (each cubic Bézier exactly); filled areas as solid +//! hatches, and text as single-line text. Images, shadings and clipping are not imported. //! //! PDF files are hostile input: the input size, page count, objects and points are capped, and //! the reader runs inside `catch_unwind` (craft-pdf's guards), so a damaged file is an error. @@ -17,7 +18,9 @@ use craft_pdf::interpret::{ }; use craft_pdf::syntax::page::Page; use draftcraft_color::Rgb; -use draftcraft_doc::{EntityKind, Hatch, HatchLoop, ImportedShape, LwPolyline, Raster, ShapeClass, Text}; +use draftcraft_doc::{ + Arc as ArcE, Circle as CircleE, EntityKind, Hatch, HatchLoop, ImportedShape, Line as LineE, LwPolyline, Raster, ShapeClass, Text, +}; use draftcraft_geom::{PolyVertex, Spline, Vec2}; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape}; @@ -274,6 +277,171 @@ impl Piece { } } +/// A piece of a subpath once its cubics are known to be circular arcs. +#[derive(Clone, Copy, Debug)] +enum Edge { + Line { + from: Vec2, + to: Vec2, + }, + /// From angle `a0` about `c`, turning by `sweep` (negative: clockwise). + Arc { + c: Vec2, + r: f64, + a0: f64, + sweep: f64, + from: Vec2, + to: Vec2, + }, +} + +impl Edge { + fn from(&self) -> Vec2 { + match *self { + Edge::Line { from, .. } | Edge::Arc { from, .. } => from, + } + } + fn to(&self) -> Vec2 { + match *self { + Edge::Line { to, .. } | Edge::Arc { to, .. } => to, + } + } +} + +/// How far a cubic may stray from the circle it stands for, as a share of the radius: a quarter +/// circle drawn as one cubic is off by 0.027 %, and writers round their handles differently. +const ARC_FIT: f64 = 2e-3; + +/// The angle `a` brought into (-π, π]. +fn wrap(a: f64) -> f64 { + let r = a.rem_euclid(std::f64::consts::TAU); + if r > std::f64::consts::PI { r - std::f64::consts::TAU } else { r } +} + +/// The point at `t` on the cubic. +fn cubic_at(p: [Vec2; 4], t: f64) -> Vec2 { + let s = 1.0 - t; + p[0] * (s * s * s) + p[1] * (3.0 * s * s * t) + p[2] * (3.0 * s * t * t) + p[3] * (t * t * t) +} + +/// The circular arc a cubic draws, when it draws one: centre, radius, start angle and sweep +/// (negative: clockwise). The centre is where the normals at the ends meet; the curve must stay +/// on that circle at its quarter points. +fn cubic_arc(p: [Vec2; 4]) -> Option<(Vec2, f64, f64, f64)> { + let [p0, p1, p2, p3] = p; + let t0 = if p1.dist(p0) > 1e-12 { p1 - p0 } else { p2 - p0 }; + let t3 = if p3.dist(p2) > 1e-12 { p3 - p2 } else { p3 - p1 }; + let (n0, n3) = (t0.perp(), t3.perp()); + let denom = n0.cross(n3); + // Parallel end tangents (or NaN): no centre to find. + if denom.is_nan() || denom.abs() <= 1e-12 * n0.len() * n3.len() { + return None; + } + let c = p0 + n0 * ((p3 - p0).cross(n3) / denom); + let r = c.dist(p0); + if !(r.is_finite() && r > 1e-9 && r < 1e8) { + return None; + } + let tol = r * ARC_FIT; + let on = |q: Vec2| (c.dist(q) - r).abs() <= tol; + if !(on(p3) && [0.25, 0.5, 0.75].iter().all(|t| on(cubic_at(p, *t)))) { + return None; + } + let ang = |q: Vec2| (q.y - c.y).atan2(q.x - c.x); + let (a0, am, a3) = (ang(p0), ang(cubic_at(p, 0.5)), ang(p3)); + let (d1, d2) = (wrap(am - a0), wrap(a3 - am)); + // Both halves turn the same way, the way the curve leaves its start. + let turn = (p0 - c).cross(t0); + if d1 * d2 <= 0.0 || d1 * turn <= 0.0 { + return None; + } + Some((c, r, a0, d1 + d2)) +} + +/// A subpath whose curves are all circular arcs as one object: a circle, an arc, a line, or a +/// polyline with arc segments, and how many points it holds. `None` when it has no curve or a +/// curve that isn't an arc (left to splines). +fn arcs_and_lines(pieces: &[Piece], closed: bool) -> Option<(EntityKind, usize)> { + if !pieces.iter().any(|p| matches!(p, Piece::Curves(_))) { + return None; + } + let mut edges: Vec = Vec::new(); + for piece in pieces { + match piece { + Piece::Lines(pts) => { + for w in pts.windows(2) { + let (Some(a), Some(b)) = (w.first(), w.get(1)) else { continue }; + if a.dist(*b) > 1e-9 { + edges.push(Edge::Line { from: *a, to: *b }); + } + } + } + Piece::Curves(pts) => { + let (first, rest) = pts.split_first()?; + let mut cur = *first; + for c in rest.chunks(3) { + let [c1, c2, to] = <[Vec2; 3]>::try_from(c).ok()?; + let (center, r, a0, sweep) = cubic_arc([cur, c1, c2, to])?; + let arc = Edge::Arc { c: center, r, a0, sweep, from: cur, to }; + // Consecutive pieces of one circle, turning the same way, are one arc. + match edges.last_mut() { + Some(Edge::Arc { c: pc, r: pr, sweep: ps, to: pt, .. }) + if pc.dist(center) <= pr.max(r) * ARC_FIT + && (*pr - r).abs() <= pr.max(r) * ARC_FIT + && *ps * sweep > 0.0 + && (*ps + sweep).abs() <= std::f64::consts::TAU + 1e-6 => + { + *ps += sweep; + *pt = to; + } + _ => edges.push(arc), + } + cur = to; + } + } + } + } + let (first, last) = (edges.first()?, edges.last()?); + let tight = |a: Vec2, b: Vec2| a.dist(b) <= 1e-6 * (1.0 + a.len()); + let ring = tight(first.from(), last.to()); + if let [Edge::Arc { c, r, a0, sweep, .. }] = edges.as_slice() { + let (c, r) = (*c, *r); + if ring && (sweep.abs() - std::f64::consts::TAU).abs() < 1e-3 { + return Some((EntityKind::Circle(CircleE { center: c.to3(0.0), radius: r }), 1)); + } + let (start, end) = if *sweep > 0.0 { (*a0, a0 + sweep) } else { (a0 + sweep, *a0) }; + let n = |a: f64| a.rem_euclid(std::f64::consts::TAU); + return Some((EntityKind::Arc(ArcE { center: c.to3(0.0), radius: r, start: n(start), end: n(end) }), 1)); + } + // A polyline: each edge from its start vertex, an arc segment by its bulge (a whole circle + // inside a polyline as two halves). + let mut vertices: Vec = Vec::with_capacity(edges.len() + 1); + for e in &edges { + match *e { + Edge::Line { from, .. } => vertices.push(PolyVertex::new(from)), + Edge::Arc { c, r, a0, sweep, from, .. } => { + if sweep.abs() >= std::f64::consts::PI * 1.999 { + let half = sweep / 2.0; + let mid = c + Vec2::new((a0 + half).cos(), (a0 + half).sin()) * r; + vertices.push(PolyVertex { bulge: (half / 4.0).tan(), ..PolyVertex::new(from) }); + vertices.push(PolyVertex { bulge: (half / 4.0).tan(), ..PolyVertex::new(mid) }); + } else { + vertices.push(PolyVertex { bulge: (sweep / 4.0).tan(), ..PolyVertex::new(from) }); + } + } + } + } + let closed = closed || ring; + if !ring { + vertices.push(PolyVertex::new(last.to())); + } + if vertices.iter().any(|v| !(v.p.is_finite() && v.bulge.is_finite())) { + return None; + } + let n = vertices.len(); + Some((EntityKind::LwPolyline(LwPolyline { vertices, closed, const_width: 0.0, elevation: 0.0, plinegen: false }), n)) +} + /// The length of the vector (1, 0) under `m`, for widths and sizes. fn mean_scale(m: Affine) -> f64 { let c = m.as_coeffs(); @@ -296,6 +464,15 @@ impl Collector { fn stroke(&mut self, path: &BezPath, m: Affine, color: Option, width: f64) { for (pieces, closed) in subpaths(path, m) { + // Circular arcs (and the lines between them) come back as arcs, circles and + // polylines with arc segments. + if let Some((kind, points)) = arcs_and_lines(&pieces, closed) { + if !self.room(points) { + return; + } + self.push(kind, color, width, ShapeClass::Vector); + continue; + } let whole = pieces.len() == 1; for piece in pieces { if !self.room(piece.len()) { @@ -311,6 +488,11 @@ impl Collector { if pts.len() < 2 { continue; } + // One straight segment is a line. + if let ([a, b], false) = (pts.as_slice(), closed) { + self.push(EntityKind::Line(LineE { a: a.to3(0.0), b: b.to3(0.0) }), color, width, ShapeClass::Vector); + continue; + } let vertices = pts.into_iter().map(PolyVertex::new).collect(); EntityKind::LwPolyline(LwPolyline { vertices, closed, const_width: 0.0, elevation: 0.0, plinegen: false }) } @@ -541,9 +723,9 @@ BT /F1 12 Tf 72 300 Td (Hi there) Tj ET"; fn import_reads_lines_curves_fills_and_text() { let (shapes, notes) = import(&sample_pdf(), 0, ImportOptions::default()).unwrap(); assert_eq!(notes, ImportNotes::default()); - let line = shapes.iter().find(|s| matches!(s.kind, EntityKind::LwPolyline(_))).unwrap(); - let EntityKind::LwPolyline(p) = &line.kind else { panic!("a polyline") }; - assert_eq!(p.vertices.iter().map(|v| v.p).collect::>(), vec![Vec2::new(72.0, 72.0), Vec2::new(144.0, 72.0)]); + let line = shapes.iter().find(|s| matches!(s.kind, EntityKind::Line(_))).unwrap(); + let EntityKind::Line(l) = &line.kind else { panic!("a line") }; + assert_eq!((l.a.xy(), l.b.xy()), (Vec2::new(72.0, 72.0), Vec2::new(144.0, 72.0))); assert_eq!(line.color, Some(Rgb(0, 0, 255))); assert!((line.width - 2.0).abs() < 1e-9); let curve = shapes.iter().find_map(|s| if let EntityKind::Spline(s) = &s.kind { Some(s) } else { None }).unwrap(); diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index a2aa8dd3..dddb45bd 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -52,6 +52,7 @@ mod multiline_attributes; mod ole2frame_roundtrip; mod paperview_marker; mod passthrough_image_roundtrip; +mod pdf_curves; mod pdf_followups; mod pdf_layers; #[path = "../support/pdf_read.rs"] diff --git a/crates/io/tests/it/pdf_curves.rs b/crates/io/tests/it/pdf_curves.rs new file mode 100644 index 00000000..2fad5147 --- /dev/null +++ b/crates/io/tests/it/pdf_curves.rs @@ -0,0 +1,107 @@ +//! PDF plots keep curves: arcs, circles, ellipses, splines and bulged polylines are written as +//! Bézier paths (not hundreds of short lines), and PDFIMPORT reads circular ones back as arcs, +//! circles and polylines with arc segments, so a DraftCraft PDF comes back as editable geometry. + +use draftcraft_doc::{Arc, Circle, Common, Drawing, Ellipse, EntityKind, Line, LwPolyline, Space}; +use draftcraft_geom::{PolyVertex, Spline, Vec2, Vec3}; +use draftcraft_io::{pdf_read, plotter}; +use serde_json::json; + +fn add(d: &mut Drawing, k: EntityKind) { + d.add(&Space::Model, Common::default(), k).unwrap(); +} + +fn drawing() -> Drawing { + let mut d = Drawing::new_metric(); + add(&mut d, EntityKind::Circle(Circle { center: Vec3::new(50.0, 50.0, 0.0), radius: 20.0 })); + add(&mut d, EntityKind::Arc(Arc { center: Vec3::new(120.0, 50.0, 0.0), radius: 15.0, start: 0.2, end: 2.6 })); + add(&mut d, EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(200.0, 0.0, 0.0) })); + let v = |x: f64, y: f64, bulge: f64| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }; + let slot = LwPolyline { + vertices: vec![v(20.0, 100.0, 0.0), v(80.0, 100.0, 1.0), v(80.0, 120.0, 0.0), v(20.0, 120.0, 1.0)], + closed: true, + const_width: 0.0, + elevation: 0.0, + plinegen: false, + }; + add(&mut d, EntityKind::LwPolyline(slot)); + add( + &mut d, + EntityKind::Ellipse(Ellipse { + center: Vec3::new(160.0, 110.0, 0.0), + major: Vec3::new(25.0, 0.0, 0.0), + ratio: 0.5, + start: 0.0, + end: std::f64::consts::TAU, + }), + ); + let spline = Spline::from_control( + vec![Vec2::new(100.0, 140.0), Vec2::new(120.0, 170.0), Vec2::new(150.0, 170.0), Vec2::new(170.0, 140.0), Vec2::new(190.0, 150.0)], + 3, + ); + add(&mut d, EntityKind::Spline(spline)); + d +} + +fn plot(d: &Drawing) -> Vec { + plotter::plot(d, &Space::Model, &json!({"compress": false})).unwrap() +} + +/// How many times the page content uses path operator `op` (`m`, `l`, `c`). +fn ops(bytes: &[u8], op: &str) -> usize { + String::from_utf8_lossy(bytes).split_whitespace().filter(|t| *t == op).count() +} + +#[test] +fn curves_are_written_as_bezier_curves_not_short_lines() { + let bytes = plot(&drawing()); + let curves = ops(&bytes, "c"); + // Circle 4, arc 2, slot 2 × 2, ellipse 4, spline 2 cubic pieces. + assert!(curves >= 16, "{curves} curve operators"); + // The line, the slot's two straight sides and the plot area's clip rectangle; tessellated + // curves would be hundreds. + let lines = ops(&bytes, "l"); + assert!(lines <= 8, "{lines} line operators: curves were tessellated"); +} + +#[test] +fn a_dashed_curve_is_still_drawn_in_dashes() { + let mut d = Drawing::new_metric(); + d.linetypes.push(draftcraft_doc::Linetype::simple("DASHED", "Dashed", &[5.0, -2.5])); + let common = Common { linetype: "DASHED".into(), ..Common::default() }; + d.add(&Space::Model, common, EntityKind::Circle(Circle { center: Vec3::new(0.0, 0.0, 0.0), radius: 100.0 })).unwrap(); + let bytes = plot(&d); + // Dashes are short lines, as before: the whole circle isn't written over them. + assert_eq!(ops(&bytes, "c"), 0); + assert!(ops(&bytes, "m") > 10); +} + +#[test] +fn pdfimport_reads_a_draftcraft_pdf_back_as_arcs_circles_and_lines() { + let bytes = plot(&drawing()); + let (shapes, _) = pdf_read::import(&bytes, 0, pdf_read::ImportOptions::default()).unwrap(); + let count = |f: fn(&EntityKind) -> bool| shapes.iter().filter(|s| f(&s.kind)).count(); + assert_eq!(count(|k| matches!(k, EntityKind::Circle(_))), 1, "the circle"); + assert_eq!(count(|k| matches!(k, EntityKind::Arc(_))), 1, "the arc"); + assert_eq!(count(|k| matches!(k, EntityKind::Line(_))), 1, "the line"); + // The slot: one closed polyline, two straight sides and two half-circle ends. + let slot = shapes + .iter() + .find_map(|s| match &s.kind { + EntityKind::LwPolyline(p) if p.vertices.iter().any(|v| v.bulge.abs() > 0.5) => Some(p), + _ => None, + }) + .expect("the slot as a polyline with arcs"); + assert!(slot.closed); + assert_eq!(slot.vertices.len(), 4, "{:?}", slot.vertices); + assert!(slot.vertices.iter().filter(|v| (v.bulge.abs() - 1.0).abs() < 1e-3).count() == 2); + // The ellipse and the spline stay curves (splines), not lines. + assert_eq!(count(|k| matches!(k, EntityKind::Spline(_))), 2); + // The circle's size survives the plot scale: its radius relative to the arc's. + let r = |f: fn(&EntityKind) -> Option| shapes.iter().find_map(|s| f(&s.kind)).unwrap(); + let rc = r(|k| if let EntityKind::Circle(c) = k { Some(c.radius) } else { None }); + let ra = r(|k| if let EntityKind::Arc(a) = k { Some(a.radius) } else { None }); + assert!((rc / ra - 20.0 / 15.0).abs() < 1e-3, "{rc} / {ra}"); + let ang = shapes.iter().find_map(|s| if let EntityKind::Arc(a) = &s.kind { Some((a.start, a.end)) } else { None }).unwrap(); + assert!((ang.0 - 0.2).abs() < 1e-3 && (ang.1 - 2.6).abs() < 1e-3, "{ang:?}"); +} diff --git a/crates/render/src/display.rs b/crates/render/src/display.rs index ddedec14..c32c3662 100644 --- a/crates/render/src/display.rs +++ b/crates/render/src/display.rs @@ -113,6 +113,37 @@ pub struct DisplayList { /// Plot style end, join and fill style per primitive (parallel to `prims`; missing entries /// are "use object"), turned into geometry by [`pen::apply`]. pub pens: Vec, + /// Plots: the exact curves (arcs, circles, ellipses, splines, bulged polylines) that some + /// polyline primitives tessellate, as Bézier paths in the list's coordinates, in primitive + /// order. A writer that draws Béziers (PDF) writes the curve instead of the polyline, so the + /// file keeps arcs and splines, not hundreds of short lines. Only primitives drawn whole get + /// one: a dashed linetype, a clip or a plot style pen turning the stroke into a fill leaves + /// the polyline. + pub curves: Vec, +} + +/// An exact curve standing for polyline primitive [`DCurve::prim`] (see [`DisplayList::curves`]). +#[derive(Clone, Debug, PartialEq)] +pub struct DCurve { + pub prim: u32, + pub path: draftcraft_geom::BezierPath, +} + +impl DisplayList { + /// The curve for primitive `i`, when it has one and is still the polyline it was drawn as. + pub fn curve(&self, i: usize) -> Option<&draftcraft_geom::BezierPath> { + let prim = self.prims.get(i).filter(|p| p.kind == Kind::Polyline)?; + let k = self.curves.binary_search_by_key(&i, |c| c.prim as usize).ok()?; + let c = self.curves.get(k)?; + let pts = self.points(prim); + let (a, b) = (pts.first()?, pts.last()?); + (same_point(*a, c.path.start) && same_point(*b, c.path.end())).then_some(&c.path) + } +} + +/// Whether two points of one list are the same, up to rounding. +pub(crate) fn same_point(a: Vec2, b: Vec2) -> bool { + a.dist(b) <= 1e-7 * (1.0 + a.len().max(b.len())) } /// A glyph of plotted text: the font glyph and, in world coordinates, where it sits. It is @@ -205,6 +236,10 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) { t })); dst.pens.extend(src.pens); + dst.curves.extend(src.curves.into_iter().map(|mut c| { + c.prim = c.prim.saturating_add(prims); + c + })); dst.bounds = dst.bounds.union(&src.bounds); dst.expanded = dst.expanded.saturating_add(src.expanded); } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 2170668d..b852d109 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -174,12 +174,16 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { EntityKind::LwPolyline(p) => { let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed }; if !b.opts.linetypes || p.plinegen || lt.is_none() { + let before = b.list.prims.len(); stroke(b, &pl.tessellate(tol)); + b.note_curve(ctx, before, || pl.bezier()); } else { for s in pl.segments() { let mut pts = Vec::new(); s.tessellate(tol, &mut pts); + let before = b.list.prims.len(); stroke(b, &pts); + b.note_curve(ctx, before, || s.bezier()); } } } @@ -233,19 +237,29 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { Prim::Seg(s) => { let mut pts = Vec::new(); s.tessellate(tol, &mut pts); + let before = b.list.prims.len(); stroke(b, &pts); + b.note_curve(ctx, before, || s.bezier()); } Prim::Circle(c) => { let mut pts = Vec::new(); c.tessellate(tol, &mut pts); + let before = b.list.prims.len(); stroke(b, &pts); + b.note_curve(ctx, before, || c.bezier()); } Prim::Ellipse(el) => { let mut pts = Vec::new(); el.tessellate(tol, &mut pts); + let before = b.list.prims.len(); stroke(b, &pts); + b.note_curve(ctx, before, || el.bezier()); + } + Prim::Spline(s) => { + let before = b.list.prims.len(); + stroke(b, &s.tessellate(tol)); + b.note_curve(ctx, before, || s.bezier()); } - Prim::Spline(s) => stroke(b, &s.tessellate(tol)), Prim::Point(p) => b.point(ctx, rgb, p), Prim::Infinite { base, dir, ray } => b.infinite(ctx, rgb, base, dir, ray), Prim::Fill(pts) => { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5814c82c..d6b35ed2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -186,6 +186,21 @@ impl<'a> Builder<'a> { len: pts.len() as u32, }); } + /// Plots: record `path` (in the entity's coordinates) as the exact curve of what the stroke + /// since primitive `before` drew, when that is one polyline running from the path's start to + /// its end (a dashed linetype draws several, or other ends). + fn note_curve(&mut self, ctx: &Ctx, before: usize, path: impl FnOnce() -> Option) { + if !self.plotting || self.list.prims.len() != before + 1 { + return; + } + let Some(path) = path().filter(|p| p.has_curves()).map(|p| p.transformed(&ctx.xf)).filter(|p| p.is_finite()) else { return }; + let Some(prim) = self.list.prims.get(before).filter(|p| p.kind == Kind::Polyline) else { return }; + let pts = self.list.points(prim); + let ends = pts.first().zip(pts.last()).is_some_and(|(a, b)| display::same_point(*a, path.start) && display::same_point(*b, path.end())); + if let (true, Ok(prim)) = (ends, u32::try_from(before)) { + self.list.curves.push(DCurve { prim, path }); + } + } /// The pixels of image `i` over its rectangle, cut to its clip boundary. fn image(&mut self, ctx: &Ctx, color: Ink, i: &draftcraft_doc::Image, raster: &std::sync::Arc) { // Where the entity puts its picture: the top-left corner, and one of its pixels to the @@ -386,7 +401,7 @@ mod text_entity; mod viewports; pub use dim_draw::{dim_text, dimension_in}; -pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; +pub use display::{DCurve, DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; pub use pipeline::{Options, build, build_entities, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index fbfee8ee..a577669f 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -208,8 +208,25 @@ pub(crate) enum Clip<'a> { /// Append `src` to `dst`, clipped to `clip`. pub(crate) fn append_clipped(dst: &mut DisplayList, src: &DisplayList, clip: &Clip) { - for p in &src.prims { + for (i, p) in src.prims.iter().enumerate() { + let first = dst.prims.len(); clip_prim(dst, src, p, clip); + keep_curve(dst, src, i, first); + } +} + +/// A curve primitive `i` of `src` carries over to `dst` when the clip left it whole: one +/// polyline (appended at `first`) with the same points. +fn keep_curve(dst: &mut DisplayList, src: &DisplayList, i: usize, first: usize) { + if dst.prims.len() != first + 1 { + return; + } + let (Some(path), Some(p), Some(q)) = (src.curve(i), src.prims.get(i), dst.prims.get(first)) else { return }; + if q.kind == Kind::Polyline + && dst.points(q) == src.points(p) + && let Ok(prim) = u32::try_from(first) + { + dst.curves.push(crate::DCurve { prim, path: path.clone() }); } } @@ -221,6 +238,7 @@ pub(crate) fn append_clipped_keep(dst: &mut DisplayList, src: &DisplayList, clip for (i, p) in src.prims.iter().enumerate() { let first = dst.prims.len(); clip_prim(dst, src, p, clip); + keep_curve(dst, src, i, first); // Each piece keeps its source's layer (block contents not on layer 0 keep theirs). if let Some(layer) = src.prim_layers.get(i).copied() { for k in first..dst.prims.len() {