Skip to main content

sb3_decoder/model/
costume.rs

1use crate::Error;
2
3/// The representation of a Scratch costume inside a sprite.
4#[derive(Clone)]
5#[non_exhaustive]
6pub struct Costume {
7    pub name: String,
8    pub data_format: CostumeFormat,
9    pub rotation_center_x: f64,
10    pub rotation_center_y: f64,
11    pub bitmap_resolution: f64,
12
13    /// Raw file data. Enable the `costumes` feature to decode it.
14    pub data: Vec<u8>,
15}
16
17impl std::fmt::Debug for Costume {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        let Self {
20            name,
21            data_format,
22            rotation_center_x,
23            rotation_center_y,
24            bitmap_resolution,
25            data,
26        } = self;
27
28        f.debug_struct("Costume")
29            .field("name", name)
30            .field("data_format", data_format)
31            .field("rotation_center_x", rotation_center_x)
32            .field("rotation_center_y", rotation_center_y)
33            .field("bitmap_resolution", bitmap_resolution)
34            .field("data_len", &data.len())
35            .finish()
36    }
37}
38
39/// The image format the costume image is stored in.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum CostumeFormat {
43    Png,
44    Jpeg,
45    Bmp,
46    Svg,
47}
48
49#[cfg(feature = "costumes")]
50impl Costume {
51    /// Decodes the image data inside this costume.
52    pub fn decode(&self) -> Result<DecodedCostume, Error> {
53        match self.data_format {
54            CostumeFormat::Png => self.decode_bitmap(image::ImageFormat::Png),
55            CostumeFormat::Jpeg => self.decode_bitmap(image::ImageFormat::Jpeg),
56            CostumeFormat::Bmp => self.decode_bitmap(image::ImageFormat::Bmp),
57            CostumeFormat::Svg => self.decode_svg(),
58        }
59    }
60
61    fn decode_bitmap(&self, format: image::ImageFormat) -> Result<DecodedCostume, Error> {
62        let image =
63            image::load_from_memory_with_format(&self.data, format).map_err(Error::image)?;
64        Ok(DecodedCostume {
65            width: image.width(),
66            height: image.height(),
67            rgba: image.into_rgba8().into_vec(),
68        })
69    }
70
71    fn decode_svg(&self) -> Result<DecodedCostume, Error> {
72        use resvg::tiny_skia::{Pixmap, Transform};
73        use resvg::usvg::{Options, Tree};
74
75        let mut opt = Options::default();
76        opt.fontdb_mut().load_system_fonts();
77
78        let tree = Tree::from_data(&self.data, &opt).map_err(Error::usvg)?;
79        let size = tree.size();
80        let (w, h) = (size.width().ceil() as u32, size.height().ceil() as u32);
81
82        let mut pixmap = Pixmap::new(w, h).ok_or_else(|| Error::InvalidCostumeSize { w, h })?;
83        resvg::render(&tree, Transform::default(), &mut pixmap.as_mut());
84
85        let rgba = pixmap
86            .pixels()
87            .iter()
88            .flat_map(|p| {
89                let c = p.demultiply();
90                [c.red(), c.green(), c.blue(), c.alpha()]
91            })
92            .collect();
93
94        Ok(DecodedCostume {
95            width: w,
96            height: h,
97            rgba,
98        })
99    }
100}
101
102/// A decoded costume file.
103#[cfg(feature = "costumes")]
104#[derive(Debug, Clone)]
105pub struct DecodedCostume {
106    pub width: u32,
107    pub height: u32,
108    pub rgba: Vec<u8>,
109}