Skip to main content

pltrs_render/
renderer.rs

1//! The drawing interface every output backend implements.
2
3use pltrs_core::{Affine2D, Path, Point, Rgba};
4use pltrs_text::TEXT_PATH_FONT_SCALE;
5use pltrs_text::tex::{TexError, TexText};
6use pltrs_text::{TextEngine, TextRun};
7
8use crate::collection::PathCollection;
9use crate::filter::{FilterFn, SharedFilter};
10use crate::gc::GraphicsContext;
11use crate::image::RgbaImage;
12use crate::quad_mesh::QuadMesh;
13
14/// One line of a text as matplotlib's `Text.draw` hands it to a
15/// renderer's `draw_text` or `draw_tex`: the line laid out (its
16/// [`TextRun::source`] says what it is) and the left end of its baseline,
17/// in display coordinates.
18#[derive(Clone, Copy, Debug)]
19pub struct TextLine<'a> {
20    /// The line laid out.
21    pub run: &'a TextRun,
22    /// The left end of its baseline.
23    pub origin: Point,
24}
25
26/// A text as matplotlib's `Text.draw` draws it through a renderer: its
27/// lines, its rotation, and what drew it (its artist and its font, as the
28/// crate drawing it describes them), for renderers that take texts whole
29/// (see [`Renderer::draw_text_lines`]).
30#[derive(Clone, Copy)]
31pub struct TextLines<'a> {
32    /// The lines, first to last.
33    pub lines: &'a [TextLine<'a>],
34    /// The rotation in degrees counter-clockwise.
35    pub angle: f64,
36    /// What drew the text, as the crate drawing it describes it.
37    pub source: &'a dyn std::any::Any,
38}
39
40impl std::fmt::Debug for TextLines<'_> {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("TextLines")
43            .field("lines", &self.lines)
44            .field("angle", &self.angle)
45            .finish_non_exhaustive()
46    }
47}
48
49/// A drawing target: a raster canvas, an SVG/PDF/PS document, a window.
50///
51/// This mirrors matplotlib's `RendererBase`. All geometry arrives in
52/// *display coordinates*: pixels at the renderer's dpi with the origin at
53/// the **bottom-left** corner and y pointing up. Transforms passed alongside
54/// paths are affine maps into that space; any non-affine part (log scales,
55/// polar projections) has already been applied by the caller.
56///
57/// Only [`draw_path`](Self::draw_path) is mandatory; the batched operations
58/// have correct but slow default implementations that backends override
59/// when they can do better (e.g. stamping a pre-rasterised marker).
60pub trait Renderer {
61    /// Canvas width and height in pixels.
62    fn canvas_size(&self) -> (f64, f64);
63
64    /// Resolution in dots per inch.
65    fn dpi(&self) -> f64;
66
67    /// Converts a length in points (1/72 inch) to pixels.
68    fn points_to_pixels(&self, points: f64) -> f64 {
69        points * self.dpi() / 72.0
70    }
71
72    /// Strokes `path` with `gc` and fills it with `fill`, if given.
73    fn draw_path(
74        &mut self,
75        gc: &GraphicsContext,
76        path: &Path,
77        transform: &Affine2D,
78        fill: Option<Rgba>,
79    );
80
81    /// Draws `marker` (in marker coordinates, mapped by `marker_transform`
82    /// to pixel offsets) at every vertex of `path` transformed by `transform`.
83    fn draw_markers(
84        &mut self,
85        gc: &GraphicsContext,
86        marker: &Path,
87        marker_transform: &Affine2D,
88        path: &Path,
89        transform: &Affine2D,
90        fill: Option<Rgba>,
91    ) {
92        for &vertex in path.vertices() {
93            let at = transform.transform_point(vertex);
94            if at.is_finite() {
95                let placed = marker_transform.translate(at.x, at.y);
96                self.draw_path(gc, marker, &placed, fill);
97            }
98        }
99    }
100
101    /// Draws many paths with per-item properties (scatter, patches, meshes).
102    fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
103        for item in collection.items(gc) {
104            self.draw_path(&item.gc, item.path, &item.transform, item.fill);
105        }
106    }
107
108    /// Draws a flat-shaded quad mesh (matplotlib's `draw_quad_mesh`): by
109    /// default as a path collection of its cells in matplotlib's order
110    /// ([`QuadMesh::cell_paths`]) with the line width of `gc`.
111    fn draw_quad_mesh(&mut self, gc: &GraphicsContext, mesh: &QuadMesh<'_>) {
112        let paths = mesh.cell_paths();
113        let widths = [gc.linewidth];
114        let flags = [mesh.antialiased];
115        self.draw_path_collection(gc, &mesh.collection(&paths, &widths, &flags));
116    }
117
118    /// Draws triangles whose vertex colours are interpolated linearly
119    /// (Gouraud shading); `transform` maps the vertices to display space.
120    fn draw_gouraud_triangles(
121        &mut self,
122        gc: &GraphicsContext,
123        triangles: &[[Point; 3]],
124        colors: &[[Rgba; 3]],
125        transform: &Affine2D,
126    );
127
128    /// Draws an image with its **bottom-left** corner at `origin` (display
129    /// coordinates). With `transform`, the image's unit square is mapped
130    /// through it instead (only used when
131    /// [`option_scale_image`](Self::option_scale_image) is `true`).
132    fn draw_image(
133        &mut self,
134        gc: &GraphicsContext,
135        origin: Point,
136        image: &RgbaImage,
137        transform: Option<&Affine2D>,
138    );
139
140    /// Draws laid-out text with its origin (left end of the baseline) at
141    /// `origin`, rotated by `angle` degrees counter-clockwise about it.
142    ///
143    /// The default fills every glyph outline and rule as a path in the
144    /// stroke colour, which is exact for vector output; raster backends
145    /// override it to reproduce `FreeType`'s glyph rendering.
146    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
147        fill_text(self, gc, run, origin, angle);
148    }
149
150    /// Draws `text` whole, as matplotlib's `Text.draw` hands a renderer a
151    /// text's lines one by one, each with its string, font and artist
152    /// (`draw_text(gc, x, y, s, prop, angle, ismath, mtext)`); whether
153    /// the renderer drew it. The renderers of this crate don't (they draw
154    /// each line through [`draw_text`](Self::draw_text) or
155    /// [`draw_tex`](Self::draw_tex)), a renderer of the program's does.
156    fn draw_text_lines(&mut self, _gc: &GraphicsContext, _text: &TextLines<'_>) -> bool {
157        false
158    }
159
160    /// Whether the renderer takes texts whole
161    /// ([`draw_text_lines`](Self::draw_text_lines)), which those drawing
162    /// texts ask before they describe one.
163    fn takes_texts_whole(&self) -> bool {
164        false
165    }
166
167    /// Draws `tex`, a line of TeX text that is the source of `run`
168    /// ([`TextSource::Tex`](pltrs_text::TextSource::Tex)), with its origin at
169    /// `origin`, rotated by `angle` degrees counter-clockwise about it
170    /// (matplotlib's `draw_tex`).
171    ///
172    /// The default fills the outline matplotlib's `TextToPath` makes of
173    /// the typeset text (`RendererBase.draw_tex`).
174    ///
175    /// # Errors
176    ///
177    /// When TeX cannot typeset the text or its fonts cannot be drawn.
178    fn draw_tex(
179        &mut self,
180        gc: &GraphicsContext,
181        _run: &TextRun,
182        tex: &TexText,
183        origin: Point,
184        angle: f64,
185    ) -> Result<(), TexError> {
186        fill_tex(self, gc, tex, origin, angle)
187    }
188
189    /// Whether the renderer rounds where it puts each glyph (and each line
190    /// of TeX) to whole numbers as Python rounds them, as matplotlib's Agg
191    /// renderer does (`round(0x40 * x)`), which refuses a position that is
192    /// not finite. Renderers drawing glyphs as paths don't.
193    fn rounds_glyph_positions(&self) -> bool {
194        false
195    }
196
197    /// Starts a named group of draw calls (vector backends emit a group).
198    fn open_group(&mut self, _name: &str, _gid: Option<&str>) {}
199
200    /// Ends the most recently opened group.
201    fn close_group(&mut self, _name: &str) {}
202
203    /// Starts a named group of the draw calls of a part of the artist
204    /// being drawn, which draws with that artist's clip regions (the
205    /// background of a figure or an axes; an axis' ticks and their lines
206    /// and labels, whose gridlines matplotlib clips to one box): a group as
207    /// [`open_group`](Self::open_group) starts, but the PDF backend does
208    /// not set the clip regions again for the parts.
209    fn open_part_group(&mut self, name: &str, gid: Option<&str>) {
210        self.open_group(name, gid);
211    }
212
213    /// Ends the most recently opened group of a part.
214    fn close_part_group(&mut self, name: &str) {
215        self.close_group(name);
216    }
217
218    /// Sends the following drawing to a raster canvas until
219    /// [`stop_rasterizing`](Self::stop_rasterizing) (matplotlib's
220    /// `start_rasterizing`); only vector output distinguishes the modes.
221    fn start_rasterizing(&mut self) {}
222
223    /// Places what was drawn since
224    /// [`start_rasterizing`](Self::start_rasterizing) in the output as an
225    /// image and resumes drawing directly.
226    fn stop_rasterizing(&mut self) {}
227
228    /// The resolution of the raster canvas drawing goes to while a vector
229    /// renderer is rasterizing, `None` otherwise. Artists drawn meanwhile
230    /// compute their geometry at it, in canvas pixels (matplotlib changes
231    /// the figure's dpi in `start_rasterizing`).
232    fn raster_dpi(&self) -> Option<f64> {
233        None
234    }
235
236    /// Sends the following drawing to a fresh transparent canvas until
237    /// [`stop_filter`](Self::stop_filter) (matplotlib's `start_filter`).
238    /// Only raster canvases filter; other backends draw as usual.
239    fn start_filter(&mut self) {}
240
241    /// Hands what was drawn since [`start_filter`](Self::start_filter),
242    /// cropped to its visible pixels, to `filter` and draws the image it
243    /// returns in its place (matplotlib's `stop_filter`).
244    fn stop_filter(&mut self, _filter: &FilterFn<'_>) {}
245
246    /// [`stop_filter`](Self::stop_filter) with a filter the renderer may
247    /// keep, as matplotlib hands renderers the artist's filter itself: a
248    /// renderer passing it on (to a program's renderer, say) overrides
249    /// this; the others filter as `stop_filter` does.
250    fn stop_shared_filter(&mut self, filter: &SharedFilter) {
251        self.stop_filter(filter.as_ref());
252    }
253
254    /// When `true`, images are drawn one by one instead of being
255    /// composited into a single image first.
256    fn option_image_nocomposite(&self) -> bool {
257        false
258    }
259
260    /// When `true`, [`draw_image`](Self::draw_image) accepts arbitrary
261    /// affine transforms (vector backends); otherwise images arrive
262    /// pre-resampled at display resolution.
263    fn option_scale_image(&self) -> bool {
264        false
265    }
266
267    /// The factor by which images are magnified before being drawn
268    /// (matplotlib's `get_image_magnification`): vector backends rasterize
269    /// images at their own resolution rather than at 72 dpi.
270    fn image_magnification(&self) -> f64 {
271        1.0
272    }
273}
274
275/// Fills the outline of TeX text at `origin`, rotated by `angle`, in the
276/// stroke colour of `gc` (matplotlib's `_draw_text_as_path` with
277/// `ismath="TeX"`): typeset at `TextToPath`'s size, then scaled to the
278/// text's size in pixels.
279pub(crate) fn fill_tex<R: Renderer + ?Sized>(
280    renderer: &mut R,
281    gc: &GraphicsContext,
282    tex: &TexText,
283    origin: Point,
284    angle: f64,
285) -> Result<(), TexError> {
286    let path = tex.text_path()?;
287    let scale = renderer.points_to_pixels(tex.size()) / TEXT_PATH_FONT_SCALE;
288    let transform = Affine2D::scaling(scale, scale)
289        .rotate_deg(angle)
290        .translate(origin.x, origin.y);
291    let mut fill_gc = gc.clone();
292    fill_gc.linewidth = 0.0;
293    renderer.draw_path(&fill_gc, &path, &transform, Some(gc.stroke_color()));
294    Ok(())
295}
296
297/// Fills `run` as one path in the colour of `gc`, laid out again from its
298/// source (matplotlib's `RendererBase._draw_text_as_path`, how path
299/// effects and Agg without its own `draw_text` draw text): typeset by
300/// `TextToPath` at [`TEXT_PATH_FONT_SCALE`] points and
301/// [`TEXT_PATH_DPI`](pltrs_text::TEXT_PATH_DPI), unhinted, then scaled to
302/// the text's size in pixels, rotated by `angle` degrees about `origin`
303/// and placed there. A run without a source is filled as it is.
304pub fn draw_text_as_path<R: Renderer + ?Sized>(
305    renderer: &mut R,
306    gc: &GraphicsContext,
307    run: &TextRun,
308    origin: Point,
309    angle: f64,
310) {
311    let engine = TextEngine::global();
312    let scaled = run.source.as_ref().and_then(|source| {
313        let laid_out = source
314            .layout(engine, TEXT_PATH_FONT_SCALE, pltrs_text::TEXT_PATH_DPI)
315            .ok()?;
316        let scale = renderer.points_to_pixels(source.size()) / TEXT_PATH_FONT_SCALE;
317        Some((laid_out.outline(engine), scale))
318    });
319    let (outline, scale) = scaled.unwrap_or_else(|| (run.outline(engine), 1.0));
320    let placement = Affine2D::scaling(scale, scale)
321        .rotate_deg(angle)
322        .translate(origin.x, origin.y);
323    let gc = GraphicsContext {
324        linewidth: 0.0,
325        ..gc.clone()
326    };
327    renderer.draw_path(&gc, &outline, &placement, Some(gc.foreground));
328}
329
330/// The transform placing text drawn at `origin`, rotated by `angle`
331/// degrees counter-clockwise about it.
332pub(crate) fn text_placement(origin: Point, angle: f64) -> Affine2D {
333    Affine2D::identity()
334        .rotate_deg(angle)
335        .translate(origin.x, origin.y)
336}
337
338/// Fills every glyph outline and rule of `run` as a path in the stroke
339/// colour of `gc` (the default [`Renderer::draw_text`], which vector
340/// backends also use for runs that carry no source).
341pub(crate) fn fill_text<R: Renderer + ?Sized>(
342    renderer: &mut R,
343    gc: &GraphicsContext,
344    run: &TextRun,
345    origin: Point,
346    angle: f64,
347) {
348    let engine = TextEngine::global();
349    let placement = text_placement(origin, angle);
350    let mut fill_gc = gc.clone();
351    fill_gc.linewidth = 0.0;
352    let color = gc.stroke_color();
353    for glyph in &run.glyphs {
354        let Ok(outline) = engine.glyph_outline(glyph.font, glyph.glyph, glyph.size, run.dpi) else {
355            continue;
356        };
357        let at = Affine2D::translation(glyph.x, glyph.y).then(placement);
358        renderer.draw_path(&fill_gc, &outline, &at, Some(color));
359    }
360    for rect in &run.rects {
361        let at = crate::unit_box(rect).then(placement);
362        renderer.draw_path(&fill_gc, &Path::unit_rectangle(), &at, Some(color));
363    }
364}