use super::{Dds, ReadError, Tex, Texture};
use byteorder::{ReadBytesExt, LE};
use ltk_io_ext::window;
use std::{
fmt::Display,
io::{self},
};
#[derive(Clone, Copy, Hash, Debug, PartialEq, Eq)]
pub enum TextureFileFormat {
DDS,
TEX,
Unknown,
}
impl Display for TextureFileFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
TextureFileFormat::DDS => "DDS",
TextureFileFormat::TEX => "TEX",
TextureFileFormat::Unknown => "unknown",
})
}
}
impl TextureFileFormat {
pub fn from_magic(magic: u32) -> Self {
match magic {
Dds::MAGIC => Self::DDS,
Tex::MAGIC => Self::TEX,
_ => Self::Unknown,
}
}
pub fn read<R: io::Read + ?Sized>(&self, reader: &mut R) -> Result<Texture, ReadError> {
match self {
TextureFileFormat::DDS => Ok(Dds::from_reader(reader)?.into()),
TextureFileFormat::TEX => Ok(Tex::from_reader(reader)?.into()),
_ => Err(ReadError::UnsupportedTextureFormat(*self)),
}
}
pub fn read_no_magic<R: io::Read + ?Sized>(
&self,
reader: &mut R,
) -> Result<Texture, ReadError> {
match self {
TextureFileFormat::DDS => Ok(Dds::from_reader_no_magic(reader)?.into()),
TextureFileFormat::TEX => Ok(Tex::from_reader_no_magic(reader)?.into()),
_ => Err(ReadError::UnsupportedTextureFormat(*self)),
}
}
pub fn identify(reader: &mut (impl io::Read + io::Seek)) -> Result<Self, ReadError> {
let magic = window(reader, |reader| -> Result<u32, io::Error> {
let magic = reader.read_u32::<LE>()?;
Ok(magic)
})?;
Ok(Self::from_magic(magic))
}
}