Skip to main content

source_vtf/
vtf.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::path::Path;
4
5use crate::cursor::range;
6use crate::image::layout;
7use crate::{Error, Header, OwnedVtf, RawImage, Resource, ResourceLocation, ResourceTag, Result, header};
8
9/// A parsed VTF over borrowed or owned file bytes
10#[derive(Clone, PartialEq)]
11pub struct Vtf<'a> {
12    pub header: Header,
13    /// In dictionary order. 7.0-7.2 have no dictionary, there the thumbnail and image come from the fixed layout
14    pub resources: Vec<Resource>,
15    bytes: Cow<'a, [u8]>,
16}
17
18// todo: add clone for vtf!
19
20impl<'a> Vtf<'a> {
21    /// Parses a VTF without copying its file data
22    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
23        Self::parse(Cow::Borrowed(bytes))
24    }
25
26    /// Data of the first resource with `tag`: the 4 inline bytes, or its range of the file
27    pub fn resource(&self, tag: ResourceTag) -> Option<&[u8]> {
28        let resource = self
29            .resources
30            .iter()
31            .find(|resource| resource.tag == tag)?;
32        match &resource.location {
33            ResourceLocation::Inline(data) => Some(data.as_slice()),
34            ResourceLocation::Data { offset, length } => self
35                .bytes
36                .get(*offset..offset.saturating_add(*length)),
37        }
38    }
39
40    pub fn thumbnail(&self) -> Option<RawImage<'_>> {
41        let header = &self.header;
42        if header.thumbnail_width == 0 || header.thumbnail_height == 0 {
43            return None;
44        }
45        Some(RawImage {
46            format: header.thumbnail_format?,
47            width: header.thumbnail_width.into(),
48            height: header.thumbnail_height.into(),
49            data: self.resource(ResourceTag::THUMBNAIL_DATA)?,
50        })
51    }
52
53    /// One mip of one frame, cubemap face and depth slice, `mip` 0 being the full-size image
54    pub fn subresource(&self, mip: u8, frame: u16, face: u8, slice: u16) -> Result<RawImage<'_>> {
55        let (offset, length, width, height) = layout::locate(&self.header, mip, frame, face, slice)?;
56        let image = self
57            .resource(ResourceTag::IMAGE_DATA)
58            .ok_or(Error::MissingResource(ResourceTag::IMAGE_DATA))?;
59        Ok(RawImage {
60            format: self.header.image_format,
61            width,
62            height,
63            data: range(image, offset, length, "subresource")?,
64        })
65    }
66
67    /// The full-resolution image of the primary frame, cubemap face and volume slice
68    pub fn base_image(&self) -> Result<RawImage<'_>> {
69        self.subresource(0, 0, 0, 0)
70    }
71
72    // todo: add 'fn mip' helper?
73
74    /// Converts a borrowed [`Vtf`] into [`OwnedVtf`], cloning the underlying bytes
75    pub fn into_owned(self) -> OwnedVtf {
76        Vtf {
77            header: self.header,
78            resources: self.resources,
79            bytes: Cow::Owned(self.bytes.into_owned()),
80        }
81    }
82
83    fn parse(bytes: Cow<'a, [u8]>) -> Result<Self> {
84        let (header, resources) = header::parse(&bytes)?;
85        Ok(Self { header, resources, bytes })
86    }
87}
88
89impl OwnedVtf {
90    /// Reads a whole VTF into memory and parses it
91    pub fn open(path: impl AsRef<Path>) -> Result<OwnedVtf> {
92        let path = path.as_ref();
93        let bytes = std::fs::read(path).map_err(|source| Error::Io { path: path.to_owned(), source })?;
94        Self::parse(Cow::Owned(bytes))
95    }
96}
97
98// A derived Debug would dump the whole file through `bytes`
99impl fmt::Debug for Vtf<'_> {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.debug_struct("Vtf")
102            .field("header", &self.header)
103            .field("resources", &self.resources)
104            .finish_non_exhaustive()
105    }
106}