Skip to main content

source_vtf/
vtf.rs

1use std::borrow::Cow;
2use std::fs;
3use std::path::Path;
4
5use crate::resource;
6use crate::subresource::{self, RawImage};
7use crate::{Error, Header, Resource, ResourceLocation, ResourceTag, Result};
8
9#[derive(Debug)]
10pub struct Vtf<'a> {
11    bytes: Cow<'a, [u8]>,
12    header: Header,
13    resources: Vec<Resource>,
14}
15
16impl<'a> Vtf<'a> {
17    /// Parses a VTF without copying its file data.
18    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
19        Self::parse(Cow::Borrowed(bytes))
20    }
21
22    pub const fn header(&self) -> &Header {
23        &self.header
24    }
25
26    pub fn resources(&self) -> &[Resource] {
27        &self.resources
28    }
29
30    pub fn resource(&self, tag: ResourceTag) -> Option<&Resource> {
31        self.resources.iter().find(|resource| resource.tag() == tag)
32    }
33
34    pub fn resource_data(&self, tag: ResourceTag) -> Option<&[u8]> {
35        let resource = self.resource(tag)?;
36        match resource.location() {
37            ResourceLocation::Inline(data) => Some(data),
38            ResourceLocation::Data { offset, length } => {
39                self.bytes.get(*offset..offset.checked_add(*length)?)
40            }
41        }
42    }
43
44    pub fn thumbnail(&self) -> Option<RawImage<'_>> {
45        let format = self.header.thumbnail_format()?;
46        let width = u16::from(self.header.thumbnail_width());
47        let height = u16::from(self.header.thumbnail_height());
48        if width == 0 || height == 0 {
49            return None;
50        }
51        let expected = format.byte_len(width, height).ok()?;
52        let data = self.resource_data(ResourceTag::THUMBNAIL_DATA)?;
53        Some(RawImage::new(format, width, height, data.get(..expected)?))
54    }
55
56    pub const fn mip_count(&self) -> u8 {
57        self.header.mip_count()
58    }
59
60    pub const fn frame_count(&self) -> u16 {
61        self.header.frame_count()
62    }
63
64    pub const fn face_count(&self) -> u8 {
65        self.header.face_count()
66    }
67
68    pub const fn depth(&self) -> u16 {
69        self.header.depth()
70    }
71
72    pub fn mip_dimensions(&self, mip: u8) -> Result<(u16, u16, u16)> {
73        if mip >= self.header.mip_count() {
74            return Err(Error::SubresourceOutOfRange {
75                axis: "mip",
76                index: u32::from(mip),
77                count: u32::from(self.header.mip_count()),
78            });
79        }
80        Ok(subresource::mip_dimensions(&self.header, mip))
81    }
82
83    /// Returns one tightly packed two-dimensional image from the high-resolution payload.
84    pub fn subresource(&self, mip: u8, frame: u16, face: u8, slice: u16) -> Result<RawImage<'_>> {
85        let (relative_offset, length, width, height) =
86            subresource::locate(&self.header, mip, frame, face, slice)?;
87        let image = self
88            .resource(ResourceTag::IMAGE_DATA)
89            .ok_or(Error::MissingResource {
90                tag: ResourceTag::IMAGE_DATA.value(),
91            })?;
92        let ResourceLocation::Data { offset, .. } = *image.location() else {
93            return Err(Error::InlineTextureData {
94                tag: ResourceTag::IMAGE_DATA.value(),
95            });
96        };
97        let start = offset
98            .checked_add(relative_offset)
99            .ok_or(Error::ArithmeticOverflow {
100                context: "subresource file offset",
101            })?;
102        let end = start.checked_add(length).ok_or(Error::ArithmeticOverflow {
103            context: "subresource file end",
104        })?;
105        let data = self.bytes.get(start..end).ok_or(Error::RangeOutOfBounds {
106            section: crate::Section::ImageData,
107            offset: start,
108            end,
109            file_size: self.bytes.len(),
110        })?;
111        Ok(RawImage::new(
112            self.header.image_format(),
113            width,
114            height,
115            data,
116        ))
117    }
118
119    fn parse(bytes: Cow<'a, [u8]>) -> Result<Self> {
120        let header = Header::parse(&bytes)?;
121        let resources = resource::parse(&bytes, &header)?;
122        Ok(Self {
123            bytes,
124            header,
125            resources,
126        })
127    }
128}
129
130impl Vtf<'static> {
131    /// Reads a complete VTF into memory and parses it.
132    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
133        let path = path.as_ref();
134        let bytes = fs::read(path).map_err(|error| Error::io(path, error))?;
135        Self::parse(Cow::Owned(bytes))
136    }
137}