use std::{fs::File, sync::Arc, path::Path, ffi::OsStr, io::Read}; use image::ImageError; use crate::{resource_manager::ResourceStorage, texture::Texture, resource::Resource}; use super::{LoaderError, ResourceLoader}; impl From for LoaderError { fn from(value: ImageError) -> Self { LoaderError::DecodingError(anyhow::Error::from(value)) } } /// A struct that implements the `ResourceLoader` trait used for loading textures. #[derive(Default)] pub struct TextureLoader; impl ResourceLoader for TextureLoader { fn extensions(&self) -> &[&str] { &[ // the extensions of these are the names of the formats "bmp", "dds", "gif", "ico", "jpeg", "jpg", "png", "qoi", "tga", "tiff", "webp", // farbfeld "ff", // pnm "pnm", "pbm", "pgm", "ppm", "pam", ] } fn does_support_file(&self, path: &str) -> bool { match Path::new(path).extension().and_then(OsStr::to_str) { Some(ext) => { self.extensions().contains(&ext) }, _ => false, } } fn load(&self, path: &str) -> Result, LoaderError> { // check if the file is supported by this loader if !self.does_support_file(path) { return Err(LoaderError::UnsupportedExtension(path.to_string())); } // read file bytes let mut file = File::open(path)?; let mut buf = vec![]; file.read_to_end(&mut buf)?; // load the image and construct Resource let image = image::load_from_memory(&buf)?; let texture = Texture { image, }; let res = Resource::with_data(path, texture); Ok(Arc::new(res)) } }