Skip to main content

devpage_design/png/
mod.rs

1//! The PNG, written band by band: each band as many rows as fit in
2//! [`BAND_BYTES`] of pixels, its rows streamed into the `png` crate's encoder
3//! as it is had, so what is held at once is one band — whatever paints or
4//! caches its pieces, and however wide the drawing is.
5
6use std::io::Write;
7
8use crate::display::List;
9use crate::render::Renderer;
10use crate::scene::{Scene, Theme};
11use crate::tiles::TILE;
12
13/// The most pixel bytes a band holds: a band is as many rows as fit, at least
14/// one. A drawing up to 16,384 pixels wide fits a whole row of tiles.
15pub const BAND_BYTES: usize = 16 << 20;
16
17/// A piece of a band, `TILE` pixels wide at column `col`: a whole tile, at
18/// tile row `row`, or a strip `rows` tall starting at pixel row `y` — what a
19/// band of a drawing too wide for a row of tiles is made of. Either is its
20/// straight RGBA pixels, `TILE` wide, row after row.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum Piece {
23    /// The whole tile at column `col`, tile row `row`.
24    Tile { col: u32, row: u32 },
25    /// A strip of column `col`, `rows` tall from pixel row `y`.
26    Strip { col: u32, y: u32, rows: u32 },
27}
28
29/// How many rows a band of a drawing `width` pixels wide holds: as many as
30/// fit in [`BAND_BYTES`], its pieces padded to whole tiles, at least one and
31/// at most a tile's.
32pub fn rows_per_band(width: u32) -> u32 {
33    let padded = width.max(1).div_ceil(TILE) as usize * TILE as usize * 4;
34    (BAND_BYTES / padded).clamp(1, TILE as usize) as u32
35}
36
37/// A scene's whole drawing, painted at 1× in `theme` and encoded as a PNG,
38/// band by band, or why it can't be: see [`Renderer::drawing`]. A drawing
39/// made afresh and kept by nothing: the server's PNG comes from its kept
40/// drawings and tiles instead. This is the reference the engine's, the
41/// module's and the canvas's tests compare a drawing against — one call,
42/// from a scene, with nothing kept.
43pub fn fresh(renderer: &mut Renderer, scene: &Scene, theme: Theme) -> Result<Vec<u8>, String> {
44    let drawing = renderer
45        .drawing(scene, theme, None)
46        .map_err(|e| e.message)?;
47    let mut png = Vec::new();
48    write(&drawing.list, &mut png).map_err(|e| format!("encoding the PNG: {e}"))?;
49    Ok(png)
50}
51
52/// The drawing at 1× as a PNG written to `out`, band by band.
53pub fn write(list: &List, out: impl Write) -> Result<(), png::EncodingError> {
54    let (w, h) = (list.area.width as u32, list.area.height as u32);
55    write_bands(w, h, out, |piece| {
56        Ok::<_, std::convert::Infallible>(match piece {
57            Piece::Tile { col, row } => crate::cpu::tile(list, 1.0, col, row),
58            Piece::Strip { col, y, rows } => crate::cpu::strip(list, col, y, rows),
59        })
60    })
61    .map_err(|e| match e {
62        Band::Encoding(e) => e,
63    })
64}
65
66/// Why writing a PNG from bands stopped: the encoder or its writer failed,
67/// or a piece couldn't be had.
68#[derive(Debug)]
69pub enum Band<E> {
70    /// The encoder or its writer failed.
71    Encoding(png::EncodingError),
72    /// A piece couldn't be had.
73    Tile(E),
74}
75
76impl<E: std::fmt::Display> std::fmt::Display for Band<E> {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        match self {
79            Band::Encoding(e) => write!(f, "{e}"),
80            Band::Tile(e) => write!(f, "{e}"),
81        }
82    }
83}
84
85/// A `width` × `height` PNG written to `out` band by band, each band's pieces
86/// from `piece` — whole tiles while a row of them fits in [`BAND_BYTES`],
87/// shorter strips otherwise — its rows streamed to the encoder as each band
88/// is had, so what is held at once is one band.
89pub fn write_bands<P: AsRef<[u8]>, E>(
90    width: u32,
91    height: u32,
92    out: impl Write,
93    mut piece: impl FnMut(Piece) -> Result<P, E>,
94) -> Result<(), Band<E>> {
95    let (w, h) = (width.max(1), height.max(1));
96    let mut encoder = png::Encoder::new(out, w, h);
97    encoder.set_color(png::ColorType::Rgba);
98    encoder.set_depth(png::BitDepth::Eight);
99    let mut header = encoder.write_header().map_err(Band::Encoding)?;
100    let mut writer = header.stream_writer().map_err(Band::Encoding)?;
101    let cols = w.div_ceil(TILE);
102    let per = rows_per_band(w);
103    let mut y = 0;
104    while y < h {
105        let rows = per.min(h - y);
106        let band = (0..cols)
107            .map(|col| {
108                piece(if per == TILE {
109                    Piece::Tile { col, row: y / TILE }
110                } else {
111                    Piece::Strip { col, y, rows }
112                })
113            })
114            .collect::<Result<Vec<P>, E>>()
115            .map_err(Band::Tile)?;
116        for r in 0..rows {
117            for (col, p) in band.iter().enumerate() {
118                let across = (w - col as u32 * TILE).min(TILE) as usize;
119                let start = r as usize * TILE as usize * 4;
120                writer
121                    .write_all(&p.as_ref()[start..start + across * 4])
122                    .map_err(|e| Band::Encoding(e.into()))?;
123            }
124        }
125        y += rows;
126    }
127    writer.finish().map_err(Band::Encoding)
128}
129
130#[cfg(test)]
131mod tests;