From d2fcae512e8fe82b7ea2bf578626f5507779cc89 Mon Sep 17 00:00:00 2001 From: Cameron Wight Date: Mon, 26 Oct 2026 11:44:31 +0000 Subject: [PATCH] Paper scene: one walk onto a writer's number grid, for every writer (#4890, C4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SVG writer kept its own number grid: each coordinate whole nanometres, every joint written once, a closed path ending exactly on its first point, slivers merged into the next piece and a path's last piece kept. PDF, PNG and the Drawing workspace's canvas need the same rules, so they move into `geom::paper::grid`, and the SVG writer only formats what the walk gives it. - `Grid`: `per_mm` steps a millimetre. `Grid::NANOMETRE` (six decimals of a millimetre) is SVG's. `Grid::new` takes 1 to 1e9; a power of two keeps every number exact as a binary float, which a writer of 32-bit numbers such as PDF can use. - `Prepared::on_grid(grid) -> OnGrid`: each group's items as paths of `Piece`s (lines, arcs of at most a quarter turn, cubics, parabolas), y up as in the scene, a closed path's closing line left to the writer's close, and a report of widths snapped and pieces merged. Slivers are measured in the grid's own steps, so a coarser grid merges more. - The SVG writer flips y on the whole numbers it's given and writes the same bytes as before. `SvgReport` is the grid's report. - Ellipses, hyperbolas and Béziers above degree 3 are still refused (A3b), now by the walk. DXF stays on its own number rule for now: it writes exact entities (ELLIPSE, SPLINE) and is being reworked under #5318 to #5321; whether its polylines take a grid is decided there. Tests: every SVG test unchanged, bytes included; the grid's rounding and its bounds; the A3 border on the grid (y up, closing line left out, fill loops closed); slivers in the grid's own steps, with the merge boundary both ways (10 and 11 steps, a 6-8 and a 7-8 step); an arc's quarters with their radius and turn in steps; a width under half a step made one step; an ellipse refused. Co-Authored-By: Claude Opus 5.5 --- crates/geom/src/paper.rs | 8 +- crates/geom/src/paper/grid.rs | 250 +++++++++++++++++++++++++++++++ crates/geom/src/paper_tests.rs | 75 +++++++++- crates/io/src/paper/svg.rs | 226 ++++++++-------------------- crates/io/src/paper/svg_tests.rs | 8 +- 5 files changed, 396 insertions(+), 171 deletions(-) create mode 100644 crates/geom/src/paper/grid.rs diff --git a/crates/geom/src/paper.rs b/crates/geom/src/paper.rs index bcafed779..fe0c6fc2a 100644 --- a/crates/geom/src/paper.rs +++ b/crates/geom/src/paper.rs @@ -30,7 +30,9 @@ //! also limit bytes and nesting. //! //! Writers read a [`Prepared`] scene, which only [`Scene::prepare`] makes, so none reads one that -//! wasn't checked. Clipping will happen there too, once, before any writer (A8). +//! wasn't checked, and format it on their number grid ([`Prepared::on_grid`], [`grid`]'s rules), +//! so every format draws the same joints, closures and merges. Clipping will happen in +//! `prepare` too, once, before any writer (A8). use serde::{Deserialize, Serialize}; @@ -38,6 +40,10 @@ use std::f64::consts::FRAC_PI_2; use crate::{EPS, Region2, Seg2, Vec2}; +pub mod grid; + +pub use grid::{Grid, GridGroup, GridItem, GridPath, GridPoint, GridReport, OnGrid, Piece}; + /// The widest line a scene may draw, in millimetres. pub const MAX_LINE_MM: f64 = 10.0; /// The longest side a sheet may have, in millimetres. diff --git a/crates/geom/src/paper/grid.rs b/crates/geom/src/paper/grid.rs new file mode 100644 index 000000000..bfd56221c --- /dev/null +++ b/crates/geom/src/paper/grid.rs @@ -0,0 +1,250 @@ +//! A prepared scene on a writer's number grid (#4890, C4): the one walk every writer formats, so +//! each format draws the same joints, closures and merges. +//! +//! - Every coordinate is a whole number of the grid's steps, x to the right and y up as in the +//! scene, so a joint is one point and a writer's flip or scale of whole numbers is exact. +//! - A closed path ends exactly on its start; a closing line is left to the writer's close +//! (SVG's `Z`, PDF's `h`). +//! - A piece ending within [`SLIVER_STEPS`] of where the path is merges into the next, and is +//! counted. A path's last piece has no next, so it is kept unless it has no length. +//! - A width under half a step is one step, and is counted. +//! - Circular arcs come in pieces of at most a quarter turn ([`arc_pieces`]). Ellipses, hyperbolas +//! and Béziers above degree 3 aren't walked yet (A3b): a scene with one is refused. + +use super::{Invalid, Item, ObjectKind, Prepared, Result, arc_pieces}; +use crate::{Seg2, Vec2}; + +/// The largest number put on a grid, in millimetres either way: far past any scene's 2e5. +const MAX_NUMBER_MM: f64 = 9e9; +/// Pieces ending this many steps or fewer from where the path is are merged into the next. +pub const SLIVER_STEPS: i64 = 10; + +/// A writer's number grid: `per_mm` steps a millimetre. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Grid { + per_mm: f64, +} + +impl Grid { + /// Whole nanometres, six decimals of a millimetre: SVG's numbers. + pub const NANOMETRE: Grid = Grid { per_mm: 1e6 }; + + /// A grid of `per_mm` steps a millimetre, from 1 to 1e9. A power of two keeps every number + /// exact in binary floating point, as a writer of 32-bit numbers (PDF) wants. + pub fn new(per_mm: f64) -> Option { + (1.0..=1e9).contains(&per_mm).then_some(Grid { per_mm }) + } + + pub fn per_mm(self) -> f64 { + self.per_mm + } + + /// `v` millimetres as whole steps. + pub fn steps(self, v: f64) -> Result { + let n = (v * self.per_mm).round(); + if n.abs() <= MAX_NUMBER_MM * self.per_mm { Ok(n as i64) } else { Err(Invalid("a number too large (or not a number) for the grid")) } + } + + pub fn point(self, p: Vec2) -> Result { + Ok(GridPoint { x: self.steps(p.x)?, y: self.steps(p.y)? }) + } +} + +/// A point on a grid, in whole steps. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct GridPoint { + pub x: i64, + pub y: i64, +} + +/// One piece of a path on the grid, from where the path is to `to`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Piece { + Line { + to: GridPoint, + }, + /// A circular arc of at most a quarter turn, of `radius` steps, turning clockwise (y up) when + /// `clockwise`. + Arc { + radius: i64, + clockwise: bool, + to: GridPoint, + }, + Cubic { + c1: GridPoint, + c2: GridPoint, + to: GridPoint, + }, + /// A parabola: a conic of weight 1 with its control point `c`. + Quadratic { + c: GridPoint, + to: GridPoint, + }, +} + +impl Piece { + pub fn to(&self) -> GridPoint { + match *self { + Piece::Line { to } | Piece::Arc { to, .. } | Piece::Cubic { to, .. } | Piece::Quadratic { to, .. } => to, + } + } +} + +/// A path on the grid: its pieces from `start`. A closed one ends on `start`, its closing line +/// left to the writer's close. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GridPath { + pub start: GridPoint, + pub pieces: Vec, + pub closed: bool, +} + +/// An item on the grid. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GridItem { + /// A stroke `width` steps wide, at least one. + Stroke { width: i64, path: GridPath }, + /// A fill's loops, each closed. + Fill { loops: Vec }, +} + +/// A group's items on the grid, in paint order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GridGroup { + pub object: u64, + pub kind: ObjectKind, + pub items: Vec, +} + +/// What the grid made of a scene that the scene didn't say. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct GridReport { + /// Widths under half a step, made one step. + pub widths_snapped: usize, + /// Pieces too short for the grid, merged into the next. + pub pieces_merged: usize, +} + +/// A scene on a grid: the sheet's size, its groups in paint order, and the report. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OnGrid { + pub size: GridPoint, + pub groups: Vec, + pub report: GridReport, +} + +impl Prepared<'_> { + /// The scene on `grid`, by the rules in this module's notes: what every writer formats. + pub fn on_grid(&self, grid: Grid) -> Result { + let mut report = GridReport::default(); + let mut groups = Vec::with_capacity(self.groups().len()); + for group in self.groups() { + let mut items = Vec::with_capacity(group.items.len()); + for item in &group.items { + match item { + Item::Stroke { path, closed, width_mm } => { + let Some(path) = walk(grid, path, *closed, &mut report)? else { continue }; + let mut width = grid.steps(*width_mm)?; + if width == 0 { + width = 1; + report.widths_snapped += 1; + } + items.push(GridItem::Stroke { width, path }); + } + Item::Fill { region } => { + let mut loops = Vec::new(); + for l in region.loops() { + loops.extend(walk(grid, &l.segs, true, &mut report)?); + } + items.push(GridItem::Fill { loops }); + } + } + } + groups.push(GridGroup { object: group.object, kind: group.kind, items }); + } + Ok(OnGrid { size: grid.point(self.size_mm())?, groups, report }) + } +} + +/// `segs` on the grid (`None` when it has no pieces). +fn walk(grid: Grid, segs: &[Seg2], closed: bool, report: &mut GridReport) -> Result> { + let (Some(first), Some((last, body))) = (segs.first(), segs.split_last()) else { return Ok(None) }; + let start = grid.point(first.start())?; + let mut w = Walk { grid, start, at: start, pieces: Vec::with_capacity(segs.len()), report }; + for seg in body { + w.piece(seg, false, false)?; + } + if !closed { + w.piece(last, false, true)?; + } else if !matches!(last, Seg2::Line { .. }) { + w.piece(last, true, true)?; + } + Ok(Some(GridPath { start, pieces: w.pieces, closed })) +} + +/// A path being walked: where it started and where it is. +struct Walk<'r> { + grid: Grid, + start: GridPoint, + at: GridPoint, + pieces: Vec, + report: &'r mut GridReport, +} + +impl Walk<'_> { + /// Whether a piece ending at `end` is too short to keep: it merges into the next. A path's + /// last piece (`keep`) has no next, so it is kept unless it has no length: an open path ends + /// where it ends, a closed one on its start exactly. + fn merged(&mut self, end: GridPoint, keep: bool) -> bool { + if keep { + return end == self.at; + } + let (dx, dy) = (end.x - self.at.x, end.y - self.at.y); + let short = dx.abs() <= SLIVER_STEPS && dy.abs() <= SLIVER_STEPS && dx * dx + dy * dy <= SLIVER_STEPS * SLIVER_STEPS; + if short { + self.report.pieces_merged += 1; + } + short + } + + fn push(&mut self, piece: Piece) { + self.at = piece.to(); + self.pieces.push(piece); + } + + /// One piece, from where the path is: `closing` makes its end the path's start, and `keep` + /// marks the path's last piece ([`Walk::merged`]). + fn piece(&mut self, seg: &Seg2, closing: bool, keep: bool) -> Result<()> { + let end = if closing { self.start } else { self.grid.point(seg.end())? }; + match *seg { + Seg2::Line { .. } => { + if !self.merged(end, keep) { + self.push(Piece::Line { to: end }); + } + } + Seg2::Arc { center, radius, start, sweep } => { + let (radius_steps, clockwise) = (self.grid.steps(radius)?, sweep < 0.0); + let mut ends = arc_pieces(center, radius, start, sweep).peekable(); + while let Some(p) = ends.next() { + let final_piece = ends.peek().is_none(); + let to = if final_piece { end } else { self.grid.point(p)? }; + if !self.merged(to, keep && final_piece) { + self.push(Piece::Arc { radius: radius_steps, clockwise, to }); + } + } + } + Seg2::Cubic { p1, p2, .. } => { + let (c1, c2) = (self.grid.point(p1)?, self.grid.point(p2)?); + self.push(Piece::Cubic { c1, c2, to: end }); + } + Seg2::Conic { apex, w, .. } if (w - 1.0).abs() <= 1e-12 => { + let c = self.grid.point(apex)?; + self.push(Piece::Quadratic { c, to: end }); + } + Seg2::Conic { .. } | Seg2::Bezier { .. } => { + return Err(Invalid("not supported yet: ellipses, hyperbolas and Béziers above degree 3 on paper (#4890, A3b)")); + } + } + Ok(()) + } +} diff --git a/crates/geom/src/paper_tests.rs b/crates/geom/src/paper_tests.rs index 8cc36a6e5..74c007c6b 100644 --- a/crates/geom/src/paper_tests.rs +++ b/crates/geom/src/paper_tests.rs @@ -1,4 +1,4 @@ -use std::f64::consts::{PI, TAU}; +use std::f64::consts::{FRAC_PI_2, PI, TAU}; use serde_json::json; @@ -303,3 +303,76 @@ fn unknown_fields_kinds_and_ids_are_refused_when_read() { v["groups"][0]["object"] = json!(u64::MAX); read(v).unwrap().validate().unwrap(); } + +/// A grid counts whole steps: half a step and less rounds to the nearer, -0 is 0, and a number +/// too large or not a number is refused. A grid has 1 to 1e9 steps a millimetre. +#[test] +fn a_grid_counts_whole_steps_and_refuses_what_it_cannot_hold() { + let nm = Grid::NANOMETRE; + assert_eq!((nm.steps(-0.0).unwrap(), nm.steps(4e-7).unwrap(), nm.steps(6e-7).unwrap()), (0, 0, 1)); + assert_eq!(nm.steps(9e9).unwrap(), 9_000_000_000_000_000); + for v in [f64::NAN, f64::INFINITY, 1e10, -1e10] { + assert!(nm.steps(v).is_err(), "{v}"); + } + for per_mm in [1.0, 2048.0, 1e9] { + assert_eq!(Grid::new(per_mm).map(Grid::per_mm), Some(per_mm)); + } + for per_mm in [0.0, 0.999, 1e9 + 1.0, -2048.0, f64::NAN, f64::INFINITY] { + assert!(Grid::new(per_mm).is_none(), "{per_mm}"); + } +} + +/// The A3 border on the nanometre grid: y up as in the scene, the closing line left to the +/// writer's close, each fill loop closed, nothing snapped or merged. +#[test] +fn a_scene_on_the_grid_keeps_y_up_and_leaves_the_closing_line_to_the_writer() { + let on = a3().prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap(); + let g = |x: i64, y: i64| GridPoint { x: x * 1_000_000, y: y * 1_000_000 }; + assert_eq!(on.size, g(420, 297)); + let group = &on.groups[0]; + assert_eq!((group.object, group.kind, group.items.len()), (1, ObjectKind::DrawingBorder, 3)); + let GridItem::Stroke { width, path } = &group.items[0] else { panic!("{:?}", group.items[0]) }; + assert_eq!(*width, 700_000); + let lines = |points: &[GridPoint]| points.iter().map(|&to| Piece::Line { to }).collect::>(); + assert_eq!(*path, GridPath { start: g(20, 10), pieces: lines(&[g(410, 10), g(410, 287), g(20, 287)]), closed: true }); + let GridItem::Fill { loops } = &group.items[1] else { panic!("{:?}", group.items[1]) }; + assert_eq!(*loops, [GridPath { start: g(0, 0), pieces: lines(&[g(10, 0), g(10, 5), g(0, 5)]), closed: true }]); + assert_eq!(on.report, GridReport::default()); +} + +/// Slivers are measured in the grid's own steps: a 5 mm piece goes straight on to the next on a +/// 1 mm grid, and stays on the nanometre grid. An arc's quarters keep its radius and turn, in +/// steps; a width under half a step is one step. A curve the walk can't take yet is refused. +#[test] +fn slivers_and_radii_are_in_the_grids_own_steps() { + let millimetre = Grid::new(1.0).unwrap(); + let walk = |scene: &Scene, grid: Grid| scene.prepare().unwrap().on_grid(grid).unwrap(); + let path = |on: &OnGrid| match &on.groups[0].items[0] { + GridItem::Stroke { width, path } => (*width, path.clone()), + other => panic!("{other:?}"), + }; + let three = open(vec![line(p(0.0, 0.0), p(100.0, 0.0)), line(p(100.0, 0.0), p(105.0, 0.0)), line(p(105.0, 0.0), p(200.0, 0.0))]); + let coarse = walk(&three, millimetre); + let to = |x: i64| Piece::Line { to: GridPoint { x, y: 0 } }; + assert_eq!(path(&coarse).1.pieces, [to(100), to(200)]); + assert_eq!(coarse.report, GridReport { widths_snapped: 1, pieces_merged: 1 }, "0.35 mm is under half a 1 mm step"); + assert_eq!(path(&coarse).0, 1); + // The boundary both ways: 10 steps along x merge, 11 don't; a (6, 8) step merges, (7, 8) doesn't. + for (dx, dy, merged) in [(10.0, 0.0, 1), (11.0, 0.0, 0), (6.0, 8.0, 1), (7.0, 8.0, 0)] { + let (a, b) = (p(100.0, 0.0), p(100.0 + dx, dy)); + let scene = open(vec![line(p(0.0, 0.0), a), line(a, b), line(b, p(200.0, 50.0))]); + assert_eq!(walk(&scene, millimetre).report.pieces_merged, merged, "({dx}, {dy})"); + } + let fine = walk(&three, Grid::NANOMETRE); + assert_eq!((path(&fine).1.pieces.len(), fine.report), (3, GridReport::default())); + // A clockwise half turn of radius 10 round (50, 50) from the top: two quarters. + let half = open(vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: FRAC_PI_2, sweep: -PI }]); + let arc = |x, y| Piece::Arc { radius: 10, clockwise: true, to: GridPoint { x, y } }; + assert_eq!( + path(&walk(&half, millimetre)).1, + GridPath { start: GridPoint { x: 50, y: 60 }, pieces: vec![arc(60, 50), arc(50, 40)], closed: false } + ); + let ellipse = open(vec![Seg2::Conic { a: p(0.0, 0.0), apex: p(10.0, 10.0), b: p(20.0, 0.0), w: 0.5 }]); + let refused = ellipse.prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap_err(); + assert!(refused.0.contains("not supported yet"), "{refused}"); +} diff --git a/crates/io/src/paper/svg.rs b/crates/io/src/paper/svg.rs index 474b8c32b..c0dc17159 100644 --- a/crates/io/src/paper/svg.rs +++ b/crates/io/src/paper/svg.rs @@ -1,63 +1,56 @@ //! A paper scene as SVG (#4890, A3): one user unit a millimetre, the paper's size in mm, and the //! scene's own curves where SVG has them. //! -//! - **Numbers** are whole nanometres, written as millimetres with up to six decimals: no exponent, no "-0", -//! nothing that depends on the locale. They are also the writer's state, so a joint is written -//! once and a closed path ends exactly on its first point. -//! - **y is flipped** by writing the page height less y, so the file's numbers are page -//! coordinates, with no transform. After the flip an anticlockwise arc turns the negative way, -//! so its sweep flag is 0. -//! - **Curves:** lines `L`, circular arcs `A` in pieces of at most a quarter turn (a half turn's -//! centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`. Ellipses, -//! hyperbolas and Béziers above degree 3 aren't written yet (A3b): a scene with one is refused. +//! - **Numbers** are the scene on the nanometre grid ([`Prepared::on_grid`], whose rules give the +//! joints, closures and merges), written as millimetres with up to six decimals: no exponent, no +//! "-0", nothing that depends on the locale. +//! - **y is flipped** by writing the page height less y, exact on the grid, so the file's numbers +//! are page coordinates, with no transform. After the flip an anticlockwise arc turns the +//! negative way, so its sweep flag is 0. +//! - **Curves:** lines `L`, circular arcs `A` in the grid's pieces of at most a quarter turn (a half +//! turn's centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`. //! - **Paint:** strokes `stroke-width`, with butt caps, miter joins and a miter limit of 4 on the //! root; fills black, even-odd. One `` per item, so each stays one object in an editor. //! - **Groups** are ``: object ids repeat and start with a digit, //! so they can't be XML ids. No background: the page stays transparent, as cutters want. -//! -//! What the grid can't express is counted, never an error: a width under half a nanometre is -//! written as one, and a piece ending within 10 nanometres of where the path is goes straight on -//! to the next. use std::fmt::Write; -use solidcraft_geom::paper::{Item, Prepared, arc_pieces}; -use solidcraft_geom::{Region2, Seg2, Vec2}; +use solidcraft_geom::paper::{Grid, GridItem, GridPath, GridPoint, GridReport, Piece, Prepared}; use crate::{IoError, MAX_DRAWING_BYTES, Result}; -/// The largest number written, in millimetres either way: far past any scene's 2e5. -const MAX_NUMBER_MM: f64 = 9e9; -/// Pieces ending this many grid steps or fewer from where the path is are merged (1e-5 mm). -const SLIVER_STEPS: i64 = 10; - -/// What writing a scene did that the scene didn't say. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct SvgReport { - /// Widths under half a nanometre, written as one nanometre. - pub widths_snapped: usize, - /// Pieces too short for the nanometre grid, merged into the next. - pub pieces_merged: usize, -} +/// What writing a scene did that the scene didn't say: the grid's report. +pub type SvgReport = GridReport; /// A scene's SVG document, and what writing it did. pub fn paper_svg(scene: &Prepared) -> Result<(Vec, SvgReport)> { - let mut w = Writer { out: String::new(), height: nano(scene.size_mm().y)?, report: SvgReport::default(), at: (0, 0), first: (0, 0) }; - let (width, height) = (number(nano(scene.size_mm().x)?), number(w.height)); + let on = scene.on_grid(Grid::NANOMETRE).map_err(|e| IoError::Invalid(e.to_string()))?; + let mut w = Writer { out: String::new(), height: on.size.y }; + let (width, height) = (number(on.size.x), number(on.size.y)); w.out.push_str("\n"); let _ = writeln!( w.out, "" ); - for group in scene.groups() { + for group in &on.groups { let kind = serde_json::to_value(group.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(); let _ = writeln!(w.out, "", group.object); for item in &group.items { match item { - Item::Stroke { path, closed, width_mm } => w.stroke(path, *closed, *width_mm)?, - Item::Fill { region } => w.fill(region)?, + GridItem::Stroke { width, path } => { + w.out.push_str(" { + w.out.push_str("\n"); if w.out.len() > MAX_DRAWING_BYTES { return Err(IoError::Invalid(format!("the SVG would be over {} MiB", MAX_DRAWING_BYTES >> 20))); } @@ -65,13 +58,7 @@ pub fn paper_svg(scene: &Prepared) -> Result<(Vec, SvgReport)> { w.out.push_str("\n"); } w.out.push_str("\n"); - Ok((w.out.into_bytes(), w.report)) -} - -/// A value in millimetres as whole nanometres. -fn nano(v: f64) -> Result { - let n = (v * 1e6).round(); - if n.abs() <= MAX_NUMBER_MM * 1e6 { Ok(n as i64) } else { Err(IoError::Invalid("a number too large (or not a number) for the SVG".into())) } + Ok((w.out.into_bytes(), on.report)) } /// Nanometres written as millimetres onto `out`: the integer part, then up to six decimals @@ -88,7 +75,7 @@ fn push_number(out: &mut String, n: i64) { } } -/// [`push_number`] as its own text, for the numbers written once per document or arc. +/// [`push_number`] as its own text, for the numbers written once per document. fn number(n: i64) -> String { let mut text = String::new(); push_number(&mut text, n); @@ -99,141 +86,52 @@ struct Writer { out: String, /// The page height, in nanometres: y is written as this less y. height: i64, - report: SvgReport, - /// Where the path is, and where its subpath started, on the grid. - at: (i64, i64), - first: (i64, i64), } impl Writer { - /// A scene point on the page's grid. - fn grid(&self, p: Vec2) -> Result<(i64, i64)> { - Ok((nano(p.x)?, self.height - nano(p.y)?)) - } - - fn point(&mut self, (x, y): (i64, i64)) { - push_number(&mut self.out, x); + fn point(&mut self, p: GridPoint) { + push_number(&mut self.out, p.x); self.out.push(' '); - push_number(&mut self.out, y); + push_number(&mut self.out, self.height - p.y); } - /// Starts a subpath at `p`. - fn move_to(&mut self, p: Vec2) -> Result<()> { - let at = self.grid(p)?; + /// A path's `d`: a closed one ends with `Z`, which draws its closing line. + fn path(&mut self, path: &GridPath) { self.out.push('M'); - self.point(at); - (self.at, self.first) = (at, at); - Ok(()) - } - - /// Whether a piece ending at `end` is too short to write: it is merged into the next. A path's - /// last piece (`keep`) has no next, so it is written unless it has no length: an open path - /// ends where it ends, a closed one on its first point exactly. - fn merged(&mut self, end: (i64, i64), keep: bool) -> bool { - if keep { - return end == self.at; - } - let (dx, dy) = (end.0 - self.at.0, end.1 - self.at.1); - let short = dx.abs() <= SLIVER_STEPS && dy.abs() <= SLIVER_STEPS && dx * dx + dy * dy <= SLIVER_STEPS * SLIVER_STEPS; - if short { - self.report.pieces_merged += 1; - } - short - } - - /// One piece, from where the path is: `closing` makes its end the subpath's first point, and - /// `keep` marks the path's last piece ([`Writer::merged`]). - fn piece(&mut self, seg: &Seg2, closing: bool, keep: bool) -> Result<()> { - let end = if closing { self.first } else { self.grid(seg.end())? }; - match *seg { - Seg2::Line { .. } => { - if !self.merged(end, keep) { + self.point(path.start); + for piece in &path.pieces { + match *piece { + Piece::Line { to } => { self.out.push('L'); - self.point(end); - self.at = end; + self.point(to); + } + Piece::Arc { radius, clockwise, to } => { + self.out.push('A'); + push_number(&mut self.out, radius); + self.out.push(' '); + push_number(&mut self.out, radius); + let _ = write!(self.out, " 0 0 {} ", u8::from(clockwise)); + self.point(to); + } + Piece::Cubic { c1, c2, to } => { + self.out.push('C'); + self.point(c1); + self.out.push(' '); + self.point(c2); + self.out.push(' '); + self.point(to); + } + Piece::Quadratic { c, to } => { + self.out.push('Q'); + self.point(c); + self.out.push(' '); + self.point(to); } } - Seg2::Arc { center, radius, start, sweep } => { - let r = number(nano(radius)?); - let flag = u8::from(sweep < 0.0); - let mut ends = arc_pieces(center, radius, start, sweep).peekable(); - while let Some(p) = ends.next() { - let final_piece = ends.peek().is_none(); - let to = if final_piece { end } else { self.grid(p)? }; - if !self.merged(to, keep && final_piece) { - let _ = write!(self.out, "A{r} {r} 0 0 {flag} "); - self.point(to); - self.at = to; - } - } - } - Seg2::Cubic { p1, p2, .. } => { - let (c1, c2) = (self.grid(p1)?, self.grid(p2)?); - self.out.push('C'); - self.point(c1); - self.out.push(' '); - self.point(c2); - self.out.push(' '); - self.point(end); - self.at = end; - } - Seg2::Conic { apex, w, .. } if (w - 1.0).abs() <= 1e-12 => { - let c = self.grid(apex)?; - self.out.push('Q'); - self.point(c); - self.out.push(' '); - self.point(end); - self.at = end; - } - Seg2::Conic { .. } | Seg2::Bezier { .. } => { - return Err(IoError::Invalid("not supported yet: SVG of ellipses, hyperbolas and Béziers above degree 3 (#4890, A3b)".into())); - } } - Ok(()) - } - - /// A path's pieces after its `M`: a closed one ends exactly on its first point, a line back to - /// it as `Z`. - fn pieces(&mut self, path: &[Seg2], closed: bool) -> Result<()> { - let Some((last, body)) = path.split_last() else { return Ok(()) }; - for seg in body { - self.piece(seg, false, false)?; + if path.closed { + self.out.push('Z'); } - if !closed { - return self.piece(last, false, true); - } - if !matches!(last, Seg2::Line { .. }) { - self.piece(last, true, true)?; - } - self.out.push('Z'); - Ok(()) - } - - fn stroke(&mut self, path: &[Seg2], closed: bool, width_mm: f64) -> Result<()> { - let Some(first) = path.first() else { return Ok(()) }; - let mut width = nano(width_mm)?; - if width == 0 { - width = 1; - self.report.widths_snapped += 1; - } - self.out.push_str("\n"); - Ok(()) - } - - fn fill(&mut self, region: &Region2) -> Result<()> { - self.out.push_str("\n"); - Ok(()) } } diff --git a/crates/io/src/paper/svg_tests.rs b/crates/io/src/paper/svg_tests.rs index 6f16b9b25..2a7d8249c 100644 --- a/crates/io/src/paper/svg_tests.rs +++ b/crates/io/src/paper/svg_tests.rs @@ -1,7 +1,7 @@ use std::f64::consts::{FRAC_PI_2, PI, TAU}; -use solidcraft_geom::paper::{Group, ObjectKind, Scene}; -use solidcraft_geom::{Loop2, Region2}; +use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; +use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; use super::*; use crate::{Geom2, read_svg}; @@ -101,14 +101,12 @@ fn cubics_and_parabolas_are_written_and_other_conics_refused() { } /// Numbers are whole nanometres: no exponent, no "-0", trailing zeros trimmed; a width under half -/// a nanometre is written as one and reported. +/// a nanometre is written as one and reported (the grid's own rounding is `geom`'s test). #[test] fn numbers_are_whole_nanometres() { for (n, text) in [(0, "0"), (1, "0.000001"), (-1, "-0.000001"), (1_500_000, "1.5"), (-420_000_000, "-420"), (123_456_789, "123.456789")] { assert_eq!(number(n), text); } - assert_eq!((nano(-0.0).unwrap(), nano(4e-7).unwrap(), nano(6e-7).unwrap()), (0, 0, 1)); - assert!(nano(f64::NAN).is_err() && nano(1e10).is_err()); let thin = sheet(vec![stroke(vec![line(p(0.0, 0.0), p(1.0, 0.0))], false, 1e-9)]); let (text, report) = svg(&thin); assert!(text.contains("stroke-width=\"0.000001\""), "{text}");