Skip to main content

source_vtf/
header.rs

1use crate::cursor::Cursor;
2use crate::{Error, ImageFormat, Result, Section, TextureFlags};
3
4const SIGNATURE: u32 = u32::from_le_bytes(*b"VTF\0");
5const LEGACY_HEADER_SIZE: u32 = 64;
6const V7_2_HEADER_SIZE: u32 = 80;
7const RESOURCE_HEADER_SIZE: u32 = 80;
8const RESOURCE_ENTRY_SIZE: u32 = 8;
9const MAX_RESOURCES: u32 = 4096;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub enum Version {
14    V7_0,
15    V7_1,
16    V7_2,
17    V7_3,
18    V7_4,
19    V7_5,
20}
21
22impl Version {
23    pub const fn major(self) -> u32 {
24        7
25    }
26
27    pub const fn minor(self) -> u32 {
28        match self {
29            Self::V7_0 => 0,
30            Self::V7_1 => 1,
31            Self::V7_2 => 2,
32            Self::V7_3 => 3,
33            Self::V7_4 => 4,
34            Self::V7_5 => 5,
35        }
36    }
37
38    pub const fn has_depth(self) -> bool {
39        matches!(self, Self::V7_2 | Self::V7_3 | Self::V7_4 | Self::V7_5)
40    }
41
42    pub const fn has_resource_table(self) -> bool {
43        matches!(self, Self::V7_3 | Self::V7_4 | Self::V7_5)
44    }
45}
46
47impl TryFrom<(u32, u32)> for Version {
48    type Error = Error;
49
50    fn try_from((major, minor): (u32, u32)) -> Result<Self> {
51        match (major, minor) {
52            (7, 0) => Ok(Self::V7_0),
53            (7, 1) => Ok(Self::V7_1),
54            (7, 2) => Ok(Self::V7_2),
55            (7, 3) => Ok(Self::V7_3),
56            (7, 4) => Ok(Self::V7_4),
57            (7, 5) => Ok(Self::V7_5),
58            _ => Err(Error::UnsupportedVersion { major, minor }),
59        }
60    }
61}
62
63#[derive(Debug, Clone, Copy)]
64#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
65pub struct Header {
66    version: Version,
67    header_size: u32,
68    width: u16,
69    height: u16,
70    flags: TextureFlags,
71    frame_count: u16,
72    start_frame: u16,
73    reflectivity: [f32; 3],
74    bump_map_scale: f32,
75    image_format_id: i32,
76    image_format: ImageFormat,
77    mip_count: u8,
78    thumbnail_format_id: i32,
79    thumbnail_format: Option<ImageFormat>,
80    thumbnail_width: u8,
81    thumbnail_height: u8,
82    depth: u16,
83    resource_count: u32,
84}
85
86impl Header {
87    pub const fn version(&self) -> Version {
88        self.version
89    }
90
91    pub const fn header_size(&self) -> u32 {
92        self.header_size
93    }
94
95    pub const fn width(&self) -> u16 {
96        self.width
97    }
98
99    pub const fn height(&self) -> u16 {
100        self.height
101    }
102
103    pub const fn flags(&self) -> TextureFlags {
104        self.flags
105    }
106
107    pub const fn frame_count(&self) -> u16 {
108        self.frame_count
109    }
110
111    pub const fn start_frame(&self) -> u16 {
112        self.start_frame
113    }
114
115    pub const fn reflectivity(&self) -> [f32; 3] {
116        self.reflectivity
117    }
118
119    pub const fn bump_map_scale(&self) -> f32 {
120        self.bump_map_scale
121    }
122
123    /// Raw image-format ID as it appeared in this VTF version's enum.
124    pub const fn image_format_id(&self) -> i32 {
125        self.image_format_id
126    }
127
128    /// Normalized image format. IDs 36–38 in VTF 7.0–7.4 are mapped to
129    /// their VTF 7.5 names while [`Header::image_format_id`] remains lossless.
130    pub const fn image_format(&self) -> ImageFormat {
131        self.image_format
132    }
133
134    pub const fn mip_count(&self) -> u8 {
135        self.mip_count
136    }
137
138    pub const fn thumbnail_format_id(&self) -> i32 {
139        self.thumbnail_format_id
140    }
141
142    pub const fn thumbnail_format(&self) -> Option<ImageFormat> {
143        self.thumbnail_format
144    }
145
146    pub const fn thumbnail_width(&self) -> u8 {
147        self.thumbnail_width
148    }
149
150    pub const fn thumbnail_height(&self) -> u8 {
151        self.thumbnail_height
152    }
153
154    pub const fn depth(&self) -> u16 {
155        self.depth
156    }
157
158    pub const fn resource_count(&self) -> u32 {
159        self.resource_count
160    }
161
162    /// Number of stored faces, including the legacy sphere-map face where the
163    /// 7.1–7.4 header says it is present.
164    pub const fn face_count(&self) -> u8 {
165        if !self.flags.contains(TextureFlags::ENVMAP) {
166            return 1;
167        }
168        match self.version {
169            Version::V7_0 | Version::V7_5 => 6,
170            Version::V7_1 | Version::V7_2 | Version::V7_3 | Version::V7_4 => {
171                if self.start_frame == u16::MAX { 6 } else { 7 }
172            }
173        }
174    }
175
176    pub(crate) fn parse(bytes: &[u8]) -> Result<Self> {
177        let mut cursor = Cursor::new(bytes, Section::Header);
178        let signature = cursor.read_u32()?;
179        if signature != SIGNATURE {
180            return Err(Error::InvalidSignature(signature));
181        }
182
183        let major = cursor.read_u32()?;
184        let minor = cursor.read_u32()?;
185        let version = Version::try_from((major, minor))?;
186        let header_size = cursor.read_u32()?;
187        let width = cursor.read_u16()?;
188        let height = cursor.read_u16()?;
189        let flags = TextureFlags::from_bits_retain(cursor.read_u32()?);
190        let frame_count = cursor.read_u16()?;
191        let start_frame = cursor.read_u16()?;
192        cursor.skip(4)?;
193        let reflectivity = [cursor.read_f32()?, cursor.read_f32()?, cursor.read_f32()?];
194        cursor.skip(4)?;
195        let bump_map_scale = cursor.read_f32()?;
196        let image_format_id = cursor.read_i32()?;
197        let image_format = ImageFormat::from_wire(image_format_id, version, "high-resolution")?;
198        let mip_count = cursor.read_u8()?;
199        let thumbnail_format_id = cursor.read_i32()?;
200        let thumbnail_width = cursor.read_u8()?;
201        let thumbnail_height = cursor.read_u8()?;
202        let thumbnail_format = if thumbnail_format_id == -1 {
203            None
204        } else {
205            Some(ImageFormat::from_wire(
206                thumbnail_format_id,
207                version,
208                "low-resolution",
209            )?)
210        };
211        let depth = if version.has_depth() {
212            cursor.read_u16()?
213        } else {
214            1
215        };
216
217        let resource_count = if version.has_resource_table() {
218            cursor.skip(3)?;
219            let count = cursor.read_u32()?;
220            cursor.skip(8)?;
221            count
222        } else {
223            0
224        };
225
226        if resource_count > MAX_RESOURCES {
227            return Err(Error::ResourceCountLimit {
228                count: resource_count,
229                limit: MAX_RESOURCES,
230            });
231        }
232
233        let expected_header_size = match version {
234            Version::V7_0 | Version::V7_1 => LEGACY_HEADER_SIZE,
235            Version::V7_2 => V7_2_HEADER_SIZE,
236            Version::V7_3 | Version::V7_4 | Version::V7_5 => RESOURCE_HEADER_SIZE
237                .checked_add(resource_count.checked_mul(RESOURCE_ENTRY_SIZE).ok_or(
238                    Error::ArithmeticOverflow {
239                        context: "VTF resource table byte length",
240                    },
241                )?)
242                .ok_or(Error::ArithmeticOverflow {
243                    context: "VTF header byte length",
244                })?,
245        };
246
247        if header_size != expected_header_size {
248            return Err(Error::InvalidHeaderSize {
249                major,
250                minor,
251                declared: header_size,
252                expected: expected_header_size,
253            });
254        }
255
256        let remaining_header = usize::try_from(header_size)
257            .ok()
258            .and_then(|size| size.checked_sub(cursor.position()))
259            .ok_or(Error::InvalidHeaderSize {
260                major,
261                minor,
262                declared: header_size,
263                expected: expected_header_size,
264            })?;
265        cursor.skip(remaining_header)?;
266
267        validate_nonzero("width", width)?;
268        validate_nonzero("height", height)?;
269        validate_nonzero("frame count", frame_count)?;
270        validate_nonzero("mip count", mip_count)?;
271        validate_nonzero("depth", depth)?;
272
273        if (thumbnail_width != 0 && thumbnail_height != 0) && thumbnail_format.is_none() {
274            return Err(Error::InvalidField {
275                field: "low-resolution image format",
276                value: thumbnail_format_id as u32 as u64,
277                reason: "a thumbnail with non-zero dimensions needs a format",
278            });
279        }
280
281        let maximum_mips = maximum_mip_count(width, height, depth);
282        if mip_count > maximum_mips {
283            return Err(Error::InvalidField {
284                field: "mip count",
285                value: u64::from(mip_count),
286                reason: "it exceeds the number of distinct mip dimensions",
287            });
288        }
289
290        Ok(Self {
291            version,
292            header_size,
293            width,
294            height,
295            flags,
296            frame_count,
297            start_frame,
298            reflectivity,
299            bump_map_scale,
300            image_format_id,
301            image_format,
302            mip_count,
303            thumbnail_format_id,
304            thumbnail_format,
305            thumbnail_width,
306            thumbnail_height,
307            depth,
308            resource_count,
309        })
310    }
311}
312
313fn validate_nonzero(field: &'static str, value: impl Into<u64> + Copy) -> Result<()> {
314    if value.into() == 0 {
315        return Err(Error::InvalidField {
316            field,
317            value: 0,
318            reason: "zero is not valid",
319        });
320    }
321    Ok(())
322}
323
324fn maximum_mip_count(width: u16, height: u16, depth: u16) -> u8 {
325    let mut largest = width.max(height).max(depth);
326    let mut count = 0;
327    while largest != 0 {
328        count += 1;
329        largest >>= 1;
330    }
331    count
332}