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#[derive(Clone, PartialEq)]
11pub struct Vtf<'a> {
12 pub header: Header,
13 pub resources: Vec<Resource>,
15 bytes: Cow<'a, [u8]>,
16}
17
18impl<'a> Vtf<'a> {
21 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
23 Self::parse(Cow::Borrowed(bytes))
24 }
25
26 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 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 pub fn base_image(&self) -> Result<RawImage<'_>> {
69 self.subresource(0, 0, 0, 0)
70 }
71
72 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 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
98impl 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}