Skip to main content

gcrecomp_runtime/texture/
cache.rs

1// Texture cache
2use image::RgbaImage;
3use std::collections::HashMap;
4
5pub struct TextureCache {
6    cache: HashMap<String, RgbaImage>,
7    max_size: usize,
8    current_size: usize,
9}
10
11impl TextureCache {
12    pub fn new() -> Self {
13        Self {
14            cache: HashMap::new(),
15            max_size: 512 * 1024 * 1024, // 512MB default
16            current_size: 0,
17        }
18    }
19
20    pub fn get(&self, key: &str) -> Option<&RgbaImage> {
21        self.cache.get(key)
22    }
23
24    pub fn insert(&mut self, key: String, texture: RgbaImage) {
25        let size = (texture.width() * texture.height() * 4) as usize;
26
27        // Evict if needed (simple LRU - would need proper implementation)
28        while self.current_size + size > self.max_size && !self.cache.is_empty() {
29            if let Some((old_key, _)) = self.cache.iter().next() {
30                let old_key = old_key.clone();
31                if let Some(old_texture) = self.cache.remove(&old_key) {
32                    let old_size = (old_texture.width() * old_texture.height() * 4) as usize;
33                    self.current_size -= old_size;
34                }
35            } else {
36                break;
37            }
38        }
39
40        self.cache.insert(key, texture);
41        self.current_size += size;
42    }
43
44    pub fn clear(&mut self) {
45        self.cache.clear();
46        self.current_size = 0;
47    }
48
49    pub fn set_max_size(&mut self, size: usize) {
50        self.max_size = size;
51        // Evict if over limit
52        while self.current_size > self.max_size {
53            if let Some((key, _)) = self.cache.iter().next() {
54                let key = key.clone();
55                if let Some(texture) = self.cache.remove(&key) {
56                    let texture_size = (texture.width() * texture.height() * 4) as usize;
57                    self.current_size -= texture_size;
58                }
59            } else {
60                break;
61            }
62        }
63    }
64}