Skip to main content

source_vtf/header/
mod.rs

1mod flags;
2mod resource;
3
4pub use flags::TextureFlags;
5pub use resource::{Resource, ResourceLocation, ResourceTag};
6
7use crate::cursor::Cursor;
8use crate::{Error, ImageFormat, Result};
9
10const SIGNATURE: u32 = u32::from_le_bytes(*b"VTF\0");
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub enum Version {
15    V7_0 = 0,
16    V7_1 = 1,
17    V7_2 = 2,
18    V7_3 = 3,
19    V7_4 = 4,
20    V7_5 = 5,
21}
22
23impl Version {
24    pub const fn minor(self) -> u32 {
25        self as u32
26    }
27
28    pub const fn has_depth(self) -> bool {
29        matches!(self, Self::V7_2 | Self::V7_3 | Self::V7_4 | Self::V7_5)
30    }
31
32    pub const fn has_resource_table(self) -> bool {
33        matches!(self, Self::V7_3 | Self::V7_4 | Self::V7_5)
34    }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct Header {
40    pub version: Version,
41    pub width: u16,
42    pub height: u16,
43    /// Slices of a volume texture, 1 for everything else
44    pub depth: u16,
45    pub flags: TextureFlags,
46    pub frame_count: u16,
47    pub start_frame: u16,
48    pub reflectivity: [f32; 3],
49    pub bump_map_scale: f32,
50    pub image_format: ImageFormat,
51    pub mip_count: u8,
52    /// `None` when the VTF has no thumbnail
53    pub thumbnail_format: Option<ImageFormat>,
54    pub thumbnail_width: u8,
55    pub thumbnail_height: u8,
56}
57
58impl Header {
59    /// 1, or 6 for cubemaps, or 7 for cubemaps that also store a spheremap
60    pub const fn face_count(&self) -> u8 {
61        if !self.flags.contains(TextureFlags::ENVMAP) {
62            return 1;
63        }
64
65        // Yes, 7 faces: 7.1-7.4 cubemaps carry a spheremap fallback (CUBEMAP_FACE_SPHEREMAP in vtf.h)
66        // todo: 0xffff = no spheremap is VTFLib's rule, and VTFLib applies it to 7.0 too, we DON'T. the cool 'SourcePP' counts by data size instead
67        match self.version {
68            Version::V7_0 | Version::V7_5 => 6,
69            _ if self.start_frame == u16::MAX => 6,
70            _ => 7,
71        }
72    }
73
74    /// Width, height and depth of a mip, mip 0 being the full size. Halved per mip, never below 1
75    pub fn mip_dimensions(&self, mip: u8) -> (u16, u16, u16) {
76        let halve = |size: u16| {
77            size.checked_shr(u32::from(mip))
78                .unwrap_or(0)
79                .max(1)
80        };
81        (halve(self.width), halve(self.height), halve(self.depth))
82    }
83}
84
85/// Reads the header and the resources it lists, since 7.3 the resource dictionary is part of the header
86pub(crate) fn parse(bytes: &[u8]) -> Result<(Header, Vec<Resource>)> {
87    // todo: this func piece of crap kinda, i dont like, but 'it just works'
88    let mut c = Cursor::new(bytes, "header");
89    let signature = c.read_u32()?;
90    if signature != SIGNATURE {
91        return Err(Error::InvalidSignature(signature));
92    }
93
94    let major = c.read_u32()?;
95    let minor = c.read_u32()?;
96    let version = match (major, minor) {
97        (7, 0) => Version::V7_0,
98        (7, 1) => Version::V7_1,
99        (7, 2) => Version::V7_2,
100        (7, 3) => Version::V7_3,
101        (7, 4) => Version::V7_4,
102        (7, 5) => Version::V7_5,
103        _ => return Err(Error::UnsupportedVersion { major, minor }),
104    };
105
106    let header_size = c.read_u32()?;
107    let width = c.read_u16()?;
108    let height = c.read_u16()?;
109    let flags = TextureFlags::from_bits_retain(c.read_u32()?);
110    let frame_count = c.read_u16()?;
111    let start_frame = c.read_u16()?;
112    c.skip(4)?; // padding, reflectivity is a VectorAligned at 32
113
114    let reflectivity = [c.read_f32()?, c.read_f32()?, c.read_f32()?];
115    c.skip(4)?; // VectorAligned's w
116
117    let bump_map_scale = c.read_f32()?;
118    let image_format = ImageFormat::from_wire(c.read_i32()?, version, "image format")?;
119    let mip_count = c.read_u8()?;
120    let thumbnail_format = match c.read_i32()? {
121        -1 => None,
122        id => Some(ImageFormat::from_wire(id, version, "thumbnail format")?),
123    };
124
125    let thumbnail_width = c.read_u8()?;
126    let thumbnail_height = c.read_u8()?;
127    let depth = if version.has_depth() { c.read_u16()? } else { 1 };
128    let resource_count = if version.has_resource_table() {
129        c.skip(3)?; // pad4
130        c.read_u32()?
131    } else {
132        0
133    };
134
135    let expected_size = match version {
136        Version::V7_0 | Version::V7_1 => 64,
137        Version::V7_2 => 80,
138        // sizeof(VTFFileHeaderV7_3_t), then an 8-byte ResourceEntryInfo per resource
139        _ => 80 + 8 * u64::from(resource_count),
140    };
141
142    if u64::from(header_size) != expected_size {
143        return Err(Error::InvalidField {
144            field: "header size",
145            value: header_size.into(),
146            reason: "doesn't match the version and resource count",
147        });
148    }
149
150    for (field, value) in [
151        ("width", width),
152        ("height", height),
153        ("depth", depth),
154        ("frame count", frame_count),
155        ("mip count", mip_count.into()),
156    ] {
157        if value == 0 {
158            return Err(Error::InvalidField { field, value: 0, reason: "cannot be zero" });
159        }
160    }
161
162    if thumbnail_format.is_none() && thumbnail_width != 0 && thumbnail_height != 0 {
163        return Err(Error::InvalidField {
164            field: "thumbnail format",
165            value: -1,
166            reason: "a thumbnail with a non-zero size needs a format",
167        });
168    }
169
170    // Full size plus one mip per halving, zero sizes are rejected above so ilog2 can't panic
171    if u32::from(mip_count) > width.max(height).max(depth).ilog2() + 1 {
172        return Err(Error::InvalidField {
173            field: "mip count",
174            value: mip_count.into(),
175            reason: "more mips than sizes down to 1x1",
176        });
177    }
178
179    let header = Header {
180        version,
181        width,
182        height,
183        depth,
184        flags,
185        frame_count,
186        start_frame,
187        reflectivity,
188        bump_map_scale,
189        image_format,
190        mip_count,
191        thumbnail_format,
192        thumbnail_width,
193        thumbnail_height,
194    };
195
196    let resources = if version.has_resource_table() {
197        resource::parse_dictionary(bytes, &header, resource_count as usize)?
198    } else {
199        resource::legacy_resources(bytes, &header, header_size as usize)?
200    };
201
202    Ok((header, resources))
203}