Skip to main content

unityrs_texture/format/
mode.rs

1// Ported from UnityPy 1.25.2 (MIT): export/Texture2DConverter.py's CONV_TABLE output modes; closed forms follow PARITY.md sections 17.1 and 19. See THIRD_PARTY_LICENSES.
2use super::Format;
3
4/// An image mode, as Pillow names it.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6pub enum Mode {
7    /// `L`: one byte a pixel.
8    L,
9    /// `RGB`: three bytes a pixel, red first.
10    Rgb,
11    /// `RGBA`: four bytes a pixel, red first, alpha last.
12    Rgba,
13}
14
15const _: () = crate::send_sync::<Mode>();
16
17impl Mode {
18    /// Pillow's name for it.
19    #[must_use]
20    pub const fn name(self) -> &'static str {
21        match self {
22            Self::L => "L",
23            Self::Rgb => "RGB",
24            Self::Rgba => "RGBA",
25        }
26    }
27
28    /// The bytes one pixel takes.
29    #[must_use]
30    pub const fn bytes_per_pixel(self) -> u64 {
31        match self {
32            Self::L => 1,
33            Self::Rgb => 3,
34            Self::Rgba => 4,
35        }
36    }
37}
38
39impl Format {
40    /// The output mode: for closed forms, PARITY.md sections 17.1 and 19;
41    /// otherwise the mode UnityPy decodes it to (`CONV_TABLE`,
42    /// `export/Texture2DConverter.py:488-566`): `L` for `BC4` (`:513`);
43    /// `RGB` for `RGB24` (`:491`), `RGB565` (`:495`), `BGR24` (`:496`), `R8`
44    /// (`:497`) and `BC5` (`:514`); `RGBA` for the rest. A texture with a
45    /// side of 0 is an empty `RGBA` image whatever its format
46    /// ([`crate::decode()`]).
47    #[must_use]
48    pub const fn mode(self) -> Mode {
49        if let Some(layout) = crate::tierb::layout(self) {
50            return if layout.channels == 4 {
51                Mode::Rgba
52            } else {
53                Mode::Rgb
54            };
55        }
56        match self {
57            Self::Bc4 => Mode::L,
58            Self::Rgb24 | Self::Rgb565 | Self::Bgr24 | Self::R8 | Self::Bc5 | Self::Bc6h => {
59                Mode::Rgb
60            }
61            _ => Mode::Rgba,
62        }
63    }
64}