summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMicha White <botahamec@outlook.com>2022-11-19 13:33:26 -0500
committerMicha White <botahamec@outlook.com>2022-11-19 13:33:26 -0500
commit622e28937c48a8a389e981b9099a839d643f7678 (patch)
tree819a8f9a65992f121d71121e403195ba9ebffd35
parentc12fc6806391eb583ea75fcc89e23caf5e4218a6 (diff)
Added a load_from_file method
-rw-r--r--alligator_resources/src/texture.rs60
1 files changed, 60 insertions, 0 deletions
diff --git a/alligator_resources/src/texture.rs b/alligator_resources/src/texture.rs
index 1bb7cb8..ac9e70f 100644
--- a/alligator_resources/src/texture.rs
+++ b/alligator_resources/src/texture.rs
@@ -176,6 +176,19 @@ impl Texture {
TextureBuffer::Disk(file) => file.load(),
}
}
+
+ fn unload(&mut self) {
+ if let TextureBuffer::Disk(file) = &mut self.buffer {
+ file.unload();
+ }
+ }
+
+ fn allocated_size(&self) -> usize {
+ match &self.buffer {
+ TextureBuffer::Memory(texture) => texture_size(texture),
+ TextureBuffer::Disk(file) => file.allocated_size(),
+ }
+ }
}
pub struct TextureRef<'a> {
@@ -277,6 +290,28 @@ impl TextureManager {
}
}
+ fn can_load(&mut self, texture: &Texture) -> bool {
+ let mut textures: Vec<&mut Texture> = self.textures.values_mut().collect();
+ textures.sort_by_key(|a| a.priority());
+ textures.reverse();
+
+ let max_size = self.max_size;
+ let priority = texture.priority();
+ let mut total_size = texture.allocated_size();
+
+ for texture in textures {
+ if total_size + texture.allocated_size() < max_size {
+ total_size += texture.allocated_size();
+ } else if texture.priority() < priority {
+ texture.unload();
+ } else {
+ return false;
+ }
+ }
+
+ true
+ }
+
/// Loads a texture from memory in the given format.
///
/// # Errors
@@ -300,6 +335,31 @@ impl TextureManager {
Ok(id)
}
+ pub fn load_from_file(
+ &mut self,
+ path: impl AsRef<Path>,
+ priority: Priority,
+ ) -> Result<TextureId, LoadError> {
+ let id = TextureId::new();
+ let mut texture = Texture::from_path(path, priority);
+
+ if priority == Priority::Urgent || self.can_load(&texture) {
+ match texture.load_texture() {
+ Ok(_) => {
+ self.textures.insert(id, texture);
+ }
+ Err(e) => {
+ self.textures.insert(id, texture);
+ return Err(e);
+ }
+ }
+ } else {
+ self.textures.insert(id, texture);
+ }
+
+ Ok(id)
+ }
+
pub fn atlas(&mut self) -> &Rgba16Texture {
let atlas = {
profiling::scope!("export atlas");