Skip to main content

sealed_surface/
raster.rs

1//! Software pixmap + in-crate PNG encoder (DEFLATE).
2
3use crate::deflate;
4use crate::error::Error;
5use crate::font;
6use crate::theme::Rgb;
7
8/// RGB888 pixmap.
9#[derive(Debug, Clone)]
10pub struct Pixmap {
11    width: u32,
12    height: u32,
13    data: Vec<u8>,
14}
15
16impl Pixmap {
17    pub(crate) fn new(width: u32, height: u32, fill: Rgb) -> Result<Self, Error> {
18        if width == 0 || height == 0 {
19            return Err(Error::Raster("width and height must be > 0"));
20        }
21        let n = (width as usize)
22            .checked_mul(height as usize)
23            .and_then(|px| px.checked_mul(3))
24            .ok_or(Error::Raster("pixmap too large"))?;
25        let mut data = vec![0u8; n];
26        for px in data.chunks_exact_mut(3) {
27            px[0] = fill.r;
28            px[1] = fill.g;
29            px[2] = fill.b;
30        }
31        Ok(Self {
32            width,
33            height,
34            data,
35        })
36    }
37
38    /// Pixel width.
39    #[must_use]
40    pub const fn width(&self) -> u32 {
41        self.width
42    }
43
44    /// Pixel height.
45    #[must_use]
46    pub const fn height(&self) -> u32 {
47        self.height
48    }
49
50    pub(crate) fn fill_rect(&mut self, x: u32, y: u32, w: u32, h: u32, color: Rgb) {
51        let x1 = x.min(self.width);
52        let y1 = y.min(self.height);
53        let x2 = x.saturating_add(w).min(self.width);
54        let y2 = y.saturating_add(h).min(self.height);
55        if x1 >= x2 || y1 >= y2 {
56            return;
57        }
58        let row_w = (x2 - x1) as usize;
59        let stride = self.width as usize * 3;
60        let first = (y1 as usize) * stride + (x1 as usize) * 3;
61        {
62            let row = &mut self.data[first..first + row_w * 3];
63            for px in row.chunks_exact_mut(3) {
64                px[0] = color.r;
65                px[1] = color.g;
66                px[2] = color.b;
67            }
68        }
69        for yy in (y1 + 1)..y2 {
70            let dest = (yy as usize) * stride + (x1 as usize) * 3;
71            self.data.copy_within(first..first + row_w * 3, dest);
72        }
73    }
74
75    pub(crate) fn hline(&mut self, x: u32, y: u32, w: u32, color: Rgb) {
76        self.fill_rect(x, y, w, 1, color);
77    }
78
79    pub(crate) fn vline(&mut self, x: u32, y: u32, h: u32, color: Rgb) {
80        self.fill_rect(x, y, 1, h, color);
81    }
82
83    pub(crate) fn put(&mut self, x: u32, y: u32, color: Rgb) {
84        if x >= self.width || y >= self.height {
85            return;
86        }
87        let i = ((y as usize) * (self.width as usize) + (x as usize)) * 3;
88        self.data[i] = color.r;
89        self.data[i + 1] = color.g;
90        self.data[i + 2] = color.b;
91    }
92
93    pub(crate) fn text_scaled(
94        &mut self,
95        x: u32,
96        y: u32,
97        s: &str,
98        color: Rgb,
99        max_w: u32,
100        scale: crate::appearance::TypeScale,
101    ) {
102        let adv = scale.advance();
103        let mut cx = x;
104        for ch in s.chars() {
105            if cx.saturating_sub(x).saturating_add(adv) > max_w {
106                break;
107            }
108            font::each_pixel_scaled(ch, scale, |px, py| {
109                self.put(cx.saturating_add(px), y.saturating_add(py), color);
110            });
111            cx = cx.saturating_add(adv);
112        }
113    }
114
115    pub(crate) fn get(&self, x: u32, y: u32) -> Option<Rgb> {
116        if x >= self.width || y >= self.height {
117            return None;
118        }
119        let i = ((y as usize) * (self.width as usize) + (x as usize)) * 3;
120        Some(Rgb::new(self.data[i], self.data[i + 1], self.data[i + 2]))
121    }
122
123    pub(crate) fn blend(&mut self, x: u32, y: u32, color: Rgb, alpha: u8) {
124        let Some(bg) = self.get(x, y) else {
125            return;
126        };
127        self.put(x, y, bg.mix(color, alpha));
128    }
129
130    /// Xiaolin Wu anti-aliased line.
131    pub(crate) fn line_aa(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, color: Rgb) {
132        let mut x0 = x0;
133        let mut y0 = y0;
134        let mut x1 = x1;
135        let mut y1 = y1;
136        let steep = (y1 - y0).abs() > (x1 - x0).abs();
137        if steep {
138            core::mem::swap(&mut x0, &mut y0);
139            core::mem::swap(&mut x1, &mut y1);
140        }
141        if x0 > x1 {
142            core::mem::swap(&mut x0, &mut x1);
143            core::mem::swap(&mut y0, &mut y1);
144        }
145        let dx = x1 - x0;
146        let dy = y1 - y0;
147        let gradient = if dx.abs() < 1e-9 { 1.0 } else { dy / dx };
148
149        let plot = |pm: &mut Self, x: i32, y: i32, a: f64| {
150            if x < 0 || y < 0 {
151                return;
152            }
153            let alpha = (a.clamp(0.0, 1.0) * 255.0) as u8;
154            if steep {
155                pm.blend(y as u32, x as u32, color, alpha);
156            } else {
157                pm.blend(x as u32, y as u32, color, alpha);
158            }
159        };
160
161        let xend = x0.round();
162        let yend = y0 + gradient * (xend - x0);
163        let xgap = 1.0 - (x0 + 0.5).fract();
164        let xpxl1 = xend as i32;
165        let ypxl1 = yend.floor() as i32;
166        plot(self, xpxl1, ypxl1, (1.0 - yend.fract()) * xgap);
167        plot(self, xpxl1, ypxl1 + 1, yend.fract() * xgap);
168        let mut intery = yend + gradient;
169
170        let xend2 = x1.round();
171        let yend2 = y1 + gradient * (xend2 - x1);
172        let xgap2 = (x1 + 0.5).fract();
173        let xpxl2 = xend2 as i32;
174        let ypxl2 = yend2.floor() as i32;
175        plot(self, xpxl2, ypxl2, (1.0 - yend2.fract()) * xgap2);
176        plot(self, xpxl2, ypxl2 + 1, yend2.fract() * xgap2);
177
178        let mut x = xpxl1 + 1;
179        while x < xpxl2 {
180            plot(self, x, intery.floor() as i32, 1.0 - intery.fract());
181            plot(self, x, intery.floor() as i32 + 1, intery.fract());
182            intery += gradient;
183            x += 1;
184        }
185    }
186
187    pub(crate) fn stroke_aa(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, color: Rgb, width: u8) {
188        self.line_aa(x0, y0, x1, y1, color);
189        if width >= 2 {
190            let dx = x1 - x0;
191            let dy = y1 - y0;
192            let len = (dx * dx + dy * dy).sqrt().max(1.0);
193            let ox = -dy / len * 0.7;
194            let oy = dx / len * 0.7;
195            self.line_aa(x0 + ox, y0 + oy, x1 + ox, y1 + oy, color);
196            if width >= 3 {
197                self.line_aa(x0 - ox, y0 - oy, x1 - ox, y1 - oy, color);
198            }
199        }
200    }
201
202    /// Encode PNG (8-bit RGB, no interlace).
203    ///
204    /// # Errors
205    ///
206    /// Returns [`Error::Raster`] if the buffer is inconsistent.
207    pub fn to_png(&self) -> Result<Vec<u8>, Error> {
208        encode_png(self.width, self.height, &self.data)
209    }
210}
211
212fn encode_png(width: u32, height: u32, rgb: &[u8]) -> Result<Vec<u8>, Error> {
213    let expected = (width as usize)
214        .checked_mul(height as usize)
215        .and_then(|px| px.checked_mul(3))
216        .ok_or(Error::Raster("png size overflow"))?;
217    if rgb.len() != expected {
218        return Err(Error::Raster("rgb length does not match dimensions"));
219    }
220
221    let mut raw = Vec::with_capacity((width as usize + 1) * height as usize * 3);
222    for y in 0..height as usize {
223        raw.push(0);
224        let start = y * width as usize * 3;
225        let end = start + width as usize * 3;
226        raw.extend_from_slice(&rgb[start..end]);
227    }
228
229    let mut out = Vec::new();
230    out.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
231    let mut ihdr = Vec::new();
232    ihdr.extend_from_slice(&width.to_be_bytes());
233    ihdr.extend_from_slice(&height.to_be_bytes());
234    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
235    write_chunk(&mut out, *b"IHDR", &ihdr);
236    let deflated = deflate::zlib_deflate(&raw);
237    write_chunk(&mut out, *b"IDAT", &deflated);
238    write_chunk(&mut out, *b"IEND", &[]);
239    Ok(out)
240}
241
242fn write_chunk(out: &mut Vec<u8>, ty: [u8; 4], data: &[u8]) {
243    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
244    out.extend_from_slice(&ty);
245    out.extend_from_slice(data);
246    let mut crc_in = Vec::with_capacity(4 + data.len());
247    crc_in.extend_from_slice(&ty);
248    crc_in.extend_from_slice(data);
249    out.extend_from_slice(&crc32(&crc_in).to_be_bytes());
250}
251
252fn crc32(data: &[u8]) -> u32 {
253    let mut crc = 0xFFFF_FFFFu32;
254    for &b in data {
255        let idx = ((crc ^ u32::from(b)) & 0xFF) as usize;
256        crc = CRC_TABLE[idx] ^ (crc >> 8);
257    }
258    crc ^ 0xFFFF_FFFF
259}
260
261const CRC_TABLE: [u32; 256] = make_crc_table();
262
263const fn make_crc_table() -> [u32; 256] {
264    let mut table = [0u32; 256];
265    let mut n = 0;
266    while n < 256 {
267        let mut c = n as u32;
268        let mut k = 0;
269        while k < 8 {
270            if c & 1 != 0 {
271                c = 0xEDB8_8320 ^ (c >> 1);
272            } else {
273                c >>= 1;
274            }
275            k += 1;
276        }
277        table[n] = c;
278        n += 1;
279    }
280    table
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn png_signature() {
289        let pm = Pixmap::new(2, 2, Rgb::new(0, 0, 0)).expect("pixmap");
290        let png = pm.to_png().expect("png");
291        assert_eq!(&png[..8], &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
292    }
293
294    #[test]
295    fn png_idat_roundtrip() {
296        let mut pm = Pixmap::new(8, 4, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
297        pm.fill_rect(1, 1, 3, 2, Rgb::new(0x3d, 0x9e, 0xff));
298        let png = pm.to_png().expect("png");
299        let raw = extract_idat_inflate(&png).expect("idat");
300        let mut expect = Vec::new();
301        for y in 0..4u32 {
302            expect.push(0);
303            for x in 0..8u32 {
304                let i = ((y * 8 + x) * 3) as usize;
305                expect.extend_from_slice(&pm.data[i..i + 3]);
306            }
307        }
308        assert_eq!(raw, expect);
309    }
310
311    #[test]
312    fn png_deflate_beats_raw_for_flat_fill() {
313        let pm = Pixmap::new(320, 180, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
314        let png = pm.to_png().expect("png");
315        let raw_rgb = (320 * 180 * 3) as usize;
316        assert!(
317            png.len() < raw_rgb / 4,
318            "compressed {} vs raw {}",
319            png.len(),
320            raw_rgb
321        );
322    }
323
324    fn extract_idat_inflate(png: &[u8]) -> Result<Vec<u8>, &'static str> {
325        let mut i = 8usize;
326        let mut z = Vec::new();
327        while i + 12 <= png.len() {
328            let len = u32::from_be_bytes(png[i..i + 4].try_into().unwrap()) as usize;
329            let ty = &png[i + 4..i + 8];
330            let data = &png[i + 8..i + 8 + len];
331            if ty == b"IDAT" {
332                z.extend_from_slice(data);
333            }
334            if ty == b"IEND" {
335                break;
336            }
337            i += 12 + len;
338        }
339        crate::deflate::zlib_inflate(&z)
340    }
341}