Skip to main content

source_vtf/
format.rs

1use num_enum::{IntoPrimitive, TryFromPrimitive};
2
3use crate::header::Version;
4use crate::{Error, Result};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, IntoPrimitive, TryFromPrimitive)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[repr(i32)]
9pub enum ImageFormat {
10    Rgba8888 = 0,
11    Abgr8888 = 1,
12    Rgb888 = 2,
13    Bgr888 = 3,
14    Rgb565 = 4,
15    I8 = 5,
16    Ia88 = 6,
17    P8 = 7,
18    A8 = 8,
19    Rgb888Bluescreen = 9,
20    Bgr888Bluescreen = 10,
21    Argb8888 = 11,
22    Bgra8888 = 12,
23    Dxt1 = 13,
24    Dxt3 = 14,
25    Dxt5 = 15,
26    Bgrx8888 = 16,
27    Bgr565 = 17,
28    Bgrx5551 = 18,
29    Bgra4444 = 19,
30    Dxt1OneBitAlpha = 20,
31    Bgra5551 = 21,
32    Uv88 = 22,
33    Uvwq8888 = 23,
34    Rgba16161616F = 24,
35    Rgba16161616 = 25,
36    Uvlx8888 = 26,
37    R32F = 27,
38    Rgb323232F = 28,
39    Rgba32323232F = 29,
40    Rg1616F = 30,
41    Rg3232F = 31,
42    Rgbx8888 = 32,
43    Empty = 33,
44    Ati2n = 34,
45    Ati1n = 35,
46    Rgba1010102 = 36,
47    Bgra1010102 = 37,
48    R16F = 38,
49}
50
51#[derive(Debug, Clone, Copy)]
52enum Storage {
53    BytesPerPixel(usize),
54    Block { bytes: usize },
55    Empty,
56}
57
58impl ImageFormat {
59    /// Numeric ID in the VTF 7.5 image-format table.
60    pub const fn id(self) -> i32 {
61        self as i32
62    }
63
64    pub const fn is_block_compressed(self) -> bool {
65        matches!(self.storage(), Storage::Block { .. })
66    }
67
68    /// Checked byte length of one two-dimensional image.
69    pub fn byte_len(self, width: u16, height: u16) -> Result<usize> {
70        let width = usize::from(width);
71        let height = usize::from(height);
72
73        match self.storage() {
74            Storage::BytesPerPixel(bytes) => width
75                .checked_mul(height)
76                .and_then(|pixels| pixels.checked_mul(bytes))
77                .ok_or(Error::ArithmeticOverflow {
78                    context: "uncompressed image byte length",
79                }),
80            Storage::Block { bytes } => {
81                let blocks_wide = width.checked_add(3).ok_or(Error::ArithmeticOverflow {
82                    context: "compressed image block width",
83                })? / 4;
84                let blocks_high = height.checked_add(3).ok_or(Error::ArithmeticOverflow {
85                    context: "compressed image block height",
86                })? / 4;
87                blocks_wide
88                    .checked_mul(blocks_high)
89                    .and_then(|blocks| blocks.checked_mul(bytes))
90                    .ok_or(Error::ArithmeticOverflow {
91                        context: "compressed image byte length",
92                    })
93            }
94            Storage::Empty => Ok(0),
95        }
96    }
97
98    pub(crate) fn from_wire(value: i32, version: Version, field: &'static str) -> Result<Self> {
99        let value = if version < Version::V7_5 {
100            match value {
101                33..=35 => {
102                    return Err(Error::UnsupportedImageFormat {
103                        value,
104                        major: version.major(),
105                        minor: version.minor(),
106                        reason: "legacy depth-buffer formats are not valid raw image payloads",
107                    });
108                }
109                36..=38 => value - 3,
110                other => other,
111            }
112        } else {
113            value
114        };
115
116        Self::try_from(value).map_err(|_| Error::UnknownImageFormat {
117            field,
118            value,
119            major: version.major(),
120            minor: version.minor(),
121        })
122    }
123
124    const fn storage(self) -> Storage {
125        match self {
126            Self::Rgba8888
127            | Self::Abgr8888
128            | Self::Argb8888
129            | Self::Bgra8888
130            | Self::Bgrx8888
131            | Self::Uvwq8888
132            | Self::Uvlx8888
133            | Self::R32F
134            | Self::Rg1616F
135            | Self::Rgbx8888
136            | Self::Rgba1010102
137            | Self::Bgra1010102 => Storage::BytesPerPixel(4),
138            Self::Rgb888 | Self::Bgr888 | Self::Rgb888Bluescreen | Self::Bgr888Bluescreen => {
139                Storage::BytesPerPixel(3)
140            }
141            Self::Rgb565
142            | Self::Ia88
143            | Self::Bgr565
144            | Self::Bgrx5551
145            | Self::Bgra4444
146            | Self::Bgra5551
147            | Self::Uv88
148            | Self::R16F => Storage::BytesPerPixel(2),
149            Self::I8 | Self::P8 | Self::A8 => Storage::BytesPerPixel(1),
150            Self::Rgba16161616F | Self::Rgba16161616 | Self::Rg3232F => Storage::BytesPerPixel(8),
151            Self::Rgb323232F => Storage::BytesPerPixel(12),
152            Self::Rgba32323232F => Storage::BytesPerPixel(16),
153            Self::Dxt1 | Self::Dxt1OneBitAlpha | Self::Ati1n => Storage::Block { bytes: 8 },
154            Self::Dxt3 | Self::Dxt5 | Self::Ati2n => Storage::Block { bytes: 16 },
155            Self::Empty => Storage::Empty,
156        }
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn rounds_compressed_images_to_complete_blocks() {
166        assert_eq!(ImageFormat::Dxt1.byte_len(1, 1).unwrap(), 8);
167        assert_eq!(ImageFormat::Dxt1.byte_len(5, 7).unwrap(), 32);
168        assert_eq!(ImageFormat::Dxt5.byte_len(5, 7).unwrap(), 64);
169    }
170
171    #[test]
172    fn translates_the_pre_75_tail_of_the_format_enum() {
173        assert_eq!(
174            ImageFormat::from_wire(36, Version::V7_4, "image").unwrap(),
175            ImageFormat::Empty
176        );
177        assert_eq!(
178            ImageFormat::from_wire(37, Version::V7_4, "image").unwrap(),
179            ImageFormat::Ati2n
180        );
181        assert_eq!(
182            ImageFormat::from_wire(38, Version::V7_4, "image").unwrap(),
183            ImageFormat::Ati1n
184        );
185    }
186}