Skip to main content

mln_style/
bitmap.rs

1// Decoding images and encoding PNGs live in //crates/core/engine/src/image,
2// so that this file stays dependency-free.
3
4use std::fmt;
5use std::marker::PhantomData;
6
7use crate::geometry::Point;
8use crate::size::Size;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum ImageAlphaMode {
12    Unassociated,
13    Premultiplied,
14    /// Alpha-channel only.
15    Exclusive,
16}
17
18/// The alpha mode of an [`Image`], as its type parameter.
19pub trait AlphaMode {
20    const MODE: ImageAlphaMode;
21    /// The bytes per pixel: 1 for `Exclusive`, 4 otherwise.
22    const CHANNELS: usize;
23}
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub struct Unassociated;
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub struct Premultiplied;
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
30pub struct Exclusive;
31
32impl AlphaMode for Unassociated {
33    const MODE: ImageAlphaMode = ImageAlphaMode::Unassociated;
34    const CHANNELS: usize = 4;
35}
36impl AlphaMode for Premultiplied {
37    const MODE: ImageAlphaMode = ImageAlphaMode::Premultiplied;
38    const CHANNELS: usize = 4;
39}
40impl AlphaMode for Exclusive {
41    const MODE: ImageAlphaMode = ImageAlphaMode::Exclusive;
42    const CHANNELS: usize = 1;
43}
44
45/// Why an image operation failed.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
47pub enum ImageError {
48    /// The pixel buffer's length doesn't match the image's size.
49    #[error("the pixels don't match the image's size")]
50    WrongLength,
51    /// The source or destination image has no pixels.
52    #[error("the image has no pixels")]
53    NoPixels,
54    /// The rectangle doesn't fit inside the source or destination image.
55    #[error("the rectangle is outside the image")]
56    OutsideImage,
57}
58
59/// An image: `size` plus `channels * width * height` bytes.
60///
61/// An empty `data` is an image without pixels, such as the default image.
62///
63/// An image crosses with its pixels as a payload (serialization/payload.rs),
64/// and only images whose pixels fill their size read back.
65pub struct Image<M: AlphaMode> {
66    pub size: Size,
67    pub data: Vec<u8>,
68    _mode: PhantomData<M>,
69}
70
71impl<M: AlphaMode> mln_wire::Wire for Image<M> {
72    fn write(&self, w: &mut mln_wire::Writer<'_>) {
73        self.size.write(w);
74        mln_wire::payload::bytes::write(&self.data, w);
75    }
76
77    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
78        let size = Size::read(r)?;
79        let data = mln_wire::payload::bytes::read(r)?;
80        Image::try_from(ImageParts { size, data }).ok().or_else(|| r.fail("pixels that don't fill their image"))
81    }
82}
83
84/// What `Image` is read from.
85struct ImageParts {
86    size: Size,
87    data: Vec<u8>,
88}
89
90impl<M: AlphaMode> TryFrom<ImageParts> for Image<M> {
91    type Error = String;
92
93    fn try_from(ImageParts { size, data }: ImageParts) -> Result<Self, String> {
94        // In u64: on wasm32 `bytes()` would wrap for a large size.
95        let bytes =
96            u64::from(size.width).checked_mul(u64::from(size.height)).and_then(|n| n.checked_mul(M::CHANNELS as u64));
97        if bytes != Some(data.len() as u64) {
98            return Err(format!("{} bytes for a {}x{} image", data.len(), size.width, size.height));
99        }
100        Ok(Image::from_vec(size, data))
101    }
102}
103
104pub type UnassociatedImage = Image<Unassociated>;
105pub type PremultipliedImage = Image<Premultiplied>;
106pub type AlphaImage = Image<Exclusive>;
107
108impl<M: AlphaMode> Image<M> {
109    pub const CHANNELS: usize = M::CHANNELS;
110
111    /// An image of zeroed pixels.
112    #[must_use]
113    pub fn new(size: Size) -> Self {
114        let bytes = M::CHANNELS * size.width as usize * size.height as usize;
115        Image { size, data: vec![0; bytes], _mode: PhantomData }
116    }
117
118    pub fn from_slice(size: Size, src: &[u8]) -> Result<Self, ImageError> {
119        let mut image = Image { size, data: Vec::new(), _mode: PhantomData };
120        if src.len() != image.bytes() {
121            return Err(ImageError::WrongLength);
122        }
123        if image.bytes() != 0 {
124            image.data = src.to_vec();
125        }
126        Ok(image)
127    }
128
129    /// Takes the buffer as is, without checking its length against `size`.
130    #[must_use]
131    pub fn from_vec(size: Size, data: Vec<u8>) -> Self {
132        Image { size, data, _mode: PhantomData }
133    }
134
135    /// Splits the image into its size and pixel buffer, which can make an
136    /// image of another alpha mode.
137    #[must_use]
138    pub fn into_parts(self) -> (Size, Vec<u8>) {
139        (self.size, self.data)
140    }
141
142    #[must_use]
143    pub fn valid(&self) -> bool {
144        !self.size.is_empty() && !self.data.is_empty()
145    }
146
147    #[must_use]
148    pub fn stride(&self) -> usize {
149        M::CHANNELS * self.size.width as usize
150    }
151
152    #[must_use]
153    pub fn bytes(&self) -> usize {
154        self.stride() * self.size.height as usize
155    }
156
157    pub fn fill(&mut self, value: u8) {
158        if self.valid() {
159            let bytes = self.bytes();
160            self.data[..bytes].fill(value);
161        }
162    }
163
164    pub fn resize(&mut self, size: Size) {
165        if self.size == size {
166            return;
167        }
168        let mut new_image = Image::<M>::new(size);
169        if !size.is_empty() && self.valid() {
170            new_image.fill(0);
171            let copy_size =
172                Size::new(std::cmp::min(self.size.width, size.width), std::cmp::min(self.size.height, size.height));
173            // Both rectangles are in bounds by construction.
174            Self::copy_rows(self, &mut new_image, Point::new(0, 0), Point::new(0, 0), copy_size);
175        }
176        *self = new_image;
177    }
178
179    /// Clears the rect area specified by `pt` and `size` from `dst_img`.
180    pub fn clear(dst_img: &mut Self, pt: Point<u32>, size: Size) -> Result<(), ImageError> {
181        if size.is_empty() {
182            return Ok(());
183        }
184
185        if !dst_img.valid() {
186            return Err(ImageError::NoPixels);
187        }
188
189        if size.width > dst_img.size.width
190            || size.height > dst_img.size.height
191            || pt.x > dst_img.size.width - size.width
192            || pt.y > dst_img.size.height - size.height
193        {
194            return Err(ImageError::OutsideImage);
195        }
196
197        let stride = dst_img.stride();
198        for y in 0..size.height {
199            let dst_offset = (pt.y + y) as usize * stride + pt.x as usize * M::CHANNELS;
200            dst_img.data[dst_offset..dst_offset + size.width as usize * M::CHANNELS].fill(0);
201        }
202        Ok(())
203    }
204
205    /// Copy image data within `rect` from `src` to the rectangle of the same
206    /// size at `pt` in `dst`. If the specified bounds exceed the bounds of the
207    /// source or destination, return `ImageError::OutsideImage`. Borrowing
208    /// rules rule out copying within a single image.
209    pub fn copy(
210        src_img: &Self,
211        dst_img: &mut Self,
212        src_pt: Point<u32>,
213        dst_pt: Point<u32>,
214        size: Size,
215    ) -> Result<(), ImageError> {
216        if size.is_empty() {
217            return Ok(());
218        }
219
220        if !src_img.valid() {
221            return Err(ImageError::NoPixels);
222        }
223
224        if !dst_img.valid() {
225            return Err(ImageError::NoPixels);
226        }
227
228        if size.width > src_img.size.width
229            || size.height > src_img.size.height
230            || src_pt.x > src_img.size.width - size.width
231            || src_pt.y > src_img.size.height - size.height
232        {
233            return Err(ImageError::OutsideImage);
234        }
235
236        if size.width > dst_img.size.width
237            || size.height > dst_img.size.height
238            || dst_pt.x > dst_img.size.width - size.width
239            || dst_pt.y > dst_img.size.height - size.height
240        {
241            return Err(ImageError::OutsideImage);
242        }
243
244        Self::copy_rows(src_img, dst_img, src_pt, dst_pt, size);
245        Ok(())
246    }
247
248    fn copy_rows(src_img: &Self, dst_img: &mut Self, src_pt: Point<u32>, dst_pt: Point<u32>, size: Size) {
249        let src_stride = src_img.stride();
250        let dst_stride = dst_img.stride();
251        let row = size.width as usize * M::CHANNELS;
252        for y in 0..size.height {
253            let src_offset = (src_pt.y + y) as usize * src_stride + src_pt.x as usize * M::CHANNELS;
254            let dst_offset = (dst_pt.y + y) as usize * dst_stride + dst_pt.x as usize * M::CHANNELS;
255            dst_img.data[dst_offset..dst_offset + row].copy_from_slice(&src_img.data[src_offset..src_offset + row]);
256        }
257    }
258
259    fn pixels(&self) -> &[u8] {
260        let bytes = self.bytes();
261        self.data.get(..bytes).unwrap_or(&self.data)
262    }
263}
264
265impl<M: AlphaMode> Default for Image<M> {
266    fn default() -> Self {
267        Image { size: Size::default(), data: Vec::new(), _mode: PhantomData }
268    }
269}
270
271impl<M: AlphaMode> Clone for Image<M> {
272    fn clone(&self) -> Self {
273        Image { size: self.size, data: self.data.clone(), _mode: PhantomData }
274    }
275}
276
277/// Images are equal when their sizes and pixels are; bytes of `data` past the
278/// pixels don't count.
279impl<M: AlphaMode> PartialEq for Image<M> {
280    fn eq(&self, other: &Self) -> bool {
281        self.size == other.size && self.pixels() == other.pixels()
282    }
283}
284
285impl<M: AlphaMode> Eq for Image<M> {}
286
287impl<M: AlphaMode> fmt::Debug for Image<M> {
288    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289        f.debug_struct("Image")
290            .field("mode", &M::MODE)
291            .field("size", &self.size)
292            .field("data.len()", &self.data.len())
293            .finish()
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn new_images_are_zeroed_and_sized_by_their_channels() {
303        let image = PremultipliedImage::new(Size::new(2, 3));
304        assert_eq!((image.bytes(), image.stride()), (24, 8));
305        assert!(image.valid() && image.data.iter().all(|&b| b == 0));
306        assert_eq!(AlphaImage::new(Size::new(2, 3)).bytes(), 6);
307        assert!(!PremultipliedImage::default().valid());
308        assert!(!PremultipliedImage::new(Size::new(0, 3)).valid());
309    }
310
311    #[test]
312    fn from_slice_takes_only_a_buffer_that_fills_the_size() {
313        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3]), Err(ImageError::WrongLength));
314        assert_eq!(PremultipliedImage::from_slice(Size::new(1, 1), &[1, 2, 3, 4]).unwrap().data, [1, 2, 3, 4]);
315    }
316
317    #[test]
318    fn resize_keeps_the_overlap_and_zeroes_the_rest() {
319        let mut image = AlphaImage::new(Size::new(0, 0));
320        image.resize(Size::new(1, 1));
321        image.fill(100);
322        image.resize(Size::new(2, 1));
323        assert_eq!((image.size, &image.data[..]), (Size::new(2, 1), &[100, 0][..]));
324        image.resize(Size::new(0, 0));
325        assert_eq!((image.size, image.data.len()), (Size::new(0, 0), 0));
326    }
327
328    #[test]
329    fn copy_writes_the_rectangle_at_the_destination_point() {
330        let mut src = UnassociatedImage::new(Size::new(4, 4));
331        let mut dst = UnassociatedImage::new(Size::new(4, 4));
332        src.fill(0xFF);
333        UnassociatedImage::copy(&src, &mut dst, Point::new(0, 0), Point::new(1, 1), Size::new(2, 2)).unwrap();
334        for y in 0..4usize {
335            for x in 0..4usize {
336                let inside = (1..3).contains(&x) && (1..3).contains(&y);
337                let px = &dst.data[(y * 4 + x) * 4..(y * 4 + x) * 4 + 4];
338                assert_eq!(px, if inside { &[0xFF; 4] } else { &[0; 4] }, "({x}, {y})");
339            }
340        }
341    }
342
343    #[test]
344    fn copy_rejects_a_rectangle_outside_either_image() {
345        let small = PremultipliedImage::new(Size::new(5, 5));
346        let large = PremultipliedImage::new(Size::new(10, 10));
347        let max = u32::MAX;
348        // (source, destination, source point, destination point, size)
349        let cases = [
350            (&small, &large, (0, 0), (0, 0), (6, 1)),
351            (&small, &large, (0, 0), (0, 0), (1, 6)),
352            (&small, &large, (1, 1), (0, 0), (5, 1)),
353            (&small, &large, (1, 1), (0, 0), (1, 5)),
354            (&large, &small, (0, 0), (0, 0), (6, 1)),
355            (&large, &small, (0, 0), (0, 0), (1, 6)),
356            (&large, &small, (0, 0), (1, 1), (5, 1)),
357            (&large, &small, (0, 0), (1, 1), (1, 5)),
358            // Points and sizes whose sums overflow.
359            (&large, &large, (max, 0), (0, 0), (1, 1)),
360            (&large, &large, (0, max), (0, 0), (1, 1)),
361            (&large, &large, (0, 0), (max, 0), (1, 1)),
362            (&large, &large, (0, 0), (0, max), (1, 1)),
363            (&large, &large, (1, 0), (0, 0), (max, 1)),
364            (&large, &large, (0, 1), (0, 0), (1, max)),
365            (&large, &large, (0, 0), (1, 0), (max, 1)),
366            (&large, &large, (0, 0), (0, 1), (1, max)),
367        ];
368        for (src, dst, (sx, sy), (dx, dy), (w, h)) in cases {
369            let mut dst = dst.clone();
370            let result =
371                PremultipliedImage::copy(src, &mut dst, Point::new(sx, sy), Point::new(dx, dy), Size::new(w, h));
372            assert_eq!(
373                result,
374                Err(ImageError::OutsideImage),
375                "{:?} {:?} {:?} into {:?}",
376                (sx, sy),
377                (dx, dy),
378                (w, h),
379                dst.size
380            );
381        }
382    }
383
384    #[test]
385    fn clear_zeroes_the_rectangle_inside_the_image() {
386        let mut image = PremultipliedImage::new(Size::new(3, 3));
387        image.fill(7);
388        PremultipliedImage::clear(&mut image, Point::new(1, 1), Size::new(2, 2)).unwrap();
389        assert_eq!(&image.data[0..16], &[7; 16]);
390        assert_eq!(&image.data[16..24], &[0; 8]);
391        assert_eq!(&image.data[24..28], &[7; 4]);
392        assert_eq!(&image.data[28..36], &[0; 8]);
393        assert_eq!(
394            PremultipliedImage::clear(&mut image, Point::new(2, 2), Size::new(2, 2)),
395            Err(ImageError::OutsideImage)
396        );
397
398        let mut empty = PremultipliedImage::default();
399        assert_eq!(PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(1, 1)), Err(ImageError::NoPixels));
400        assert_eq!(PremultipliedImage::clear(&mut empty, Point::new(0, 0), Size::new(0, 1)), Ok(()));
401    }
402
403    #[test]
404    fn equality_ignores_bytes_past_the_pixels() {
405        let a = PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]);
406        assert_eq!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4, 9]));
407        assert_ne!(a, PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 5]));
408    }
409
410    #[test]
411    fn only_pixels_that_fill_their_image_cross_the_wire() {
412        let image = PremultipliedImage::from_vec(Size::new(1, 1), vec![1, 2, 3, 4]);
413        let bytes = mln_wire::to_vec(&image).unwrap();
414        assert_eq!(mln_wire::from_slice::<PremultipliedImage>(&bytes).unwrap(), image);
415
416        let short = PremultipliedImage::from_vec(Size::new(2, 1), vec![1, 2, 3, 4]);
417        assert!(mln_wire::from_slice::<PremultipliedImage>(&mln_wire::to_vec(&short).unwrap()).is_err());
418    }
419}