Skip to main content

lactea_host/
textures.rs

1//! Directory-backed [`TextureProvider`]. Scanning mirrors projectM's `FileScanner` + `TextureManager`:
2//! recursive (depth 8), keyed by lowercase base name, files of one directory in path order, earlier
3//! directories first. The random pool is sorted by name.
4
5use lactea::{Image, Media, MediaFiles, TextureProvider, decode_gif};
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8
9/// Extensions of the plain `sampler_<name>` / `rand##` textures (projectM's list).
10pub const TEXTURE_EXTENSIONS: [&str; 7] = ["jpg", "jpeg", "dds", "png", "tga", "bmp", "dib"];
11
12/// Folders of the MD3 data root; when a scanned directory is one of them its siblings are indexed too.
13const MD3_FOLDERS: [&str; 3] = ["textures", "sprites", "gifs"];
14
15const MAX_DEPTH: u32 = 8;
16
17fn ext_of(path: &Path) -> Option<String> {
18    Some(path.extension()?.to_str()?.to_ascii_lowercase())
19}
20
21/// Every file below `dir` (recursively, each directory in path order) as `(path relative to the data root, file)`.
22fn walk(dir: &Path, rel: &str, depth: u32, out: &mut Vec<(String, PathBuf)>) {
23    let Ok(rd) = std::fs::read_dir(dir) else {
24        return;
25    };
26    let mut entries: Vec<PathBuf> = rd.flatten().map(|e| e.path()).collect();
27    entries.sort();
28    for p in entries {
29        let Some(name) = p.file_name().and_then(|n| n.to_str()).map(str::to_owned) else {
30            continue;
31        };
32        let path = if rel.is_empty() {
33            name
34        } else {
35            format!("{rel}/{name}")
36        };
37        if p.is_dir() {
38            if depth < MAX_DEPTH {
39                walk(&p, &path, depth + 1, out);
40            }
41        } else {
42            out.push((path, p));
43        }
44    }
45}
46
47/// Strip a directory prefix and a known image extension: `"textures/Clouds2.JPG"` -> `"clouds2"`.
48fn normalize(name: &str) -> String {
49    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
50    let lower = base.to_ascii_lowercase();
51    for ext in TEXTURE_EXTENSIONS {
52        if let Some(stem) = lower.strip_suffix(&format!(".{ext}")) {
53            return stem.to_string();
54        }
55    }
56    lower
57}
58
59/// Decode an image the way projectM does (`stbi_load(.., 4)`, content sniffed). JPEG goes through the
60/// stb-exact decoder (libjpeg-family decoders differ by up to 4 code values, which comp shaders amplify)
61/// and a JPEG it rejects is an error; the other formats go through the `image` crate.
62pub fn decode_image(bytes: &[u8]) -> Result<Image, String> {
63    if lactea_jpeg::is_jpeg(bytes) {
64        let img = lactea_jpeg::decode_rgba(bytes).map_err(|e| e.to_string())?;
65        return Ok(Image {
66            width: img.width,
67            height: img.height,
68            rgba8: img.rgba,
69        });
70    }
71    let rgba = image::load_from_memory(bytes)
72        .map_err(|e| e.to_string())?
73        .to_rgba8();
74    Ok(Image {
75        width: rgba.width(),
76        height: rgba.height(),
77        rgba8: rgba.into_raw(),
78    })
79}
80
81/// [`decode_image`] of the file at `path`.
82pub fn decode_file(path: &Path) -> Result<Image, String> {
83    decode_image(&std::fs::read(path).map_err(|e| e.to_string())?)
84}
85
86/// A GIF (by content) as frames, anything else as a still image.
87pub fn decode_media(path: &Path) -> Result<Media, String> {
88    let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
89    if bytes.starts_with(b"GIF8") {
90        return decode_gif(&bytes)
91            .map(Media::Animated)
92            .map_err(|e| e.to_string());
93    }
94    decode_image(&bytes).map(Media::Still)
95}
96
97/// Directories' textures for the engine: plain lookups by base name, MD3 sprites / GIFs / shader
98/// textures through a [`MediaFiles`] index of the same directories.
99pub struct DirTextures {
100    dirs: Vec<PathBuf>,
101    /// (lowercase base name, path) in priority order: earlier directories first, then path order.
102    files: Vec<(String, PathBuf)>,
103    /// Lowercase base names, one per file, sorted.
104    pool: Vec<String>,
105    media: MediaFiles<PathBuf>,
106    /// Decoded plain textures by name (`None` = not found / undecodable); presets re-request the
107    /// same texture on every load. Off by default: a host with many large textures pays memory for it.
108    cache: Option<HashMap<String, Option<Image>>>,
109}
110
111impl DirTextures {
112    /// Index `dirs` (earlier directories take priority). A directory that is one of the MD3 folders
113    /// (`textures`, `sprites`, `gifs`) makes its parent the data root too, so a preset's `sprites\x.png`
114    /// resolves next to the textures.
115    pub fn new(dirs: &[PathBuf]) -> Self {
116        let mut files = Vec::new();
117        let mut media = MediaFiles::new();
118        for dir in dirs {
119            let mut all = Vec::new();
120            walk(dir, "", 0, &mut all);
121            for (rel, path) in &all {
122                let Some(ext) = ext_of(path) else { continue };
123                if TEXTURE_EXTENSIONS.contains(&ext.as_str())
124                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
125                {
126                    files.push((stem.to_ascii_lowercase(), path.clone()));
127                }
128                if lactea::TEXTURE_EXTENSIONS.contains(&ext.as_str()) {
129                    media.add(rel, path.clone());
130                }
131            }
132            let is_folder = dir
133                .file_name()
134                .and_then(|n| n.to_str())
135                .is_some_and(|n| MD3_FOLDERS.contains(&n.to_ascii_lowercase().as_str()));
136            if let (true, Some(parent)) = (is_folder, dir.parent()) {
137                for sub in MD3_FOLDERS {
138                    let mut all = Vec::new();
139                    walk(&parent.join(sub), sub, 0, &mut all);
140                    for (rel, path) in all {
141                        if ext_of(&path)
142                            .is_some_and(|e| lactea::TEXTURE_EXTENSIONS.contains(&e.as_str()))
143                        {
144                            media.add(&rel, path);
145                        }
146                    }
147                }
148            }
149        }
150        let mut pool: Vec<String> = files.iter().map(|(n, _)| n.clone()).collect();
151        pool.sort();
152        Self {
153            dirs: dirs.to_vec(),
154            files,
155            pool,
156            media,
157            cache: None,
158        }
159    }
160
161    /// Index the single directory `root`.
162    pub fn scan(root: &Path) -> Self {
163        Self::new(&[root.to_path_buf()])
164    }
165
166    /// Keep decoded plain textures in memory.
167    #[must_use]
168    pub fn with_cache(mut self) -> Self {
169        self.cache = Some(HashMap::new());
170        self
171    }
172
173    /// The directories given to [`DirTextures::new`].
174    pub fn dirs(&self) -> &[PathBuf] {
175        &self.dirs
176    }
177
178    /// Number of plain textures indexed.
179    pub fn len(&self) -> usize {
180        self.files.len()
181    }
182
183    pub fn is_empty(&self) -> bool {
184        self.files.is_empty()
185    }
186}
187
188impl TextureProvider for DirTextures {
189    fn load(&mut self, name: &str) -> Option<Image> {
190        let key = normalize(name);
191        if let Some(hit) = self.cache.as_ref().and_then(|c| c.get(&key)) {
192            return hit.clone();
193        }
194        let img = self
195            .files
196            .iter()
197            .filter(|(n, _)| *n == key)
198            .find_map(|(_, path)| decode_file(path).ok());
199        if let Some(cache) = &mut self.cache {
200            cache.insert(key, img.clone());
201        }
202        img
203    }
204
205    fn random_pool(&self) -> Vec<String> {
206        self.pool.clone()
207    }
208
209    fn load_md3_texture(&mut self, name: &str) -> Option<Media> {
210        decode_media(self.media.find_texture(name)?).ok()
211    }
212
213    fn load_sprite(&mut self, path: &str) -> Option<Media> {
214        decode_media(self.media.find_sprite(path)?).ok()
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    /// The smallest GIF89a: one transparent 1x1 frame with no delay.
223    const TINY_GIF: &[u8] = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
224
225    fn tmp(name: &str) -> PathBuf {
226        let d = std::env::temp_dir().join(format!("lactea-host-{name}-{}", std::process::id()));
227        let _ = std::fs::remove_dir_all(&d);
228        std::fs::create_dir_all(&d).unwrap();
229        d
230    }
231
232    fn png(path: &Path, w: u32, h: u32, px: [u8; 4]) {
233        image::RgbaImage::from_pixel(w, h, image::Rgba(px))
234            .save(path)
235            .unwrap();
236    }
237
238    /// A texture folder: sprites resolve against the parent (the MD3 data root), shader textures are
239    /// found in `textures`, `sprites` and `gifs`, and a GIF comes back as frames.
240    #[test]
241    fn md3_sprites_and_gifs_resolve_from_a_textures_folder() {
242        let root = tmp("md3");
243        for d in ["textures", "sprites", "gifs"] {
244            std::fs::create_dir_all(root.join(d)).unwrap();
245        }
246        png(&root.join("textures/clouds.png"), 2, 2, [1, 2, 3, 255]);
247        png(&root.join("sprites/Logo.PNG"), 4, 2, [9, 8, 7, 255]);
248        std::fs::write(root.join("gifs/blink.gif"), TINY_GIF).unwrap();
249        let mut p = DirTextures::scan(&root.join("textures"));
250
251        let Some(Media::Still(s)) = p.load_sprite("sprites\\logo.png") else {
252            panic!("sprite");
253        };
254        assert_eq!((s.width, s.height), (4, 2));
255        assert!(p.load_sprite("sprites\\missing.png").is_none());
256        let Some(Media::Animated(a)) = p.load_sprite("gifs\\blink.gif") else {
257            panic!("gif sprite");
258        };
259        assert_eq!((a.width, a.height, a.frames.len()), (1, 1, 1));
260        assert_eq!(a.frames[0].delay, 0.1);
261        assert!(matches!(
262            p.load_md3_texture("clouds"),
263            Some(Media::Still(_))
264        ));
265        assert!(matches!(p.load_md3_texture("LOGO"), Some(Media::Still(_))));
266        assert!(matches!(
267            p.load_md3_texture("blink"),
268            Some(Media::Animated(_))
269        ));
270        // plain `load` and the random pool keep their projectM behaviour: no GIFs
271        assert!(p.random_pool().contains(&"clouds".to_string()));
272        assert!(p.load("blink").is_none());
273        let _ = std::fs::remove_dir_all(root);
274    }
275
276    #[test]
277    fn lookup_ignores_case_folder_and_extension_and_earlier_dir_wins() {
278        let a = tmp("a");
279        let b = tmp("b");
280        std::fs::create_dir_all(a.join("sub")).unwrap();
281        png(&a.join("sub/Clouds2.PNG"), 4, 2, [10, 20, 30, 255]);
282        png(&b.join("clouds2.png"), 1, 1, [1, 1, 1, 255]);
283        let mut p = DirTextures::new(&[a.clone(), b.clone()]).with_cache();
284        assert_eq!(p.len(), 2);
285        for name in ["clouds2", "CLOUDS2", "Clouds2.png", "x/clouds2.jpg"] {
286            let img = p.load(name).unwrap_or_else(|| panic!("{name}"));
287            assert_eq!((img.width, img.height), (4, 2), "{name}");
288        }
289        assert!(p.load("nope").is_none());
290        assert_eq!(p.random_pool(), ["clouds2", "clouds2"]);
291        let mut p = DirTextures::new(&[b.clone(), a.clone()]);
292        assert_eq!(p.load("clouds2").unwrap().width, 1);
293        let _ = std::fs::remove_dir_all(a);
294        let _ = std::fs::remove_dir_all(b);
295    }
296
297    #[test]
298    fn a_jpeg_the_stb_decoder_rejects_is_an_error() {
299        let bad = [0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0];
300        assert!(decode_image(&bad).is_err());
301    }
302}