pltrs_render/raster/mod.rs
1//! The raster backend: matplotlib's `RendererAgg` on top of `pltrs-raster`.
2//!
3//! Every drawing call conditions its geometry with pltrs-core's port of
4//! matplotlib's path converters, chained exactly as `_backend_agg.h` chains
5//! them, and rasterizes it with pltrs-raster's port of Agg, so the pixels
6//! match matplotlib's Agg output.
7
8mod bitmap;
9mod condition;
10mod draw;
11mod filter;
12mod glyph;
13mod mono;
14mod tex;
15mod text;
16
17use std::cell::RefCell;
18use std::fmt;
19use std::rc::Rc;
20
21use pltrs_codec::png::{self, EncodeError, ImageRef};
22use pltrs_core::Path;
23use pltrs_core::path::convert::SimplifySettings;
24use pltrs_raster::{Mask, Painter, Pixmap, RasterError, Rgba8};
25
26use crate::gc::ClipPath;
27use crate::image::RgbaImage;
28use crate::vector::PngMetadata;
29
30pub use self::bitmap::{GlyphBitmap, GlyphShape, glyph_axis_aligned, render_glyph};
31
32pltrs_core::thread_state! {
33 /// What says whether the thread's raster canvases draw text as paths.
34 static TEXTS_AS_PATHS: RefCell<Option<Rc<dyn Fn() -> bool>>> = const { RefCell::new(None) };
35}
36
37/// Makes the raster canvases of this thread draw text as paths whenever
38/// `rule` says so (or as glyphs again, with `None`), as matplotlib's Agg
39/// renderer does without its own `draw_text`: `RendererBase.draw_text`
40/// fills the outlines `TextToPath` makes of the text
41/// (`_draw_text_as_path`). The rule is asked each time a canvas draws
42/// text, so that it can follow the program (pltrs (Python): whether
43/// `RendererAgg.draw_text` is taken away).
44pub fn set_texts_as_paths(rule: Option<Rc<dyn Fn() -> bool>>) {
45 TEXTS_AS_PATHS.set(rule);
46}
47
48/// Whether the thread's raster canvases draw text as paths now.
49fn texts_as_paths() -> bool {
50 TEXTS_AS_PATHS
51 .with_borrow(Clone::clone)
52 .is_some_and(|rule| rule())
53}
54
55/// Why a raster canvas could not be created or encoded.
56#[derive(Debug)]
57pub enum RasterBackendError {
58 /// The canvas size is invalid (matplotlib caps each side below 2²³).
59 Canvas(RasterError),
60 /// The resolution is not a positive finite number.
61 Dpi(f64),
62 /// PNG encoding failed.
63 Encode(EncodeError),
64}
65
66impl fmt::Display for RasterBackendError {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 match self {
69 Self::Canvas(err) => write!(f, "invalid canvas: {err}"),
70 Self::Dpi(dpi) => write!(f, "dpi must be positive, got {dpi}"),
71 Self::Encode(err) => write!(f, "PNG encoding failed: {err}"),
72 }
73 }
74}
75
76impl std::error::Error for RasterBackendError {
77 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78 match self {
79 Self::Canvas(err) => Some(err),
80 Self::Encode(err) => Some(err),
81 Self::Dpi(_) => None,
82 }
83 }
84}
85
86/// A rasterized clip path, reused while the same clip path and transform
87/// come back (matplotlib's `lastclippath` cache).
88#[derive(Debug)]
89struct CachedClip {
90 key: ClipPath,
91 mask: Mask,
92}
93
94/// Renders into an RGBA pixel buffer exactly like matplotlib's
95/// `RendererAgg` (straight alpha, initially transparent white).
96#[derive(Debug)]
97pub struct RasterRenderer {
98 pixmap: Pixmap,
99 painter: Painter,
100 /// Canvas size as requested; the buffer holds its truncated size, as
101 /// matplotlib's `RendererAgg(int(width), int(height), dpi)` does.
102 size: (f64, f64),
103 dpi: f64,
104 simplify: SimplifySettings,
105 /// Long unfilled paths are drawn in pieces of at most this many
106 /// vertices (matplotlib's `agg.path.chunksize`; 0 never splits).
107 chunksize: usize,
108 clip_cache: Option<CachedClip>,
109 /// The last conditioned path, kept for its allocations.
110 conditioned: Path,
111 /// The last conditioned path with its curves flattened, likewise.
112 flattened: Path,
113 /// Canvases set aside while filtered artists draw (`None` where the
114 /// canvas to draw them on could not be made).
115 set_aside: Vec<Option<Pixmap>>,
116 errors: Vec<RasterError>,
117}
118
119impl RasterRenderer {
120 /// A canvas of `width × height` display pixels at `dpi`.
121 pub fn new(width: f64, height: f64, dpi: f64) -> Result<Self, RasterBackendError> {
122 if !(dpi.is_finite() && dpi > 0.0) {
123 return Err(RasterBackendError::Dpi(dpi));
124 }
125 let pixmap = Pixmap::filled(width as u32, height as u32, Rgba8::TRANSPARENT_WHITE)
126 .map_err(RasterBackendError::Canvas)?;
127 Ok(Self {
128 pixmap,
129 painter: Painter::new(),
130 size: (width, height),
131 dpi,
132 simplify: SimplifySettings::default(),
133 chunksize: 0,
134 clip_cache: None,
135 conditioned: Path::default(),
136 flattened: Path::default(),
137 set_aside: Vec::new(),
138 errors: Vec::new(),
139 })
140 }
141
142 /// Uses matplotlib's `path.simplify` / `path.simplify_threshold`
143 /// settings (the defaults otherwise).
144 #[must_use]
145 pub fn with_simplify(mut self, settings: SimplifySettings) -> Self {
146 self.simplify = settings;
147 self
148 }
149
150 /// Draws unfilled, unhatched paths that would be simplified in pieces
151 /// of at most `chunksize` vertices when they have more, as matplotlib
152 /// does with `agg.path.chunksize` (0, the default, never splits; nor do
153 /// sizes up to 100).
154 #[must_use]
155 pub fn with_path_chunksize(mut self, chunksize: usize) -> Self {
156 self.chunksize = chunksize;
157 self
158 }
159
160 /// The pixels drawn so far.
161 pub fn pixmap(&self) -> &Pixmap {
162 &self.pixmap
163 }
164
165 /// The pixels, for changes made outside drawing calls (matplotlib's
166 /// `restore_region` writes saved pixels back into the canvas).
167 pub fn pixmap_mut(&mut self) -> &mut Pixmap {
168 &mut self.pixmap
169 }
170
171 /// Consumes the renderer, returning its pixels.
172 pub fn into_pixmap(self) -> Pixmap {
173 self.pixmap
174 }
175
176 /// The pixels as an [`RgbaImage`] (a copy; see
177 /// [`into_image`](Self::into_image)).
178 pub fn to_image(&self) -> RgbaImage {
179 filter::image_of(self.pixmap.clone())
180 }
181
182 /// Consumes the renderer, returning its pixels as an [`RgbaImage`]
183 /// without copying them.
184 pub fn into_image(self) -> RgbaImage {
185 filter::image_of(self.pixmap)
186 }
187
188 /// Encodes the pixels as an RGBA PNG carrying the resolution, without
189 /// text entries.
190 ///
191 /// # Errors
192 ///
193 /// When the image cannot be encoded.
194 pub fn to_png(&self) -> Result<Vec<u8>, RasterBackendError> {
195 self.to_png_with(&PngMetadata::none())
196 }
197
198 /// Encodes the canvas as PNG with the text entries of `metadata`, as
199 /// matplotlib's `savefig` writes them.
200 ///
201 /// # Errors
202 ///
203 /// When the image cannot be encoded, or a keyword is not a valid PNG
204 /// keyword (1 to 79 printable Latin-1 characters).
205 pub fn to_png_with(&self, metadata: &PngMetadata) -> Result<Vec<u8>, RasterBackendError> {
206 let image = ImageRef::rgba8(
207 self.pixmap.width(),
208 self.pixmap.height(),
209 self.pixmap.data(),
210 )
211 .map_err(RasterBackendError::Encode)?;
212 metadata
213 .apply_to(png::Encoder::new().dpi(self.dpi))
214 .encode(image)
215 .map_err(RasterBackendError::Encode)
216 }
217
218 /// Resets every pixel to transparent white (matplotlib's `clear()`).
219 pub fn clear(&mut self) {
220 self.pixmap.fill(Rgba8::TRANSPARENT_WHITE);
221 }
222
223 /// Problems met while drawing (matplotlib would have raised, e.g.
224 /// `OverflowError` for paths exceeding the cell limit), oldest first.
225 pub fn take_errors(&mut self) -> Vec<RasterError> {
226 std::mem::take(&mut self.errors)
227 }
228
229 /// Records the outcome of one raster operation.
230 fn record(&mut self, result: Result<(), RasterError>) {
231 if let Err(err) = result {
232 self.errors.push(err);
233 }
234 }
235
236 fn width(&self) -> u32 {
237 self.pixmap.width()
238 }
239
240 fn height(&self) -> u32 {
241 self.pixmap.height()
242 }
243}
244
245#[cfg(test)]
246mod tests;