Skip to main content

plotine_backend_skia/
lib.rs

1//! Raster backend powered by tiny-skia + plotine-text.
2
3use std::fs::File;
4use std::io::BufWriter;
5use std::path::Path;
6
7use kurbo::{BezPath, PathEl};
8use plotine_core::{Color, PlotError, Point, Rect, Result};
9use plotine_render::{
10    FillStyle, LineCap, LineJoin, Renderer, StrokeStyle, TextAlign, TextBaseline, TextStyle,
11};
12use plotine_text::TextEngine;
13use tiny_skia::{
14    FillRule, FilterQuality, LineCap as SkiaCap, LineJoin as SkiaJoin, Mask, Paint,
15    Path as SkiaPath, PathBuilder, Pixmap, PixmapPaint, PremultipliedColorU8, Stroke, StrokeDash,
16    Transform,
17};
18
19/// In-memory RGBA pixmap renderer.
20pub struct SkiaRenderer {
21    pixmap: Pixmap,
22    text: TextEngine,
23    clip_stack: Vec<Option<Mask>>,
24}
25
26impl SkiaRenderer {
27    pub fn new(width: u32, height: u32) -> Result<Self> {
28        let pixmap = Pixmap::new(width.max(1), height.max(1)).ok_or_else(|| {
29            PlotError::render(format!("failed to allocate pixmap {width}x{height}"))
30        })?;
31        Ok(Self {
32            pixmap,
33            text: TextEngine::new(),
34            clip_stack: Vec::new(),
35        })
36    }
37
38    pub fn pixmap(&self) -> &Pixmap {
39        &self.pixmap
40    }
41
42    pub fn into_pixmap(self) -> Pixmap {
43        self.pixmap
44    }
45
46    pub fn encode_png(&self) -> Result<Vec<u8>> {
47        let rgba = self.pixmap.data();
48        let width = self.pixmap.width();
49        let height = self.pixmap.height();
50
51        // Drop the alpha channel when every pixel is opaque — typical for
52        // publication figures and much closer to matplotlib's PNG sizes.
53        let fully_opaque = rgba.chunks_exact(4).all(|px| px[3] == 255);
54        let (color, payload) = if fully_opaque {
55            let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
56            for px in rgba.chunks_exact(4) {
57                rgb.extend_from_slice(&px[..3]);
58            }
59            (png::ColorType::Rgb, rgb)
60        } else {
61            (png::ColorType::Rgba, rgba.to_vec())
62        };
63
64        let mut bytes = Vec::new();
65        {
66            let mut cursor = std::io::Cursor::new(&mut bytes);
67            let mut encoder = png::Encoder::new(&mut cursor, width, height);
68            encoder.set_color(color);
69            encoder.set_depth(png::BitDepth::Eight);
70            // Deterministic and competitive with matplotlib/Pillow zlib defaults.
71            encoder.set_compression(png::Compression::Best);
72            encoder.set_filter(png::FilterType::Paeth);
73            encoder.set_adaptive_filter(png::AdaptiveFilterType::Adaptive);
74            let mut writer = encoder
75                .write_header()
76                .map_err(|e| PlotError::io(e.to_string()))?;
77            writer
78                .write_image_data(&payload)
79                .map_err(|e| PlotError::io(e.to_string()))?;
80        }
81        Ok(bytes)
82    }
83
84    pub fn save_png(&self, path: impl AsRef<Path>) -> Result<()> {
85        let path = path.as_ref();
86        if let Some(parent) = path.parent() {
87            if !parent.as_os_str().is_empty() {
88                std::fs::create_dir_all(parent).map_err(|e| PlotError::io(e.to_string()))?;
89            }
90        }
91        let bytes = self.encode_png()?;
92        let file = File::create(path).map_err(|e| PlotError::io(e.to_string()))?;
93        let mut writer = BufWriter::new(file);
94        use std::io::Write;
95        writer
96            .write_all(&bytes)
97            .map_err(|e| PlotError::io(e.to_string()))?;
98        Ok(())
99    }
100
101    fn paint_from(color: Color, anti_alias: bool) -> Paint<'static> {
102        let mut paint = Paint::default();
103        paint.set_color_rgba8(color.r, color.g, color.b, color.a);
104        paint.anti_alias = anti_alias;
105        paint
106    }
107
108    fn to_skia_path(path: &BezPath) -> Result<SkiaPath> {
109        let mut pb = PathBuilder::new();
110        for el in path.elements() {
111            match el {
112                PathEl::MoveTo(p) => pb.move_to(p.x as f32, p.y as f32),
113                PathEl::LineTo(p) => pb.line_to(p.x as f32, p.y as f32),
114                PathEl::QuadTo(p1, p2) => {
115                    pb.quad_to(p1.x as f32, p1.y as f32, p2.x as f32, p2.y as f32)
116                }
117                PathEl::CurveTo(p1, p2, p3) => pb.cubic_to(
118                    p1.x as f32,
119                    p1.y as f32,
120                    p2.x as f32,
121                    p2.y as f32,
122                    p3.x as f32,
123                    p3.y as f32,
124                ),
125                PathEl::ClosePath => pb.close(),
126            }
127        }
128        pb.finish()
129            .ok_or_else(|| PlotError::render("failed to build skia path"))
130    }
131
132    fn stroke_from(style: &StrokeStyle) -> Stroke {
133        let dash = style.dash.as_ref().and_then(|pattern| {
134            let arr: Vec<f32> = pattern.iter().map(|v| *v as f32).collect();
135            StrokeDash::new(arr, 0.0)
136        });
137        Stroke {
138            width: style.width as f32,
139            miter_limit: 4.0,
140            line_cap: match style.cap {
141                LineCap::Butt => SkiaCap::Butt,
142                LineCap::Round => SkiaCap::Round,
143                LineCap::Square => SkiaCap::Square,
144            },
145            line_join: match style.join {
146                LineJoin::Miter => SkiaJoin::Miter,
147                LineJoin::Round => SkiaJoin::Round,
148                LineJoin::Bevel => SkiaJoin::Bevel,
149            },
150            dash,
151        }
152    }
153
154    fn blit_glyph(&mut self, glyph: &plotine_text::GlyphImage, color: Color, bold: bool) {
155        use plotine_text::GlyphContent;
156        let w = glyph.width as i32;
157        let h = glyph.height as i32;
158        let pm_w = self.pixmap.width() as i32;
159        let pm_h = self.pixmap.height() as i32;
160        let data = self.pixmap.data_mut();
161
162        for gy in 0..h {
163            for gx in 0..w {
164                let px = glyph.x + gx;
165                let py = glyph.y + gy;
166                if px < 0 || py < 0 || px >= pm_w || py >= pm_h {
167                    continue;
168                }
169                let idx = (gy as u32 * glyph.width + gx as u32) as usize;
170                let coverage = match glyph.content {
171                    GlyphContent::Mask => glyph.data[idx] as f32 / 255.0,
172                    // Average RGB coverage (do not drop G/B — that softens stems).
173                    GlyphContent::SubpixelMask => {
174                        let i = idx * 3;
175                        let r = glyph.data[i] as f32;
176                        let g = glyph.data[i + 1] as f32;
177                        let b = glyph.data[i + 2] as f32;
178                        (r + g + b) / (3.0 * 255.0)
179                    }
180                    GlyphContent::Color => glyph.data[idx * 4 + 3] as f32 / 255.0,
181                };
182                // Body text: mild fringe cleanup. Contour clabels: denser stems.
183                let coverage = if bold {
184                    sharpen_glyph_coverage_bold(coverage)
185                } else {
186                    sharpen_glyph_coverage(coverage)
187                };
188                if coverage <= 0.0 {
189                    continue;
190                }
191                let di = ((py * pm_w + px) * 4) as usize;
192                let src_a = (color.a as f32 / 255.0) * coverage;
193                let dst_a = data[di + 3] as f32 / 255.0;
194                let out_a = src_a + dst_a * (1.0 - src_a);
195                if out_a <= 0.0 {
196                    continue;
197                }
198                let blend = |s: u8, d: u8| -> u8 {
199                    let s = s as f32 / 255.0;
200                    let d = d as f32 / 255.0;
201                    (((s * src_a + d * dst_a * (1.0 - src_a)) / out_a) * 255.0).round() as u8
202                };
203                data[di] = blend(color.r, data[di]);
204                data[di + 1] = blend(color.g, data[di + 1]);
205                data[di + 2] = blend(color.b, data[di + 2]);
206                data[di + 3] = (out_a * 255.0).round() as u8;
207            }
208        }
209    }
210
211    fn draw_text_upright(&mut self, text: &str, position: Point, style: &TextStyle) -> Result<()> {
212        let (w, h) = self
213            .text
214            .measure_styled(text, style.size_px, style.italic)?;
215        let mut origin = position;
216        match style.align {
217            TextAlign::Left => {}
218            TextAlign::Center => origin.x -= w * 0.5,
219            TextAlign::Right => origin.x -= w,
220        }
221        match style.baseline {
222            TextBaseline::Alphabetic => {}
223            TextBaseline::Top => origin.y += style.size_px as f64 * 0.8,
224            TextBaseline::Middle => origin.y += h * 0.25,
225            TextBaseline::Bottom => origin.y -= style.size_px as f64 * 0.2,
226        }
227        // Snap to the pixel grid so swash hinting lands on integer advances.
228        origin.x = origin.x.round();
229        origin.y = origin.y.round();
230
231        let glyphs = self
232            .text
233            .glyphs_at_styled(text, origin, style.size_px, style.italic)?;
234        for glyph in glyphs {
235            self.blit_glyph(&glyph, style.color, style.bold);
236        }
237        Ok(())
238    }
239
240    fn draw_text_rotated(&mut self, text: &str, position: Point, style: &TextStyle) -> Result<()> {
241        let (w, h) = self
242            .text
243            .measure_styled(text, style.size_px, style.italic)?;
244        let pad = 4u32;
245        let tw = (w.ceil() as u32 + pad * 2).max(1);
246        let th = (h.ceil() as u32 + pad * 2).max(1);
247        let mut tmp = SkiaRenderer::new(tw, th)?;
248        tmp.pixmap.fill(tiny_skia::Color::from_rgba8(0, 0, 0, 0));
249
250        let local = TextStyle {
251            rotation_deg: 0.0,
252            align: TextAlign::Left,
253            baseline: TextBaseline::Alphabetic,
254            ..style.clone()
255        };
256        let ox = pad as f64;
257        let oy = pad as f64 + style.size_px as f64 * 0.85;
258        tmp.draw_text_upright(text, Point::new(ox, oy), &local)?;
259
260        let mut ax = ox;
261        let mut ay = oy;
262        match style.align {
263            TextAlign::Left => {}
264            TextAlign::Center => ax += w * 0.5,
265            TextAlign::Right => ax += w,
266        }
267        match style.baseline {
268            TextBaseline::Alphabetic => {}
269            TextBaseline::Top => ay -= style.size_px as f64 * 0.8,
270            TextBaseline::Middle => ay -= h * 0.25,
271            TextBaseline::Bottom => ay += style.size_px as f64 * 0.2,
272        }
273
274        let angle = style.rotation_deg;
275        let norm = ((angle % 360.0) + 360.0) % 360.0;
276
277        // ±90° / 180°: integer pixel remaps — no filtered resampling.
278        if (norm - 90.0).abs() < 0.5 {
279            let (rotated, nax, nay) = rotate_pixmap_cw90(&tmp.pixmap, ax, ay);
280            self.blit_pixmap_integer(&rotated, position.x - nax, position.y - nay);
281            return Ok(());
282        }
283        if (norm - 270.0).abs() < 0.5 || (norm + 90.0).abs() < 0.5 {
284            let (rotated, nax, nay) = rotate_pixmap_ccw90(&tmp.pixmap, ax, ay);
285            self.blit_pixmap_integer(&rotated, position.x - nax, position.y - nay);
286            return Ok(());
287        }
288        if (norm - 180.0).abs() < 0.5 {
289            let (rotated, nax, nay) = rotate_pixmap_180(&tmp.pixmap, ax, ay);
290            self.blit_pixmap_integer(&rotated, position.x - nax, position.y - nay);
291            return Ok(());
292        }
293
294        // Arbitrary angles (clabel / tilted ticks): 2× supersample + nearest rotate.
295        let ss = 2.0_f32;
296        let style_ss = TextStyle {
297            size_px: style.size_px * ss,
298            rotation_deg: 0.0,
299            align: TextAlign::Left,
300            baseline: TextBaseline::Alphabetic,
301            ..style.clone()
302        };
303        let (w2, h2) = self
304            .text
305            .measure_styled(text, style_ss.size_px, style_ss.italic)?;
306        let pad2 = pad * 2;
307        let tw2 = (w2.ceil() as u32 + pad2 * 2).max(1);
308        let th2 = (h2.ceil() as u32 + pad2 * 2).max(1);
309        let mut tmp2 = SkiaRenderer::new(tw2, th2)?;
310        tmp2.pixmap.fill(tiny_skia::Color::from_rgba8(0, 0, 0, 0));
311        let ox2 = pad2 as f64;
312        let oy2 = pad2 as f64 + style_ss.size_px as f64 * 0.85;
313        tmp2.draw_text_upright(text, Point::new(ox2, oy2), &style_ss)?;
314        let mut ax2 = ox2;
315        let mut ay2 = oy2;
316        match style.align {
317            TextAlign::Left => {}
318            TextAlign::Center => ax2 += w2 * 0.5,
319            TextAlign::Right => ax2 += w2,
320        }
321        match style.baseline {
322            TextBaseline::Alphabetic => {}
323            TextBaseline::Top => ay2 -= style_ss.size_px as f64 * 0.8,
324            TextBaseline::Middle => ay2 -= h2 * 0.25,
325            TextBaseline::Bottom => ay2 += style_ss.size_px as f64 * 0.2,
326        }
327
328        // Map 2× buffer → destination with rotate around anchor, then /2 scale.
329        let transform = Transform::from_translate(position.x as f32, position.y as f32)
330            .pre_concat(Transform::from_scale(1.0 / ss, 1.0 / ss))
331            .pre_concat(Transform::from_rotate(style.rotation_deg as f32))
332            .pre_concat(Transform::from_translate(-ax2 as f32, -ay2 as f32));
333        let paint = PixmapPaint {
334            quality: FilterQuality::Nearest,
335            ..PixmapPaint::default()
336        };
337        let src = tmp2.pixmap;
338        self.clipped_draw(|pixmap, clip| {
339            pixmap.draw_pixmap(0, 0, src.as_ref(), &paint, transform, clip);
340        });
341        Ok(())
342    }
343
344    fn blit_pixmap_integer(&mut self, src: &Pixmap, dx: f64, dy: f64) {
345        let x = dx.round() as i32;
346        let y = dy.round() as i32;
347        let paint = PixmapPaint {
348            quality: FilterQuality::Nearest,
349            ..PixmapPaint::default()
350        };
351        self.clipped_draw(|pixmap, clip| {
352            pixmap.draw_pixmap(x, y, src.as_ref(), &paint, Transform::identity(), clip);
353        });
354    }
355
356    /// Draw with the active clip mask. Uses raw pointer to break the
357    /// `&mut pixmap` / `&clip_stack` borrow conflict safely: the callback
358    /// never mutates the clip_stack and we hold `&mut self` for the duration.
359    fn clipped_draw<F>(&mut self, f: F)
360    where
361        F: FnOnce(&mut Pixmap, Option<&Mask>),
362    {
363        let clip_ptr = self.clip_stack.as_ptr();
364        let clip_len = self.clip_stack.len();
365        // SAFETY: we hold &mut self exclusively; the closure only writes to
366        // pixmap, never touches clip_stack. The slice is valid for the call.
367        let clip = unsafe {
368            std::slice::from_raw_parts(clip_ptr, clip_len)
369                .iter()
370                .rev()
371                .flatten()
372                .next()
373        };
374        f(&mut self.pixmap, clip);
375    }
376}
377
378impl Renderer for SkiaRenderer {
379    fn clear(&mut self, color: Color) -> Result<()> {
380        self.pixmap.fill(tiny_skia::Color::from_rgba8(
381            color.r, color.g, color.b, color.a,
382        ));
383        Ok(())
384    }
385
386    fn fill_rect(&mut self, rect: Rect, style: &FillStyle) -> Result<()> {
387        let mut pb = PathBuilder::new();
388        pb.push_rect(
389            tiny_skia::Rect::from_xywh(
390                rect.x0 as f32,
391                rect.y0 as f32,
392                rect.width() as f32,
393                rect.height() as f32,
394            )
395            .ok_or_else(|| PlotError::render("invalid fill rect"))?,
396        );
397        let path = pb
398            .finish()
399            .ok_or_else(|| PlotError::render("failed to build rect path"))?;
400        let paint = Self::paint_from(style.color, style.anti_alias);
401        self.clipped_draw(|pixmap, clip| {
402            pixmap.fill_path(
403                &path,
404                &paint,
405                FillRule::Winding,
406                Transform::identity(),
407                clip,
408            );
409        });
410        Ok(())
411    }
412
413    fn stroke_rect(&mut self, rect: Rect, style: &StrokeStyle) -> Result<()> {
414        let mut path = BezPath::new();
415        path.move_to(kurbo::Point::new(rect.x0, rect.y0));
416        path.line_to(kurbo::Point::new(rect.x1, rect.y0));
417        path.line_to(kurbo::Point::new(rect.x1, rect.y1));
418        path.line_to(kurbo::Point::new(rect.x0, rect.y1));
419        path.close_path();
420        self.stroke_path(&path, style)
421    }
422
423    fn fill_path(&mut self, path: &BezPath, style: &FillStyle) -> Result<()> {
424        let sk = Self::to_skia_path(path)?;
425        let paint = Self::paint_from(style.color, style.anti_alias);
426        self.clipped_draw(|pixmap, clip| {
427            pixmap.fill_path(&sk, &paint, FillRule::Winding, Transform::identity(), clip);
428        });
429        Ok(())
430    }
431
432    fn stroke_path(&mut self, path: &BezPath, style: &StrokeStyle) -> Result<()> {
433        let sk = Self::to_skia_path(path)?;
434        let paint = Self::paint_from(style.color, true);
435        let stroke = Self::stroke_from(style);
436        self.clipped_draw(|pixmap, clip| {
437            pixmap.stroke_path(&sk, &paint, &stroke, Transform::identity(), clip);
438        });
439        Ok(())
440    }
441
442    fn draw_text(&mut self, text: &str, position: Point, style: &TextStyle) -> Result<()> {
443        if text.is_empty() {
444            return Ok(());
445        }
446        if style.rotation_deg.abs() < 1e-6 {
447            self.draw_text_upright(text, position, style)
448        } else {
449            self.draw_text_rotated(text, position, style)
450        }
451    }
452
453    fn draw_rgba_image(
454        &mut self,
455        rgba: &[u8],
456        width: u32,
457        height: u32,
458        position: Point,
459    ) -> Result<()> {
460        let expected = (width as usize)
461            .saturating_mul(height as usize)
462            .saturating_mul(4);
463        if rgba.len() != expected {
464            return Err(PlotError::render(format!(
465                "RGBA buffer length {} != {width}×{height}×4",
466                rgba.len()
467            )));
468        }
469        if width == 0 || height == 0 {
470            return Ok(());
471        }
472        let mut src = Pixmap::new(width, height)
473            .ok_or_else(|| PlotError::render("failed to allocate RGBA pixmap"))?;
474        for (i, px) in src.pixels_mut().iter_mut().enumerate() {
475            let o = i * 4;
476            *px = PremultipliedColorU8::from_rgba(rgba[o], rgba[o + 1], rgba[o + 2], rgba[o + 3])
477                .unwrap_or_else(|| PremultipliedColorU8::from_rgba(0, 0, 0, 0).unwrap());
478        }
479        self.blit_pixmap_integer(&src, position.x, position.y);
480        Ok(())
481    }
482
483    fn measure_text_styled(&self, text: &str, size_px: f32, italic: bool) -> Result<(f64, f64)> {
484        self.text.measure_styled(text, size_px, italic)
485    }
486
487    fn push_clip_rect(&mut self, rect: Rect) -> Result<()> {
488        let mut pb = PathBuilder::new();
489        pb.push_rect(
490            tiny_skia::Rect::from_xywh(
491                rect.x0 as f32,
492                rect.y0 as f32,
493                rect.width().max(0.0) as f32,
494                rect.height().max(0.0) as f32,
495            )
496            .ok_or_else(|| PlotError::render("invalid clip rect"))?,
497        );
498        let path = pb
499            .finish()
500            .ok_or_else(|| PlotError::render("failed to build clip path"))?;
501        let mut mask = Mask::new(self.pixmap.width(), self.pixmap.height())
502            .ok_or_else(|| PlotError::render("failed to allocate clip mask"))?;
503        mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
504        self.clip_stack.push(Some(mask));
505        Ok(())
506    }
507
508    fn pop_clip(&mut self) -> Result<()> {
509        self.clip_stack.pop();
510        Ok(())
511    }
512
513    fn width(&self) -> u32 {
514        self.pixmap.width()
515    }
516
517    fn height(&self) -> u32 {
518        self.pixmap.height()
519    }
520}
521
522/// Mild AA cleanup for regular body text (titles / ticks / axis labels).
523///
524/// Former curve fattened stems vs FreeType/Agg; keep only light fringe dust
525/// cut so glyphs stay regular weight (contour clabels use the bold path).
526#[inline]
527fn sharpen_glyph_coverage(c: f32) -> f32 {
528    if c < 0.08 {
529        return 0.0;
530    }
531    // Near-identity: drop soft halo only.
532    (c * 1.02).clamp(0.0, 1.0)
533}
534
535/// Denser stems for contour clabels (`TextStyle::bold`).
536#[inline]
537fn sharpen_glyph_coverage_bold(c: f32) -> f32 {
538    if c < 0.05 {
539        return 0.0;
540    }
541    let c = c.powf(0.55).clamp(0.0, 1.0);
542    (1.0 - (1.0 - c).powf(2.15)).clamp(0.0, 1.0)
543}
544
545/// Rotate pixmap 90° clockwise (y-down). Returns `(rotated, new_ax, new_ay)`.
546fn rotate_pixmap_cw90(src: &Pixmap, ax: f64, ay: f64) -> (Pixmap, f64, f64) {
547    let w = src.width();
548    let h = src.height();
549    let mut dst = Pixmap::new(h, w).expect("rotate cw pixmap");
550    let s = src.data();
551    let d = dst.data_mut();
552    for y in 0..h {
553        for x in 0..w {
554            let si = ((y * w + x) * 4) as usize;
555            let nx = h - 1 - y;
556            let ny = x;
557            let di = ((ny * h + nx) * 4) as usize;
558            d[di..di + 4].copy_from_slice(&s[si..si + 4]);
559        }
560    }
561    // (x,y) → (h-y, x)
562    (dst, h as f64 - ay, ax)
563}
564
565/// Rotate pixmap 90° counter-clockwise (y-down).
566fn rotate_pixmap_ccw90(src: &Pixmap, ax: f64, ay: f64) -> (Pixmap, f64, f64) {
567    let w = src.width();
568    let h = src.height();
569    let mut dst = Pixmap::new(h, w).expect("rotate ccw pixmap");
570    let s = src.data();
571    let d = dst.data_mut();
572    for y in 0..h {
573        for x in 0..w {
574            let si = ((y * w + x) * 4) as usize;
575            let nx = y;
576            let ny = w - 1 - x;
577            let di = ((ny * h + nx) * 4) as usize;
578            d[di..di + 4].copy_from_slice(&s[si..si + 4]);
579        }
580    }
581    // (x,y) → (y, w-x)
582    (dst, ay, w as f64 - ax)
583}
584
585/// Rotate pixmap 180°.
586fn rotate_pixmap_180(src: &Pixmap, ax: f64, ay: f64) -> (Pixmap, f64, f64) {
587    let w = src.width();
588    let h = src.height();
589    let mut dst = Pixmap::new(w, h).expect("rotate 180 pixmap");
590    let s = src.data();
591    let d = dst.data_mut();
592    for y in 0..h {
593        for x in 0..w {
594            let si = ((y * w + x) * 4) as usize;
595            let nx = w - 1 - x;
596            let ny = h - 1 - y;
597            let di = ((ny * w + nx) * 4) as usize;
598            d[di..di + 4].copy_from_slice(&s[si..si + 4]);
599        }
600    }
601    (dst, w as f64 - ax, h as f64 - ay)
602}