Skip to main content

ggplot_rs/render/
pixel_backend.rs

1//! A self-contained RGBA raster [`DrawBackend`] (feature `canvas`).
2//!
3//! Unlike the plotters bitmap backend it compiles to wasm and is tuned for
4//! large-N: it rasterises points/lines/polygons/text into an RGBA byte buffer in
5//! pure Rust (text via `ab_glyph` + the bundled font), so there's no per-mark
6//! DOM node and no wasm↔JS call per draw. Hand `into_rgba()` to a `<canvas>`
7//! (`putImageData`) in the browser, or `into_png()` a file natively.
8
9// The low-level rasterisers take (buf, w, h, coords…, colour, alpha) — plenty of
10// scalar arguments by nature.
11#![allow(clippy::too_many_arguments)]
12
13use ab_glyph::{point, Font, FontRef, PxScale, ScaleFont};
14
15use super::backend::{
16    DrawBackend, FillPattern, FontFace, LineStyle, PointStyle, RectStyle, TextAnchor, TextStyle,
17};
18use super::{Rect, RenderError};
19use std::borrow::Cow;
20
21const FONT: &[u8] = include_bytes!("../../assets/fonts/DejaVuSans.ttf");
22
23/// An in-memory RGBA canvas (row-major, 4 bytes/pixel, opaque white ground).
24pub struct PixelBackend {
25    width: usize,
26    height: usize,
27    buf: Vec<u8>,
28    plot_area: Rect,
29    total_area: Rect,
30    font: FontRef<'static>,
31    /// #273: panel-corner boxes claimed so far this render pass — see
32    /// [`DrawBackend::corner_claims`]/[`DrawBackend::claim_corner_box`].
33    corner_claims: Vec<Rect>,
34    /// #527: pixels per layout unit. The renderer lays out and draws in
35    /// layout units (`total_area`, `plot_area`, every coordinate and size);
36    /// the canvas has `k` times as many pixels each way, so text and lines
37    /// keep their size relative to the chart at any resolution.
38    k: f64,
39}
40
41/// A point, a list of points or a style in canvas pixels: `k` × layout units
42/// (borrowed unchanged when `k` is 1).
43fn sc_pt(k: f64, (x, y): (f64, f64)) -> (f64, f64) {
44    (x * k, y * k)
45}
46fn sc_pts(k: f64, pts: &[(f64, f64)]) -> Cow<'_, [(f64, f64)]> {
47    if k == 1.0 {
48        Cow::Borrowed(pts)
49    } else {
50        Cow::Owned(pts.iter().map(|&p| sc_pt(k, p)).collect())
51    }
52}
53fn sc_rings(k: f64, rings: &[Vec<(f64, f64)>]) -> Cow<'_, [Vec<(f64, f64)>]> {
54    if k == 1.0 {
55        Cow::Borrowed(rings)
56    } else {
57        Cow::Owned(rings.iter().map(|r| sc_pts(k, r).into_owned()).collect())
58    }
59}
60fn sc_line(k: f64, s: &LineStyle) -> Cow<'_, LineStyle> {
61    if k == 1.0 {
62        return Cow::Borrowed(s);
63    }
64    Cow::Owned(LineStyle {
65        width: s.width * k,
66        ..s.clone()
67    })
68}
69fn sc_rect(k: f64, s: &RectStyle) -> Cow<'_, RectStyle> {
70    if k == 1.0 {
71        return Cow::Borrowed(s);
72    }
73    Cow::Owned(RectStyle {
74        stroke_width: s.stroke_width * k,
75        corner_radius: s.corner_radius * k,
76        ..s.clone()
77    })
78}
79fn sc_text(k: f64, s: &TextStyle) -> Cow<'_, TextStyle> {
80    if k == 1.0 {
81        return Cow::Borrowed(s);
82    }
83    Cow::Owned(TextStyle {
84        size: s.size * k,
85        bg_r: s.bg_r * k,
86        ..s.clone()
87    })
88}
89fn sc_area(k: f64, r: &Rect) -> Rect {
90    Rect {
91        x: r.x * k,
92        y: r.y * k,
93        width: r.width * k,
94        height: r.height * k,
95    }
96}
97
98impl PixelBackend {
99    pub fn new(width: u32, height: u32, plot_area: Rect) -> Self {
100        let (w, h) = (width as usize, height as usize);
101        PixelBackend {
102            width: w,
103            height: h,
104            buf: vec![255; w * h * 4], // white, opaque
105            plot_area,
106            total_area: Rect {
107                x: 0.0,
108                y: 0.0,
109                width: width as f64,
110                height: height as f64,
111            },
112            font: FontRef::try_from_slice(FONT).expect("bundled font parses"),
113            corner_claims: Vec::new(),
114            k: 1.0,
115        }
116    }
117
118    /// #527: a canvas for a `width` × `height` layout (in layout units, e.g.
119    /// points) drawn `k` pixels per unit — `k` = dpi / 72 for a layout in
120    /// points. `plot_area` is in layout units too, as the renderer sees it.
121    pub fn with_scale(width: f64, height: f64, plot_area: Rect, k: f64) -> Self {
122        let k = if k.is_finite() && k > 0.0 { k } else { 1.0 };
123        let (pw, ph) = ((width * k).round().max(1.0), (height * k).round().max(1.0));
124        let mut b = PixelBackend::new(pw as u32, ph as u32, plot_area);
125        b.total_area = Rect {
126            x: 0.0,
127            y: 0.0,
128            width,
129            height,
130        };
131        b.k = k;
132        b
133    }
134
135    pub fn dimensions(&self) -> (u32, u32) {
136        (self.width as u32, self.height as u32)
137    }
138
139    /// The raw RGBA buffer (`width*height*4` bytes) for `ctx.putImageData`.
140    pub fn into_rgba(self) -> Vec<u8> {
141        self.buf
142    }
143
144    /// Encode the canvas to PNG bytes.
145    pub fn into_png(self) -> Result<Vec<u8>, RenderError> {
146        let img = image::RgbaImage::from_raw(self.width as u32, self.height as u32, self.buf)
147            .ok_or_else(|| RenderError::BackendError("buffer size mismatch".into()))?;
148        let mut out = std::io::Cursor::new(Vec::new());
149        img.write_to(&mut out, image::ImageOutputFormat::Png)
150            .map_err(|e| RenderError::BackendError(format!("{e:?}")))?;
151        Ok(out.into_inner())
152    }
153}
154
155/// Alpha-blend one pixel (source-over onto the opaque ground).
156fn blend(buf: &mut [u8], w: usize, h: usize, x: i32, y: i32, (r, g, b): (u8, u8, u8), a: f64) {
157    if x < 0 || y < 0 || x as usize >= w || y as usize >= h {
158        return;
159    }
160    let a = a.clamp(0.0, 1.0);
161    if a <= 0.0 {
162        return;
163    }
164    let i = (y as usize * w + x as usize) * 4;
165    let inv = 1.0 - a;
166    buf[i] = (r as f64 * a + buf[i] as f64 * inv).round() as u8;
167    buf[i + 1] = (g as f64 * a + buf[i + 1] as f64 * inv).round() as u8;
168    buf[i + 2] = (b as f64 * a + buf[i + 2] as f64 * inv).round() as u8;
169    buf[i + 3] = 255;
170}
171
172/// An anti-aliased filled disc — the hot path for scatter points.
173fn fill_circle(
174    buf: &mut [u8],
175    w: usize,
176    h: usize,
177    cx: f64,
178    cy: f64,
179    r: f64,
180    c: (u8, u8, u8),
181    a: f64,
182) {
183    let r = r.max(0.5);
184    let (x0, x1) = ((cx - r - 1.0).floor() as i32, (cx + r + 1.0).ceil() as i32);
185    let (y0, y1) = ((cy - r - 1.0).floor() as i32, (cy + r + 1.0).ceil() as i32);
186    for y in y0..=y1 {
187        for x in x0..=x1 {
188            let d = ((x as f64 + 0.5 - cx).powi(2) + (y as f64 + 0.5 - cy).powi(2)).sqrt();
189            let cov = (r - d + 0.5).clamp(0.0, 1.0); // 1px AA edge
190            if cov > 0.0 {
191                blend(buf, w, h, x, y, c, cov * a);
192            }
193        }
194    }
195}
196
197/// A thick segment, drawn by stamping small discs along it.
198#[allow(clippy::too_many_arguments)]
199fn segment(
200    buf: &mut [u8],
201    w: usize,
202    h: usize,
203    x0: f64,
204    y0: f64,
205    x1: f64,
206    y1: f64,
207    c: (u8, u8, u8),
208    width: f64,
209    a: f64,
210) {
211    let r = (width / 2.0).max(0.5);
212    let (dx, dy) = (x1 - x0, y1 - y0);
213    let len = (dx * dx + dy * dy).sqrt().max(1.0);
214    let steps = len.ceil() as i32;
215    for s in 0..=steps {
216        let t = s as f64 / steps as f64;
217        fill_circle(buf, w, h, x0 + dx * t, y0 + dy * t, r, c, a);
218    }
219}
220
221/// Even-odd scanline polygon fill, one ring.
222fn fill_polygon(buf: &mut [u8], w: usize, h: usize, pts: &[(f64, f64)], c: (u8, u8, u8), a: f64) {
223    fill_polygon_rings(buf, w, h, &[pts], c, a);
224}
225
226/// Even-odd scanline fill across every ring at once (`geom_sf`'s polygon
227/// holes, #178): every ring's edges are collected before sorting each
228/// scanline's crossings, so a hole ring's pair of crossings on a given row
229/// cancels the exterior's fill between them — the standard even-odd
230/// definition generalises directly from one ring to several.
231fn fill_polygon_rings(
232    buf: &mut [u8],
233    w: usize,
234    h: usize,
235    rings: &[&[(f64, f64)]],
236    c: (u8, u8, u8),
237    a: f64,
238) {
239    fill_polygon_rings_with(buf, w, h, rings, a, |_, _| c);
240}
241
242/// [`fill_polygon_rings`], but filled per pixel through `color_at(x, y)`
243/// instead of one flat colour — a scale's `na_pattern` (#206: "raster
244/// stripes"), via [`FillPattern::color_at`].
245fn fill_polygon_rings_pattern(
246    buf: &mut [u8],
247    w: usize,
248    h: usize,
249    rings: &[&[(f64, f64)]],
250    pattern: &FillPattern,
251    a: f64,
252) {
253    fill_polygon_rings_with(buf, w, h, rings, a, |x, y| pattern.color_at(x, y));
254}
255
256/// The even-odd scanline fill both [`fill_polygon_rings`] and
257/// [`fill_polygon_rings_pattern`] run, parameterised over how a pixel's
258/// colour is chosen.
259fn fill_polygon_rings_with(
260    buf: &mut [u8],
261    w: usize,
262    h: usize,
263    rings: &[&[(f64, f64)]],
264    a: f64,
265    color_at: impl Fn(f64, f64) -> (u8, u8, u8),
266) {
267    let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);
268    for ring in rings {
269        if ring.len() < 3 {
270            continue;
271        }
272        for p in ring.iter() {
273            y0 = y0.min(p.1);
274            y1 = y1.max(p.1);
275        }
276    }
277    if !(y0.is_finite() && y1.is_finite()) {
278        return;
279    }
280    let (y0, y1) = (y0.floor() as i32, y1.ceil() as i32);
281    for y in y0..=y1 {
282        let yc = y as f64 + 0.5;
283        let mut xs: Vec<f64> = Vec::new();
284        for ring in rings {
285            let n = ring.len();
286            if n < 3 {
287                continue;
288            }
289            for i in 0..n {
290                let (ax, ay) = ring[i];
291                let (bx, by) = ring[(i + 1) % n];
292                if (ay <= yc && by > yc) || (by <= yc && ay > yc) {
293                    xs.push(ax + (yc - ay) / (by - ay) * (bx - ax));
294                }
295            }
296        }
297        xs.sort_by(|p, q| p.total_cmp(q));
298        for span in xs.chunks(2) {
299            if let [xa, xb] = span {
300                for x in xa.round() as i32..=xb.round() as i32 {
301                    blend(buf, w, h, x, y, color_at(x as f64, yc), a);
302                }
303            }
304        }
305    }
306}
307
308impl DrawBackend for PixelBackend {
309    /// #325: nearest-neighbour blit, blended at `alpha` × the image's own.
310    fn draw_image(
311        &mut self,
312        bytes: &[u8],
313        rect: &Rect,
314        clip: &Rect,
315        alpha: f64,
316    ) -> Result<(), RenderError> {
317        let (rect, clip) = (&sc_area(self.k, rect), &sc_area(self.k, clip));
318        let Some(((x0, y0), img)) = crate::render::raster::decode_visible(
319            bytes,
320            rect,
321            clip,
322            self.width as u32,
323            self.height as u32,
324        ) else {
325            return Ok(());
326        };
327        for (dx, dy, p) in img.enumerate_pixels() {
328            let [r, g, b, a] = p.0;
329            blend(
330                &mut self.buf,
331                self.width,
332                self.height,
333                x0 + dx as i32,
334                y0 + dy as i32,
335                (r, g, b),
336                alpha * a as f64 / 255.0,
337            );
338        }
339        Ok(())
340    }
341
342    fn plot_area(&self) -> Rect {
343        self.plot_area.clone()
344    }
345    fn total_area(&self) -> Rect {
346        self.total_area.clone()
347    }
348
349    fn corner_claims(&self) -> Vec<Rect> {
350        self.corner_claims.clone()
351    }
352    fn claim_corner_box(&mut self, rect: Rect) {
353        self.corner_claims.push(rect);
354    }
355    fn clear_corner_claims(&mut self) {
356        self.corner_claims.clear();
357    }
358
359    fn draw_circle(
360        &mut self,
361        (cx, cy): (f64, f64),
362        radius: f64,
363        style: &PointStyle,
364    ) -> Result<(), RenderError> {
365        let (cx, cy, radius) = (cx * self.k, cy * self.k, radius * self.k);
366        fill_circle(
367            &mut self.buf,
368            self.width,
369            self.height,
370            cx,
371            cy,
372            radius,
373            style.color,
374            style.alpha,
375        );
376        Ok(())
377    }
378
379    fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
380        let (pts, style) = (sc_pts(self.k, pts), sc_line(self.k, style));
381        for w in pts.windows(2) {
382            segment(
383                &mut self.buf,
384                self.width,
385                self.height,
386                w[0].0,
387                w[0].1,
388                w[1].0,
389                w[1].1,
390                style.color,
391                style.width,
392                style.alpha,
393            );
394        }
395        Ok(())
396    }
397
398    fn draw_rect(
399        &mut self,
400        (x0, y0): (f64, f64),
401        (x1, y1): (f64, f64),
402        style: &RectStyle,
403    ) -> Result<(), RenderError> {
404        let ((x0, y0), (x1, y1)) = (sc_pt(self.k, (x0, y0)), sc_pt(self.k, (x1, y1)));
405        let style = sc_rect(self.k, style);
406        let style: &RectStyle = &style;
407        // No native rounded-rect primitive here: approximate as a polygon
408        // (a plain rectangle when corner_radius is 0, same as before).
409        let r = if style.corner_radius > 0.0 {
410            super::backend::rounded_rect_points(x0, y0, x1, y1, style.corner_radius)
411        } else {
412            vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
413        };
414        if let Some(fill) = style.fill {
415            fill_polygon(
416                &mut self.buf,
417                self.width,
418                self.height,
419                &r,
420                fill,
421                style.alpha,
422            );
423        }
424        if let Some(stroke) = style.stroke {
425            let n = r.len();
426            for i in 0..n {
427                let (a, b) = (r[i], r[(i + 1) % n]);
428                segment(
429                    &mut self.buf,
430                    self.width,
431                    self.height,
432                    a.0,
433                    a.1,
434                    b.0,
435                    b.1,
436                    stroke,
437                    style.stroke_width,
438                    style.alpha,
439                );
440            }
441        }
442        Ok(())
443    }
444
445    fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
446        let pts = sc_pts(self.k, pts);
447        let pts: &[(f64, f64)] = &pts;
448        let style = sc_rect(self.k, style);
449        let style: &RectStyle = &style;
450        if let Some(fill) = style.fill {
451            fill_polygon(
452                &mut self.buf,
453                self.width,
454                self.height,
455                pts,
456                fill,
457                style.alpha,
458            );
459        }
460        if let Some(stroke) = style.stroke {
461            for w in pts.windows(2) {
462                segment(
463                    &mut self.buf,
464                    self.width,
465                    self.height,
466                    w[0].0,
467                    w[0].1,
468                    w[1].0,
469                    w[1].1,
470                    stroke,
471                    style.stroke_width,
472                    style.alpha,
473                );
474            }
475            if let (Some(first), Some(last)) = (pts.first(), pts.last()) {
476                segment(
477                    &mut self.buf,
478                    self.width,
479                    self.height,
480                    last.0,
481                    last.1,
482                    first.0,
483                    first.1,
484                    stroke,
485                    style.stroke_width,
486                    style.alpha,
487                );
488            }
489        }
490        Ok(())
491    }
492
493    fn draw_polygon_rings(
494        &mut self,
495        rings: &[Vec<(f64, f64)>],
496        style: &RectStyle,
497    ) -> Result<(), RenderError> {
498        let rings = sc_rings(self.k, rings);
499        let rings: &[Vec<(f64, f64)>] = &rings;
500        let style = sc_rect(self.k, style);
501        let style: &RectStyle = &style;
502        if let Some(fill) = style.fill {
503            let ring_refs: Vec<&[(f64, f64)]> = rings.iter().map(Vec::as_slice).collect();
504            fill_polygon_rings(
505                &mut self.buf,
506                self.width,
507                self.height,
508                &ring_refs,
509                fill,
510                style.alpha,
511            );
512        }
513        if let Some(stroke) = style.stroke {
514            for ring in rings {
515                if ring.len() < 2 {
516                    continue;
517                }
518                for w in ring.windows(2) {
519                    segment(
520                        &mut self.buf,
521                        self.width,
522                        self.height,
523                        w[0].0,
524                        w[0].1,
525                        w[1].0,
526                        w[1].1,
527                        stroke,
528                        style.stroke_width,
529                        style.alpha,
530                    );
531                }
532                if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
533                    segment(
534                        &mut self.buf,
535                        self.width,
536                        self.height,
537                        last.0,
538                        last.1,
539                        first.0,
540                        first.1,
541                        stroke,
542                        style.stroke_width,
543                        style.alpha,
544                    );
545                }
546            }
547        }
548        Ok(())
549    }
550
551    /// #206: like [`draw_rect`](Self::draw_rect), but rasterises
552    /// `pattern`'s actual stripes per pixel ("raster stripes") instead of
553    /// a flat `style.fill`.
554    fn draw_rect_pattern(
555        &mut self,
556        (x0, y0): (f64, f64),
557        (x1, y1): (f64, f64),
558        pattern: &FillPattern,
559        style: &RectStyle,
560    ) -> Result<(), RenderError> {
561        let ((x0, y0), (x1, y1)) = (sc_pt(self.k, (x0, y0)), sc_pt(self.k, (x1, y1)));
562        let style = sc_rect(self.k, style);
563        let style: &RectStyle = &style;
564        let r = if style.corner_radius > 0.0 {
565            super::backend::rounded_rect_points(x0, y0, x1, y1, style.corner_radius)
566        } else {
567            vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
568        };
569        fill_polygon_rings_pattern(
570            &mut self.buf,
571            self.width,
572            self.height,
573            &[&r],
574            pattern,
575            style.alpha,
576        );
577        if let Some(stroke) = style.stroke {
578            let n = r.len();
579            for i in 0..n {
580                let (a, b) = (r[i], r[(i + 1) % n]);
581                segment(
582                    &mut self.buf,
583                    self.width,
584                    self.height,
585                    a.0,
586                    a.1,
587                    b.0,
588                    b.1,
589                    stroke,
590                    style.stroke_width,
591                    style.alpha,
592                );
593            }
594        }
595        Ok(())
596    }
597
598    /// #206: like [`draw_polygon`](Self::draw_polygon), rasterised
599    /// per-pixel — see [`draw_rect_pattern`](Self::draw_rect_pattern).
600    fn draw_polygon_pattern(
601        &mut self,
602        pts: &[(f64, f64)],
603        pattern: &FillPattern,
604        style: &RectStyle,
605    ) -> Result<(), RenderError> {
606        let pts = sc_pts(self.k, pts);
607        let pts: &[(f64, f64)] = &pts;
608        let style = sc_rect(self.k, style);
609        let style: &RectStyle = &style;
610        fill_polygon_rings_pattern(
611            &mut self.buf,
612            self.width,
613            self.height,
614            &[pts],
615            pattern,
616            style.alpha,
617        );
618        if let Some(stroke) = style.stroke {
619            for w in pts.windows(2) {
620                segment(
621                    &mut self.buf,
622                    self.width,
623                    self.height,
624                    w[0].0,
625                    w[0].1,
626                    w[1].0,
627                    w[1].1,
628                    stroke,
629                    style.stroke_width,
630                    style.alpha,
631                );
632            }
633            if let (Some(first), Some(last)) = (pts.first(), pts.last()) {
634                segment(
635                    &mut self.buf,
636                    self.width,
637                    self.height,
638                    last.0,
639                    last.1,
640                    first.0,
641                    first.1,
642                    stroke,
643                    style.stroke_width,
644                    style.alpha,
645                );
646            }
647        }
648        Ok(())
649    }
650
651    /// #206: like [`draw_polygon_rings`](Self::draw_polygon_rings) —
652    /// holes still cut out under the same even-odd rule — rasterised
653    /// per-pixel instead of flat-filled; see
654    /// [`draw_rect_pattern`](Self::draw_rect_pattern).
655    fn draw_polygon_rings_pattern(
656        &mut self,
657        rings: &[Vec<(f64, f64)>],
658        pattern: &FillPattern,
659        style: &RectStyle,
660    ) -> Result<(), RenderError> {
661        let rings = sc_rings(self.k, rings);
662        let rings: &[Vec<(f64, f64)>] = &rings;
663        let style = sc_rect(self.k, style);
664        let style: &RectStyle = &style;
665        let ring_refs: Vec<&[(f64, f64)]> = rings.iter().map(Vec::as_slice).collect();
666        fill_polygon_rings_pattern(
667            &mut self.buf,
668            self.width,
669            self.height,
670            &ring_refs,
671            pattern,
672            style.alpha,
673        );
674        if let Some(stroke) = style.stroke {
675            for ring in rings {
676                if ring.len() < 2 {
677                    continue;
678                }
679                for w in ring.windows(2) {
680                    segment(
681                        &mut self.buf,
682                        self.width,
683                        self.height,
684                        w[0].0,
685                        w[0].1,
686                        w[1].0,
687                        w[1].1,
688                        stroke,
689                        style.stroke_width,
690                        style.alpha,
691                    );
692                }
693                if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
694                    segment(
695                        &mut self.buf,
696                        self.width,
697                        self.height,
698                        last.0,
699                        last.1,
700                        first.0,
701                        first.1,
702                        stroke,
703                        style.stroke_width,
704                        style.alpha,
705                    );
706                }
707            }
708        }
709        Ok(())
710    }
711
712    fn draw_text(
713        &mut self,
714        text: &str,
715        (x, y): (f64, f64),
716        style: &TextStyle,
717    ) -> Result<(), RenderError> {
718        let (x, y) = sc_pt(self.k, (x, y));
719        let style = sc_text(self.k, style);
720        let style: &TextStyle = &style;
721        let scale = PxScale::from(style.size as f32);
722        let font = &self.font;
723        let scaled = font.as_scaled(scale);
724        let width: f32 = text
725            .chars()
726            .map(|c| scaled.h_advance(font.glyph_id(c)))
727            .sum();
728        let start_x = match style.anchor {
729            TextAnchor::Start => x,
730            TextAnchor::Middle => x - width as f64 / 2.0,
731            TextAnchor::End => x - width as f64,
732        };
733        // Approximate the SVG "middle" baseline; bold faked by a bump in coverage.
734        let baseline = (y + style.size * 0.35) as f32;
735        let bold = style.face == FontFace::Bold;
736        let (bw, bh) = (self.width, self.height);
737
738        // #229: a text halo — no native stroke-text in this backend, so
739        // approximate the SVG `stroke`/`paint-order="stroke"` outline by
740        // drawing the same glyphs in `bg_colour` at 8 offsets around the
741        // radius before the normal pass, which then paints over the
742        // middle. `bg_colour: None` (the default) skips this entirely, so
743        // existing output is unchanged.
744        if let Some(bg) = style.bg_colour {
745            let r = if style.bg_r.is_finite() {
746                style.bg_r
747            } else {
748                0.0
749            } as f32;
750            if r > 0.0 {
751                for i in 0..8 {
752                    let theta = i as f32 * std::f32::consts::FRAC_PI_4;
753                    let (dx, dy) = (r * theta.cos(), r * theta.sin());
754                    draw_glyph_pass(
755                        &mut self.buf,
756                        bw,
757                        bh,
758                        font,
759                        scale,
760                        start_x as f32 + dx,
761                        baseline + dy,
762                        bg,
763                        bold,
764                        text,
765                    );
766                }
767            }
768        }
769
770        draw_glyph_pass(
771            &mut self.buf,
772            bw,
773            bh,
774            font,
775            scale,
776            start_x as f32,
777            baseline,
778            style.color,
779            bold,
780            text,
781        );
782        Ok(())
783    }
784}
785
786/// One pass of `text`'s glyphs in `color`, starting at `(start_x,
787/// baseline)` — factored out of [`PixelBackend::draw_text`] so #229's halo
788/// can run it several times (once per offset, in `bg_colour`) before the
789/// normal pass.
790#[allow(clippy::too_many_arguments)]
791fn draw_glyph_pass(
792    buf: &mut [u8],
793    bw: usize,
794    bh: usize,
795    font: &FontRef<'static>,
796    scale: PxScale,
797    start_x: f32,
798    baseline: f32,
799    color: (u8, u8, u8),
800    bold: bool,
801    text: &str,
802) {
803    let scaled = font.as_scaled(scale);
804    let mut pen = start_x;
805    for ch in text.chars() {
806        let gid = font.glyph_id(ch);
807        let glyph = gid.with_scale_and_position(scale, point(pen, baseline));
808        if let Some(outlined) = font.outline_glyph(glyph) {
809            let bounds = outlined.px_bounds();
810            outlined.draw(|gx, gy, cov| {
811                let a = if bold {
812                    (cov as f64 * 1.4).min(1.0)
813                } else {
814                    cov as f64
815                };
816                blend(
817                    buf,
818                    bw,
819                    bh,
820                    bounds.min.x as i32 + gx as i32,
821                    bounds.min.y as i32 + gy as i32,
822                    color,
823                    a,
824                );
825            });
826        }
827        pen += scaled.h_advance(gid);
828    }
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834
835    fn pixel(buf: &[u8], w: usize, x: i32, y: i32) -> (u8, u8, u8) {
836        let i = (y as usize * w + x as usize) * 4;
837        (buf[i], buf[i + 1], buf[i + 2])
838    }
839
840    /// A ring after the other is a hole cut out of the fill under the
841    /// even-odd rule (`geom_sf`'s `Polygon`, #178) — a 20×20 square with a
842    /// 6×6 hole in the middle leaves the hole's centre at the white ground,
843    /// while a point between the hole and the exterior edge is filled.
844    #[test]
845    fn fill_polygon_rings_cuts_out_a_hole() {
846        let (w, h) = (20usize, 20usize);
847        let mut buf = vec![255u8; w * h * 4];
848        let exterior: Vec<(f64, f64)> = vec![(1.0, 1.0), (19.0, 1.0), (19.0, 19.0), (1.0, 19.0)];
849        let hole: Vec<(f64, f64)> = vec![(7.0, 7.0), (13.0, 7.0), (13.0, 13.0), (7.0, 13.0)];
850        fill_polygon_rings(&mut buf, w, h, &[&exterior, &hole], (200, 50, 50), 1.0);
851        assert_eq!(pixel(&buf, w, 10, 10), (255, 255, 255), "hole stays blank");
852        assert_eq!(
853            pixel(&buf, w, 3, 3),
854            (200, 50, 50),
855            "ring between is filled"
856        );
857        // Without the hole ring, the same point would be filled — proving
858        // it's the second ring that cuts it, not some other effect.
859        let mut filled = vec![255u8; w * h * 4];
860        fill_polygon_rings(&mut filled, w, h, &[&exterior], (200, 50, 50), 1.0);
861        assert_eq!(pixel(&filled, w, 10, 10), (200, 50, 50));
862    }
863
864    /// Two disjoint rings (a multipolygon's two parts, drawn in one call)
865    /// each fill independently.
866    #[test]
867    fn fill_polygon_rings_handles_disjoint_rings() {
868        let (w, h) = (20usize, 20usize);
869        let mut buf = vec![255u8; w * h * 4];
870        let a: Vec<(f64, f64)> = vec![(1.0, 1.0), (5.0, 1.0), (5.0, 5.0), (1.0, 5.0)];
871        let b: Vec<(f64, f64)> = vec![(14.0, 14.0), (18.0, 14.0), (18.0, 18.0), (14.0, 18.0)];
872        fill_polygon_rings(&mut buf, w, h, &[&a, &b], (10, 20, 30), 1.0);
873        assert_eq!(pixel(&buf, w, 3, 3), (10, 20, 30));
874        assert_eq!(pixel(&buf, w, 16, 16), (10, 20, 30));
875        assert_eq!(
876            pixel(&buf, w, 10, 10),
877            (255, 255, 255),
878            "gap between stays blank"
879        );
880    }
881
882    /// The `DrawBackend::draw_polygon_rings` trait method itself (not just
883    /// the free `fill_polygon_rings` the unit tests above call directly):
884    /// fills with a real hole cut-out *and* strokes every ring, through
885    /// dynamic dispatch (`&mut dyn DrawBackend`), the way `geom_sf` calls
886    /// it.
887    #[test]
888    fn draw_polygon_rings_trait_method_fills_and_strokes_every_ring() {
889        let pa = Rect {
890            x: 0.0,
891            y: 0.0,
892            width: 20.0,
893            height: 20.0,
894        };
895        let mut backend = PixelBackend::new(20, 20, pa);
896        let dyn_backend: &mut dyn DrawBackend = &mut backend;
897        let exterior = vec![(1.0, 1.0), (19.0, 1.0), (19.0, 19.0), (1.0, 19.0)];
898        let hole = vec![(7.0, 7.0), (13.0, 7.0), (13.0, 13.0), (7.0, 13.0)];
899        dyn_backend
900            .draw_polygon_rings(
901                &[exterior, hole],
902                &RectStyle {
903                    fill: Some((200, 50, 50)),
904                    stroke: Some((0, 0, 0)),
905                    stroke_width: 1.0,
906                    alpha: 1.0,
907                    clip: true,
908                    corner_radius: 0.0,
909                },
910            )
911            .unwrap();
912        let buf = backend.into_rgba();
913        assert_eq!(pixel(&buf, 20, 10, 10), (255, 255, 255), "hole stays blank");
914        assert_eq!(
915            pixel(&buf, 20, 3, 3),
916            (200, 50, 50),
917            "ring between is filled"
918        );
919        // The hole's own outline should be stroked (near-black somewhere
920        // along it), distinguishing this from a plain single-ring fill.
921        let near_hole_edge = pixel(&buf, 20, 7, 10);
922        assert_ne!(near_hole_edge, (255, 255, 255), "hole outline is stroked");
923    }
924
925    /// A ring with fewer than 2 points is skipped by the stroke loop
926    /// (rather than panicking on `windows(2)`/`first()`/`last()`), while a
927    /// valid sibling ring still strokes normally.
928    #[test]
929    fn draw_polygon_rings_skips_a_degenerate_ring_when_stroking() {
930        let pa = Rect {
931            x: 0.0,
932            y: 0.0,
933            width: 20.0,
934            height: 20.0,
935        };
936        let mut backend = PixelBackend::new(20, 20, pa);
937        let dyn_backend: &mut dyn DrawBackend = &mut backend;
938        let degenerate: Vec<(f64, f64)> = vec![(5.0, 5.0)];
939        let real = vec![(1.0, 1.0), (10.0, 1.0), (10.0, 10.0), (1.0, 10.0)];
940        dyn_backend
941            .draw_polygon_rings(
942                &[degenerate, real],
943                &RectStyle {
944                    fill: None,
945                    stroke: Some((0, 0, 0)),
946                    stroke_width: 1.0,
947                    alpha: 1.0,
948                    clip: true,
949                    corner_radius: 0.0,
950                },
951            )
952            .unwrap();
953        // No panic is the main assertion; the real ring's top edge should
954        // still be stroked.
955        let buf = backend.into_rgba();
956        assert_ne!(pixel(&buf, 20, 5, 1), (255, 255, 255));
957    }
958
959    // #206: pattern fills ("raster stripes" on this backend).
960
961    /// #527: at scale 2 every primitive lands at twice its coordinates, its
962    /// sizes doubled; the areas stay in layout units.
963    #[test]
964    fn a_scaled_canvas_draws_every_primitive_at_k_times() {
965        let area = Rect {
966            x: 0.0,
967            y: 0.0,
968            width: 50.0,
969            height: 50.0,
970        };
971        let mut b = PixelBackend::with_scale(50.0, 50.0, area.clone(), 2.0);
972        assert_eq!(b.dimensions(), (100, 100));
973        assert_eq!((b.total_area().width, b.plot_area().width), (50.0, 50.0));
974        let fill = |c| RectStyle {
975            fill: Some(c),
976            stroke: None,
977            ..RectStyle::default()
978        };
979        let red = (200, 0, 0);
980        // a rect at layout (5,5)-(10,10): pixels 10..20
981        b.draw_rect((5.0, 5.0), (10.0, 10.0), &fill(red)).unwrap();
982        // a polygon and rings at layout x 20..25
983        b.draw_polygon(
984            &[(20.0, 5.0), (25.0, 5.0), (25.0, 10.0), (20.0, 10.0)],
985            &fill(red),
986        )
987        .unwrap();
988        b.draw_polygon_rings(
989            &[vec![(30.0, 5.0), (35.0, 5.0), (35.0, 10.0), (30.0, 10.0)]],
990            &fill(red),
991        )
992        .unwrap();
993        // patterns
994        b.draw_rect_pattern((5.0, 20.0), (10.0, 25.0), &stripe(), &fill(red))
995            .unwrap();
996        b.draw_polygon_pattern(
997            &[(20.0, 20.0), (25.0, 20.0), (25.0, 25.0), (20.0, 25.0)],
998            &stripe(),
999            &fill(red),
1000        )
1001        .unwrap();
1002        b.draw_polygon_rings_pattern(
1003            &[vec![(30.0, 20.0), (35.0, 20.0), (35.0, 25.0), (30.0, 25.0)]],
1004            &stripe(),
1005            &fill(red),
1006        )
1007        .unwrap();
1008        // a circle of radius 2 at (45, 7): 4 px from the centre at (90, 14)
1009        b.draw_circle(
1010            (45.0, 7.0),
1011            2.0,
1012            &PointStyle {
1013                color: red,
1014                ..PointStyle::default()
1015            },
1016        )
1017        .unwrap();
1018        // a 1-unit line: 2 px wide
1019        b.draw_line(
1020            &[(5.0, 40.0), (45.0, 40.0)],
1021            &LineStyle {
1022                color: red,
1023                width: 1.0,
1024                ..LineStyle::default()
1025            },
1026        )
1027        .unwrap();
1028        // text: drawn, at twice the size
1029        b.draw_text(
1030            "W",
1031            (40.0, 30.0),
1032            &TextStyle {
1033                color: red,
1034                size: 8.0,
1035                ..TextStyle::default()
1036            },
1037        )
1038        .unwrap();
1039        let w = b.width;
1040        let buf = b.into_rgba();
1041        let at = |x, y| pixel(&buf, w, x, y);
1042        for (x, y) in [(15, 15), (45, 15), (65, 15), (90, 14), (50, 79), (50, 80)] {
1043            assert_ne!(at(x, y), (255, 255, 255), "({x}, {y}) should be drawn");
1044        }
1045        for (x, y) in [(7, 7), (22, 15), (95, 14), (50, 84)] {
1046            assert_eq!(at(x, y), (255, 255, 255), "({x}, {y}) should stay blank");
1047        }
1048        // the patterns filled their doubled areas (both colours inside)
1049        for x0 in [10, 40, 60] {
1050            let row: Vec<_> = (x0..x0 + 10).map(|x| at(x, 45)).collect();
1051            assert!(row.iter().all(|p| *p != (255, 255, 255)), "pattern at {x0}");
1052        }
1053        let ink = (70..100)
1054            .flat_map(|x| (50..75).map(move |y| (x, y)))
1055            .filter(|&(x, y)| at(x, y) != (255, 255, 255))
1056            .count();
1057        assert!(ink > 20, "the text drew ({ink} px)");
1058    }
1059
1060    fn stripe() -> FillPattern {
1061        FillPattern::Stripe {
1062            fg: (10, 20, 30),
1063            bg: (200, 210, 220),
1064            size_px: 4.0,
1065            angle_deg: 0.0, // horizontal rotation -> vertical stripes along x
1066        }
1067    }
1068
1069    #[test]
1070    fn a_pattern_fill_rasterises_both_colours_not_a_flat_one() {
1071        let pa = Rect {
1072            x: 0.0,
1073            y: 0.0,
1074            width: 20.0,
1075            height: 20.0,
1076        };
1077        let mut backend = PixelBackend::new(20, 20, pa);
1078        let dyn_backend: &mut dyn DrawBackend = &mut backend;
1079        let square = vec![(0.0, 0.0), (20.0, 0.0), (20.0, 20.0), (0.0, 20.0)];
1080        dyn_backend
1081            .draw_polygon_pattern(&square, &stripe(), &RectStyle::default())
1082            .unwrap();
1083        let buf = backend.into_rgba();
1084        let pixels: std::collections::HashSet<(u8, u8, u8)> =
1085            (0..20).map(|x| pixel(&buf, 20, x, 10)).collect();
1086        assert!(pixels.contains(&(10, 20, 30)), "{pixels:?}");
1087        assert!(pixels.contains(&(200, 210, 220)), "{pixels:?}");
1088    }
1089
1090    #[test]
1091    fn pattern_fill_still_cuts_out_a_hole() {
1092        let (w, h) = (20usize, 20usize);
1093        let mut buf = vec![255u8; w * h * 4];
1094        let exterior: Vec<(f64, f64)> = vec![(1.0, 1.0), (19.0, 1.0), (19.0, 19.0), (1.0, 19.0)];
1095        let hole: Vec<(f64, f64)> = vec![(7.0, 7.0), (13.0, 7.0), (13.0, 13.0), (7.0, 13.0)];
1096        fill_polygon_rings_pattern(&mut buf, w, h, &[&exterior, &hole], &stripe(), 1.0);
1097        assert_eq!(pixel(&buf, w, 10, 10), (255, 255, 255), "hole stays blank");
1098    }
1099
1100    #[test]
1101    fn draw_rect_pattern_also_strokes_normally() {
1102        let pa = Rect {
1103            x: 0.0,
1104            y: 0.0,
1105            width: 20.0,
1106            height: 20.0,
1107        };
1108        let mut backend = PixelBackend::new(20, 20, pa);
1109        let dyn_backend: &mut dyn DrawBackend = &mut backend;
1110        dyn_backend
1111            .draw_rect_pattern(
1112                (2.0, 2.0),
1113                (18.0, 18.0),
1114                &stripe(),
1115                &RectStyle {
1116                    fill: None,
1117                    stroke: Some((0, 0, 0)),
1118                    stroke_width: 1.0,
1119                    alpha: 1.0,
1120                    clip: true,
1121                    corner_radius: 0.0,
1122                },
1123            )
1124            .unwrap();
1125        let buf = backend.into_rgba();
1126        assert_ne!(pixel(&buf, 20, 2, 10), (255, 255, 255), "left edge stroked");
1127    }
1128
1129    #[test]
1130    fn draw_rect_pattern_still_rounds_its_corners() {
1131        let pa = Rect {
1132            x: 0.0,
1133            y: 0.0,
1134            width: 20.0,
1135            height: 20.0,
1136        };
1137        let mut backend = PixelBackend::new(20, 20, pa);
1138        let dyn_backend: &mut dyn DrawBackend = &mut backend;
1139        dyn_backend
1140            .draw_rect_pattern(
1141                (0.0, 0.0),
1142                (20.0, 20.0),
1143                &stripe(),
1144                &RectStyle {
1145                    fill: None,
1146                    stroke: None,
1147                    stroke_width: 0.0,
1148                    alpha: 1.0,
1149                    clip: true,
1150                    corner_radius: 8.0,
1151                },
1152            )
1153            .unwrap();
1154        let buf = backend.into_rgba();
1155        // A true corner is cut off by the rounding; the centre is well
1156        // inside and always filled regardless of the radius.
1157        assert_eq!(
1158            pixel(&buf, 20, 0, 0),
1159            (255, 255, 255),
1160            "corner rounded away"
1161        );
1162        assert_ne!(
1163            pixel(&buf, 20, 10, 10),
1164            (255, 255, 255),
1165            "centre still filled"
1166        );
1167    }
1168}