Skip to main content

pdf/
geom.rs

1// geom -- matrices, colours, paths and the stroke parameters of a canvas
2
3use alloc::vec::Vec;
4
5/// an affine matrix as PDF writes it (`a b c d e f cm`): x' = a x + c y + e, y' = b x + d y + f
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct Matrix {
8    pub a: f64,
9    pub b: f64,
10    pub c: f64,
11    pub d: f64,
12    pub e: f64,
13    pub f: f64,
14}
15
16impl Matrix {
17    pub const IDENTITY: Matrix = Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 };
18
19    pub const fn new(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> Matrix {
20        Matrix { a, b, c, d, e, f }
21    }
22
23    pub const fn translate(tx: f64, ty: f64) -> Matrix {
24        Matrix { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: tx, f: ty }
25    }
26
27    pub const fn scale(sx: f64, sy: f64) -> Matrix {
28        Matrix { a: sx, b: 0.0, c: 0.0, d: sy, e: 0.0, f: 0.0 }
29    }
30
31    /// a rotation by `angle` radians: counter-clockwise where y points up, clockwise on a canvas
32    /// whose y points down
33    pub fn rotate(angle: f64) -> Matrix {
34        let (s, c) = gfx::xform::sincos(angle);
35        Matrix { a: c, b: s, c: -s, d: c, e: 0.0, f: 0.0 }
36    }
37
38    /// self first, then `next` (PDF's self × next)
39    pub fn then(&self, next: &Matrix) -> Matrix {
40        Matrix {
41            a: self.a * next.a + self.b * next.c,
42            b: self.a * next.b + self.b * next.d,
43            c: self.c * next.a + self.d * next.c,
44            d: self.c * next.b + self.d * next.d,
45            e: self.e * next.a + self.f * next.c + next.e,
46            f: self.e * next.b + self.f * next.d + next.f,
47        }
48    }
49
50    pub fn apply(&self, x: f64, y: f64) -> (f64, f64) {
51        (self.a * x + self.c * y + self.e, self.b * x + self.d * y + self.f)
52    }
53
54    pub fn det(&self) -> f64 {
55        self.a * self.d - self.b * self.c
56    }
57
58    /// the inverse; None when the matrix is singular or not finite
59    pub fn invert(&self) -> Option<Matrix> {
60        let det = self.det();
61        if !(det.is_finite() && det.abs() > 1e-300) {
62            return None;
63        }
64        let i = 1.0 / det;
65        let m = Matrix {
66            a: self.d * i,
67            b: -self.b * i,
68            c: -self.c * i,
69            d: self.a * i,
70            e: (self.c * self.f - self.d * self.e) * i,
71            f: (self.b * self.e - self.a * self.f) * i,
72        };
73        [m.a, m.b, m.c, m.d, m.e, m.f].iter().all(|v| v.is_finite()).then_some(m)
74    }
75
76    pub(crate) fn is_finite(&self) -> bool {
77        [self.a, self.b, self.c, self.d, self.e, self.f].iter().all(|v| v.is_finite())
78    }
79}
80
81/// gfx's matrix (x' = a x + b y + c, y' = d x + e y + f) as PDF writes it
82impl From<gfx::xform::Matrix> for Matrix {
83    fn from(m: gfx::xform::Matrix) -> Matrix {
84        Matrix { a: m.a, b: m.d, c: m.b, d: m.e, e: m.c, f: m.f }
85    }
86}
87
88/// an RGB colour, each part 0 to 1 (DeviceRGB)
89#[derive(Clone, Copy, Debug, PartialEq)]
90pub struct Rgb {
91    pub r: f64,
92    pub g: f64,
93    pub b: f64,
94}
95
96impl Rgb {
97    pub const BLACK: Rgb = Rgb { r: 0.0, g: 0.0, b: 0.0 };
98    pub const WHITE: Rgb = Rgb { r: 1.0, g: 1.0, b: 1.0 };
99
100    pub const fn new(r: f64, g: f64, b: f64) -> Rgb {
101        Rgb { r, g, b }
102    }
103
104    /// from 0..255 parts
105    pub fn from_u8(r: u8, g: u8, b: u8) -> Rgb {
106        Rgb { r: r as f64 / 255.0, g: g as f64 / 255.0, b: b as f64 / 255.0 }
107    }
108
109    /// from 0xRRGGBB
110    pub fn hex(rgb: u32) -> Rgb {
111        Rgb::from_u8((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
112    }
113
114    pub(crate) fn clamped(&self) -> Rgb {
115        let c = |v: f64| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
116        Rgb { r: c(self.r), g: c(self.g), b: c(self.b) }
117    }
118}
119
120/// which parts of a path a fill covers (PDF `f` / `f*`)
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
122pub enum FillRule {
123    #[default]
124    NonZero,
125    EvenOdd,
126}
127
128/// the ends of open subpaths and dashes (PDF `J`)
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
130pub enum LineCap {
131    #[default]
132    Butt,
133    Round,
134    Square,
135}
136
137/// the corners of a stroke (PDF `j`)
138#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
139pub enum LineJoin {
140    #[default]
141    Miter,
142    Round,
143    Bevel,
144}
145
146/// how text is painted (PDF `Tr`)
147#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
148pub enum TextMode {
149    #[default]
150    Fill,
151    Stroke,
152    FillStroke,
153    /// not painted, but found by search and copied (e.g. text over a scanned page)
154    Invisible,
155}
156
157#[derive(Clone, Copy, Debug, PartialEq)]
158pub(crate) enum Seg {
159    Move(f64, f64),
160    Line(f64, f64),
161    Cubic(f64, f64, f64, f64, f64, f64),
162    Rect(f64, f64, f64, f64),
163    Close,
164}
165
166/// the circle constant of cubic arcs: 4/3 (sqrt 2 - 1)
167const KAPPA: f64 = 0.552_284_749_830_793_6;
168
169/// a path: subpaths of lines and cubic curves, built once and drawn on any canvas
170/// (Canvas::append_path) or built on the canvas itself (its move_to, line_to, ...)
171#[derive(Clone, Debug, Default, PartialEq)]
172pub struct Path {
173    pub(crate) segs: Vec<Seg>,
174    cur: Option<(f64, f64)>,
175    start: (f64, f64),
176}
177
178impl Path {
179    pub fn new() -> Path {
180        Path::default()
181    }
182
183    pub fn is_empty(&self) -> bool {
184        self.segs.is_empty()
185    }
186
187    pub fn clear(&mut self) {
188        self.segs.clear();
189        self.cur = None;
190    }
191
192    /// the current point (None before the first move_to and after clear)
193    pub fn current(&self) -> Option<(f64, f64)> {
194        self.cur
195    }
196
197    /// starts a subpath
198    pub fn move_to(&mut self, x: f64, y: f64) -> &mut Path {
199        self.segs.push(Seg::Move(x, y));
200        self.cur = Some((x, y));
201        self.start = (x, y);
202        self
203    }
204
205    /// a straight line from the current point (without one: a move_to)
206    pub fn line_to(&mut self, x: f64, y: f64) -> &mut Path {
207        if self.cur.is_none() {
208            return self.move_to(x, y);
209        }
210        self.segs.push(Seg::Line(x, y));
211        self.cur = Some((x, y));
212        self
213    }
214
215    /// a cubic Bézier curve with control points (x1, y1) and (x2, y2) to (x, y)
216    pub fn curve_to(&mut self, x1: f64, y1: f64, x2: f64, y2: f64, x: f64, y: f64) -> &mut Path {
217        if self.cur.is_none() {
218            self.move_to(x1, y1);
219        }
220        self.segs.push(Seg::Cubic(x1, y1, x2, y2, x, y));
221        self.cur = Some((x, y));
222        self
223    }
224
225    /// a quadratic Bézier curve (written as the same cubic)
226    pub fn quad_to(&mut self, x1: f64, y1: f64, x: f64, y: f64) -> &mut Path {
227        let (x0, y0) = match self.cur {
228            Some(p) => p,
229            None => {
230                self.move_to(x1, y1);
231                (x1, y1)
232            }
233        };
234        let c1 = (x0 + (x1 - x0) * (2.0 / 3.0), y0 + (y1 - y0) * (2.0 / 3.0));
235        let c2 = (x + (x1 - x) * (2.0 / 3.0), y + (y1 - y) * (2.0 / 3.0));
236        self.curve_to(c1.0, c1.1, c2.0, c2.1, x, y)
237    }
238
239    /// closes the subpath with a line to its start
240    pub fn close(&mut self) -> &mut Path {
241        if self.cur.is_some() {
242            self.segs.push(Seg::Close);
243            self.cur = Some(self.start);
244        }
245        self
246    }
247
248    /// a closed rectangle as its own subpath (PDF `re`)
249    pub fn rect(&mut self, x: f64, y: f64, w: f64, h: f64) -> &mut Path {
250        self.segs.push(Seg::Rect(x, y, w, h));
251        self.cur = Some((x, y));
252        self.start = (x, y);
253        self
254    }
255
256    /// a closed ellipse around (cx, cy) as four cubic curves
257    pub fn ellipse(&mut self, cx: f64, cy: f64, rx: f64, ry: f64) -> &mut Path {
258        let (kx, ky) = (rx * KAPPA, ry * KAPPA);
259        self.move_to(cx + rx, cy);
260        self.curve_to(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry);
261        self.curve_to(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy);
262        self.curve_to(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry);
263        self.curve_to(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy);
264        self.close()
265    }
266
267    pub fn circle(&mut self, cx: f64, cy: f64, r: f64) -> &mut Path {
268        self.ellipse(cx, cy, r, r)
269    }
270
271    /// a closed rectangle with corners rounded by r (at most half the shorter side)
272    pub fn rounded_rect(&mut self, x: f64, y: f64, w: f64, h: f64, r: f64) -> &mut Path {
273        let r = r.max(0.0).min(w.abs() / 2.0).min(h.abs() / 2.0);
274        if r <= 0.0 || !r.is_finite() {
275            return self.rect(x, y, w, h);
276        }
277        let (x0, x1) = if w < 0.0 { (x + w, x) } else { (x, x + w) };
278        let (y0, y1) = if h < 0.0 { (y + h, y) } else { (y, y + h) };
279        let k = r * (1.0 - KAPPA);
280        self.move_to(x0 + r, y0);
281        self.line_to(x1 - r, y0);
282        self.curve_to(x1 - k, y0, x1, y0 + k, x1, y0 + r);
283        self.line_to(x1, y1 - r);
284        self.curve_to(x1, y1 - k, x1 - k, y1, x1 - r, y1);
285        self.line_to(x0 + r, y1);
286        self.curve_to(x0 + k, y1, x0, y1 - k, x0, y1 - r);
287        self.line_to(x0, y0 + r);
288        self.curve_to(x0, y0 + k, x0 + k, y0, x0 + r, y0);
289        self.close()
290    }
291
292    /// an elliptical arc around (cx, cy) from angle `start` over `sweep` radians (positive:
293    /// from +x towards +y), as cubic curves of at most 90 degrees; it continues the subpath
294    /// with a line to its start, or starts one
295    pub fn arc(&mut self, cx: f64, cy: f64, rx: f64, ry: f64, start: f64, sweep: f64) -> &mut Path {
296        if !(start.is_finite() && sweep.is_finite()) {
297            return self;
298        }
299        let sweep = sweep.clamp(-core::f64::consts::TAU, core::f64::consts::TAU);
300        let n = ((sweep.abs() / core::f64::consts::FRAC_PI_2) - 1e-9).max(0.0) as usize + 1;
301        let step = sweep / n as f64;
302        let (sq, cq) = gfx::xform::sincos(step / 4.0);
303        let k = 4.0 / 3.0 * sq / cq;
304        let (s0, c0) = gfx::xform::sincos(start);
305        let p0 = (cx + rx * c0, cy + ry * s0);
306        if self.cur.is_some() {
307            self.line_to(p0.0, p0.1);
308        } else {
309            self.move_to(p0.0, p0.1);
310        }
311        let mut a = start;
312        for _ in 0..n {
313            let (sa, ca) = gfx::xform::sincos(a);
314            let (sb, cb) = gfx::xform::sincos(a + step);
315            self.curve_to(
316                cx + rx * (ca - k * sa),
317                cy + ry * (sa + k * ca),
318                cx + rx * (cb + k * sb),
319                cy + ry * (sb - k * cb),
320                cx + rx * cb,
321                cy + ry * sb,
322            );
323            a += step;
324        }
325        self
326    }
327
328    /// appends another path's subpaths
329    pub fn append(&mut self, other: &Path) -> &mut Path {
330        self.segs.extend_from_slice(&other.segs);
331        if other.cur.is_some() {
332            self.cur = other.cur;
333            self.start = other.start;
334        }
335        self
336    }
337
338    /// every point mapped by m (a rectangle becomes four lines when m turns it)
339    pub fn transform(&mut self, m: &Matrix) {
340        let mut out = Vec::with_capacity(self.segs.len());
341        let keeps_rect = m.b == 0.0 && m.c == 0.0;
342        for s in &self.segs {
343            let seg = match *s {
344                Seg::Move(x, y) => {
345                    let p = m.apply(x, y);
346                    Seg::Move(p.0, p.1)
347                }
348                Seg::Line(x, y) => {
349                    let p = m.apply(x, y);
350                    Seg::Line(p.0, p.1)
351                }
352                Seg::Cubic(a, b, c, d, e, f) => {
353                    let p1 = m.apply(a, b);
354                    let p2 = m.apply(c, d);
355                    let p3 = m.apply(e, f);
356                    Seg::Cubic(p1.0, p1.1, p2.0, p2.1, p3.0, p3.1)
357                }
358                Seg::Rect(x, y, w, h) if keeps_rect => {
359                    let p = m.apply(x, y);
360                    Seg::Rect(p.0, p.1, w * m.a, h * m.d)
361                }
362                Seg::Rect(x, y, w, h) => {
363                    let pts = [m.apply(x, y), m.apply(x + w, y), m.apply(x + w, y + h), m.apply(x, y + h)];
364                    out.push(Seg::Move(pts[0].0, pts[0].1));
365                    out.push(Seg::Line(pts[1].0, pts[1].1));
366                    out.push(Seg::Line(pts[2].0, pts[2].1));
367                    out.push(Seg::Line(pts[3].0, pts[3].1));
368                    Seg::Close
369                }
370                Seg::Close => Seg::Close,
371            };
372            out.push(seg);
373        }
374        self.segs = out;
375        self.cur = self.cur.map(|(x, y)| m.apply(x, y));
376        self.start = m.apply(self.start.0, self.start.1);
377    }
378}