Skip to main content

pltrs_render/
collection.rs

1//! Batched drawing of many paths with per-item properties.
2
3use std::rc::Rc;
4
5use pltrs_core::{Affine2D, Path, Point, Rgba};
6
7use crate::gc::{Dashes, GraphicsContext};
8
9/// The arguments of matplotlib's `draw_path_collection`.
10///
11/// Every per-item sequence is *cycled* to the item count (see
12/// [`ItemCycle`]); an empty sequence means "use the base graphics context"
13/// (or, for colours, "do not fill/stroke").
14#[derive(Clone, Debug, Default)]
15pub struct PathCollection<'a> {
16    /// Applied after each item's own transform.
17    pub master_transform: Affine2D,
18    /// Item shapes.
19    pub paths: &'a [Path],
20    /// Per-item transforms applied before `master_transform`.
21    pub path_transforms: &'a [Affine2D],
22    /// Per-item translations in display coordinates.
23    pub offsets: &'a [Point],
24    /// Face colours; empty = no fills.
25    pub facecolors: &'a [Rgba],
26    /// Edge colours; empty = no strokes.
27    pub edgecolors: &'a [Rgba],
28    /// Hatch colours.
29    pub hatchcolors: &'a [Rgba],
30    /// Edge line widths in points.
31    pub linewidths: &'a [f64],
32    /// Edge dash patterns.
33    pub dashes: &'a [Dashes],
34    /// Per-item anti-aliasing.
35    pub antialiased: &'a [bool],
36    /// Per-item hyperlinks.
37    pub urls: &'a [Option<String>],
38}
39
40/// How the items of a [`PathCollection`] cycle through its shapes and
41/// their transforms, which matplotlib's backends do two ways.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum ItemCycle {
44    /// `RendererBase._iter_collection`, which the vector backends use:
45    /// `max(max(paths, path_transforms), offsets)` items, item `i` drawing
46    /// the raw path (a shape with its transform, see
47    /// [`PathCollection::raw_paths`]) `i mod max(paths, path_transforms)`.
48    #[default]
49    RawPaths,
50    /// Agg's `draw_path_collection`: `max(paths, offsets)` items, item `i`
51    /// drawing shape `i mod paths` with transform `i mod
52    /// path_transforms`, so that transforms beyond the items are never
53    /// drawn.
54    Agg,
55}
56
57/// One resolved item of a [`PathCollection`].
58#[derive(Clone, Debug)]
59pub struct CollectionItem<'a> {
60    /// The shape.
61    pub path: &'a Path,
62    /// Index of the shape in [`PathCollection::raw_paths`] (in `paths`
63    /// for items in [`ItemCycle::Agg`]).
64    pub path_index: usize,
65    /// Translation of the item in display coordinates.
66    pub offset: Point,
67    /// Full transform to display coordinates (offset included).
68    pub transform: Affine2D,
69    /// The graphics context with per-item overrides applied, shared with
70    /// the items before it until an override changes it.
71    pub gc: Rc<GraphicsContext>,
72    /// Face colour, or `None` when the item is not filled.
73    pub fill: Option<Rgba>,
74}
75
76impl<'a> PathCollection<'a> {
77    /// Number of items that will be drawn (before skipping non-finite offsets).
78    pub fn len(&self) -> usize {
79        if self.paths.is_empty() {
80            return 0;
81        }
82        self.paths
83            .len()
84            .max(self.path_transforms.len())
85            .max(self.offsets.len())
86    }
87
88    /// Number of distinct shapes: `max(paths, path_transforms)`.
89    fn raw_path_count(&self) -> usize {
90        if self.paths.is_empty() {
91            0
92        } else {
93            self.paths.len().max(self.path_transforms.len())
94        }
95    }
96
97    /// Every shape with its transform before the offset (matplotlib's
98    /// `_iter_collection_raw_paths`); items refer to them by
99    /// [`CollectionItem::path_index`].
100    pub fn raw_paths(&self) -> impl Iterator<Item = (&'a Path, Affine2D)> + '_ {
101        (0..self.raw_path_count()).map(|i| {
102            let own = cycled(self.path_transforms, i).copied().unwrap_or_default();
103            (
104                &self.paths[i % self.paths.len()],
105                own.then(self.master_transform),
106            )
107        })
108    }
109
110    /// How often each raw path is used, rounded up (matplotlib's
111    /// `_iter_collection_uses_per_path`); zero when nothing is filled or
112    /// stroked.
113    pub fn uses_per_path(&self) -> usize {
114        let raw = self.raw_path_count();
115        if raw == 0 || (self.facecolors.is_empty() && self.edgecolors.is_empty()) {
116            return 0;
117        }
118        self.len().div_ceil(raw)
119    }
120
121    /// Returns `true` when nothing would be drawn.
122    pub fn is_empty(&self) -> bool {
123        self.len() == 0
124            || (self.facecolors.is_empty()
125                && self.edgecolors.is_empty()
126                && self.hatchcolors.is_empty())
127    }
128
129    /// Resolves every drawable item, exactly as matplotlib's
130    /// `RendererBase._iter_collection` does: items with non-finite offsets
131    /// are skipped, fully transparent faces become unfilled, and fully
132    /// transparent edges disable stroking.
133    ///
134    /// The context is copied only when an override changes it while an
135    /// earlier item still holds it, so items dropped before the next is
136    /// taken share one context.
137    pub fn items(&self, base: &GraphicsContext) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
138        self.items_cycled(base, ItemCycle::RawPaths)
139    }
140
141    /// [`PathCollection::items`], cycling through the shapes and their
142    /// transforms as `cycle` says.
143    pub fn items_cycled(
144        &self,
145        base: &GraphicsContext,
146        cycle: ItemCycle,
147    ) -> impl Iterator<Item = CollectionItem<'a>> + '_ {
148        let count = match cycle {
149            _ if self.is_empty() => 0,
150            ItemCycle::RawPaths => self.len(),
151            ItemCycle::Agg => self.paths.len().max(self.offsets.len()),
152        };
153        let raw_count = self.raw_path_count();
154        let mut shared = Rc::new(base.clone());
155        if self.edgecolors.is_empty() {
156            Rc::make_mut(&mut shared).linewidth = 0.0;
157        }
158        (0..count).filter_map(move |i| {
159            let offset = cycled(self.offsets, i).copied().unwrap_or(Point::ORIGIN);
160            if !offset.is_finite() {
161                return None;
162            }
163            if let Some(&edge) = cycled(self.edgecolors, i) {
164                let gc = Rc::make_mut(&mut shared);
165                if let Some(&width) = cycled(self.linewidths, i) {
166                    gc.linewidth = width;
167                }
168                if let Some(dashes) = cycled(self.dashes, i) {
169                    gc.dashes.clone_from(dashes);
170                }
171                if edge.is_transparent() {
172                    gc.linewidth = 0.0;
173                } else {
174                    gc.foreground = edge;
175                }
176            }
177            if let Some(&aa) = cycled(self.antialiased, i) {
178                Rc::make_mut(&mut shared).antialiased = aa;
179            }
180            if let Some(url) = cycled(self.urls, i) {
181                Rc::make_mut(&mut shared).url.clone_from(url);
182            }
183            if let Some(&color) = cycled(self.hatchcolors, i)
184                && let Some(hatch) = Rc::make_mut(&mut shared).hatch.as_mut()
185            {
186                hatch.color = color;
187            }
188            let fill = cycled(self.facecolors, i)
189                .copied()
190                .filter(|c| !c.is_transparent());
191            let (path_index, shape, own) = match cycle {
192                // Items cycle through the raw paths, as matplotlib's
193                // `_iter_collection` cycles through the path ids.
194                ItemCycle::RawPaths => {
195                    let raw = wrap(i, raw_count);
196                    let shape = wrap(raw, self.paths.len());
197                    (raw, shape, cycled(self.path_transforms, raw))
198                }
199                ItemCycle::Agg => {
200                    let shape = wrap(i, self.paths.len());
201                    (shape, shape, cycled(self.path_transforms, i))
202                }
203            };
204            // Agg composes the item's transform with the master's in C++
205            // (`trans *= master_transform`), the vector backends' iteration
206            // with numpy.
207            let own = own.copied().unwrap_or_default();
208            let transform = match cycle {
209                ItemCycle::RawPaths => own.then(self.master_transform),
210                ItemCycle::Agg => own.agg_then(self.master_transform),
211            }
212            .translate(offset.x, offset.y);
213            Some(CollectionItem {
214                path: &self.paths[shape],
215                path_index,
216                offset,
217                transform,
218                gc: Rc::clone(&shared),
219                fill,
220            })
221        })
222    }
223}
224
225/// The arguments of a [`PathCollection`] owned rather than borrowed, for
226/// a drawing kept until it is drawn (what a program drew through a
227/// renderer of its own, see `pltrs::artist::Drawing`).
228#[derive(Clone, Debug, Default, PartialEq)]
229pub struct PathCollectionData {
230    /// Applied after each item's own transform.
231    pub master_transform: Affine2D,
232    /// Item shapes.
233    pub paths: Vec<Path>,
234    /// Per-item transforms applied before `master_transform`.
235    pub path_transforms: Vec<Affine2D>,
236    /// Per-item translations in display coordinates.
237    pub offsets: Vec<Point>,
238    /// Face colours; empty = no fills.
239    pub facecolors: Vec<Rgba>,
240    /// Edge colours; empty = no strokes.
241    pub edgecolors: Vec<Rgba>,
242    /// Hatch colours.
243    pub hatchcolors: Vec<Rgba>,
244    /// Edge line widths in points.
245    pub linewidths: Vec<f64>,
246    /// Edge dash patterns.
247    pub dashes: Vec<Dashes>,
248    /// Per-item anti-aliasing.
249    pub antialiased: Vec<bool>,
250    /// Per-item hyperlinks.
251    pub urls: Vec<Option<String>>,
252}
253
254impl PathCollectionData {
255    /// The collection these arguments describe.
256    pub fn view(&self) -> PathCollection<'_> {
257        PathCollection {
258            master_transform: self.master_transform,
259            paths: &self.paths,
260            path_transforms: &self.path_transforms,
261            offsets: &self.offsets,
262            facecolors: &self.facecolors,
263            edgecolors: &self.edgecolors,
264            hatchcolors: &self.hatchcolors,
265            linewidths: &self.linewidths,
266            dashes: &self.dashes,
267            antialiased: &self.antialiased,
268            urls: &self.urls,
269        }
270    }
271}
272
273/// Item `i` of `items` repeated cyclically, or `None` when there are none.
274fn cycled<T>(items: &[T], i: usize) -> Option<&T> {
275    (!items.is_empty()).then(|| &items[wrap(i, items.len())])
276}
277
278/// `i % len`, without the division in the usual case of an index in range
279/// (collections draw thousands of items per call).
280fn wrap(i: usize, len: usize) -> usize {
281    if i < len { i } else { i % len }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    #[test]
289    fn cycles_properties_and_skips_non_finite_offsets() {
290        let paths = [Path::unit_rectangle()];
291        let offsets = [
292            Point::new(1.0, 1.0),
293            Point::new(f64::NAN, 0.0),
294            Point::new(3.0, 3.0),
295        ];
296        let faces = [Rgba::BLACK, Rgba::TRANSPARENT];
297        let collection = PathCollection {
298            paths: &paths,
299            offsets: &offsets,
300            facecolors: &faces,
301            ..PathCollection::default()
302        };
303        let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
304        assert_eq!(items.len(), 2);
305        assert_eq!(items[0].fill, Some(Rgba::BLACK));
306        assert_eq!(
307            items[1].fill,
308            Some(Rgba::BLACK),
309            "third item cycles back to the first face"
310        );
311        assert_eq!(items[1].transform.translation_part(), Point::new(3.0, 3.0));
312        assert_eq!(
313            items[0].gc.linewidth, 0.0,
314            "no edge colours means no stroke"
315        );
316    }
317
318    #[test]
319    fn transparent_edges_disable_stroke() {
320        let paths = [Path::unit_rectangle(), Path::unit_circle()];
321        let edges = [Rgba::BLACK, Rgba::TRANSPARENT];
322        let widths = [2.0];
323        let collection = PathCollection {
324            paths: &paths,
325            edgecolors: &edges,
326            linewidths: &widths,
327            ..PathCollection::default()
328        };
329        let items: Vec<_> = collection.items(&GraphicsContext::default()).collect();
330        assert_eq!(items[0].gc.linewidth, 2.0);
331        assert_eq!(items[1].gc.linewidth, 0.0);
332        assert_eq!(items[1].fill, None);
333    }
334
335    #[test]
336    fn agg_items_leave_extra_transforms_undrawn() {
337        let paths = [Path::unit_rectangle(), Path::unit_circle()];
338        let transforms = [
339            Affine2D::scaling(2.0, 2.0),
340            Affine2D::scaling(3.0, 3.0),
341            Affine2D::scaling(4.0, 4.0),
342        ];
343        let offsets = [Point::ORIGIN; 4];
344        let faces = [Rgba::BLACK];
345        let collection = PathCollection {
346            paths: &paths[..1],
347            path_transforms: &transforms,
348            facecolors: &faces,
349            ..PathCollection::default()
350        };
351        let gc = GraphicsContext::default();
352        assert_eq!(collection.items(&gc).count(), 3);
353        let agg: Vec<_> = collection.items_cycled(&gc, ItemCycle::Agg).collect();
354        assert_eq!(agg.len(), 1);
355        assert_eq!(agg[0].transform, transforms[0]);
356        // With more offsets than raw paths, Agg cycles the shapes and the
357        // transforms apart; the raw paths cycle together.
358        let collection = PathCollection {
359            paths: &paths,
360            offsets: &offsets,
361            ..collection
362        };
363        let shapes = |cycle| {
364            collection
365                .items_cycled(&gc, cycle)
366                .map(|item| (item.path.vertices().len(), item.transform))
367                .collect::<Vec<_>>()
368        };
369        let (rect, circle) = (paths[0].vertices().len(), paths[1].vertices().len());
370        assert_eq!(
371            shapes(ItemCycle::Agg),
372            [
373                (rect, transforms[0]),
374                (circle, transforms[1]),
375                (rect, transforms[2]),
376                (circle, transforms[0]),
377            ]
378        );
379        assert_eq!(shapes(ItemCycle::RawPaths)[3], (rect, transforms[0]));
380    }
381
382    #[test]
383    fn empty_collections_draw_nothing() {
384        let collection = PathCollection::default();
385        assert!(collection.is_empty());
386        assert_eq!(collection.items(&GraphicsContext::default()).count(), 0);
387        assert!(PathCollectionData::default().view().is_empty());
388    }
389
390    #[test]
391    fn owned_arguments_describe_the_same_collection() {
392        let data = PathCollectionData {
393            paths: vec![Path::unit_rectangle()],
394            offsets: vec![Point::new(1.0, 2.0), Point::new(3.0, 4.0)],
395            facecolors: vec![Rgba::BLACK],
396            ..PathCollectionData::default()
397        };
398        let items: Vec<_> = data.view().items(&GraphicsContext::default()).collect();
399        assert_eq!(items.len(), 2);
400        assert_eq!(items[1].offset, Point::new(3.0, 4.0));
401    }
402}