Skip to main content

pltrs_render/raster/
draw.rs

1//! The [`Renderer`] implementation: one method per `RendererAgg` entry
2//! point, each conditioning and clipping exactly like `_backend_agg.h`.
3
4use std::ops::Range;
5
6use pltrs_core::hatch;
7use pltrs_core::path::convert::{SnapMode as PathSnap, VertexSource};
8use pltrs_core::{Affine2D, Path, PathCode, Point, Rgba};
9use pltrs_raster::{Antialias, Clip, ClipBox, FillRule, Pixmap, RasterError, Rgba8};
10use pltrs_text::TextRun;
11use pltrs_text::tex::{TexError, TexText};
12
13use super::RasterRenderer;
14use super::condition::{Conditioning, cached_mask, mpl_round, sketch_params, snap_mode};
15use crate::collection::{ItemCycle, PathCollection};
16use crate::filter::FilterFn;
17use crate::gc::GraphicsContext;
18use crate::image::RgbaImage;
19use crate::quad_mesh::QuadMesh;
20use crate::renderer::{Renderer, draw_text_as_path};
21
22/// Whether an 8-bit colour would draw anything.
23fn visible(color: Rgba) -> bool {
24    Rgba8::from(color).a != 0
25}
26
27impl RasterRenderer {
28    /// `RendererAgg::_draw_path`: face, hatch and stroke of an already
29    /// conditioned path, under the clip box and mask prepared by the caller.
30    fn draw_conditioned(
31        &mut self,
32        gc: &GraphicsContext,
33        path: &Path,
34        face: Option<Rgba>,
35        rect: Option<ClipBox>,
36        masked: bool,
37    ) {
38        let aa = Antialias::from(gc.antialiased);
39        if let Some(face) = face {
40            let clip = Clip {
41                rect,
42                mask: cached_mask(self.clip_cache.as_ref(), masked),
43            };
44            let result =
45                self.painter
46                    .fill_path(&mut self.pixmap, path, face, FillRule::NonZero, aa, &clip);
47            self.record(result);
48        }
49        if let Some(tile) = self.hatch_tile(gc) {
50            let clip = Clip {
51                rect,
52                mask: cached_mask(self.clip_cache.as_ref(), masked),
53            };
54            let result = self.painter.fill_path_with_pattern(
55                &mut self.pixmap,
56                path,
57                &tile,
58                FillRule::NonZero,
59                &clip,
60            );
61            self.record(result);
62        }
63        if gc.linewidth != 0.0 {
64            let style = self.stroke_style(gc);
65            let clip = Clip {
66                rect,
67                mask: cached_mask(self.clip_cache.as_ref(), masked),
68            };
69            let result = self.painter.stroke_path(
70                &mut self.pixmap,
71                path,
72                gc.stroke_color(),
73                &style,
74                aa,
75                &clip,
76            );
77            self.record(result);
78        }
79    }
80
81    /// The hatch tile of `gc`: matplotlib's hatch path (density 6) scaled
82    /// to an `int(dpi)`-pixel tile, filled and stroked with square caps.
83    fn hatch_tile(&mut self, gc: &GraphicsContext) -> Option<Pixmap> {
84        let spec = gc.hatch.as_ref()?;
85        let unit = hatch::pattern_path(&spec.pattern, hatch::DEFAULT_DENSITY).ok()?;
86        if unit.is_empty() {
87            return None;
88        }
89        let size = self.dpi as u32;
90        let s = f64::from(size);
91        let tile_path = unit.transformed(&Affine2D::from_values(s, 0.0, 0.0, -s, 0.0, s));
92        let linewidth = self.px(spec.linewidth);
93        match self.painter.hatch_tile(
94            size,
95            &tile_path,
96            spec.color,
97            linewidth,
98            Rgba8::TRANSPARENT_WHITE,
99        ) {
100            Ok(tile) => Some(tile),
101            Err(err) => {
102                self.errors.push(err);
103                None
104            }
105        }
106    }
107
108    /// The marker path in stamp coordinates (`draw_markers`): flipped,
109    /// snapped, and moved to pixel centres when not snapping.
110    fn marker_geometry(
111        &self,
112        gc: &GraphicsContext,
113        marker: &Path,
114        marker_transform: &Affine2D,
115    ) -> Path {
116        let trans = marker_transform.then(Affine2D::scaling(1.0, -1.0));
117        let has_codes = marker.codes().is_some();
118        let width = self.px(gc.linewidth);
119        let snapped = marker
120            .iter_vertices()
121            .transform(trans)
122            .remove_nans(true, has_codes)
123            .snap(snap_mode(gc.snap), marker.len(), width);
124        if snapped.is_snapping() {
125            return snapped.flatten_curves(true).collect_path();
126        }
127        // matplotlib shifts the (shared) marker transform by half a pixel
128        // after the snapping decision was taken.
129        marker
130            .iter_vertices()
131            .transform(trans.then(Affine2D::translation(0.5, 0.5)))
132            .remove_nans(true, has_codes)
133            .snap(PathSnap::Never, marker.len(), width)
134            .flatten_curves(true)
135            .collect_path()
136    }
137}
138
139impl Renderer for RasterRenderer {
140    fn canvas_size(&self) -> (f64, f64) {
141        self.size
142    }
143
144    fn dpi(&self) -> f64 {
145        self.dpi
146    }
147
148    fn draw_path(
149        &mut self,
150        gc: &GraphicsContext,
151        path: &Path,
152        transform: &Affine2D,
153        fill: Option<Rgba>,
154    ) {
155        let chunked = fill.is_none()
156            && gc.hatch.is_none()
157            && self.chunksize > 100
158            && path.len() > self.chunksize
159            && self.simplify.applies_to(path);
160        if chunked {
161            for chunk in chunks(path, self.chunksize) {
162                self.draw_whole_path(gc, &chunk, transform, None);
163            }
164        } else if (fill.is_some() || gc.hatch.is_some())
165            && gc.sketch.is_some_and(|sketch| sketch.scale.is_infinite())
166        {
167            // Agg rasterizes the fill of an infinite sketch into more cells
168            // than it allows, and matplotlib cannot split the path.
169            self.errors.push(RasterError::UnsplittablePath {
170                filled: fill.is_some(),
171                hatched: gc.hatch.is_some(),
172                simplifiable: self.simplify.applies_to(path),
173            });
174        } else {
175            self.draw_whole_path(gc, path, transform, fill);
176        }
177    }
178
179    fn draw_markers(
180        &mut self,
181        gc: &GraphicsContext,
182        marker: &Path,
183        marker_transform: &Affine2D,
184        path: &Path,
185        transform: &Affine2D,
186        fill: Option<Rgba>,
187    ) {
188        let marker_path = self.marker_geometry(gc, marker, marker_transform);
189        let to_pixels = transform
190            .then(Affine2D::scaling(1.0, -1.0))
191            .then(Affine2D::translation(0.5, f64::from(self.height()) + 0.5));
192        let positions: Vec<Point> = path
193            .iter_vertices()
194            .transform(to_pixels)
195            .remove_nans(false, false)
196            .flatten_curves(true)
197            .map(|v| v.point)
198            .collect();
199        let face = fill.map(|c| gc.fill_color(c)).filter(|c| c.a != 0.0);
200        let edge = Some(gc.stroke_color()).filter(|&c| visible(c));
201        let style = self.solid_stroke_style(gc);
202        let stamp =
203            match self
204                .painter
205                .marker_stamp(&marker_path, face.is_some(), edge.map(|_| &style))
206            {
207                Ok(stamp) => stamp,
208                Err(err) => {
209                    self.errors.push(err);
210                    return;
211                }
212            };
213        // Markers clip to the clip box inclusively; under a clip path
214        // (rasterized unclipped here) the clip box is not applied at all.
215        let masked = self.prepare_clip_mask(gc, None);
216        let rect = if masked {
217            None
218        } else {
219            self.clip_box(gc).map(ClipBox::inclusive)
220        };
221        let clip = Clip {
222            rect,
223            mask: cached_mask(self.clip_cache.as_ref(), masked),
224        };
225        let result = stamp.draw(&mut self.pixmap, &positions, face, edge, &clip);
226        self.record(result);
227    }
228
229    fn draw_path_collection(&mut self, gc: &GraphicsContext, collection: &PathCollection<'_>) {
230        if collection.is_empty() {
231            return;
232        }
233        let rect = self.clip_box(gc);
234        let masked = self.prepare_clip_mask(gc, Some(rect.unwrap_or_else(|| self.full_box())));
235        let clip = collection.facecolors.is_empty() && gc.hatch.is_none();
236        let mut conditioned = std::mem::take(&mut self.conditioned);
237        let mut flattened = std::mem::take(&mut self.flattened);
238        for item in collection.items_cycled(gc, ItemCycle::Agg) {
239            let conditioning = Conditioning {
240                has_codes: true,
241                clip,
242                snap: snap_mode(item.gc.snap),
243                snap_width: self.px(item.gc.linewidth),
244                simplify: None,
245                sketch: sketch_params(item.gc.sketch),
246            };
247            let transform = self.to_device(&item.transform);
248            self.condition_into(item.path, transform, &conditioning, &mut conditioned);
249            // The fill and the stroke would each flatten the curves (of a
250            // marker, say) the same way: flatten them once.
251            let path = if conditioned.has_curves() {
252                conditioned
253                    .iter_vertices()
254                    .flatten_curves(true)
255                    .collect_path_into(&mut flattened);
256                &flattened
257            } else {
258                &conditioned
259            };
260            let face = item.fill.map(|c| item.gc.fill_color(c));
261            self.draw_conditioned(&item.gc, path, face, rect, masked);
262        }
263        self.conditioned = conditioned;
264        self.flattened = flattened;
265    }
266
267    fn draw_gouraud_triangles(
268        &mut self,
269        gc: &GraphicsContext,
270        triangles: &[[Point; 3]],
271        colors: &[[Rgba; 3]],
272        transform: &Affine2D,
273    ) {
274        let rect = self.clip_box(gc);
275        let masked = self.prepare_clip_mask(gc, Some(rect.unwrap_or_else(|| self.full_box())));
276        let to_pixels = self.to_device(transform);
277        for (triangle, colors) in triangles.iter().zip(colors) {
278            let points = triangle.map(|p| to_pixels.agg_transform_point(p));
279            if points.iter().any(|p| p.x.is_nan() || p.y.is_nan()) {
280                continue;
281            }
282            let clip = Clip {
283                rect,
284                mask: cached_mask(self.clip_cache.as_ref(), masked),
285            };
286            let result = self
287                .painter
288                .gouraud_triangle(&mut self.pixmap, points, *colors, &clip);
289            self.record(result);
290        }
291    }
292
293    /// matplotlib's wrapper rounds the position and forces the image alpha
294    /// to 1 (images arrive with their opacity applied).
295    fn draw_image(
296        &mut self,
297        gc: &GraphicsContext,
298        origin: Point,
299        image: &RgbaImage,
300        _transform: Option<&Affine2D>,
301    ) {
302        let (Ok(width), Ok(height)) = (u32::try_from(image.width()), u32::try_from(image.height()))
303        else {
304            return;
305        };
306        let Ok(source) = Pixmap::from_vec(width, height, image.data().to_vec()) else {
307            return;
308        };
309        let x = mpl_round(origin.x);
310        let y = mpl_round(origin.y);
311        let top = f64::from(self.height()) - (y + f64::from(height));
312        let rect = self.clip_box(gc);
313        let raster_box = rect.unwrap_or_else(|| self.full_box());
314        let masked = self.prepare_clip_mask(gc, Some(raster_box));
315        // Masked images go through the rasterizer clip box; unmasked ones
316        // through `renderer_base`, which includes the far edges.
317        let clip = if masked {
318            Clip {
319                rect: Some(raster_box),
320                mask: cached_mask(self.clip_cache.as_ref(), true),
321            }
322        } else {
323            Clip::rect(rect.map_or(raster_box, ClipBox::inclusive))
324        };
325        let result =
326            pltrs_raster::draw_image(&mut self.pixmap, &source, x as i32, top as i32, 1.0, &clip);
327        self.record(result);
328    }
329
330    /// Glyph outlines filled at `FreeType`'s pen positions, unsnapped; see
331    /// the `text` module. While the thread draws text as paths
332    /// ([`set_texts_as_paths`](super::set_texts_as_paths)), the outlines
333    /// `TextToPath` makes are filled as paths instead.
334    fn draw_text(&mut self, gc: &GraphicsContext, run: &TextRun, origin: Point, angle: f64) {
335        if super::texts_as_paths() {
336            draw_text_as_path(self, gc, run, origin, angle);
337        } else {
338            self.draw_text_run(gc, run, origin, angle);
339        }
340    }
341
342    /// Glyphs are placed on the 26.6 grid as matplotlib's Agg renderer
343    /// rounds them, unless they are drawn as paths.
344    fn rounds_glyph_positions(&self) -> bool {
345        !super::texts_as_paths()
346    }
347
348    /// TeX text from its DVI glyphs or `dvipng`'s image; see the `tex`
349    /// module.
350    fn draw_tex(
351        &mut self,
352        gc: &GraphicsContext,
353        _run: &TextRun,
354        tex: &TexText,
355        origin: Point,
356        angle: f64,
357    ) -> Result<(), TexError> {
358        self.draw_tex_text(gc, tex, origin, angle)
359    }
360
361    /// Agg's quad mesh generator walks every cell down its first column
362    /// first. Colours given per cell (or one for all) are split with the
363    /// cells, which are then drawn a block at a time, so that their
364    /// outlines need not all exist at once.
365    fn draw_quad_mesh(&mut self, gc: &GraphicsContext, mesh: &QuadMesh<'_>) {
366        let widths = [gc.linewidth];
367        let flags = [mesh.antialiased];
368        let cells = mesh.cell_count();
369        let splits = |colors: &[Rgba]| colors.len() <= 1 || colors.len() == cells;
370        if !(splits(mesh.facecolors) && splits(mesh.edgecolors)) {
371            let paths = mesh.agg_cell_paths();
372            self.draw_path_collection(gc, &mesh.collection(&paths, &widths, &flags));
373            return;
374        }
375        let mut paths = Vec::new();
376        for start in (0..cells).step_by(MESH_BLOCK) {
377            let block = start..cells.min(start + MESH_BLOCK);
378            mesh.agg_cell_paths_into(block.clone(), &mut paths);
379            let collection = PathCollection {
380                facecolors: block_colors(mesh.facecolors, &block),
381                edgecolors: block_colors(mesh.edgecolors, &block),
382                ..mesh.collection(&paths, &widths, &flags)
383            };
384            self.draw_path_collection(gc, &collection);
385        }
386    }
387
388    fn start_filter(&mut self) {
389        self.start_filtering();
390    }
391
392    fn stop_filter(&mut self, filter: &FilterFn<'_>) {
393        self.stop_filtering(filter);
394    }
395
396    /// Agg composites each image straight onto the canvas.
397    fn option_image_nocomposite(&self) -> bool {
398        true
399    }
400}
401
402/// Cells of a quad mesh drawn as one path collection.
403const MESH_BLOCK: usize = 4096;
404
405/// The colours of the cells in `block`: their own when given per cell,
406/// else the one colour (or none) for all.
407fn block_colors<'a>(colors: &'a [Rgba], block: &Range<usize>) -> &'a [Rgba] {
408    if colors.len() > 1 {
409        &colors[block.clone()]
410    } else {
411        colors
412    }
413}
414
415impl RasterRenderer {
416    /// Draws `path` in one piece (matplotlib's `_renderer.draw_path`).
417    fn draw_whole_path(
418        &mut self,
419        gc: &GraphicsContext,
420        path: &Path,
421        transform: &Affine2D,
422        fill: Option<Rgba>,
423    ) {
424        let face = fill.map(|c| gc.fill_color(c)).filter(|c| c.a != 0.0);
425        let rect = self.clip_box(gc);
426        let masked = self.prepare_clip_mask(gc, Some(rect.unwrap_or_else(|| self.full_box())));
427        let clip = face.is_none() && gc.hatch.is_none();
428        let snap_width = if gc.stroke_color().a == 0.0 {
429            0.0
430        } else {
431            self.px(gc.linewidth)
432        };
433        let conditioning = Conditioning {
434            has_codes: path.codes().is_some(),
435            clip,
436            snap: snap_mode(gc.snap),
437            snap_width,
438            simplify: if clip {
439                self.simplify.for_path(path)
440            } else {
441                None
442            },
443            sketch: sketch_params(gc.sketch),
444        };
445        let mut conditioned = std::mem::take(&mut self.conditioned);
446        self.condition_into(
447            path,
448            self.to_device(transform),
449            &conditioning,
450            &mut conditioned,
451        );
452        self.draw_conditioned(gc, &conditioned, face, rect, masked);
453        self.conditioned = conditioned;
454    }
455}
456
457/// The pieces matplotlib's `RendererAgg.draw_path` splits a long path into
458/// for `agg.path.chunksize`: equal runs of vertices, each starting with a
459/// move, where the vertex before each run's start is left out.
460fn chunks(path: &Path, chunksize: usize) -> Vec<Path> {
461    let points = path.len();
462    let count = points.div_ceil(chunksize);
463    let size = points.div_ceil(count);
464    let starts: Vec<usize> = (0..points).step_by(size).collect();
465    starts
466        .iter()
467        .enumerate()
468        .map(|(i, &start)| {
469            let end = starts.get(i + 1).map_or(points, |next| next - 1);
470            let vertices = path.vertices()[start..end].to_vec();
471            match path.codes() {
472                Some(codes) => {
473                    let mut codes = codes[start..end].to_vec();
474                    if let Some(first) = codes.first_mut() {
475                        *first = PathCode::MoveTo;
476                    }
477                    Path::new(vertices, codes).expect("chunks start with a move")
478                }
479                None => Path::polyline(vertices),
480            }
481        })
482        .collect()
483}