use std::collections::HashMap; use std::path::Path; use sdl2::image::LoadTexture; use sdl2::render::{Texture, TextureCreator}; pub const ASSET_PATH_STR: &str = "assets"; pub struct TextureManager { texture_creator: TextureCreator, textures: HashMap, } impl TextureManager { pub fn new(texture_creator: TextureCreator) -> Self { Self { texture_creator, textures: HashMap::new(), } } pub fn preload(&mut self, filename: S) -> Result<(), String> where S: AsRef, { let filename_str = filename .as_ref() .to_str() .expect("Only filenames with valid Unicode are allowed."); if self.textures.contains_key(filename_str) { return Ok(()); } let texture = self .texture_creator .load_texture(Path::new(ASSET_PATH_STR).join(&filename))?; self.textures.insert(filename_str.to_string(), texture); Ok(()) } pub fn get(&mut self, filename: S) -> Result<&Texture, String> where S: AsRef, { self.preload(&filename)?; Ok(self .textures .get(filename.as_ref().to_str().unwrap()) .unwrap()) } pub fn get_never_load(&self, filename: S) -> Option<&Texture> where S: AsRef, { self.textures.get(filename.as_ref().to_str().unwrap()) } }